mlx: use aligned memory to register regions
[dpdk.git] / drivers / net / mlx4 / mlx4.c
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright 2012-2015 6WIND S.A.
5  *   Copyright 2012 Mellanox.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  *
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of 6WIND S.A. nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  *
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33
34 /*
35  * Known limitations:
36  * - RSS hash key and options cannot be modified.
37  * - Hardware counters aren't implemented.
38  */
39
40 /* System headers. */
41 #include <stddef.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <stdint.h>
45 #include <inttypes.h>
46 #include <string.h>
47 #include <errno.h>
48 #include <unistd.h>
49 #include <limits.h>
50 #include <assert.h>
51 #include <arpa/inet.h>
52 #include <net/if.h>
53 #include <dirent.h>
54 #include <sys/ioctl.h>
55 #include <sys/socket.h>
56 #include <netinet/in.h>
57 #include <linux/if.h>
58 #include <linux/ethtool.h>
59 #include <linux/sockios.h>
60 #include <fcntl.h>
61
62 /* Verbs header. */
63 /* ISO C doesn't support unnamed structs/unions, disabling -pedantic. */
64 #ifdef PEDANTIC
65 #pragma GCC diagnostic ignored "-pedantic"
66 #endif
67 #include <infiniband/verbs.h>
68 #ifdef PEDANTIC
69 #pragma GCC diagnostic error "-pedantic"
70 #endif
71
72 /* DPDK headers don't like -pedantic. */
73 #ifdef PEDANTIC
74 #pragma GCC diagnostic ignored "-pedantic"
75 #endif
76 #include <rte_ether.h>
77 #include <rte_ethdev.h>
78 #include <rte_dev.h>
79 #include <rte_mbuf.h>
80 #include <rte_errno.h>
81 #include <rte_mempool.h>
82 #include <rte_prefetch.h>
83 #include <rte_malloc.h>
84 #include <rte_spinlock.h>
85 #include <rte_atomic.h>
86 #include <rte_version.h>
87 #include <rte_log.h>
88 #include <rte_alarm.h>
89 #include <rte_memory.h>
90 #ifdef PEDANTIC
91 #pragma GCC diagnostic error "-pedantic"
92 #endif
93
94 /* Generated configuration header. */
95 #include "mlx4_autoconf.h"
96
97 /* PMD header. */
98 #include "mlx4.h"
99
100 /* Runtime logging through RTE_LOG() is enabled when not in debugging mode.
101  * Intermediate LOG_*() macros add the required end-of-line characters. */
102 #ifndef NDEBUG
103 #define INFO(...) DEBUG(__VA_ARGS__)
104 #define WARN(...) DEBUG(__VA_ARGS__)
105 #define ERROR(...) DEBUG(__VA_ARGS__)
106 #else
107 #define LOG__(level, m, ...) \
108         RTE_LOG(level, PMD, MLX4_DRIVER_NAME ": " m "%c", __VA_ARGS__)
109 #define LOG_(level, ...) LOG__(level, __VA_ARGS__, '\n')
110 #define INFO(...) LOG_(INFO, __VA_ARGS__)
111 #define WARN(...) LOG_(WARNING, __VA_ARGS__)
112 #define ERROR(...) LOG_(ERR, __VA_ARGS__)
113 #endif
114
115 /* Convenience macros for accessing mbuf fields. */
116 #define NEXT(m) ((m)->next)
117 #define DATA_LEN(m) ((m)->data_len)
118 #define PKT_LEN(m) ((m)->pkt_len)
119 #define DATA_OFF(m) ((m)->data_off)
120 #define SET_DATA_OFF(m, o) ((m)->data_off = (o))
121 #define NB_SEGS(m) ((m)->nb_segs)
122 #define PORT(m) ((m)->port)
123
124 /* Work Request ID data type (64 bit). */
125 typedef union {
126         struct {
127                 uint32_t id;
128                 uint16_t offset;
129         } data;
130         uint64_t raw;
131 } wr_id_t;
132
133 #define WR_ID(o) (((wr_id_t *)&(o))->data)
134
135 /* Transpose flags. Useful to convert IBV to DPDK flags. */
136 #define TRANSPOSE(val, from, to) \
137         (((from) >= (to)) ? \
138          (((val) & (from)) / ((from) / (to))) : \
139          (((val) & (from)) * ((to) / (from))))
140
141 struct mlx4_rxq_stats {
142         unsigned int idx; /**< Mapping index. */
143 #ifdef MLX4_PMD_SOFT_COUNTERS
144         uint64_t ipackets;  /**< Total of successfully received packets. */
145         uint64_t ibytes;    /**< Total of successfully received bytes. */
146 #endif
147         uint64_t idropped;  /**< Total of packets dropped when RX ring full. */
148         uint64_t rx_nombuf; /**< Total of RX mbuf allocation failures. */
149 };
150
151 struct mlx4_txq_stats {
152         unsigned int idx; /**< Mapping index. */
153 #ifdef MLX4_PMD_SOFT_COUNTERS
154         uint64_t opackets; /**< Total of successfully sent packets. */
155         uint64_t obytes;   /**< Total of successfully sent bytes. */
156 #endif
157         uint64_t odropped; /**< Total of packets not sent when TX ring full. */
158 };
159
160 /* RX element (scattered packets). */
161 struct rxq_elt_sp {
162         struct ibv_recv_wr wr; /* Work Request. */
163         struct ibv_sge sges[MLX4_PMD_SGE_WR_N]; /* Scatter/Gather Elements. */
164         struct rte_mbuf *bufs[MLX4_PMD_SGE_WR_N]; /* SGEs buffers. */
165 };
166
167 /* RX element. */
168 struct rxq_elt {
169         struct ibv_recv_wr wr; /* Work Request. */
170         struct ibv_sge sge; /* Scatter/Gather Element. */
171         /* mbuf pointer is derived from WR_ID(wr.wr_id).offset. */
172 };
173
174 /* RX queue descriptor. */
175 struct rxq {
176         struct priv *priv; /* Back pointer to private data. */
177         struct rte_mempool *mp; /* Memory Pool for allocations. */
178         struct ibv_mr *mr; /* Memory Region (for mp). */
179         struct ibv_cq *cq; /* Completion Queue. */
180         struct ibv_qp *qp; /* Queue Pair. */
181         struct ibv_exp_qp_burst_family *if_qp; /* QP burst interface. */
182         struct ibv_exp_cq_family *if_cq; /* CQ interface. */
183         /*
184          * Each VLAN ID requires a separate flow steering rule.
185          */
186         BITFIELD_DECLARE(mac_configured, uint32_t, MLX4_MAX_MAC_ADDRESSES);
187         struct ibv_flow *mac_flow[MLX4_MAX_MAC_ADDRESSES][MLX4_MAX_VLAN_IDS];
188         struct ibv_flow *promisc_flow; /* Promiscuous flow. */
189         struct ibv_flow *allmulti_flow; /* Multicast flow. */
190         unsigned int port_id; /* Port ID for incoming packets. */
191         unsigned int elts_n; /* (*elts)[] length. */
192         unsigned int elts_head; /* Current index in (*elts)[]. */
193         union {
194                 struct rxq_elt_sp (*sp)[]; /* Scattered RX elements. */
195                 struct rxq_elt (*no_sp)[]; /* RX elements. */
196         } elts;
197         unsigned int sp:1; /* Use scattered RX elements. */
198         unsigned int csum:1; /* Enable checksum offloading. */
199         unsigned int csum_l2tun:1; /* Same for L2 tunnels. */
200         uint32_t mb_len; /* Length of a mp-issued mbuf. */
201         struct mlx4_rxq_stats stats; /* RX queue counters. */
202         unsigned int socket; /* CPU socket ID for allocations. */
203         struct ibv_exp_res_domain *rd; /* Resource Domain. */
204 };
205
206 /* TX element. */
207 struct txq_elt {
208         struct rte_mbuf *buf;
209 };
210
211 /* Linear buffer type. It is used when transmitting buffers with too many
212  * segments that do not fit the hardware queue (see max_send_sge).
213  * Extra segments are copied (linearized) in such buffers, replacing the
214  * last SGE during TX.
215  * The size is arbitrary but large enough to hold a jumbo frame with
216  * 8 segments considering mbuf.buf_len is about 2048 bytes. */
217 typedef uint8_t linear_t[16384];
218
219 /* TX queue descriptor. */
220 struct txq {
221         struct priv *priv; /* Back pointer to private data. */
222         struct {
223                 const struct rte_mempool *mp; /* Cached Memory Pool. */
224                 struct ibv_mr *mr; /* Memory Region (for mp). */
225                 uint32_t lkey; /* mr->lkey */
226         } mp2mr[MLX4_PMD_TX_MP_CACHE]; /* MP to MR translation table. */
227         struct ibv_cq *cq; /* Completion Queue. */
228         struct ibv_qp *qp; /* Queue Pair. */
229         struct ibv_exp_qp_burst_family *if_qp; /* QP burst interface. */
230         struct ibv_exp_cq_family *if_cq; /* CQ interface. */
231 #if MLX4_PMD_MAX_INLINE > 0
232         uint32_t max_inline; /* Max inline send size <= MLX4_PMD_MAX_INLINE. */
233 #endif
234         unsigned int elts_n; /* (*elts)[] length. */
235         struct txq_elt (*elts)[]; /* TX elements. */
236         unsigned int elts_head; /* Current index in (*elts)[]. */
237         unsigned int elts_tail; /* First element awaiting completion. */
238         unsigned int elts_comp; /* Number of completion requests. */
239         unsigned int elts_comp_cd; /* Countdown for next completion request. */
240         unsigned int elts_comp_cd_init; /* Initial value for countdown. */
241         struct mlx4_txq_stats stats; /* TX queue counters. */
242         linear_t (*elts_linear)[]; /* Linearized buffers. */
243         struct ibv_mr *mr_linear; /* Memory Region for linearized buffers. */
244         unsigned int socket; /* CPU socket ID for allocations. */
245         struct ibv_exp_res_domain *rd; /* Resource Domain. */
246 };
247
248 struct priv {
249         struct rte_eth_dev *dev; /* Ethernet device. */
250         struct ibv_context *ctx; /* Verbs context. */
251         struct ibv_device_attr device_attr; /* Device properties. */
252         struct ibv_pd *pd; /* Protection Domain. */
253         /*
254          * MAC addresses array and configuration bit-field.
255          * An extra entry that cannot be modified by the DPDK is reserved
256          * for broadcast frames (destination MAC address ff:ff:ff:ff:ff:ff).
257          */
258         struct ether_addr mac[MLX4_MAX_MAC_ADDRESSES];
259         BITFIELD_DECLARE(mac_configured, uint32_t, MLX4_MAX_MAC_ADDRESSES);
260         /* VLAN filters. */
261         struct {
262                 unsigned int enabled:1; /* If enabled. */
263                 unsigned int id:12; /* VLAN ID (0-4095). */
264         } vlan_filter[MLX4_MAX_VLAN_IDS]; /* VLAN filters table. */
265         /* Device properties. */
266         uint16_t mtu; /* Configured MTU. */
267         uint8_t port; /* Physical port number. */
268         unsigned int started:1; /* Device started, flows enabled. */
269         unsigned int promisc:1; /* Device in promiscuous mode. */
270         unsigned int allmulti:1; /* Device receives all multicast packets. */
271         unsigned int hw_qpg:1; /* QP groups are supported. */
272         unsigned int hw_tss:1; /* TSS is supported. */
273         unsigned int hw_rss:1; /* RSS is supported. */
274         unsigned int hw_csum:1; /* Checksum offload is supported. */
275         unsigned int hw_csum_l2tun:1; /* Same for L2 tunnels. */
276         unsigned int rss:1; /* RSS is enabled. */
277         unsigned int vf:1; /* This is a VF device. */
278         unsigned int pending_alarm:1; /* An alarm is pending. */
279 #ifdef INLINE_RECV
280         unsigned int inl_recv_size; /* Inline recv size */
281 #endif
282         unsigned int max_rss_tbl_sz; /* Maximum number of RSS queues. */
283         /* RX/TX queues. */
284         struct rxq rxq_parent; /* Parent queue when RSS is enabled. */
285         unsigned int rxqs_n; /* RX queues array size. */
286         unsigned int txqs_n; /* TX queues array size. */
287         struct rxq *(*rxqs)[]; /* RX queues. */
288         struct txq *(*txqs)[]; /* TX queues. */
289         struct rte_intr_handle intr_handle; /* Interrupt handler. */
290         rte_spinlock_t lock; /* Lock for control functions. */
291 };
292
293 /* Local storage for secondary process data. */
294 struct mlx4_secondary_data {
295         struct rte_eth_dev_data data; /* Local device data. */
296         struct priv *primary_priv; /* Private structure from primary. */
297         struct rte_eth_dev_data *shared_dev_data; /* Shared device data. */
298         rte_spinlock_t lock; /* Port configuration lock. */
299 } mlx4_secondary_data[RTE_MAX_ETHPORTS];
300
301 /**
302  * Check if running as a secondary process.
303  *
304  * @return
305  *   Nonzero if running as a secondary process.
306  */
307 static inline int
308 mlx4_is_secondary(void)
309 {
310         return rte_eal_process_type() != RTE_PROC_PRIMARY;
311 }
312
313 /**
314  * Return private structure associated with an Ethernet device.
315  *
316  * @param dev
317  *   Pointer to Ethernet device structure.
318  *
319  * @return
320  *   Pointer to private structure.
321  */
322 static struct priv *
323 mlx4_get_priv(struct rte_eth_dev *dev)
324 {
325         struct mlx4_secondary_data *sd;
326
327         if (!mlx4_is_secondary())
328                 return dev->data->dev_private;
329         sd = &mlx4_secondary_data[dev->data->port_id];
330         return sd->data.dev_private;
331 }
332
333 /**
334  * Lock private structure to protect it from concurrent access in the
335  * control path.
336  *
337  * @param priv
338  *   Pointer to private structure.
339  */
340 static void
341 priv_lock(struct priv *priv)
342 {
343         rte_spinlock_lock(&priv->lock);
344 }
345
346 /**
347  * Unlock private structure.
348  *
349  * @param priv
350  *   Pointer to private structure.
351  */
352 static void
353 priv_unlock(struct priv *priv)
354 {
355         rte_spinlock_unlock(&priv->lock);
356 }
357
358 /* Allocate a buffer on the stack and fill it with a printf format string. */
359 #define MKSTR(name, ...) \
360         char name[snprintf(NULL, 0, __VA_ARGS__) + 1]; \
361         \
362         snprintf(name, sizeof(name), __VA_ARGS__)
363
364 /**
365  * Get interface name from private structure.
366  *
367  * @param[in] priv
368  *   Pointer to private structure.
369  * @param[out] ifname
370  *   Interface name output buffer.
371  *
372  * @return
373  *   0 on success, -1 on failure and errno is set.
374  */
375 static int
376 priv_get_ifname(const struct priv *priv, char (*ifname)[IF_NAMESIZE])
377 {
378         DIR *dir;
379         struct dirent *dent;
380         unsigned int dev_type = 0;
381         unsigned int dev_port_prev = ~0u;
382         char match[IF_NAMESIZE] = "";
383
384         {
385                 MKSTR(path, "%s/device/net", priv->ctx->device->ibdev_path);
386
387                 dir = opendir(path);
388                 if (dir == NULL)
389                         return -1;
390         }
391         while ((dent = readdir(dir)) != NULL) {
392                 char *name = dent->d_name;
393                 FILE *file;
394                 unsigned int dev_port;
395                 int r;
396
397                 if ((name[0] == '.') &&
398                     ((name[1] == '\0') ||
399                      ((name[1] == '.') && (name[2] == '\0'))))
400                         continue;
401
402                 MKSTR(path, "%s/device/net/%s/%s",
403                       priv->ctx->device->ibdev_path, name,
404                       (dev_type ? "dev_id" : "dev_port"));
405
406                 file = fopen(path, "rb");
407                 if (file == NULL) {
408                         if (errno != ENOENT)
409                                 continue;
410                         /*
411                          * Switch to dev_id when dev_port does not exist as
412                          * is the case with Linux kernel versions < 3.15.
413                          */
414 try_dev_id:
415                         match[0] = '\0';
416                         if (dev_type)
417                                 break;
418                         dev_type = 1;
419                         dev_port_prev = ~0u;
420                         rewinddir(dir);
421                         continue;
422                 }
423                 r = fscanf(file, (dev_type ? "%x" : "%u"), &dev_port);
424                 fclose(file);
425                 if (r != 1)
426                         continue;
427                 /*
428                  * Switch to dev_id when dev_port returns the same value for
429                  * all ports. May happen when using a MOFED release older than
430                  * 3.0 with a Linux kernel >= 3.15.
431                  */
432                 if (dev_port == dev_port_prev)
433                         goto try_dev_id;
434                 dev_port_prev = dev_port;
435                 if (dev_port == (priv->port - 1u))
436                         snprintf(match, sizeof(match), "%s", name);
437         }
438         closedir(dir);
439         if (match[0] == '\0')
440                 return -1;
441         strncpy(*ifname, match, sizeof(*ifname));
442         return 0;
443 }
444
445 /**
446  * Read from sysfs entry.
447  *
448  * @param[in] priv
449  *   Pointer to private structure.
450  * @param[in] entry
451  *   Entry name relative to sysfs path.
452  * @param[out] buf
453  *   Data output buffer.
454  * @param size
455  *   Buffer size.
456  *
457  * @return
458  *   0 on success, -1 on failure and errno is set.
459  */
460 static int
461 priv_sysfs_read(const struct priv *priv, const char *entry,
462                 char *buf, size_t size)
463 {
464         char ifname[IF_NAMESIZE];
465         FILE *file;
466         int ret;
467         int err;
468
469         if (priv_get_ifname(priv, &ifname))
470                 return -1;
471
472         MKSTR(path, "%s/device/net/%s/%s", priv->ctx->device->ibdev_path,
473               ifname, entry);
474
475         file = fopen(path, "rb");
476         if (file == NULL)
477                 return -1;
478         ret = fread(buf, 1, size, file);
479         err = errno;
480         if (((size_t)ret < size) && (ferror(file)))
481                 ret = -1;
482         else
483                 ret = size;
484         fclose(file);
485         errno = err;
486         return ret;
487 }
488
489 /**
490  * Write to sysfs entry.
491  *
492  * @param[in] priv
493  *   Pointer to private structure.
494  * @param[in] entry
495  *   Entry name relative to sysfs path.
496  * @param[in] buf
497  *   Data buffer.
498  * @param size
499  *   Buffer size.
500  *
501  * @return
502  *   0 on success, -1 on failure and errno is set.
503  */
504 static int
505 priv_sysfs_write(const struct priv *priv, const char *entry,
506                  char *buf, size_t size)
507 {
508         char ifname[IF_NAMESIZE];
509         FILE *file;
510         int ret;
511         int err;
512
513         if (priv_get_ifname(priv, &ifname))
514                 return -1;
515
516         MKSTR(path, "%s/device/net/%s/%s", priv->ctx->device->ibdev_path,
517               ifname, entry);
518
519         file = fopen(path, "wb");
520         if (file == NULL)
521                 return -1;
522         ret = fwrite(buf, 1, size, file);
523         err = errno;
524         if (((size_t)ret < size) || (ferror(file)))
525                 ret = -1;
526         else
527                 ret = size;
528         fclose(file);
529         errno = err;
530         return ret;
531 }
532
533 /**
534  * Get unsigned long sysfs property.
535  *
536  * @param priv
537  *   Pointer to private structure.
538  * @param[in] name
539  *   Entry name relative to sysfs path.
540  * @param[out] value
541  *   Value output buffer.
542  *
543  * @return
544  *   0 on success, -1 on failure and errno is set.
545  */
546 static int
547 priv_get_sysfs_ulong(struct priv *priv, const char *name, unsigned long *value)
548 {
549         int ret;
550         unsigned long value_ret;
551         char value_str[32];
552
553         ret = priv_sysfs_read(priv, name, value_str, (sizeof(value_str) - 1));
554         if (ret == -1) {
555                 DEBUG("cannot read %s value from sysfs: %s",
556                       name, strerror(errno));
557                 return -1;
558         }
559         value_str[ret] = '\0';
560         errno = 0;
561         value_ret = strtoul(value_str, NULL, 0);
562         if (errno) {
563                 DEBUG("invalid %s value `%s': %s", name, value_str,
564                       strerror(errno));
565                 return -1;
566         }
567         *value = value_ret;
568         return 0;
569 }
570
571 /**
572  * Set unsigned long sysfs property.
573  *
574  * @param priv
575  *   Pointer to private structure.
576  * @param[in] name
577  *   Entry name relative to sysfs path.
578  * @param value
579  *   Value to set.
580  *
581  * @return
582  *   0 on success, -1 on failure and errno is set.
583  */
584 static int
585 priv_set_sysfs_ulong(struct priv *priv, const char *name, unsigned long value)
586 {
587         int ret;
588         MKSTR(value_str, "%lu", value);
589
590         ret = priv_sysfs_write(priv, name, value_str, (sizeof(value_str) - 1));
591         if (ret == -1) {
592                 DEBUG("cannot write %s `%s' (%lu) to sysfs: %s",
593                       name, value_str, value, strerror(errno));
594                 return -1;
595         }
596         return 0;
597 }
598
599 /**
600  * Perform ifreq ioctl() on associated Ethernet device.
601  *
602  * @param[in] priv
603  *   Pointer to private structure.
604  * @param req
605  *   Request number to pass to ioctl().
606  * @param[out] ifr
607  *   Interface request structure output buffer.
608  *
609  * @return
610  *   0 on success, -1 on failure and errno is set.
611  */
612 static int
613 priv_ifreq(const struct priv *priv, int req, struct ifreq *ifr)
614 {
615         int sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
616         int ret = -1;
617
618         if (sock == -1)
619                 return ret;
620         if (priv_get_ifname(priv, &ifr->ifr_name) == 0)
621                 ret = ioctl(sock, req, ifr);
622         close(sock);
623         return ret;
624 }
625
626 /**
627  * Get device MTU.
628  *
629  * @param priv
630  *   Pointer to private structure.
631  * @param[out] mtu
632  *   MTU value output buffer.
633  *
634  * @return
635  *   0 on success, -1 on failure and errno is set.
636  */
637 static int
638 priv_get_mtu(struct priv *priv, uint16_t *mtu)
639 {
640         unsigned long ulong_mtu;
641
642         if (priv_get_sysfs_ulong(priv, "mtu", &ulong_mtu) == -1)
643                 return -1;
644         *mtu = ulong_mtu;
645         return 0;
646 }
647
648 /**
649  * Set device MTU.
650  *
651  * @param priv
652  *   Pointer to private structure.
653  * @param mtu
654  *   MTU value to set.
655  *
656  * @return
657  *   0 on success, -1 on failure and errno is set.
658  */
659 static int
660 priv_set_mtu(struct priv *priv, uint16_t mtu)
661 {
662         return priv_set_sysfs_ulong(priv, "mtu", mtu);
663 }
664
665 /**
666  * Set device flags.
667  *
668  * @param priv
669  *   Pointer to private structure.
670  * @param keep
671  *   Bitmask for flags that must remain untouched.
672  * @param flags
673  *   Bitmask for flags to modify.
674  *
675  * @return
676  *   0 on success, -1 on failure and errno is set.
677  */
678 static int
679 priv_set_flags(struct priv *priv, unsigned int keep, unsigned int flags)
680 {
681         unsigned long tmp;
682
683         if (priv_get_sysfs_ulong(priv, "flags", &tmp) == -1)
684                 return -1;
685         tmp &= keep;
686         tmp |= flags;
687         return priv_set_sysfs_ulong(priv, "flags", tmp);
688 }
689
690 /* Device configuration. */
691
692 static int
693 txq_setup(struct rte_eth_dev *dev, struct txq *txq, uint16_t desc,
694           unsigned int socket, const struct rte_eth_txconf *conf);
695
696 static void
697 txq_cleanup(struct txq *txq);
698
699 static int
700 rxq_setup(struct rte_eth_dev *dev, struct rxq *rxq, uint16_t desc,
701           unsigned int socket, const struct rte_eth_rxconf *conf,
702           struct rte_mempool *mp);
703
704 static void
705 rxq_cleanup(struct rxq *rxq);
706
707 /**
708  * Ethernet device configuration.
709  *
710  * Prepare the driver for a given number of TX and RX queues.
711  * Allocate parent RSS queue when several RX queues are requested.
712  *
713  * @param dev
714  *   Pointer to Ethernet device structure.
715  *
716  * @return
717  *   0 on success, errno value on failure.
718  */
719 static int
720 dev_configure(struct rte_eth_dev *dev)
721 {
722         struct priv *priv = dev->data->dev_private;
723         unsigned int rxqs_n = dev->data->nb_rx_queues;
724         unsigned int txqs_n = dev->data->nb_tx_queues;
725         unsigned int tmp;
726         int ret;
727
728         priv->rxqs = (void *)dev->data->rx_queues;
729         priv->txqs = (void *)dev->data->tx_queues;
730         if (txqs_n != priv->txqs_n) {
731                 INFO("%p: TX queues number update: %u -> %u",
732                      (void *)dev, priv->txqs_n, txqs_n);
733                 priv->txqs_n = txqs_n;
734         }
735         if (rxqs_n == priv->rxqs_n)
736                 return 0;
737         if ((rxqs_n & (rxqs_n - 1)) != 0) {
738                 ERROR("%p: invalid number of RX queues (%u),"
739                       " must be a power of 2",
740                       (void *)dev, rxqs_n);
741                 return EINVAL;
742         }
743         INFO("%p: RX queues number update: %u -> %u",
744              (void *)dev, priv->rxqs_n, rxqs_n);
745         /* If RSS is enabled, disable it first. */
746         if (priv->rss) {
747                 unsigned int i;
748
749                 /* Only if there are no remaining child RX queues. */
750                 for (i = 0; (i != priv->rxqs_n); ++i)
751                         if ((*priv->rxqs)[i] != NULL)
752                                 return EINVAL;
753                 rxq_cleanup(&priv->rxq_parent);
754                 priv->rss = 0;
755                 priv->rxqs_n = 0;
756         }
757         if (rxqs_n <= 1) {
758                 /* Nothing else to do. */
759                 priv->rxqs_n = rxqs_n;
760                 return 0;
761         }
762         /* Allocate a new RSS parent queue if supported by hardware. */
763         if (!priv->hw_rss) {
764                 ERROR("%p: only a single RX queue can be configured when"
765                       " hardware doesn't support RSS",
766                       (void *)dev);
767                 return EINVAL;
768         }
769         /* Fail if hardware doesn't support that many RSS queues. */
770         if (rxqs_n >= priv->max_rss_tbl_sz) {
771                 ERROR("%p: only %u RX queues can be configured for RSS",
772                       (void *)dev, priv->max_rss_tbl_sz);
773                 return EINVAL;
774         }
775         priv->rss = 1;
776         tmp = priv->rxqs_n;
777         priv->rxqs_n = rxqs_n;
778         ret = rxq_setup(dev, &priv->rxq_parent, 0, 0, NULL, NULL);
779         if (!ret)
780                 return 0;
781         /* Failure, rollback. */
782         priv->rss = 0;
783         priv->rxqs_n = tmp;
784         assert(ret > 0);
785         return ret;
786 }
787
788 /**
789  * DPDK callback for Ethernet device configuration.
790  *
791  * @param dev
792  *   Pointer to Ethernet device structure.
793  *
794  * @return
795  *   0 on success, negative errno value on failure.
796  */
797 static int
798 mlx4_dev_configure(struct rte_eth_dev *dev)
799 {
800         struct priv *priv = dev->data->dev_private;
801         int ret;
802
803         if (mlx4_is_secondary())
804                 return -E_RTE_SECONDARY;
805         priv_lock(priv);
806         ret = dev_configure(dev);
807         assert(ret >= 0);
808         priv_unlock(priv);
809         return -ret;
810 }
811
812 static uint16_t mlx4_tx_burst(void *, struct rte_mbuf **, uint16_t);
813 static uint16_t removed_rx_burst(void *, struct rte_mbuf **, uint16_t);
814
815 /**
816  * Configure secondary process queues from a private data pointer (primary
817  * or secondary) and update burst callbacks. Can take place only once.
818  *
819  * All queues must have been previously created by the primary process to
820  * avoid undefined behavior.
821  *
822  * @param priv
823  *   Private data pointer from either primary or secondary process.
824  *
825  * @return
826  *   Private data pointer from secondary process, NULL in case of error.
827  */
828 static struct priv *
829 mlx4_secondary_data_setup(struct priv *priv)
830 {
831         unsigned int port_id = 0;
832         struct mlx4_secondary_data *sd;
833         void **tx_queues;
834         void **rx_queues;
835         unsigned int nb_tx_queues;
836         unsigned int nb_rx_queues;
837         unsigned int i;
838
839         /* priv must be valid at this point. */
840         assert(priv != NULL);
841         /* priv->dev must also be valid but may point to local memory from
842          * another process, possibly with the same address and must not
843          * be dereferenced yet. */
844         assert(priv->dev != NULL);
845         /* Determine port ID by finding out where priv comes from. */
846         while (1) {
847                 sd = &mlx4_secondary_data[port_id];
848                 rte_spinlock_lock(&sd->lock);
849                 /* Primary process? */
850                 if (sd->primary_priv == priv)
851                         break;
852                 /* Secondary process? */
853                 if (sd->data.dev_private == priv)
854                         break;
855                 rte_spinlock_unlock(&sd->lock);
856                 if (++port_id == RTE_DIM(mlx4_secondary_data))
857                         port_id = 0;
858         }
859         /* Switch to secondary private structure. If private data has already
860          * been updated by another thread, there is nothing else to do. */
861         priv = sd->data.dev_private;
862         if (priv->dev->data == &sd->data)
863                 goto end;
864         /* Sanity checks. Secondary private structure is supposed to point
865          * to local eth_dev, itself still pointing to the shared device data
866          * structure allocated by the primary process. */
867         assert(sd->shared_dev_data != &sd->data);
868         assert(sd->data.nb_tx_queues == 0);
869         assert(sd->data.tx_queues == NULL);
870         assert(sd->data.nb_rx_queues == 0);
871         assert(sd->data.rx_queues == NULL);
872         assert(priv != sd->primary_priv);
873         assert(priv->dev->data == sd->shared_dev_data);
874         assert(priv->txqs_n == 0);
875         assert(priv->txqs == NULL);
876         assert(priv->rxqs_n == 0);
877         assert(priv->rxqs == NULL);
878         nb_tx_queues = sd->shared_dev_data->nb_tx_queues;
879         nb_rx_queues = sd->shared_dev_data->nb_rx_queues;
880         /* Allocate local storage for queues. */
881         tx_queues = rte_zmalloc("secondary ethdev->tx_queues",
882                                 sizeof(sd->data.tx_queues[0]) * nb_tx_queues,
883                                 RTE_CACHE_LINE_SIZE);
884         rx_queues = rte_zmalloc("secondary ethdev->rx_queues",
885                                 sizeof(sd->data.rx_queues[0]) * nb_rx_queues,
886                                 RTE_CACHE_LINE_SIZE);
887         if (tx_queues == NULL || rx_queues == NULL)
888                 goto error;
889         /* Lock to prevent control operations during setup. */
890         priv_lock(priv);
891         /* TX queues. */
892         for (i = 0; i != nb_tx_queues; ++i) {
893                 struct txq *primary_txq = (*sd->primary_priv->txqs)[i];
894                 struct txq *txq;
895
896                 if (primary_txq == NULL)
897                         continue;
898                 txq = rte_calloc_socket("TXQ", 1, sizeof(*txq), 0,
899                                         primary_txq->socket);
900                 if (txq != NULL) {
901                         if (txq_setup(priv->dev,
902                                       txq,
903                                       primary_txq->elts_n * MLX4_PMD_SGE_WR_N,
904                                       primary_txq->socket,
905                                       NULL) == 0) {
906                                 txq->stats.idx = primary_txq->stats.idx;
907                                 tx_queues[i] = txq;
908                                 continue;
909                         }
910                         rte_free(txq);
911                 }
912                 while (i) {
913                         txq = tx_queues[--i];
914                         txq_cleanup(txq);
915                         rte_free(txq);
916                 }
917                 goto error;
918         }
919         /* RX queues. */
920         for (i = 0; i != nb_rx_queues; ++i) {
921                 struct rxq *primary_rxq = (*sd->primary_priv->rxqs)[i];
922
923                 if (primary_rxq == NULL)
924                         continue;
925                 /* Not supported yet. */
926                 rx_queues[i] = NULL;
927         }
928         /* Update everything. */
929         priv->txqs = (void *)tx_queues;
930         priv->txqs_n = nb_tx_queues;
931         priv->rxqs = (void *)rx_queues;
932         priv->rxqs_n = nb_rx_queues;
933         sd->data.rx_queues = rx_queues;
934         sd->data.tx_queues = tx_queues;
935         sd->data.nb_rx_queues = nb_rx_queues;
936         sd->data.nb_tx_queues = nb_tx_queues;
937         sd->data.dev_link = sd->shared_dev_data->dev_link;
938         sd->data.mtu = sd->shared_dev_data->mtu;
939         memcpy(sd->data.rx_queue_state, sd->shared_dev_data->rx_queue_state,
940                sizeof(sd->data.rx_queue_state));
941         memcpy(sd->data.tx_queue_state, sd->shared_dev_data->tx_queue_state,
942                sizeof(sd->data.tx_queue_state));
943         sd->data.dev_flags = sd->shared_dev_data->dev_flags;
944         /* Use local data from now on. */
945         rte_mb();
946         priv->dev->data = &sd->data;
947         rte_mb();
948         priv->dev->tx_pkt_burst = mlx4_tx_burst;
949         priv->dev->rx_pkt_burst = removed_rx_burst;
950         priv_unlock(priv);
951 end:
952         /* More sanity checks. */
953         assert(priv->dev->tx_pkt_burst == mlx4_tx_burst);
954         assert(priv->dev->rx_pkt_burst == removed_rx_burst);
955         assert(priv->dev->data == &sd->data);
956         rte_spinlock_unlock(&sd->lock);
957         return priv;
958 error:
959         priv_unlock(priv);
960         rte_free(tx_queues);
961         rte_free(rx_queues);
962         rte_spinlock_unlock(&sd->lock);
963         return NULL;
964 }
965
966 /* TX queues handling. */
967
968 /**
969  * Allocate TX queue elements.
970  *
971  * @param txq
972  *   Pointer to TX queue structure.
973  * @param elts_n
974  *   Number of elements to allocate.
975  *
976  * @return
977  *   0 on success, errno value on failure.
978  */
979 static int
980 txq_alloc_elts(struct txq *txq, unsigned int elts_n)
981 {
982         unsigned int i;
983         struct txq_elt (*elts)[elts_n] =
984                 rte_calloc_socket("TXQ", 1, sizeof(*elts), 0, txq->socket);
985         linear_t (*elts_linear)[elts_n] =
986                 rte_calloc_socket("TXQ", 1, sizeof(*elts_linear), 0,
987                                   txq->socket);
988         struct ibv_mr *mr_linear = NULL;
989         int ret = 0;
990
991         if ((elts == NULL) || (elts_linear == NULL)) {
992                 ERROR("%p: can't allocate packets array", (void *)txq);
993                 ret = ENOMEM;
994                 goto error;
995         }
996         mr_linear =
997                 ibv_reg_mr(txq->priv->pd, elts_linear, sizeof(*elts_linear),
998                            (IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE));
999         if (mr_linear == NULL) {
1000                 ERROR("%p: unable to configure MR, ibv_reg_mr() failed",
1001                       (void *)txq);
1002                 ret = EINVAL;
1003                 goto error;
1004         }
1005         for (i = 0; (i != elts_n); ++i) {
1006                 struct txq_elt *elt = &(*elts)[i];
1007
1008                 elt->buf = NULL;
1009         }
1010         DEBUG("%p: allocated and configured %u WRs", (void *)txq, elts_n);
1011         txq->elts_n = elts_n;
1012         txq->elts = elts;
1013         txq->elts_head = 0;
1014         txq->elts_tail = 0;
1015         txq->elts_comp = 0;
1016         /* Request send completion every MLX4_PMD_TX_PER_COMP_REQ packets or
1017          * at least 4 times per ring. */
1018         txq->elts_comp_cd_init =
1019                 ((MLX4_PMD_TX_PER_COMP_REQ < (elts_n / 4)) ?
1020                  MLX4_PMD_TX_PER_COMP_REQ : (elts_n / 4));
1021         txq->elts_comp_cd = txq->elts_comp_cd_init;
1022         txq->elts_linear = elts_linear;
1023         txq->mr_linear = mr_linear;
1024         assert(ret == 0);
1025         return 0;
1026 error:
1027         if (mr_linear != NULL)
1028                 claim_zero(ibv_dereg_mr(mr_linear));
1029
1030         rte_free(elts_linear);
1031         rte_free(elts);
1032
1033         DEBUG("%p: failed, freed everything", (void *)txq);
1034         assert(ret > 0);
1035         return ret;
1036 }
1037
1038 /**
1039  * Free TX queue elements.
1040  *
1041  * @param txq
1042  *   Pointer to TX queue structure.
1043  */
1044 static void
1045 txq_free_elts(struct txq *txq)
1046 {
1047         unsigned int i;
1048         unsigned int elts_n = txq->elts_n;
1049         struct txq_elt (*elts)[elts_n] = txq->elts;
1050         linear_t (*elts_linear)[elts_n] = txq->elts_linear;
1051         struct ibv_mr *mr_linear = txq->mr_linear;
1052
1053         DEBUG("%p: freeing WRs", (void *)txq);
1054         txq->elts_n = 0;
1055         txq->elts = NULL;
1056         txq->elts_linear = NULL;
1057         txq->mr_linear = NULL;
1058         if (mr_linear != NULL)
1059                 claim_zero(ibv_dereg_mr(mr_linear));
1060
1061         rte_free(elts_linear);
1062         if (elts == NULL)
1063                 return;
1064         for (i = 0; (i != elemof(*elts)); ++i) {
1065                 struct txq_elt *elt = &(*elts)[i];
1066
1067                 if (elt->buf == NULL)
1068                         continue;
1069                 rte_pktmbuf_free(elt->buf);
1070         }
1071         rte_free(elts);
1072 }
1073
1074
1075 /**
1076  * Clean up a TX queue.
1077  *
1078  * Destroy objects, free allocated memory and reset the structure for reuse.
1079  *
1080  * @param txq
1081  *   Pointer to TX queue structure.
1082  */
1083 static void
1084 txq_cleanup(struct txq *txq)
1085 {
1086         struct ibv_exp_release_intf_params params;
1087         size_t i;
1088
1089         DEBUG("cleaning up %p", (void *)txq);
1090         txq_free_elts(txq);
1091         if (txq->if_qp != NULL) {
1092                 assert(txq->priv != NULL);
1093                 assert(txq->priv->ctx != NULL);
1094                 assert(txq->qp != NULL);
1095                 params = (struct ibv_exp_release_intf_params){
1096                         .comp_mask = 0,
1097                 };
1098                 claim_zero(ibv_exp_release_intf(txq->priv->ctx,
1099                                                 txq->if_qp,
1100                                                 &params));
1101         }
1102         if (txq->if_cq != NULL) {
1103                 assert(txq->priv != NULL);
1104                 assert(txq->priv->ctx != NULL);
1105                 assert(txq->cq != NULL);
1106                 params = (struct ibv_exp_release_intf_params){
1107                         .comp_mask = 0,
1108                 };
1109                 claim_zero(ibv_exp_release_intf(txq->priv->ctx,
1110                                                 txq->if_cq,
1111                                                 &params));
1112         }
1113         if (txq->qp != NULL)
1114                 claim_zero(ibv_destroy_qp(txq->qp));
1115         if (txq->cq != NULL)
1116                 claim_zero(ibv_destroy_cq(txq->cq));
1117         if (txq->rd != NULL) {
1118                 struct ibv_exp_destroy_res_domain_attr attr = {
1119                         .comp_mask = 0,
1120                 };
1121
1122                 assert(txq->priv != NULL);
1123                 assert(txq->priv->ctx != NULL);
1124                 claim_zero(ibv_exp_destroy_res_domain(txq->priv->ctx,
1125                                                       txq->rd,
1126                                                       &attr));
1127         }
1128         for (i = 0; (i != elemof(txq->mp2mr)); ++i) {
1129                 if (txq->mp2mr[i].mp == NULL)
1130                         break;
1131                 assert(txq->mp2mr[i].mr != NULL);
1132                 claim_zero(ibv_dereg_mr(txq->mp2mr[i].mr));
1133         }
1134         memset(txq, 0, sizeof(*txq));
1135 }
1136
1137 /**
1138  * Manage TX completions.
1139  *
1140  * When sending a burst, mlx4_tx_burst() posts several WRs.
1141  * To improve performance, a completion event is only required once every
1142  * MLX4_PMD_TX_PER_COMP_REQ sends. Doing so discards completion information
1143  * for other WRs, but this information would not be used anyway.
1144  *
1145  * @param txq
1146  *   Pointer to TX queue structure.
1147  *
1148  * @return
1149  *   0 on success, -1 on failure.
1150  */
1151 static int
1152 txq_complete(struct txq *txq)
1153 {
1154         unsigned int elts_comp = txq->elts_comp;
1155         unsigned int elts_tail = txq->elts_tail;
1156         const unsigned int elts_n = txq->elts_n;
1157         int wcs_n;
1158
1159         if (unlikely(elts_comp == 0))
1160                 return 0;
1161 #ifdef DEBUG_SEND
1162         DEBUG("%p: processing %u work requests completions",
1163               (void *)txq, elts_comp);
1164 #endif
1165         wcs_n = txq->if_cq->poll_cnt(txq->cq, elts_comp);
1166         if (unlikely(wcs_n == 0))
1167                 return 0;
1168         if (unlikely(wcs_n < 0)) {
1169                 DEBUG("%p: ibv_poll_cq() failed (wcs_n=%d)",
1170                       (void *)txq, wcs_n);
1171                 return -1;
1172         }
1173         elts_comp -= wcs_n;
1174         assert(elts_comp <= txq->elts_comp);
1175         /*
1176          * Assume WC status is successful as nothing can be done about it
1177          * anyway.
1178          */
1179         elts_tail += wcs_n * txq->elts_comp_cd_init;
1180         if (elts_tail >= elts_n)
1181                 elts_tail -= elts_n;
1182         txq->elts_tail = elts_tail;
1183         txq->elts_comp = elts_comp;
1184         return 0;
1185 }
1186
1187 /* For best performance, this function should not be inlined. */
1188 static struct ibv_mr *mlx4_mp2mr(struct ibv_pd *, const struct rte_mempool *)
1189         __attribute__((noinline));
1190
1191 /**
1192  * Register mempool as a memory region.
1193  *
1194  * @param pd
1195  *   Pointer to protection domain.
1196  * @param mp
1197  *   Pointer to memory pool.
1198  *
1199  * @return
1200  *   Memory region pointer, NULL in case of error.
1201  */
1202 static struct ibv_mr *
1203 mlx4_mp2mr(struct ibv_pd *pd, const struct rte_mempool *mp)
1204 {
1205         const struct rte_memseg *ms = rte_eal_get_physmem_layout();
1206         uintptr_t start = mp->elt_va_start;
1207         uintptr_t end = mp->elt_va_end;
1208         unsigned int i;
1209
1210         DEBUG("mempool %p area start=%p end=%p size=%zu",
1211               (const void *)mp, (void *)start, (void *)end,
1212               (size_t)(end - start));
1213         /* Round start and end to page boundary if found in memory segments. */
1214         for (i = 0; (i < RTE_MAX_MEMSEG) && (ms[i].addr != NULL); ++i) {
1215                 uintptr_t addr = (uintptr_t)ms[i].addr;
1216                 size_t len = ms[i].len;
1217                 unsigned int align = ms[i].hugepage_sz;
1218
1219                 if ((start > addr) && (start < addr + len))
1220                         start = RTE_ALIGN_FLOOR(start, align);
1221                 if ((end > addr) && (end < addr + len))
1222                         end = RTE_ALIGN_CEIL(end, align);
1223         }
1224         DEBUG("mempool %p using start=%p end=%p size=%zu for MR",
1225               (const void *)mp, (void *)start, (void *)end,
1226               (size_t)(end - start));
1227         return ibv_reg_mr(pd,
1228                           (void *)start,
1229                           end - start,
1230                           IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE);
1231 }
1232
1233 /**
1234  * Get Memory Pool (MP) from mbuf. If mbuf is indirect, the pool from which
1235  * the cloned mbuf is allocated is returned instead.
1236  *
1237  * @param buf
1238  *   Pointer to mbuf.
1239  *
1240  * @return
1241  *   Memory pool where data is located for given mbuf.
1242  */
1243 static struct rte_mempool *
1244 txq_mb2mp(struct rte_mbuf *buf)
1245 {
1246         if (unlikely(RTE_MBUF_INDIRECT(buf)))
1247                 return rte_mbuf_from_indirect(buf)->pool;
1248         return buf->pool;
1249 }
1250
1251 /**
1252  * Get Memory Region (MR) <-> Memory Pool (MP) association from txq->mp2mr[].
1253  * Add MP to txq->mp2mr[] if it's not registered yet. If mp2mr[] is full,
1254  * remove an entry first.
1255  *
1256  * @param txq
1257  *   Pointer to TX queue structure.
1258  * @param[in] mp
1259  *   Memory Pool for which a Memory Region lkey must be returned.
1260  *
1261  * @return
1262  *   mr->lkey on success, (uint32_t)-1 on failure.
1263  */
1264 static uint32_t
1265 txq_mp2mr(struct txq *txq, const struct rte_mempool *mp)
1266 {
1267         unsigned int i;
1268         struct ibv_mr *mr;
1269
1270         for (i = 0; (i != elemof(txq->mp2mr)); ++i) {
1271                 if (unlikely(txq->mp2mr[i].mp == NULL)) {
1272                         /* Unknown MP, add a new MR for it. */
1273                         break;
1274                 }
1275                 if (txq->mp2mr[i].mp == mp) {
1276                         assert(txq->mp2mr[i].lkey != (uint32_t)-1);
1277                         assert(txq->mp2mr[i].mr->lkey == txq->mp2mr[i].lkey);
1278                         return txq->mp2mr[i].lkey;
1279                 }
1280         }
1281         /* Add a new entry, register MR first. */
1282         DEBUG("%p: discovered new memory pool \"%s\" (%p)",
1283               (void *)txq, mp->name, (const void *)mp);
1284         mr = mlx4_mp2mr(txq->priv->pd, mp);
1285         if (unlikely(mr == NULL)) {
1286                 DEBUG("%p: unable to configure MR, ibv_reg_mr() failed.",
1287                       (void *)txq);
1288                 return (uint32_t)-1;
1289         }
1290         if (unlikely(i == elemof(txq->mp2mr))) {
1291                 /* Table is full, remove oldest entry. */
1292                 DEBUG("%p: MR <-> MP table full, dropping oldest entry.",
1293                       (void *)txq);
1294                 --i;
1295                 claim_zero(ibv_dereg_mr(txq->mp2mr[0].mr));
1296                 memmove(&txq->mp2mr[0], &txq->mp2mr[1],
1297                         (sizeof(txq->mp2mr) - sizeof(txq->mp2mr[0])));
1298         }
1299         /* Store the new entry. */
1300         txq->mp2mr[i].mp = mp;
1301         txq->mp2mr[i].mr = mr;
1302         txq->mp2mr[i].lkey = mr->lkey;
1303         DEBUG("%p: new MR lkey for MP \"%s\" (%p): 0x%08" PRIu32,
1304               (void *)txq, mp->name, (const void *)mp, txq->mp2mr[i].lkey);
1305         return txq->mp2mr[i].lkey;
1306 }
1307
1308 struct txq_mp2mr_mbuf_check_data {
1309         const struct rte_mempool *mp;
1310         int ret;
1311 };
1312
1313 /**
1314  * Callback function for rte_mempool_obj_iter() to check whether a given
1315  * mempool object looks like a mbuf.
1316  *
1317  * @param[in, out] arg
1318  *   Context data (struct txq_mp2mr_mbuf_check_data). Contains mempool pointer
1319  *   and return value.
1320  * @param[in] start
1321  *   Object start address.
1322  * @param[in] end
1323  *   Object end address.
1324  * @param index
1325  *   Unused.
1326  *
1327  * @return
1328  *   Nonzero value when object is not a mbuf.
1329  */
1330 static void
1331 txq_mp2mr_mbuf_check(void *arg, void *start, void *end,
1332                      uint32_t index __rte_unused)
1333 {
1334         struct txq_mp2mr_mbuf_check_data *data = arg;
1335         struct rte_mbuf *buf =
1336                 (void *)((uintptr_t)start + data->mp->header_size);
1337
1338         (void)index;
1339         /* Check whether mbuf structure fits element size and whether mempool
1340          * pointer is valid. */
1341         if (((uintptr_t)end >= (uintptr_t)(buf + 1)) &&
1342             (buf->pool == data->mp))
1343                 data->ret = 0;
1344         else
1345                 data->ret = -1;
1346 }
1347
1348 /**
1349  * Iterator function for rte_mempool_walk() to register existing mempools and
1350  * fill the MP to MR cache of a TX queue.
1351  *
1352  * @param[in] mp
1353  *   Memory Pool to register.
1354  * @param *arg
1355  *   Pointer to TX queue structure.
1356  */
1357 static void
1358 txq_mp2mr_iter(const struct rte_mempool *mp, void *arg)
1359 {
1360         struct txq *txq = arg;
1361         struct txq_mp2mr_mbuf_check_data data = {
1362                 .mp = mp,
1363                 .ret = -1,
1364         };
1365
1366         /* Discard empty mempools. */
1367         if (mp->size == 0)
1368                 return;
1369         /* Register mempool only if the first element looks like a mbuf. */
1370         rte_mempool_obj_iter((void *)mp->elt_va_start,
1371                              1,
1372                              mp->header_size + mp->elt_size + mp->trailer_size,
1373                              1,
1374                              mp->elt_pa,
1375                              mp->pg_num,
1376                              mp->pg_shift,
1377                              txq_mp2mr_mbuf_check,
1378                              &data);
1379         if (data.ret)
1380                 return;
1381         txq_mp2mr(txq, mp);
1382 }
1383
1384 #if MLX4_PMD_SGE_WR_N > 1
1385
1386 /**
1387  * Copy scattered mbuf contents to a single linear buffer.
1388  *
1389  * @param[out] linear
1390  *   Linear output buffer.
1391  * @param[in] buf
1392  *   Scattered input buffer.
1393  *
1394  * @return
1395  *   Number of bytes copied to the output buffer or 0 if not large enough.
1396  */
1397 static unsigned int
1398 linearize_mbuf(linear_t *linear, struct rte_mbuf *buf)
1399 {
1400         unsigned int size = 0;
1401         unsigned int offset;
1402
1403         do {
1404                 unsigned int len = DATA_LEN(buf);
1405
1406                 offset = size;
1407                 size += len;
1408                 if (unlikely(size > sizeof(*linear)))
1409                         return 0;
1410                 memcpy(&(*linear)[offset],
1411                        rte_pktmbuf_mtod(buf, uint8_t *),
1412                        len);
1413                 buf = NEXT(buf);
1414         } while (buf != NULL);
1415         return size;
1416 }
1417
1418 /**
1419  * Handle scattered buffers for mlx4_tx_burst().
1420  *
1421  * @param txq
1422  *   TX queue structure.
1423  * @param segs
1424  *   Number of segments in buf.
1425  * @param elt
1426  *   TX queue element to fill.
1427  * @param[in] buf
1428  *   Buffer to process.
1429  * @param elts_head
1430  *   Index of the linear buffer to use if necessary (normally txq->elts_head).
1431  * @param[out] sges
1432  *   Array filled with SGEs on success.
1433  *
1434  * @return
1435  *   A structure containing the processed packet size in bytes and the
1436  *   number of SGEs. Both fields are set to (unsigned int)-1 in case of
1437  *   failure.
1438  */
1439 static struct tx_burst_sg_ret {
1440         unsigned int length;
1441         unsigned int num;
1442 }
1443 tx_burst_sg(struct txq *txq, unsigned int segs, struct txq_elt *elt,
1444             struct rte_mbuf *buf, unsigned int elts_head,
1445             struct ibv_sge (*sges)[MLX4_PMD_SGE_WR_N])
1446 {
1447         unsigned int sent_size = 0;
1448         unsigned int j;
1449         int linearize = 0;
1450
1451         /* When there are too many segments, extra segments are
1452          * linearized in the last SGE. */
1453         if (unlikely(segs > elemof(*sges))) {
1454                 segs = (elemof(*sges) - 1);
1455                 linearize = 1;
1456         }
1457         /* Update element. */
1458         elt->buf = buf;
1459         /* Register segments as SGEs. */
1460         for (j = 0; (j != segs); ++j) {
1461                 struct ibv_sge *sge = &(*sges)[j];
1462                 uint32_t lkey;
1463
1464                 /* Retrieve Memory Region key for this memory pool. */
1465                 lkey = txq_mp2mr(txq, txq_mb2mp(buf));
1466                 if (unlikely(lkey == (uint32_t)-1)) {
1467                         /* MR does not exist. */
1468                         DEBUG("%p: unable to get MP <-> MR association",
1469                               (void *)txq);
1470                         /* Clean up TX element. */
1471                         elt->buf = NULL;
1472                         goto stop;
1473                 }
1474                 /* Update SGE. */
1475                 sge->addr = rte_pktmbuf_mtod(buf, uintptr_t);
1476                 if (txq->priv->vf)
1477                         rte_prefetch0((volatile void *)
1478                                       (uintptr_t)sge->addr);
1479                 sge->length = DATA_LEN(buf);
1480                 sge->lkey = lkey;
1481                 sent_size += sge->length;
1482                 buf = NEXT(buf);
1483         }
1484         /* If buf is not NULL here and is not going to be linearized,
1485          * nb_segs is not valid. */
1486         assert(j == segs);
1487         assert((buf == NULL) || (linearize));
1488         /* Linearize extra segments. */
1489         if (linearize) {
1490                 struct ibv_sge *sge = &(*sges)[segs];
1491                 linear_t *linear = &(*txq->elts_linear)[elts_head];
1492                 unsigned int size = linearize_mbuf(linear, buf);
1493
1494                 assert(segs == (elemof(*sges) - 1));
1495                 if (size == 0) {
1496                         /* Invalid packet. */
1497                         DEBUG("%p: packet too large to be linearized.",
1498                               (void *)txq);
1499                         /* Clean up TX element. */
1500                         elt->buf = NULL;
1501                         goto stop;
1502                 }
1503                 /* If MLX4_PMD_SGE_WR_N is 1, free mbuf immediately. */
1504                 if (elemof(*sges) == 1) {
1505                         do {
1506                                 struct rte_mbuf *next = NEXT(buf);
1507
1508                                 rte_pktmbuf_free_seg(buf);
1509                                 buf = next;
1510                         } while (buf != NULL);
1511                         elt->buf = NULL;
1512                 }
1513                 /* Update SGE. */
1514                 sge->addr = (uintptr_t)&(*linear)[0];
1515                 sge->length = size;
1516                 sge->lkey = txq->mr_linear->lkey;
1517                 sent_size += size;
1518                 /* Include last segment. */
1519                 segs++;
1520         }
1521         return (struct tx_burst_sg_ret){
1522                 .length = sent_size,
1523                 .num = segs,
1524         };
1525 stop:
1526         return (struct tx_burst_sg_ret){
1527                 .length = -1,
1528                 .num = -1,
1529         };
1530 }
1531
1532 #endif /* MLX4_PMD_SGE_WR_N > 1 */
1533
1534 /**
1535  * DPDK callback for TX.
1536  *
1537  * @param dpdk_txq
1538  *   Generic pointer to TX queue structure.
1539  * @param[in] pkts
1540  *   Packets to transmit.
1541  * @param pkts_n
1542  *   Number of packets in array.
1543  *
1544  * @return
1545  *   Number of packets successfully transmitted (<= pkts_n).
1546  */
1547 static uint16_t
1548 mlx4_tx_burst(void *dpdk_txq, struct rte_mbuf **pkts, uint16_t pkts_n)
1549 {
1550         struct txq *txq = (struct txq *)dpdk_txq;
1551         unsigned int elts_head = txq->elts_head;
1552         const unsigned int elts_n = txq->elts_n;
1553         unsigned int elts_comp_cd = txq->elts_comp_cd;
1554         unsigned int elts_comp = 0;
1555         unsigned int i;
1556         unsigned int max;
1557         int err;
1558
1559         assert(elts_comp_cd != 0);
1560         txq_complete(txq);
1561         max = (elts_n - (elts_head - txq->elts_tail));
1562         if (max > elts_n)
1563                 max -= elts_n;
1564         assert(max >= 1);
1565         assert(max <= elts_n);
1566         /* Always leave one free entry in the ring. */
1567         --max;
1568         if (max == 0)
1569                 return 0;
1570         if (max > pkts_n)
1571                 max = pkts_n;
1572         for (i = 0; (i != max); ++i) {
1573                 struct rte_mbuf *buf = pkts[i];
1574                 unsigned int elts_head_next =
1575                         (((elts_head + 1) == elts_n) ? 0 : elts_head + 1);
1576                 struct txq_elt *elt_next = &(*txq->elts)[elts_head_next];
1577                 struct txq_elt *elt = &(*txq->elts)[elts_head];
1578                 unsigned int segs = NB_SEGS(buf);
1579 #ifdef MLX4_PMD_SOFT_COUNTERS
1580                 unsigned int sent_size = 0;
1581 #endif
1582                 uint32_t send_flags = 0;
1583
1584                 /* Clean up old buffer. */
1585                 if (likely(elt->buf != NULL)) {
1586                         struct rte_mbuf *tmp = elt->buf;
1587
1588                         /* Faster than rte_pktmbuf_free(). */
1589                         do {
1590                                 struct rte_mbuf *next = NEXT(tmp);
1591
1592                                 rte_pktmbuf_free_seg(tmp);
1593                                 tmp = next;
1594                         } while (tmp != NULL);
1595                 }
1596                 /* Request TX completion. */
1597                 if (unlikely(--elts_comp_cd == 0)) {
1598                         elts_comp_cd = txq->elts_comp_cd_init;
1599                         ++elts_comp;
1600                         send_flags |= IBV_EXP_QP_BURST_SIGNALED;
1601                 }
1602                 /* Should we enable HW CKSUM offload */
1603                 if (buf->ol_flags &
1604                     (PKT_TX_IP_CKSUM | PKT_TX_TCP_CKSUM | PKT_TX_UDP_CKSUM)) {
1605                         send_flags |= IBV_EXP_QP_BURST_IP_CSUM;
1606                         /* HW does not support checksum offloads at arbitrary
1607                          * offsets but automatically recognizes the packet
1608                          * type. For inner L3/L4 checksums, only VXLAN (UDP)
1609                          * tunnels are currently supported. */
1610                         if (RTE_ETH_IS_TUNNEL_PKT(buf->packet_type))
1611                                 send_flags |= IBV_EXP_QP_BURST_TUNNEL;
1612                 }
1613                 if (likely(segs == 1)) {
1614                         uintptr_t addr;
1615                         uint32_t length;
1616                         uint32_t lkey;
1617
1618                         /* Retrieve buffer information. */
1619                         addr = rte_pktmbuf_mtod(buf, uintptr_t);
1620                         length = DATA_LEN(buf);
1621                         /* Retrieve Memory Region key for this memory pool. */
1622                         lkey = txq_mp2mr(txq, txq_mb2mp(buf));
1623                         if (unlikely(lkey == (uint32_t)-1)) {
1624                                 /* MR does not exist. */
1625                                 DEBUG("%p: unable to get MP <-> MR"
1626                                       " association", (void *)txq);
1627                                 /* Clean up TX element. */
1628                                 elt->buf = NULL;
1629                                 goto stop;
1630                         }
1631                         /* Update element. */
1632                         elt->buf = buf;
1633                         if (txq->priv->vf)
1634                                 rte_prefetch0((volatile void *)
1635                                               (uintptr_t)addr);
1636                         RTE_MBUF_PREFETCH_TO_FREE(elt_next->buf);
1637                         /* Put packet into send queue. */
1638 #if MLX4_PMD_MAX_INLINE > 0
1639                         if (length <= txq->max_inline)
1640                                 err = txq->if_qp->send_pending_inline
1641                                         (txq->qp,
1642                                          (void *)addr,
1643                                          length,
1644                                          send_flags);
1645                         else
1646 #endif
1647                                 err = txq->if_qp->send_pending
1648                                         (txq->qp,
1649                                          addr,
1650                                          length,
1651                                          lkey,
1652                                          send_flags);
1653                         if (unlikely(err))
1654                                 goto stop;
1655 #ifdef MLX4_PMD_SOFT_COUNTERS
1656                         sent_size += length;
1657 #endif
1658                 } else {
1659 #if MLX4_PMD_SGE_WR_N > 1
1660                         struct ibv_sge sges[MLX4_PMD_SGE_WR_N];
1661                         struct tx_burst_sg_ret ret;
1662
1663                         ret = tx_burst_sg(txq, segs, elt, buf, elts_head,
1664                                           &sges);
1665                         if (ret.length == (unsigned int)-1)
1666                                 goto stop;
1667                         RTE_MBUF_PREFETCH_TO_FREE(elt_next->buf);
1668                         /* Put SG list into send queue. */
1669                         err = txq->if_qp->send_pending_sg_list
1670                                 (txq->qp,
1671                                  sges,
1672                                  ret.num,
1673                                  send_flags);
1674                         if (unlikely(err))
1675                                 goto stop;
1676 #ifdef MLX4_PMD_SOFT_COUNTERS
1677                         sent_size += ret.length;
1678 #endif
1679 #else /* MLX4_PMD_SGE_WR_N > 1 */
1680                         DEBUG("%p: TX scattered buffers support not"
1681                               " compiled in", (void *)txq);
1682                         goto stop;
1683 #endif /* MLX4_PMD_SGE_WR_N > 1 */
1684                 }
1685                 elts_head = elts_head_next;
1686 #ifdef MLX4_PMD_SOFT_COUNTERS
1687                 /* Increment sent bytes counter. */
1688                 txq->stats.obytes += sent_size;
1689 #endif
1690         }
1691 stop:
1692         /* Take a shortcut if nothing must be sent. */
1693         if (unlikely(i == 0))
1694                 return 0;
1695 #ifdef MLX4_PMD_SOFT_COUNTERS
1696         /* Increment sent packets counter. */
1697         txq->stats.opackets += i;
1698 #endif
1699         /* Ring QP doorbell. */
1700         err = txq->if_qp->send_flush(txq->qp);
1701         if (unlikely(err)) {
1702                 /* A nonzero value is not supposed to be returned.
1703                  * Nothing can be done about it. */
1704                 DEBUG("%p: send_flush() failed with error %d",
1705                       (void *)txq, err);
1706         }
1707         txq->elts_head = elts_head;
1708         txq->elts_comp += elts_comp;
1709         txq->elts_comp_cd = elts_comp_cd;
1710         return i;
1711 }
1712
1713 /**
1714  * DPDK callback for TX in secondary processes.
1715  *
1716  * This function configures all queues from primary process information
1717  * if necessary before reverting to the normal TX burst callback.
1718  *
1719  * @param dpdk_txq
1720  *   Generic pointer to TX queue structure.
1721  * @param[in] pkts
1722  *   Packets to transmit.
1723  * @param pkts_n
1724  *   Number of packets in array.
1725  *
1726  * @return
1727  *   Number of packets successfully transmitted (<= pkts_n).
1728  */
1729 static uint16_t
1730 mlx4_tx_burst_secondary_setup(void *dpdk_txq, struct rte_mbuf **pkts,
1731                               uint16_t pkts_n)
1732 {
1733         struct txq *txq = dpdk_txq;
1734         struct priv *priv = mlx4_secondary_data_setup(txq->priv);
1735         struct priv *primary_priv;
1736         unsigned int index;
1737
1738         if (priv == NULL)
1739                 return 0;
1740         primary_priv =
1741                 mlx4_secondary_data[priv->dev->data->port_id].primary_priv;
1742         /* Look for queue index in both private structures. */
1743         for (index = 0; index != priv->txqs_n; ++index)
1744                 if (((*primary_priv->txqs)[index] == txq) ||
1745                     ((*priv->txqs)[index] == txq))
1746                         break;
1747         if (index == priv->txqs_n)
1748                 return 0;
1749         txq = (*priv->txqs)[index];
1750         return priv->dev->tx_pkt_burst(txq, pkts, pkts_n);
1751 }
1752
1753 /**
1754  * Configure a TX queue.
1755  *
1756  * @param dev
1757  *   Pointer to Ethernet device structure.
1758  * @param txq
1759  *   Pointer to TX queue structure.
1760  * @param desc
1761  *   Number of descriptors to configure in queue.
1762  * @param socket
1763  *   NUMA socket on which memory must be allocated.
1764  * @param[in] conf
1765  *   Thresholds parameters.
1766  *
1767  * @return
1768  *   0 on success, errno value on failure.
1769  */
1770 static int
1771 txq_setup(struct rte_eth_dev *dev, struct txq *txq, uint16_t desc,
1772           unsigned int socket, const struct rte_eth_txconf *conf)
1773 {
1774         struct priv *priv = mlx4_get_priv(dev);
1775         struct txq tmpl = {
1776                 .priv = priv,
1777                 .socket = socket
1778         };
1779         union {
1780                 struct ibv_exp_query_intf_params params;
1781                 struct ibv_exp_qp_init_attr init;
1782                 struct ibv_exp_res_domain_init_attr rd;
1783                 struct ibv_exp_cq_init_attr cq;
1784                 struct ibv_exp_qp_attr mod;
1785         } attr;
1786         enum ibv_exp_query_intf_status status;
1787         int ret = 0;
1788
1789         (void)conf; /* Thresholds configuration (ignored). */
1790         if (priv == NULL)
1791                 return EINVAL;
1792         if ((desc == 0) || (desc % MLX4_PMD_SGE_WR_N)) {
1793                 ERROR("%p: invalid number of TX descriptors (must be a"
1794                       " multiple of %d)", (void *)dev, MLX4_PMD_SGE_WR_N);
1795                 return EINVAL;
1796         }
1797         desc /= MLX4_PMD_SGE_WR_N;
1798         /* MRs will be registered in mp2mr[] later. */
1799         attr.rd = (struct ibv_exp_res_domain_init_attr){
1800                 .comp_mask = (IBV_EXP_RES_DOMAIN_THREAD_MODEL |
1801                               IBV_EXP_RES_DOMAIN_MSG_MODEL),
1802                 .thread_model = IBV_EXP_THREAD_SINGLE,
1803                 .msg_model = IBV_EXP_MSG_HIGH_BW,
1804         };
1805         tmpl.rd = ibv_exp_create_res_domain(priv->ctx, &attr.rd);
1806         if (tmpl.rd == NULL) {
1807                 ret = ENOMEM;
1808                 ERROR("%p: RD creation failure: %s",
1809                       (void *)dev, strerror(ret));
1810                 goto error;
1811         }
1812         attr.cq = (struct ibv_exp_cq_init_attr){
1813                 .comp_mask = IBV_EXP_CQ_INIT_ATTR_RES_DOMAIN,
1814                 .res_domain = tmpl.rd,
1815         };
1816         tmpl.cq = ibv_exp_create_cq(priv->ctx, desc, NULL, NULL, 0, &attr.cq);
1817         if (tmpl.cq == NULL) {
1818                 ret = ENOMEM;
1819                 ERROR("%p: CQ creation failure: %s",
1820                       (void *)dev, strerror(ret));
1821                 goto error;
1822         }
1823         DEBUG("priv->device_attr.max_qp_wr is %d",
1824               priv->device_attr.max_qp_wr);
1825         DEBUG("priv->device_attr.max_sge is %d",
1826               priv->device_attr.max_sge);
1827         attr.init = (struct ibv_exp_qp_init_attr){
1828                 /* CQ to be associated with the send queue. */
1829                 .send_cq = tmpl.cq,
1830                 /* CQ to be associated with the receive queue. */
1831                 .recv_cq = tmpl.cq,
1832                 .cap = {
1833                         /* Max number of outstanding WRs. */
1834                         .max_send_wr = ((priv->device_attr.max_qp_wr < desc) ?
1835                                         priv->device_attr.max_qp_wr :
1836                                         desc),
1837                         /* Max number of scatter/gather elements in a WR. */
1838                         .max_send_sge = ((priv->device_attr.max_sge <
1839                                           MLX4_PMD_SGE_WR_N) ?
1840                                          priv->device_attr.max_sge :
1841                                          MLX4_PMD_SGE_WR_N),
1842 #if MLX4_PMD_MAX_INLINE > 0
1843                         .max_inline_data = MLX4_PMD_MAX_INLINE,
1844 #endif
1845                 },
1846                 .qp_type = IBV_QPT_RAW_PACKET,
1847                 /* Do *NOT* enable this, completions events are managed per
1848                  * TX burst. */
1849                 .sq_sig_all = 0,
1850                 .pd = priv->pd,
1851                 .res_domain = tmpl.rd,
1852                 .comp_mask = (IBV_EXP_QP_INIT_ATTR_PD |
1853                               IBV_EXP_QP_INIT_ATTR_RES_DOMAIN),
1854         };
1855         tmpl.qp = ibv_exp_create_qp(priv->ctx, &attr.init);
1856         if (tmpl.qp == NULL) {
1857                 ret = (errno ? errno : EINVAL);
1858                 ERROR("%p: QP creation failure: %s",
1859                       (void *)dev, strerror(ret));
1860                 goto error;
1861         }
1862 #if MLX4_PMD_MAX_INLINE > 0
1863         /* ibv_create_qp() updates this value. */
1864         tmpl.max_inline = attr.init.cap.max_inline_data;
1865 #endif
1866         attr.mod = (struct ibv_exp_qp_attr){
1867                 /* Move the QP to this state. */
1868                 .qp_state = IBV_QPS_INIT,
1869                 /* Primary port number. */
1870                 .port_num = priv->port
1871         };
1872         ret = ibv_exp_modify_qp(tmpl.qp, &attr.mod,
1873                                 (IBV_EXP_QP_STATE | IBV_EXP_QP_PORT));
1874         if (ret) {
1875                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
1876                       (void *)dev, strerror(ret));
1877                 goto error;
1878         }
1879         ret = txq_alloc_elts(&tmpl, desc);
1880         if (ret) {
1881                 ERROR("%p: TXQ allocation failed: %s",
1882                       (void *)dev, strerror(ret));
1883                 goto error;
1884         }
1885         attr.mod = (struct ibv_exp_qp_attr){
1886                 .qp_state = IBV_QPS_RTR
1887         };
1888         ret = ibv_exp_modify_qp(tmpl.qp, &attr.mod, IBV_EXP_QP_STATE);
1889         if (ret) {
1890                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
1891                       (void *)dev, strerror(ret));
1892                 goto error;
1893         }
1894         attr.mod.qp_state = IBV_QPS_RTS;
1895         ret = ibv_exp_modify_qp(tmpl.qp, &attr.mod, IBV_EXP_QP_STATE);
1896         if (ret) {
1897                 ERROR("%p: QP state to IBV_QPS_RTS failed: %s",
1898                       (void *)dev, strerror(ret));
1899                 goto error;
1900         }
1901         attr.params = (struct ibv_exp_query_intf_params){
1902                 .intf_scope = IBV_EXP_INTF_GLOBAL,
1903                 .intf = IBV_EXP_INTF_CQ,
1904                 .obj = tmpl.cq,
1905         };
1906         tmpl.if_cq = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
1907         if (tmpl.if_cq == NULL) {
1908                 ERROR("%p: CQ interface family query failed with status %d",
1909                       (void *)dev, status);
1910                 goto error;
1911         }
1912         attr.params = (struct ibv_exp_query_intf_params){
1913                 .intf_scope = IBV_EXP_INTF_GLOBAL,
1914                 .intf = IBV_EXP_INTF_QP_BURST,
1915                 .obj = tmpl.qp,
1916 #ifdef HAVE_EXP_QP_BURST_CREATE_DISABLE_ETH_LOOPBACK
1917                 /* MC loopback must be disabled when not using a VF. */
1918                 .family_flags =
1919                         (!priv->vf ?
1920                          IBV_EXP_QP_BURST_CREATE_DISABLE_ETH_LOOPBACK :
1921                          0),
1922 #endif
1923         };
1924         tmpl.if_qp = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
1925         if (tmpl.if_qp == NULL) {
1926                 ERROR("%p: QP interface family query failed with status %d",
1927                       (void *)dev, status);
1928                 goto error;
1929         }
1930         /* Clean up txq in case we're reinitializing it. */
1931         DEBUG("%p: cleaning-up old txq just in case", (void *)txq);
1932         txq_cleanup(txq);
1933         *txq = tmpl;
1934         DEBUG("%p: txq updated with %p", (void *)txq, (void *)&tmpl);
1935         /* Pre-register known mempools. */
1936         rte_mempool_walk(txq_mp2mr_iter, txq);
1937         assert(ret == 0);
1938         return 0;
1939 error:
1940         txq_cleanup(&tmpl);
1941         assert(ret > 0);
1942         return ret;
1943 }
1944
1945 /**
1946  * DPDK callback to configure a TX queue.
1947  *
1948  * @param dev
1949  *   Pointer to Ethernet device structure.
1950  * @param idx
1951  *   TX queue index.
1952  * @param desc
1953  *   Number of descriptors to configure in queue.
1954  * @param socket
1955  *   NUMA socket on which memory must be allocated.
1956  * @param[in] conf
1957  *   Thresholds parameters.
1958  *
1959  * @return
1960  *   0 on success, negative errno value on failure.
1961  */
1962 static int
1963 mlx4_tx_queue_setup(struct rte_eth_dev *dev, uint16_t idx, uint16_t desc,
1964                     unsigned int socket, const struct rte_eth_txconf *conf)
1965 {
1966         struct priv *priv = dev->data->dev_private;
1967         struct txq *txq = (*priv->txqs)[idx];
1968         int ret;
1969
1970         if (mlx4_is_secondary())
1971                 return -E_RTE_SECONDARY;
1972         priv_lock(priv);
1973         DEBUG("%p: configuring queue %u for %u descriptors",
1974               (void *)dev, idx, desc);
1975         if (idx >= priv->txqs_n) {
1976                 ERROR("%p: queue index out of range (%u >= %u)",
1977                       (void *)dev, idx, priv->txqs_n);
1978                 priv_unlock(priv);
1979                 return -EOVERFLOW;
1980         }
1981         if (txq != NULL) {
1982                 DEBUG("%p: reusing already allocated queue index %u (%p)",
1983                       (void *)dev, idx, (void *)txq);
1984                 if (priv->started) {
1985                         priv_unlock(priv);
1986                         return -EEXIST;
1987                 }
1988                 (*priv->txqs)[idx] = NULL;
1989                 txq_cleanup(txq);
1990         } else {
1991                 txq = rte_calloc_socket("TXQ", 1, sizeof(*txq), 0, socket);
1992                 if (txq == NULL) {
1993                         ERROR("%p: unable to allocate queue index %u",
1994                               (void *)dev, idx);
1995                         priv_unlock(priv);
1996                         return -ENOMEM;
1997                 }
1998         }
1999         ret = txq_setup(dev, txq, desc, socket, conf);
2000         if (ret)
2001                 rte_free(txq);
2002         else {
2003                 txq->stats.idx = idx;
2004                 DEBUG("%p: adding TX queue %p to list",
2005                       (void *)dev, (void *)txq);
2006                 (*priv->txqs)[idx] = txq;
2007                 /* Update send callback. */
2008                 dev->tx_pkt_burst = mlx4_tx_burst;
2009         }
2010         priv_unlock(priv);
2011         return -ret;
2012 }
2013
2014 /**
2015  * DPDK callback to release a TX queue.
2016  *
2017  * @param dpdk_txq
2018  *   Generic TX queue pointer.
2019  */
2020 static void
2021 mlx4_tx_queue_release(void *dpdk_txq)
2022 {
2023         struct txq *txq = (struct txq *)dpdk_txq;
2024         struct priv *priv;
2025         unsigned int i;
2026
2027         if (mlx4_is_secondary())
2028                 return;
2029         if (txq == NULL)
2030                 return;
2031         priv = txq->priv;
2032         priv_lock(priv);
2033         for (i = 0; (i != priv->txqs_n); ++i)
2034                 if ((*priv->txqs)[i] == txq) {
2035                         DEBUG("%p: removing TX queue %p from list",
2036                               (void *)priv->dev, (void *)txq);
2037                         (*priv->txqs)[i] = NULL;
2038                         break;
2039                 }
2040         txq_cleanup(txq);
2041         rte_free(txq);
2042         priv_unlock(priv);
2043 }
2044
2045 /* RX queues handling. */
2046
2047 /**
2048  * Allocate RX queue elements with scattered packets support.
2049  *
2050  * @param rxq
2051  *   Pointer to RX queue structure.
2052  * @param elts_n
2053  *   Number of elements to allocate.
2054  * @param[in] pool
2055  *   If not NULL, fetch buffers from this array instead of allocating them
2056  *   with rte_pktmbuf_alloc().
2057  *
2058  * @return
2059  *   0 on success, errno value on failure.
2060  */
2061 static int
2062 rxq_alloc_elts_sp(struct rxq *rxq, unsigned int elts_n,
2063                   struct rte_mbuf **pool)
2064 {
2065         unsigned int i;
2066         struct rxq_elt_sp (*elts)[elts_n] =
2067                 rte_calloc_socket("RXQ elements", 1, sizeof(*elts), 0,
2068                                   rxq->socket);
2069         int ret = 0;
2070
2071         if (elts == NULL) {
2072                 ERROR("%p: can't allocate packets array", (void *)rxq);
2073                 ret = ENOMEM;
2074                 goto error;
2075         }
2076         /* For each WR (packet). */
2077         for (i = 0; (i != elts_n); ++i) {
2078                 unsigned int j;
2079                 struct rxq_elt_sp *elt = &(*elts)[i];
2080                 struct ibv_recv_wr *wr = &elt->wr;
2081                 struct ibv_sge (*sges)[(elemof(elt->sges))] = &elt->sges;
2082
2083                 /* These two arrays must have the same size. */
2084                 assert(elemof(elt->sges) == elemof(elt->bufs));
2085                 /* Configure WR. */
2086                 wr->wr_id = i;
2087                 wr->next = &(*elts)[(i + 1)].wr;
2088                 wr->sg_list = &(*sges)[0];
2089                 wr->num_sge = elemof(*sges);
2090                 /* For each SGE (segment). */
2091                 for (j = 0; (j != elemof(elt->bufs)); ++j) {
2092                         struct ibv_sge *sge = &(*sges)[j];
2093                         struct rte_mbuf *buf;
2094
2095                         if (pool != NULL) {
2096                                 buf = *(pool++);
2097                                 assert(buf != NULL);
2098                                 rte_pktmbuf_reset(buf);
2099                         } else
2100                                 buf = rte_pktmbuf_alloc(rxq->mp);
2101                         if (buf == NULL) {
2102                                 assert(pool == NULL);
2103                                 ERROR("%p: empty mbuf pool", (void *)rxq);
2104                                 ret = ENOMEM;
2105                                 goto error;
2106                         }
2107                         elt->bufs[j] = buf;
2108                         /* Headroom is reserved by rte_pktmbuf_alloc(). */
2109                         assert(DATA_OFF(buf) == RTE_PKTMBUF_HEADROOM);
2110                         /* Buffer is supposed to be empty. */
2111                         assert(rte_pktmbuf_data_len(buf) == 0);
2112                         assert(rte_pktmbuf_pkt_len(buf) == 0);
2113                         /* sge->addr must be able to store a pointer. */
2114                         assert(sizeof(sge->addr) >= sizeof(uintptr_t));
2115                         if (j == 0) {
2116                                 /* The first SGE keeps its headroom. */
2117                                 sge->addr = rte_pktmbuf_mtod(buf, uintptr_t);
2118                                 sge->length = (buf->buf_len -
2119                                                RTE_PKTMBUF_HEADROOM);
2120                         } else {
2121                                 /* Subsequent SGEs lose theirs. */
2122                                 assert(DATA_OFF(buf) == RTE_PKTMBUF_HEADROOM);
2123                                 SET_DATA_OFF(buf, 0);
2124                                 sge->addr = (uintptr_t)buf->buf_addr;
2125                                 sge->length = buf->buf_len;
2126                         }
2127                         sge->lkey = rxq->mr->lkey;
2128                         /* Redundant check for tailroom. */
2129                         assert(sge->length == rte_pktmbuf_tailroom(buf));
2130                 }
2131         }
2132         /* The last WR pointer must be NULL. */
2133         (*elts)[(i - 1)].wr.next = NULL;
2134         DEBUG("%p: allocated and configured %u WRs (%zu segments)",
2135               (void *)rxq, elts_n, (elts_n * elemof((*elts)[0].sges)));
2136         rxq->elts_n = elts_n;
2137         rxq->elts_head = 0;
2138         rxq->elts.sp = elts;
2139         assert(ret == 0);
2140         return 0;
2141 error:
2142         if (elts != NULL) {
2143                 assert(pool == NULL);
2144                 for (i = 0; (i != elemof(*elts)); ++i) {
2145                         unsigned int j;
2146                         struct rxq_elt_sp *elt = &(*elts)[i];
2147
2148                         for (j = 0; (j != elemof(elt->bufs)); ++j) {
2149                                 struct rte_mbuf *buf = elt->bufs[j];
2150
2151                                 if (buf != NULL)
2152                                         rte_pktmbuf_free_seg(buf);
2153                         }
2154                 }
2155                 rte_free(elts);
2156         }
2157         DEBUG("%p: failed, freed everything", (void *)rxq);
2158         assert(ret > 0);
2159         return ret;
2160 }
2161
2162 /**
2163  * Free RX queue elements with scattered packets support.
2164  *
2165  * @param rxq
2166  *   Pointer to RX queue structure.
2167  */
2168 static void
2169 rxq_free_elts_sp(struct rxq *rxq)
2170 {
2171         unsigned int i;
2172         unsigned int elts_n = rxq->elts_n;
2173         struct rxq_elt_sp (*elts)[elts_n] = rxq->elts.sp;
2174
2175         DEBUG("%p: freeing WRs", (void *)rxq);
2176         rxq->elts_n = 0;
2177         rxq->elts.sp = NULL;
2178         if (elts == NULL)
2179                 return;
2180         for (i = 0; (i != elemof(*elts)); ++i) {
2181                 unsigned int j;
2182                 struct rxq_elt_sp *elt = &(*elts)[i];
2183
2184                 for (j = 0; (j != elemof(elt->bufs)); ++j) {
2185                         struct rte_mbuf *buf = elt->bufs[j];
2186
2187                         if (buf != NULL)
2188                                 rte_pktmbuf_free_seg(buf);
2189                 }
2190         }
2191         rte_free(elts);
2192 }
2193
2194 /**
2195  * Allocate RX queue elements.
2196  *
2197  * @param rxq
2198  *   Pointer to RX queue structure.
2199  * @param elts_n
2200  *   Number of elements to allocate.
2201  * @param[in] pool
2202  *   If not NULL, fetch buffers from this array instead of allocating them
2203  *   with rte_pktmbuf_alloc().
2204  *
2205  * @return
2206  *   0 on success, errno value on failure.
2207  */
2208 static int
2209 rxq_alloc_elts(struct rxq *rxq, unsigned int elts_n, struct rte_mbuf **pool)
2210 {
2211         unsigned int i;
2212         struct rxq_elt (*elts)[elts_n] =
2213                 rte_calloc_socket("RXQ elements", 1, sizeof(*elts), 0,
2214                                   rxq->socket);
2215         int ret = 0;
2216
2217         if (elts == NULL) {
2218                 ERROR("%p: can't allocate packets array", (void *)rxq);
2219                 ret = ENOMEM;
2220                 goto error;
2221         }
2222         /* For each WR (packet). */
2223         for (i = 0; (i != elts_n); ++i) {
2224                 struct rxq_elt *elt = &(*elts)[i];
2225                 struct ibv_recv_wr *wr = &elt->wr;
2226                 struct ibv_sge *sge = &(*elts)[i].sge;
2227                 struct rte_mbuf *buf;
2228
2229                 if (pool != NULL) {
2230                         buf = *(pool++);
2231                         assert(buf != NULL);
2232                         rte_pktmbuf_reset(buf);
2233                 } else
2234                         buf = rte_pktmbuf_alloc(rxq->mp);
2235                 if (buf == NULL) {
2236                         assert(pool == NULL);
2237                         ERROR("%p: empty mbuf pool", (void *)rxq);
2238                         ret = ENOMEM;
2239                         goto error;
2240                 }
2241                 /* Configure WR. Work request ID contains its own index in
2242                  * the elts array and the offset between SGE buffer header and
2243                  * its data. */
2244                 WR_ID(wr->wr_id).id = i;
2245                 WR_ID(wr->wr_id).offset =
2246                         (((uintptr_t)buf->buf_addr + RTE_PKTMBUF_HEADROOM) -
2247                          (uintptr_t)buf);
2248                 wr->next = &(*elts)[(i + 1)].wr;
2249                 wr->sg_list = sge;
2250                 wr->num_sge = 1;
2251                 /* Headroom is reserved by rte_pktmbuf_alloc(). */
2252                 assert(DATA_OFF(buf) == RTE_PKTMBUF_HEADROOM);
2253                 /* Buffer is supposed to be empty. */
2254                 assert(rte_pktmbuf_data_len(buf) == 0);
2255                 assert(rte_pktmbuf_pkt_len(buf) == 0);
2256                 /* sge->addr must be able to store a pointer. */
2257                 assert(sizeof(sge->addr) >= sizeof(uintptr_t));
2258                 /* SGE keeps its headroom. */
2259                 sge->addr = (uintptr_t)
2260                         ((uint8_t *)buf->buf_addr + RTE_PKTMBUF_HEADROOM);
2261                 sge->length = (buf->buf_len - RTE_PKTMBUF_HEADROOM);
2262                 sge->lkey = rxq->mr->lkey;
2263                 /* Redundant check for tailroom. */
2264                 assert(sge->length == rte_pktmbuf_tailroom(buf));
2265                 /* Make sure elts index and SGE mbuf pointer can be deduced
2266                  * from WR ID. */
2267                 if ((WR_ID(wr->wr_id).id != i) ||
2268                     ((void *)((uintptr_t)sge->addr -
2269                         WR_ID(wr->wr_id).offset) != buf)) {
2270                         ERROR("%p: cannot store index and offset in WR ID",
2271                               (void *)rxq);
2272                         sge->addr = 0;
2273                         rte_pktmbuf_free(buf);
2274                         ret = EOVERFLOW;
2275                         goto error;
2276                 }
2277         }
2278         /* The last WR pointer must be NULL. */
2279         (*elts)[(i - 1)].wr.next = NULL;
2280         DEBUG("%p: allocated and configured %u single-segment WRs",
2281               (void *)rxq, elts_n);
2282         rxq->elts_n = elts_n;
2283         rxq->elts_head = 0;
2284         rxq->elts.no_sp = elts;
2285         assert(ret == 0);
2286         return 0;
2287 error:
2288         if (elts != NULL) {
2289                 assert(pool == NULL);
2290                 for (i = 0; (i != elemof(*elts)); ++i) {
2291                         struct rxq_elt *elt = &(*elts)[i];
2292                         struct rte_mbuf *buf;
2293
2294                         if (elt->sge.addr == 0)
2295                                 continue;
2296                         assert(WR_ID(elt->wr.wr_id).id == i);
2297                         buf = (void *)((uintptr_t)elt->sge.addr -
2298                                 WR_ID(elt->wr.wr_id).offset);
2299                         rte_pktmbuf_free_seg(buf);
2300                 }
2301                 rte_free(elts);
2302         }
2303         DEBUG("%p: failed, freed everything", (void *)rxq);
2304         assert(ret > 0);
2305         return ret;
2306 }
2307
2308 /**
2309  * Free RX queue elements.
2310  *
2311  * @param rxq
2312  *   Pointer to RX queue structure.
2313  */
2314 static void
2315 rxq_free_elts(struct rxq *rxq)
2316 {
2317         unsigned int i;
2318         unsigned int elts_n = rxq->elts_n;
2319         struct rxq_elt (*elts)[elts_n] = rxq->elts.no_sp;
2320
2321         DEBUG("%p: freeing WRs", (void *)rxq);
2322         rxq->elts_n = 0;
2323         rxq->elts.no_sp = NULL;
2324         if (elts == NULL)
2325                 return;
2326         for (i = 0; (i != elemof(*elts)); ++i) {
2327                 struct rxq_elt *elt = &(*elts)[i];
2328                 struct rte_mbuf *buf;
2329
2330                 if (elt->sge.addr == 0)
2331                         continue;
2332                 assert(WR_ID(elt->wr.wr_id).id == i);
2333                 buf = (void *)((uintptr_t)elt->sge.addr -
2334                         WR_ID(elt->wr.wr_id).offset);
2335                 rte_pktmbuf_free_seg(buf);
2336         }
2337         rte_free(elts);
2338 }
2339
2340 /**
2341  * Delete flow steering rule.
2342  *
2343  * @param rxq
2344  *   Pointer to RX queue structure.
2345  * @param mac_index
2346  *   MAC address index.
2347  * @param vlan_index
2348  *   VLAN index.
2349  */
2350 static void
2351 rxq_del_flow(struct rxq *rxq, unsigned int mac_index, unsigned int vlan_index)
2352 {
2353 #ifndef NDEBUG
2354         struct priv *priv = rxq->priv;
2355         const uint8_t (*mac)[ETHER_ADDR_LEN] =
2356                 (const uint8_t (*)[ETHER_ADDR_LEN])
2357                 priv->mac[mac_index].addr_bytes;
2358 #endif
2359         assert(rxq->mac_flow[mac_index][vlan_index] != NULL);
2360         DEBUG("%p: removing MAC address %02x:%02x:%02x:%02x:%02x:%02x index %u"
2361               " (VLAN ID %" PRIu16 ")",
2362               (void *)rxq,
2363               (*mac)[0], (*mac)[1], (*mac)[2], (*mac)[3], (*mac)[4], (*mac)[5],
2364               mac_index, priv->vlan_filter[vlan_index].id);
2365         claim_zero(ibv_destroy_flow(rxq->mac_flow[mac_index][vlan_index]));
2366         rxq->mac_flow[mac_index][vlan_index] = NULL;
2367 }
2368
2369 /**
2370  * Unregister a MAC address from a RX queue.
2371  *
2372  * @param rxq
2373  *   Pointer to RX queue structure.
2374  * @param mac_index
2375  *   MAC address index.
2376  */
2377 static void
2378 rxq_mac_addr_del(struct rxq *rxq, unsigned int mac_index)
2379 {
2380         struct priv *priv = rxq->priv;
2381         unsigned int i;
2382         unsigned int vlans = 0;
2383
2384         assert(mac_index < elemof(priv->mac));
2385         if (!BITFIELD_ISSET(rxq->mac_configured, mac_index))
2386                 return;
2387         for (i = 0; (i != elemof(priv->vlan_filter)); ++i) {
2388                 if (!priv->vlan_filter[i].enabled)
2389                         continue;
2390                 rxq_del_flow(rxq, mac_index, i);
2391                 vlans++;
2392         }
2393         if (!vlans) {
2394                 rxq_del_flow(rxq, mac_index, 0);
2395         }
2396         BITFIELD_RESET(rxq->mac_configured, mac_index);
2397 }
2398
2399 /**
2400  * Unregister all MAC addresses from a RX queue.
2401  *
2402  * @param rxq
2403  *   Pointer to RX queue structure.
2404  */
2405 static void
2406 rxq_mac_addrs_del(struct rxq *rxq)
2407 {
2408         struct priv *priv = rxq->priv;
2409         unsigned int i;
2410
2411         for (i = 0; (i != elemof(priv->mac)); ++i)
2412                 rxq_mac_addr_del(rxq, i);
2413 }
2414
2415 static int rxq_promiscuous_enable(struct rxq *);
2416 static void rxq_promiscuous_disable(struct rxq *);
2417
2418 /**
2419  * Add single flow steering rule.
2420  *
2421  * @param rxq
2422  *   Pointer to RX queue structure.
2423  * @param mac_index
2424  *   MAC address index to register.
2425  * @param vlan_index
2426  *   VLAN index. Use -1 for a flow without VLAN.
2427  *
2428  * @return
2429  *   0 on success, errno value on failure.
2430  */
2431 static int
2432 rxq_add_flow(struct rxq *rxq, unsigned int mac_index, unsigned int vlan_index)
2433 {
2434         struct ibv_flow *flow;
2435         struct priv *priv = rxq->priv;
2436         const uint8_t (*mac)[ETHER_ADDR_LEN] =
2437                         (const uint8_t (*)[ETHER_ADDR_LEN])
2438                         priv->mac[mac_index].addr_bytes;
2439
2440         /* Allocate flow specification on the stack. */
2441         struct __attribute__((packed)) {
2442                 struct ibv_flow_attr attr;
2443                 struct ibv_flow_spec_eth spec;
2444         } data;
2445         struct ibv_flow_attr *attr = &data.attr;
2446         struct ibv_flow_spec_eth *spec = &data.spec;
2447
2448         assert(mac_index < elemof(priv->mac));
2449         assert((vlan_index < elemof(priv->vlan_filter)) || (vlan_index == -1u));
2450         /*
2451          * No padding must be inserted by the compiler between attr and spec.
2452          * This layout is expected by libibverbs.
2453          */
2454         assert(((uint8_t *)attr + sizeof(*attr)) == (uint8_t *)spec);
2455         *attr = (struct ibv_flow_attr){
2456                 .type = IBV_FLOW_ATTR_NORMAL,
2457                 .num_of_specs = 1,
2458                 .port = priv->port,
2459                 .flags = 0
2460         };
2461         *spec = (struct ibv_flow_spec_eth){
2462                 .type = IBV_FLOW_SPEC_ETH,
2463                 .size = sizeof(*spec),
2464                 .val = {
2465                         .dst_mac = {
2466                                 (*mac)[0], (*mac)[1], (*mac)[2],
2467                                 (*mac)[3], (*mac)[4], (*mac)[5]
2468                         },
2469                         .vlan_tag = ((vlan_index != -1u) ?
2470                                      htons(priv->vlan_filter[vlan_index].id) :
2471                                      0),
2472                 },
2473                 .mask = {
2474                         .dst_mac = "\xff\xff\xff\xff\xff\xff",
2475                         .vlan_tag = ((vlan_index != -1u) ? htons(0xfff) : 0),
2476                 }
2477         };
2478         DEBUG("%p: adding MAC address %02x:%02x:%02x:%02x:%02x:%02x index %u"
2479               " (VLAN %s %" PRIu16 ")",
2480               (void *)rxq,
2481               (*mac)[0], (*mac)[1], (*mac)[2], (*mac)[3], (*mac)[4], (*mac)[5],
2482               mac_index,
2483               ((vlan_index != -1u) ? "ID" : "index"),
2484               ((vlan_index != -1u) ? priv->vlan_filter[vlan_index].id : -1u));
2485         /* Create related flow. */
2486         errno = 0;
2487         flow = ibv_create_flow(rxq->qp, attr);
2488         if (flow == NULL) {
2489                 /* It's not clear whether errno is always set in this case. */
2490                 ERROR("%p: flow configuration failed, errno=%d: %s",
2491                       (void *)rxq, errno,
2492                       (errno ? strerror(errno) : "Unknown error"));
2493                 if (errno)
2494                         return errno;
2495                 return EINVAL;
2496         }
2497         if (vlan_index == -1u)
2498                 vlan_index = 0;
2499         assert(rxq->mac_flow[mac_index][vlan_index] == NULL);
2500         rxq->mac_flow[mac_index][vlan_index] = flow;
2501         return 0;
2502 }
2503
2504 /**
2505  * Register a MAC address in a RX queue.
2506  *
2507  * @param rxq
2508  *   Pointer to RX queue structure.
2509  * @param mac_index
2510  *   MAC address index to register.
2511  *
2512  * @return
2513  *   0 on success, errno value on failure.
2514  */
2515 static int
2516 rxq_mac_addr_add(struct rxq *rxq, unsigned int mac_index)
2517 {
2518         struct priv *priv = rxq->priv;
2519         unsigned int i;
2520         unsigned int vlans = 0;
2521         int ret;
2522
2523         assert(mac_index < elemof(priv->mac));
2524         if (BITFIELD_ISSET(rxq->mac_configured, mac_index))
2525                 rxq_mac_addr_del(rxq, mac_index);
2526         /* Fill VLAN specifications. */
2527         for (i = 0; (i != elemof(priv->vlan_filter)); ++i) {
2528                 if (!priv->vlan_filter[i].enabled)
2529                         continue;
2530                 /* Create related flow. */
2531                 ret = rxq_add_flow(rxq, mac_index, i);
2532                 if (!ret) {
2533                         vlans++;
2534                         continue;
2535                 }
2536                 /* Failure, rollback. */
2537                 while (i != 0)
2538                         if (priv->vlan_filter[--i].enabled)
2539                                 rxq_del_flow(rxq, mac_index, i);
2540                 assert(ret > 0);
2541                 return ret;
2542         }
2543         /* In case there is no VLAN filter. */
2544         if (!vlans) {
2545                 ret = rxq_add_flow(rxq, mac_index, -1);
2546                 if (ret)
2547                         return ret;
2548         }
2549         BITFIELD_SET(rxq->mac_configured, mac_index);
2550         return 0;
2551 }
2552
2553 /**
2554  * Register all MAC addresses in a RX queue.
2555  *
2556  * @param rxq
2557  *   Pointer to RX queue structure.
2558  *
2559  * @return
2560  *   0 on success, errno value on failure.
2561  */
2562 static int
2563 rxq_mac_addrs_add(struct rxq *rxq)
2564 {
2565         struct priv *priv = rxq->priv;
2566         unsigned int i;
2567         int ret;
2568
2569         for (i = 0; (i != elemof(priv->mac)); ++i) {
2570                 if (!BITFIELD_ISSET(priv->mac_configured, i))
2571                         continue;
2572                 ret = rxq_mac_addr_add(rxq, i);
2573                 if (!ret)
2574                         continue;
2575                 /* Failure, rollback. */
2576                 while (i != 0)
2577                         rxq_mac_addr_del(rxq, --i);
2578                 assert(ret > 0);
2579                 return ret;
2580         }
2581         return 0;
2582 }
2583
2584 /**
2585  * Unregister a MAC address.
2586  *
2587  * In RSS mode, the MAC address is unregistered from the parent queue,
2588  * otherwise it is unregistered from each queue directly.
2589  *
2590  * @param priv
2591  *   Pointer to private structure.
2592  * @param mac_index
2593  *   MAC address index.
2594  */
2595 static void
2596 priv_mac_addr_del(struct priv *priv, unsigned int mac_index)
2597 {
2598         unsigned int i;
2599
2600         assert(mac_index < elemof(priv->mac));
2601         if (!BITFIELD_ISSET(priv->mac_configured, mac_index))
2602                 return;
2603         if (priv->rss) {
2604                 rxq_mac_addr_del(&priv->rxq_parent, mac_index);
2605                 goto end;
2606         }
2607         for (i = 0; (i != priv->dev->data->nb_rx_queues); ++i)
2608                 rxq_mac_addr_del((*priv->rxqs)[i], mac_index);
2609 end:
2610         BITFIELD_RESET(priv->mac_configured, mac_index);
2611 }
2612
2613 /**
2614  * Register a MAC address.
2615  *
2616  * In RSS mode, the MAC address is registered in the parent queue,
2617  * otherwise it is registered in each queue directly.
2618  *
2619  * @param priv
2620  *   Pointer to private structure.
2621  * @param mac_index
2622  *   MAC address index to use.
2623  * @param mac
2624  *   MAC address to register.
2625  *
2626  * @return
2627  *   0 on success, errno value on failure.
2628  */
2629 static int
2630 priv_mac_addr_add(struct priv *priv, unsigned int mac_index,
2631                   const uint8_t (*mac)[ETHER_ADDR_LEN])
2632 {
2633         unsigned int i;
2634         int ret;
2635
2636         assert(mac_index < elemof(priv->mac));
2637         /* First, make sure this address isn't already configured. */
2638         for (i = 0; (i != elemof(priv->mac)); ++i) {
2639                 /* Skip this index, it's going to be reconfigured. */
2640                 if (i == mac_index)
2641                         continue;
2642                 if (!BITFIELD_ISSET(priv->mac_configured, i))
2643                         continue;
2644                 if (memcmp(priv->mac[i].addr_bytes, *mac, sizeof(*mac)))
2645                         continue;
2646                 /* Address already configured elsewhere, return with error. */
2647                 return EADDRINUSE;
2648         }
2649         if (BITFIELD_ISSET(priv->mac_configured, mac_index))
2650                 priv_mac_addr_del(priv, mac_index);
2651         priv->mac[mac_index] = (struct ether_addr){
2652                 {
2653                         (*mac)[0], (*mac)[1], (*mac)[2],
2654                         (*mac)[3], (*mac)[4], (*mac)[5]
2655                 }
2656         };
2657         /* If device isn't started, this is all we need to do. */
2658         if (!priv->started) {
2659 #ifndef NDEBUG
2660                 /* Verify that all queues have this index disabled. */
2661                 for (i = 0; (i != priv->rxqs_n); ++i) {
2662                         if ((*priv->rxqs)[i] == NULL)
2663                                 continue;
2664                         assert(!BITFIELD_ISSET
2665                                ((*priv->rxqs)[i]->mac_configured, mac_index));
2666                 }
2667 #endif
2668                 goto end;
2669         }
2670         if (priv->rss) {
2671                 ret = rxq_mac_addr_add(&priv->rxq_parent, mac_index);
2672                 if (ret)
2673                         return ret;
2674                 goto end;
2675         }
2676         for (i = 0; (i != priv->rxqs_n); ++i) {
2677                 if ((*priv->rxqs)[i] == NULL)
2678                         continue;
2679                 ret = rxq_mac_addr_add((*priv->rxqs)[i], mac_index);
2680                 if (!ret)
2681                         continue;
2682                 /* Failure, rollback. */
2683                 while (i != 0)
2684                         if ((*priv->rxqs)[(--i)] != NULL)
2685                                 rxq_mac_addr_del((*priv->rxqs)[i], mac_index);
2686                 return ret;
2687         }
2688 end:
2689         BITFIELD_SET(priv->mac_configured, mac_index);
2690         return 0;
2691 }
2692
2693 /**
2694  * Enable allmulti mode in a RX queue.
2695  *
2696  * @param rxq
2697  *   Pointer to RX queue structure.
2698  *
2699  * @return
2700  *   0 on success, errno value on failure.
2701  */
2702 static int
2703 rxq_allmulticast_enable(struct rxq *rxq)
2704 {
2705         struct ibv_flow *flow;
2706         struct ibv_flow_attr attr = {
2707                 .type = IBV_FLOW_ATTR_MC_DEFAULT,
2708                 .num_of_specs = 0,
2709                 .port = rxq->priv->port,
2710                 .flags = 0
2711         };
2712
2713         DEBUG("%p: enabling allmulticast mode", (void *)rxq);
2714         if (rxq->allmulti_flow != NULL)
2715                 return EBUSY;
2716         errno = 0;
2717         flow = ibv_create_flow(rxq->qp, &attr);
2718         if (flow == NULL) {
2719                 /* It's not clear whether errno is always set in this case. */
2720                 ERROR("%p: flow configuration failed, errno=%d: %s",
2721                       (void *)rxq, errno,
2722                       (errno ? strerror(errno) : "Unknown error"));
2723                 if (errno)
2724                         return errno;
2725                 return EINVAL;
2726         }
2727         rxq->allmulti_flow = flow;
2728         DEBUG("%p: allmulticast mode enabled", (void *)rxq);
2729         return 0;
2730 }
2731
2732 /**
2733  * Disable allmulti mode in a RX queue.
2734  *
2735  * @param rxq
2736  *   Pointer to RX queue structure.
2737  */
2738 static void
2739 rxq_allmulticast_disable(struct rxq *rxq)
2740 {
2741         DEBUG("%p: disabling allmulticast mode", (void *)rxq);
2742         if (rxq->allmulti_flow == NULL)
2743                 return;
2744         claim_zero(ibv_destroy_flow(rxq->allmulti_flow));
2745         rxq->allmulti_flow = NULL;
2746         DEBUG("%p: allmulticast mode disabled", (void *)rxq);
2747 }
2748
2749 /**
2750  * Enable promiscuous mode in a RX queue.
2751  *
2752  * @param rxq
2753  *   Pointer to RX queue structure.
2754  *
2755  * @return
2756  *   0 on success, errno value on failure.
2757  */
2758 static int
2759 rxq_promiscuous_enable(struct rxq *rxq)
2760 {
2761         struct ibv_flow *flow;
2762         struct ibv_flow_attr attr = {
2763                 .type = IBV_FLOW_ATTR_ALL_DEFAULT,
2764                 .num_of_specs = 0,
2765                 .port = rxq->priv->port,
2766                 .flags = 0
2767         };
2768
2769         if (rxq->priv->vf)
2770                 return 0;
2771         DEBUG("%p: enabling promiscuous mode", (void *)rxq);
2772         if (rxq->promisc_flow != NULL)
2773                 return EBUSY;
2774         errno = 0;
2775         flow = ibv_create_flow(rxq->qp, &attr);
2776         if (flow == NULL) {
2777                 /* It's not clear whether errno is always set in this case. */
2778                 ERROR("%p: flow configuration failed, errno=%d: %s",
2779                       (void *)rxq, errno,
2780                       (errno ? strerror(errno) : "Unknown error"));
2781                 if (errno)
2782                         return errno;
2783                 return EINVAL;
2784         }
2785         rxq->promisc_flow = flow;
2786         DEBUG("%p: promiscuous mode enabled", (void *)rxq);
2787         return 0;
2788 }
2789
2790 /**
2791  * Disable promiscuous mode in a RX queue.
2792  *
2793  * @param rxq
2794  *   Pointer to RX queue structure.
2795  */
2796 static void
2797 rxq_promiscuous_disable(struct rxq *rxq)
2798 {
2799         if (rxq->priv->vf)
2800                 return;
2801         DEBUG("%p: disabling promiscuous mode", (void *)rxq);
2802         if (rxq->promisc_flow == NULL)
2803                 return;
2804         claim_zero(ibv_destroy_flow(rxq->promisc_flow));
2805         rxq->promisc_flow = NULL;
2806         DEBUG("%p: promiscuous mode disabled", (void *)rxq);
2807 }
2808
2809 /**
2810  * Clean up a RX queue.
2811  *
2812  * Destroy objects, free allocated memory and reset the structure for reuse.
2813  *
2814  * @param rxq
2815  *   Pointer to RX queue structure.
2816  */
2817 static void
2818 rxq_cleanup(struct rxq *rxq)
2819 {
2820         struct ibv_exp_release_intf_params params;
2821
2822         DEBUG("cleaning up %p", (void *)rxq);
2823         if (rxq->sp)
2824                 rxq_free_elts_sp(rxq);
2825         else
2826                 rxq_free_elts(rxq);
2827         if (rxq->if_qp != NULL) {
2828                 assert(rxq->priv != NULL);
2829                 assert(rxq->priv->ctx != NULL);
2830                 assert(rxq->qp != NULL);
2831                 params = (struct ibv_exp_release_intf_params){
2832                         .comp_mask = 0,
2833                 };
2834                 claim_zero(ibv_exp_release_intf(rxq->priv->ctx,
2835                                                 rxq->if_qp,
2836                                                 &params));
2837         }
2838         if (rxq->if_cq != NULL) {
2839                 assert(rxq->priv != NULL);
2840                 assert(rxq->priv->ctx != NULL);
2841                 assert(rxq->cq != NULL);
2842                 params = (struct ibv_exp_release_intf_params){
2843                         .comp_mask = 0,
2844                 };
2845                 claim_zero(ibv_exp_release_intf(rxq->priv->ctx,
2846                                                 rxq->if_cq,
2847                                                 &params));
2848         }
2849         if (rxq->qp != NULL) {
2850                 rxq_promiscuous_disable(rxq);
2851                 rxq_allmulticast_disable(rxq);
2852                 rxq_mac_addrs_del(rxq);
2853                 claim_zero(ibv_destroy_qp(rxq->qp));
2854         }
2855         if (rxq->cq != NULL)
2856                 claim_zero(ibv_destroy_cq(rxq->cq));
2857         if (rxq->rd != NULL) {
2858                 struct ibv_exp_destroy_res_domain_attr attr = {
2859                         .comp_mask = 0,
2860                 };
2861
2862                 assert(rxq->priv != NULL);
2863                 assert(rxq->priv->ctx != NULL);
2864                 claim_zero(ibv_exp_destroy_res_domain(rxq->priv->ctx,
2865                                                       rxq->rd,
2866                                                       &attr));
2867         }
2868         if (rxq->mr != NULL)
2869                 claim_zero(ibv_dereg_mr(rxq->mr));
2870         memset(rxq, 0, sizeof(*rxq));
2871 }
2872
2873 /**
2874  * Translate RX completion flags to packet type.
2875  *
2876  * @param flags
2877  *   RX completion flags returned by poll_length_flags().
2878  *
2879  * @return
2880  *   Packet type for struct rte_mbuf.
2881  */
2882 static inline uint32_t
2883 rxq_cq_to_pkt_type(uint32_t flags)
2884 {
2885         uint32_t pkt_type;
2886
2887         if (flags & IBV_EXP_CQ_RX_TUNNEL_PACKET)
2888                 pkt_type =
2889                         TRANSPOSE(flags,
2890                                   IBV_EXP_CQ_RX_OUTER_IPV4_PACKET, RTE_PTYPE_L3_IPV4) |
2891                         TRANSPOSE(flags,
2892                                   IBV_EXP_CQ_RX_OUTER_IPV6_PACKET, RTE_PTYPE_L3_IPV6) |
2893                         TRANSPOSE(flags,
2894                                   IBV_EXP_CQ_RX_IPV4_PACKET, RTE_PTYPE_INNER_L3_IPV4) |
2895                         TRANSPOSE(flags,
2896                                   IBV_EXP_CQ_RX_IPV6_PACKET, RTE_PTYPE_INNER_L3_IPV6);
2897         else
2898                 pkt_type =
2899                         TRANSPOSE(flags,
2900                                   IBV_EXP_CQ_RX_IPV4_PACKET, RTE_PTYPE_L3_IPV4) |
2901                         TRANSPOSE(flags,
2902                                   IBV_EXP_CQ_RX_IPV6_PACKET, RTE_PTYPE_L3_IPV6);
2903         return pkt_type;
2904 }
2905
2906 /**
2907  * Translate RX completion flags to offload flags.
2908  *
2909  * @param[in] rxq
2910  *   Pointer to RX queue structure.
2911  * @param flags
2912  *   RX completion flags returned by poll_length_flags().
2913  *
2914  * @return
2915  *   Offload flags (ol_flags) for struct rte_mbuf.
2916  */
2917 static inline uint32_t
2918 rxq_cq_to_ol_flags(const struct rxq *rxq, uint32_t flags)
2919 {
2920         uint32_t ol_flags = 0;
2921
2922         if (rxq->csum)
2923                 ol_flags |=
2924                         TRANSPOSE(~flags,
2925                                   IBV_EXP_CQ_RX_IP_CSUM_OK,
2926                                   PKT_RX_IP_CKSUM_BAD) |
2927                         TRANSPOSE(~flags,
2928                                   IBV_EXP_CQ_RX_TCP_UDP_CSUM_OK,
2929                                   PKT_RX_L4_CKSUM_BAD);
2930         /*
2931          * PKT_RX_IP_CKSUM_BAD and PKT_RX_L4_CKSUM_BAD are used in place
2932          * of PKT_RX_EIP_CKSUM_BAD because the latter is not functional
2933          * (its value is 0).
2934          */
2935         if ((flags & IBV_EXP_CQ_RX_TUNNEL_PACKET) && (rxq->csum_l2tun))
2936                 ol_flags |=
2937                         TRANSPOSE(~flags,
2938                                   IBV_EXP_CQ_RX_OUTER_IP_CSUM_OK,
2939                                   PKT_RX_IP_CKSUM_BAD) |
2940                         TRANSPOSE(~flags,
2941                                   IBV_EXP_CQ_RX_OUTER_TCP_UDP_CSUM_OK,
2942                                   PKT_RX_L4_CKSUM_BAD);
2943         return ol_flags;
2944 }
2945
2946 static uint16_t
2947 mlx4_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n);
2948
2949 /**
2950  * DPDK callback for RX with scattered packets support.
2951  *
2952  * @param dpdk_rxq
2953  *   Generic pointer to RX queue structure.
2954  * @param[out] pkts
2955  *   Array to store received packets.
2956  * @param pkts_n
2957  *   Maximum number of packets in array.
2958  *
2959  * @return
2960  *   Number of packets successfully received (<= pkts_n).
2961  */
2962 static uint16_t
2963 mlx4_rx_burst_sp(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
2964 {
2965         struct rxq *rxq = (struct rxq *)dpdk_rxq;
2966         struct rxq_elt_sp (*elts)[rxq->elts_n] = rxq->elts.sp;
2967         const unsigned int elts_n = rxq->elts_n;
2968         unsigned int elts_head = rxq->elts_head;
2969         struct ibv_recv_wr head;
2970         struct ibv_recv_wr **next = &head.next;
2971         struct ibv_recv_wr *bad_wr;
2972         unsigned int i;
2973         unsigned int pkts_ret = 0;
2974         int ret;
2975
2976         if (unlikely(!rxq->sp))
2977                 return mlx4_rx_burst(dpdk_rxq, pkts, pkts_n);
2978         if (unlikely(elts == NULL)) /* See RTE_DEV_CMD_SET_MTU. */
2979                 return 0;
2980         for (i = 0; (i != pkts_n); ++i) {
2981                 struct rxq_elt_sp *elt = &(*elts)[elts_head];
2982                 struct ibv_recv_wr *wr = &elt->wr;
2983                 uint64_t wr_id = wr->wr_id;
2984                 unsigned int len;
2985                 unsigned int pkt_buf_len;
2986                 struct rte_mbuf *pkt_buf = NULL; /* Buffer returned in pkts. */
2987                 struct rte_mbuf **pkt_buf_next = &pkt_buf;
2988                 unsigned int seg_headroom = RTE_PKTMBUF_HEADROOM;
2989                 unsigned int j = 0;
2990                 uint32_t flags;
2991
2992                 /* Sanity checks. */
2993 #ifdef NDEBUG
2994                 (void)wr_id;
2995 #endif
2996                 assert(wr_id < rxq->elts_n);
2997                 assert(wr->sg_list == elt->sges);
2998                 assert(wr->num_sge == elemof(elt->sges));
2999                 assert(elts_head < rxq->elts_n);
3000                 assert(rxq->elts_head < rxq->elts_n);
3001                 ret = rxq->if_cq->poll_length_flags(rxq->cq, NULL, NULL,
3002                                                     &flags);
3003                 if (unlikely(ret < 0)) {
3004                         struct ibv_wc wc;
3005                         int wcs_n;
3006
3007                         DEBUG("rxq=%p, poll_length() failed (ret=%d)",
3008                               (void *)rxq, ret);
3009                         /* ibv_poll_cq() must be used in case of failure. */
3010                         wcs_n = ibv_poll_cq(rxq->cq, 1, &wc);
3011                         if (unlikely(wcs_n == 0))
3012                                 break;
3013                         if (unlikely(wcs_n < 0)) {
3014                                 DEBUG("rxq=%p, ibv_poll_cq() failed (wcs_n=%d)",
3015                                       (void *)rxq, wcs_n);
3016                                 break;
3017                         }
3018                         assert(wcs_n == 1);
3019                         if (unlikely(wc.status != IBV_WC_SUCCESS)) {
3020                                 /* Whatever, just repost the offending WR. */
3021                                 DEBUG("rxq=%p, wr_id=%" PRIu64 ": bad work"
3022                                       " completion status (%d): %s",
3023                                       (void *)rxq, wc.wr_id, wc.status,
3024                                       ibv_wc_status_str(wc.status));
3025 #ifdef MLX4_PMD_SOFT_COUNTERS
3026                                 /* Increment dropped packets counter. */
3027                                 ++rxq->stats.idropped;
3028 #endif
3029                                 /* Link completed WRs together for repost. */
3030                                 *next = wr;
3031                                 next = &wr->next;
3032                                 goto repost;
3033                         }
3034                         ret = wc.byte_len;
3035                 }
3036                 if (ret == 0)
3037                         break;
3038                 len = ret;
3039                 pkt_buf_len = len;
3040                 /* Link completed WRs together for repost. */
3041                 *next = wr;
3042                 next = &wr->next;
3043                 /*
3044                  * Replace spent segments with new ones, concatenate and
3045                  * return them as pkt_buf.
3046                  */
3047                 while (1) {
3048                         struct ibv_sge *sge = &elt->sges[j];
3049                         struct rte_mbuf *seg = elt->bufs[j];
3050                         struct rte_mbuf *rep;
3051                         unsigned int seg_tailroom;
3052
3053                         /*
3054                          * Fetch initial bytes of packet descriptor into a
3055                          * cacheline while allocating rep.
3056                          */
3057                         rte_prefetch0(seg);
3058                         rep = __rte_mbuf_raw_alloc(rxq->mp);
3059                         if (unlikely(rep == NULL)) {
3060                                 /*
3061                                  * Unable to allocate a replacement mbuf,
3062                                  * repost WR.
3063                                  */
3064                                 DEBUG("rxq=%p, wr_id=%" PRIu64 ":"
3065                                       " can't allocate a new mbuf",
3066                                       (void *)rxq, wr_id);
3067                                 if (pkt_buf != NULL) {
3068                                         *pkt_buf_next = NULL;
3069                                         rte_pktmbuf_free(pkt_buf);
3070                                 }
3071                                 /* Increase out of memory counters. */
3072                                 ++rxq->stats.rx_nombuf;
3073                                 ++rxq->priv->dev->data->rx_mbuf_alloc_failed;
3074                                 goto repost;
3075                         }
3076 #ifndef NDEBUG
3077                         /* Poison user-modifiable fields in rep. */
3078                         NEXT(rep) = (void *)((uintptr_t)-1);
3079                         SET_DATA_OFF(rep, 0xdead);
3080                         DATA_LEN(rep) = 0xd00d;
3081                         PKT_LEN(rep) = 0xdeadd00d;
3082                         NB_SEGS(rep) = 0x2a;
3083                         PORT(rep) = 0x2a;
3084                         rep->ol_flags = -1;
3085 #endif
3086                         assert(rep->buf_len == seg->buf_len);
3087                         assert(rep->buf_len == rxq->mb_len);
3088                         /* Reconfigure sge to use rep instead of seg. */
3089                         assert(sge->lkey == rxq->mr->lkey);
3090                         sge->addr = ((uintptr_t)rep->buf_addr + seg_headroom);
3091                         elt->bufs[j] = rep;
3092                         ++j;
3093                         /* Update pkt_buf if it's the first segment, or link
3094                          * seg to the previous one and update pkt_buf_next. */
3095                         *pkt_buf_next = seg;
3096                         pkt_buf_next = &NEXT(seg);
3097                         /* Update seg information. */
3098                         seg_tailroom = (seg->buf_len - seg_headroom);
3099                         assert(sge->length == seg_tailroom);
3100                         SET_DATA_OFF(seg, seg_headroom);
3101                         if (likely(len <= seg_tailroom)) {
3102                                 /* Last segment. */
3103                                 DATA_LEN(seg) = len;
3104                                 PKT_LEN(seg) = len;
3105                                 /* Sanity check. */
3106                                 assert(rte_pktmbuf_headroom(seg) ==
3107                                        seg_headroom);
3108                                 assert(rte_pktmbuf_tailroom(seg) ==
3109                                        (seg_tailroom - len));
3110                                 break;
3111                         }
3112                         DATA_LEN(seg) = seg_tailroom;
3113                         PKT_LEN(seg) = seg_tailroom;
3114                         /* Sanity check. */
3115                         assert(rte_pktmbuf_headroom(seg) == seg_headroom);
3116                         assert(rte_pktmbuf_tailroom(seg) == 0);
3117                         /* Fix len and clear headroom for next segments. */
3118                         len -= seg_tailroom;
3119                         seg_headroom = 0;
3120                 }
3121                 /* Update head and tail segments. */
3122                 *pkt_buf_next = NULL;
3123                 assert(pkt_buf != NULL);
3124                 assert(j != 0);
3125                 NB_SEGS(pkt_buf) = j;
3126                 PORT(pkt_buf) = rxq->port_id;
3127                 PKT_LEN(pkt_buf) = pkt_buf_len;
3128                 pkt_buf->packet_type = rxq_cq_to_pkt_type(flags);
3129                 pkt_buf->ol_flags = rxq_cq_to_ol_flags(rxq, flags);
3130
3131                 /* Return packet. */
3132                 *(pkts++) = pkt_buf;
3133                 ++pkts_ret;
3134 #ifdef MLX4_PMD_SOFT_COUNTERS
3135                 /* Increase bytes counter. */
3136                 rxq->stats.ibytes += pkt_buf_len;
3137 #endif
3138 repost:
3139                 if (++elts_head >= elts_n)
3140                         elts_head = 0;
3141                 continue;
3142         }
3143         if (unlikely(i == 0))
3144                 return 0;
3145         *next = NULL;
3146         /* Repost WRs. */
3147 #ifdef DEBUG_RECV
3148         DEBUG("%p: reposting %d WRs", (void *)rxq, i);
3149 #endif
3150         ret = ibv_post_recv(rxq->qp, head.next, &bad_wr);
3151         if (unlikely(ret)) {
3152                 /* Inability to repost WRs is fatal. */
3153                 DEBUG("%p: ibv_post_recv(): failed for WR %p: %s",
3154                       (void *)rxq->priv,
3155                       (void *)bad_wr,
3156                       strerror(ret));
3157                 abort();
3158         }
3159         rxq->elts_head = elts_head;
3160 #ifdef MLX4_PMD_SOFT_COUNTERS
3161         /* Increase packets counter. */
3162         rxq->stats.ipackets += pkts_ret;
3163 #endif
3164         return pkts_ret;
3165 }
3166
3167 /**
3168  * DPDK callback for RX.
3169  *
3170  * The following function is the same as mlx4_rx_burst_sp(), except it doesn't
3171  * manage scattered packets. Improves performance when MRU is lower than the
3172  * size of the first segment.
3173  *
3174  * @param dpdk_rxq
3175  *   Generic pointer to RX queue structure.
3176  * @param[out] pkts
3177  *   Array to store received packets.
3178  * @param pkts_n
3179  *   Maximum number of packets in array.
3180  *
3181  * @return
3182  *   Number of packets successfully received (<= pkts_n).
3183  */
3184 static uint16_t
3185 mlx4_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
3186 {
3187         struct rxq *rxq = (struct rxq *)dpdk_rxq;
3188         struct rxq_elt (*elts)[rxq->elts_n] = rxq->elts.no_sp;
3189         const unsigned int elts_n = rxq->elts_n;
3190         unsigned int elts_head = rxq->elts_head;
3191         struct ibv_sge sges[pkts_n];
3192         unsigned int i;
3193         unsigned int pkts_ret = 0;
3194         int ret;
3195
3196         if (unlikely(rxq->sp))
3197                 return mlx4_rx_burst_sp(dpdk_rxq, pkts, pkts_n);
3198         for (i = 0; (i != pkts_n); ++i) {
3199                 struct rxq_elt *elt = &(*elts)[elts_head];
3200                 struct ibv_recv_wr *wr = &elt->wr;
3201                 uint64_t wr_id = wr->wr_id;
3202                 unsigned int len;
3203                 struct rte_mbuf *seg = (void *)((uintptr_t)elt->sge.addr -
3204                         WR_ID(wr_id).offset);
3205                 struct rte_mbuf *rep;
3206                 uint32_t flags;
3207
3208                 /* Sanity checks. */
3209                 assert(WR_ID(wr_id).id < rxq->elts_n);
3210                 assert(wr->sg_list == &elt->sge);
3211                 assert(wr->num_sge == 1);
3212                 assert(elts_head < rxq->elts_n);
3213                 assert(rxq->elts_head < rxq->elts_n);
3214                 /*
3215                  * Fetch initial bytes of packet descriptor into a
3216                  * cacheline while allocating rep.
3217                  */
3218                 rte_prefetch0(seg);
3219                 rte_prefetch0(&seg->cacheline1);
3220                 ret = rxq->if_cq->poll_length_flags(rxq->cq, NULL, NULL,
3221                                                     &flags);
3222                 if (unlikely(ret < 0)) {
3223                         struct ibv_wc wc;
3224                         int wcs_n;
3225
3226                         DEBUG("rxq=%p, poll_length() failed (ret=%d)",
3227                               (void *)rxq, ret);
3228                         /* ibv_poll_cq() must be used in case of failure. */
3229                         wcs_n = ibv_poll_cq(rxq->cq, 1, &wc);
3230                         if (unlikely(wcs_n == 0))
3231                                 break;
3232                         if (unlikely(wcs_n < 0)) {
3233                                 DEBUG("rxq=%p, ibv_poll_cq() failed (wcs_n=%d)",
3234                                       (void *)rxq, wcs_n);
3235                                 break;
3236                         }
3237                         assert(wcs_n == 1);
3238                         if (unlikely(wc.status != IBV_WC_SUCCESS)) {
3239                                 /* Whatever, just repost the offending WR. */
3240                                 DEBUG("rxq=%p, wr_id=%" PRIu64 ": bad work"
3241                                       " completion status (%d): %s",
3242                                       (void *)rxq, wc.wr_id, wc.status,
3243                                       ibv_wc_status_str(wc.status));
3244 #ifdef MLX4_PMD_SOFT_COUNTERS
3245                                 /* Increment dropped packets counter. */
3246                                 ++rxq->stats.idropped;
3247 #endif
3248                                 /* Add SGE to array for repost. */
3249                                 sges[i] = elt->sge;
3250                                 goto repost;
3251                         }
3252                         ret = wc.byte_len;
3253                 }
3254                 if (ret == 0)
3255                         break;
3256                 len = ret;
3257                 rep = __rte_mbuf_raw_alloc(rxq->mp);
3258                 if (unlikely(rep == NULL)) {
3259                         /*
3260                          * Unable to allocate a replacement mbuf,
3261                          * repost WR.
3262                          */
3263                         DEBUG("rxq=%p, wr_id=%" PRIu32 ":"
3264                               " can't allocate a new mbuf",
3265                               (void *)rxq, WR_ID(wr_id).id);
3266                         /* Increase out of memory counters. */
3267                         ++rxq->stats.rx_nombuf;
3268                         ++rxq->priv->dev->data->rx_mbuf_alloc_failed;
3269                         goto repost;
3270                 }
3271
3272                 /* Reconfigure sge to use rep instead of seg. */
3273                 elt->sge.addr = (uintptr_t)rep->buf_addr + RTE_PKTMBUF_HEADROOM;
3274                 assert(elt->sge.lkey == rxq->mr->lkey);
3275                 WR_ID(wr->wr_id).offset =
3276                         (((uintptr_t)rep->buf_addr + RTE_PKTMBUF_HEADROOM) -
3277                          (uintptr_t)rep);
3278                 assert(WR_ID(wr->wr_id).id == WR_ID(wr_id).id);
3279
3280                 /* Add SGE to array for repost. */
3281                 sges[i] = elt->sge;
3282
3283                 /* Update seg information. */
3284                 SET_DATA_OFF(seg, RTE_PKTMBUF_HEADROOM);
3285                 NB_SEGS(seg) = 1;
3286                 PORT(seg) = rxq->port_id;
3287                 NEXT(seg) = NULL;
3288                 PKT_LEN(seg) = len;
3289                 DATA_LEN(seg) = len;
3290                 seg->packet_type = rxq_cq_to_pkt_type(flags);
3291                 seg->ol_flags = rxq_cq_to_ol_flags(rxq, flags);
3292
3293                 /* Return packet. */
3294                 *(pkts++) = seg;
3295                 ++pkts_ret;
3296 #ifdef MLX4_PMD_SOFT_COUNTERS
3297                 /* Increase bytes counter. */
3298                 rxq->stats.ibytes += len;
3299 #endif
3300 repost:
3301                 if (++elts_head >= elts_n)
3302                         elts_head = 0;
3303                 continue;
3304         }
3305         if (unlikely(i == 0))
3306                 return 0;
3307         /* Repost WRs. */
3308 #ifdef DEBUG_RECV
3309         DEBUG("%p: reposting %u WRs", (void *)rxq, i);
3310 #endif
3311         ret = rxq->if_qp->recv_burst(rxq->qp, sges, i);
3312         if (unlikely(ret)) {
3313                 /* Inability to repost WRs is fatal. */
3314                 DEBUG("%p: recv_burst(): failed (ret=%d)",
3315                       (void *)rxq->priv,
3316                       ret);
3317                 abort();
3318         }
3319         rxq->elts_head = elts_head;
3320 #ifdef MLX4_PMD_SOFT_COUNTERS
3321         /* Increase packets counter. */
3322         rxq->stats.ipackets += pkts_ret;
3323 #endif
3324         return pkts_ret;
3325 }
3326
3327 /**
3328  * DPDK callback for RX in secondary processes.
3329  *
3330  * This function configures all queues from primary process information
3331  * if necessary before reverting to the normal RX burst callback.
3332  *
3333  * @param dpdk_rxq
3334  *   Generic pointer to RX queue structure.
3335  * @param[out] pkts
3336  *   Array to store received packets.
3337  * @param pkts_n
3338  *   Maximum number of packets in array.
3339  *
3340  * @return
3341  *   Number of packets successfully received (<= pkts_n).
3342  */
3343 static uint16_t
3344 mlx4_rx_burst_secondary_setup(void *dpdk_rxq, struct rte_mbuf **pkts,
3345                               uint16_t pkts_n)
3346 {
3347         struct rxq *rxq = dpdk_rxq;
3348         struct priv *priv = mlx4_secondary_data_setup(rxq->priv);
3349         struct priv *primary_priv;
3350         unsigned int index;
3351
3352         if (priv == NULL)
3353                 return 0;
3354         primary_priv =
3355                 mlx4_secondary_data[priv->dev->data->port_id].primary_priv;
3356         /* Look for queue index in both private structures. */
3357         for (index = 0; index != priv->rxqs_n; ++index)
3358                 if (((*primary_priv->rxqs)[index] == rxq) ||
3359                     ((*priv->rxqs)[index] == rxq))
3360                         break;
3361         if (index == priv->rxqs_n)
3362                 return 0;
3363         rxq = (*priv->rxqs)[index];
3364         return priv->dev->rx_pkt_burst(rxq, pkts, pkts_n);
3365 }
3366
3367 /**
3368  * Allocate a Queue Pair.
3369  * Optionally setup inline receive if supported.
3370  *
3371  * @param priv
3372  *   Pointer to private structure.
3373  * @param cq
3374  *   Completion queue to associate with QP.
3375  * @param desc
3376  *   Number of descriptors in QP (hint only).
3377  *
3378  * @return
3379  *   QP pointer or NULL in case of error.
3380  */
3381 static struct ibv_qp *
3382 rxq_setup_qp(struct priv *priv, struct ibv_cq *cq, uint16_t desc,
3383              struct ibv_exp_res_domain *rd)
3384 {
3385         struct ibv_exp_qp_init_attr attr = {
3386                 /* CQ to be associated with the send queue. */
3387                 .send_cq = cq,
3388                 /* CQ to be associated with the receive queue. */
3389                 .recv_cq = cq,
3390                 .cap = {
3391                         /* Max number of outstanding WRs. */
3392                         .max_recv_wr = ((priv->device_attr.max_qp_wr < desc) ?
3393                                         priv->device_attr.max_qp_wr :
3394                                         desc),
3395                         /* Max number of scatter/gather elements in a WR. */
3396                         .max_recv_sge = ((priv->device_attr.max_sge <
3397                                           MLX4_PMD_SGE_WR_N) ?
3398                                          priv->device_attr.max_sge :
3399                                          MLX4_PMD_SGE_WR_N),
3400                 },
3401                 .qp_type = IBV_QPT_RAW_PACKET,
3402                 .comp_mask = (IBV_EXP_QP_INIT_ATTR_PD |
3403                               IBV_EXP_QP_INIT_ATTR_RES_DOMAIN),
3404                 .pd = priv->pd,
3405                 .res_domain = rd,
3406         };
3407
3408 #ifdef INLINE_RECV
3409         attr.max_inl_recv = priv->inl_recv_size;
3410         attr.comp_mask |= IBV_EXP_QP_INIT_ATTR_INL_RECV;
3411 #endif
3412         return ibv_exp_create_qp(priv->ctx, &attr);
3413 }
3414
3415 #ifdef RSS_SUPPORT
3416
3417 /**
3418  * Allocate a RSS Queue Pair.
3419  * Optionally setup inline receive if supported.
3420  *
3421  * @param priv
3422  *   Pointer to private structure.
3423  * @param cq
3424  *   Completion queue to associate with QP.
3425  * @param desc
3426  *   Number of descriptors in QP (hint only).
3427  * @param parent
3428  *   If nonzero, create a parent QP, otherwise a child.
3429  *
3430  * @return
3431  *   QP pointer or NULL in case of error.
3432  */
3433 static struct ibv_qp *
3434 rxq_setup_qp_rss(struct priv *priv, struct ibv_cq *cq, uint16_t desc,
3435                  int parent, struct ibv_exp_res_domain *rd)
3436 {
3437         struct ibv_exp_qp_init_attr attr = {
3438                 /* CQ to be associated with the send queue. */
3439                 .send_cq = cq,
3440                 /* CQ to be associated with the receive queue. */
3441                 .recv_cq = cq,
3442                 .cap = {
3443                         /* Max number of outstanding WRs. */
3444                         .max_recv_wr = ((priv->device_attr.max_qp_wr < desc) ?
3445                                         priv->device_attr.max_qp_wr :
3446                                         desc),
3447                         /* Max number of scatter/gather elements in a WR. */
3448                         .max_recv_sge = ((priv->device_attr.max_sge <
3449                                           MLX4_PMD_SGE_WR_N) ?
3450                                          priv->device_attr.max_sge :
3451                                          MLX4_PMD_SGE_WR_N),
3452                 },
3453                 .qp_type = IBV_QPT_RAW_PACKET,
3454                 .comp_mask = (IBV_EXP_QP_INIT_ATTR_PD |
3455                               IBV_EXP_QP_INIT_ATTR_RES_DOMAIN |
3456                               IBV_EXP_QP_INIT_ATTR_QPG),
3457                 .pd = priv->pd,
3458                 .res_domain = rd,
3459         };
3460
3461 #ifdef INLINE_RECV
3462         attr.max_inl_recv = priv->inl_recv_size,
3463         attr.comp_mask |= IBV_EXP_QP_INIT_ATTR_INL_RECV;
3464 #endif
3465         if (parent) {
3466                 attr.qpg.qpg_type = IBV_EXP_QPG_PARENT;
3467                 /* TSS isn't necessary. */
3468                 attr.qpg.parent_attrib.tss_child_count = 0;
3469                 attr.qpg.parent_attrib.rss_child_count = priv->rxqs_n;
3470                 DEBUG("initializing parent RSS queue");
3471         } else {
3472                 attr.qpg.qpg_type = IBV_EXP_QPG_CHILD_RX;
3473                 attr.qpg.qpg_parent = priv->rxq_parent.qp;
3474                 DEBUG("initializing child RSS queue");
3475         }
3476         return ibv_exp_create_qp(priv->ctx, &attr);
3477 }
3478
3479 #endif /* RSS_SUPPORT */
3480
3481 /**
3482  * Reconfigure a RX queue with new parameters.
3483  *
3484  * rxq_rehash() does not allocate mbufs, which, if not done from the right
3485  * thread (such as a control thread), may corrupt the pool.
3486  * In case of failure, the queue is left untouched.
3487  *
3488  * @param dev
3489  *   Pointer to Ethernet device structure.
3490  * @param rxq
3491  *   RX queue pointer.
3492  *
3493  * @return
3494  *   0 on success, errno value on failure.
3495  */
3496 static int
3497 rxq_rehash(struct rte_eth_dev *dev, struct rxq *rxq)
3498 {
3499         struct priv *priv = rxq->priv;
3500         struct rxq tmpl = *rxq;
3501         unsigned int mbuf_n;
3502         unsigned int desc_n;
3503         struct rte_mbuf **pool;
3504         unsigned int i, k;
3505         struct ibv_exp_qp_attr mod;
3506         struct ibv_recv_wr *bad_wr;
3507         int err;
3508         int parent = (rxq == &priv->rxq_parent);
3509
3510         if (parent) {
3511                 ERROR("%p: cannot rehash parent queue %p",
3512                       (void *)dev, (void *)rxq);
3513                 return EINVAL;
3514         }
3515         DEBUG("%p: rehashing queue %p", (void *)dev, (void *)rxq);
3516         /* Number of descriptors and mbufs currently allocated. */
3517         desc_n = (tmpl.elts_n * (tmpl.sp ? MLX4_PMD_SGE_WR_N : 1));
3518         mbuf_n = desc_n;
3519         /* Toggle RX checksum offload if hardware supports it. */
3520         if (priv->hw_csum) {
3521                 tmpl.csum = !!dev->data->dev_conf.rxmode.hw_ip_checksum;
3522                 rxq->csum = tmpl.csum;
3523         }
3524         if (priv->hw_csum_l2tun) {
3525                 tmpl.csum_l2tun = !!dev->data->dev_conf.rxmode.hw_ip_checksum;
3526                 rxq->csum_l2tun = tmpl.csum_l2tun;
3527         }
3528         /* Enable scattered packets support for this queue if necessary. */
3529         if ((dev->data->dev_conf.rxmode.jumbo_frame) &&
3530             (dev->data->dev_conf.rxmode.max_rx_pkt_len >
3531              (tmpl.mb_len - RTE_PKTMBUF_HEADROOM))) {
3532                 tmpl.sp = 1;
3533                 desc_n /= MLX4_PMD_SGE_WR_N;
3534         } else
3535                 tmpl.sp = 0;
3536         DEBUG("%p: %s scattered packets support (%u WRs)",
3537               (void *)dev, (tmpl.sp ? "enabling" : "disabling"), desc_n);
3538         /* If scatter mode is the same as before, nothing to do. */
3539         if (tmpl.sp == rxq->sp) {
3540                 DEBUG("%p: nothing to do", (void *)dev);
3541                 return 0;
3542         }
3543         /* Remove attached flows if RSS is disabled (no parent queue). */
3544         if (!priv->rss) {
3545                 rxq_allmulticast_disable(&tmpl);
3546                 rxq_promiscuous_disable(&tmpl);
3547                 rxq_mac_addrs_del(&tmpl);
3548                 /* Update original queue in case of failure. */
3549                 rxq->allmulti_flow = tmpl.allmulti_flow;
3550                 rxq->promisc_flow = tmpl.promisc_flow;
3551                 memcpy(rxq->mac_configured, tmpl.mac_configured,
3552                        sizeof(rxq->mac_configured));
3553                 memcpy(rxq->mac_flow, tmpl.mac_flow, sizeof(rxq->mac_flow));
3554         }
3555         /* From now on, any failure will render the queue unusable.
3556          * Reinitialize QP. */
3557         mod = (struct ibv_exp_qp_attr){ .qp_state = IBV_QPS_RESET };
3558         err = ibv_exp_modify_qp(tmpl.qp, &mod, IBV_EXP_QP_STATE);
3559         if (err) {
3560                 ERROR("%p: cannot reset QP: %s", (void *)dev, strerror(err));
3561                 assert(err > 0);
3562                 return err;
3563         }
3564         err = ibv_resize_cq(tmpl.cq, desc_n);
3565         if (err) {
3566                 ERROR("%p: cannot resize CQ: %s", (void *)dev, strerror(err));
3567                 assert(err > 0);
3568                 return err;
3569         }
3570         mod = (struct ibv_exp_qp_attr){
3571                 /* Move the QP to this state. */
3572                 .qp_state = IBV_QPS_INIT,
3573                 /* Primary port number. */
3574                 .port_num = priv->port
3575         };
3576         err = ibv_exp_modify_qp(tmpl.qp, &mod,
3577                                 (IBV_EXP_QP_STATE |
3578 #ifdef RSS_SUPPORT
3579                                  (parent ? IBV_EXP_QP_GROUP_RSS : 0) |
3580 #endif /* RSS_SUPPORT */
3581                                  IBV_EXP_QP_PORT));
3582         if (err) {
3583                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
3584                       (void *)dev, strerror(err));
3585                 assert(err > 0);
3586                 return err;
3587         };
3588         /* Reconfigure flows. Do not care for errors. */
3589         if (!priv->rss) {
3590                 rxq_mac_addrs_add(&tmpl);
3591                 if (priv->promisc)
3592                         rxq_promiscuous_enable(&tmpl);
3593                 if (priv->allmulti)
3594                         rxq_allmulticast_enable(&tmpl);
3595                 /* Update original queue in case of failure. */
3596                 rxq->allmulti_flow = tmpl.allmulti_flow;
3597                 rxq->promisc_flow = tmpl.promisc_flow;
3598                 memcpy(rxq->mac_configured, tmpl.mac_configured,
3599                        sizeof(rxq->mac_configured));
3600                 memcpy(rxq->mac_flow, tmpl.mac_flow, sizeof(rxq->mac_flow));
3601         }
3602         /* Allocate pool. */
3603         pool = rte_malloc(__func__, (mbuf_n * sizeof(*pool)), 0);
3604         if (pool == NULL) {
3605                 ERROR("%p: cannot allocate memory", (void *)dev);
3606                 return ENOBUFS;
3607         }
3608         /* Snatch mbufs from original queue. */
3609         k = 0;
3610         if (rxq->sp) {
3611                 struct rxq_elt_sp (*elts)[rxq->elts_n] = rxq->elts.sp;
3612
3613                 for (i = 0; (i != elemof(*elts)); ++i) {
3614                         struct rxq_elt_sp *elt = &(*elts)[i];
3615                         unsigned int j;
3616
3617                         for (j = 0; (j != elemof(elt->bufs)); ++j) {
3618                                 assert(elt->bufs[j] != NULL);
3619                                 pool[k++] = elt->bufs[j];
3620                         }
3621                 }
3622         } else {
3623                 struct rxq_elt (*elts)[rxq->elts_n] = rxq->elts.no_sp;
3624
3625                 for (i = 0; (i != elemof(*elts)); ++i) {
3626                         struct rxq_elt *elt = &(*elts)[i];
3627                         struct rte_mbuf *buf = (void *)
3628                                 ((uintptr_t)elt->sge.addr -
3629                                  WR_ID(elt->wr.wr_id).offset);
3630
3631                         assert(WR_ID(elt->wr.wr_id).id == i);
3632                         pool[k++] = buf;
3633                 }
3634         }
3635         assert(k == mbuf_n);
3636         tmpl.elts_n = 0;
3637         tmpl.elts.sp = NULL;
3638         assert((void *)&tmpl.elts.sp == (void *)&tmpl.elts.no_sp);
3639         err = ((tmpl.sp) ?
3640                rxq_alloc_elts_sp(&tmpl, desc_n, pool) :
3641                rxq_alloc_elts(&tmpl, desc_n, pool));
3642         if (err) {
3643                 ERROR("%p: cannot reallocate WRs, aborting", (void *)dev);
3644                 rte_free(pool);
3645                 assert(err > 0);
3646                 return err;
3647         }
3648         assert(tmpl.elts_n == desc_n);
3649         assert(tmpl.elts.sp != NULL);
3650         rte_free(pool);
3651         /* Clean up original data. */
3652         rxq->elts_n = 0;
3653         rte_free(rxq->elts.sp);
3654         rxq->elts.sp = NULL;
3655         /* Post WRs. */
3656         err = ibv_post_recv(tmpl.qp,
3657                             (tmpl.sp ?
3658                              &(*tmpl.elts.sp)[0].wr :
3659                              &(*tmpl.elts.no_sp)[0].wr),
3660                             &bad_wr);
3661         if (err) {
3662                 ERROR("%p: ibv_post_recv() failed for WR %p: %s",
3663                       (void *)dev,
3664                       (void *)bad_wr,
3665                       strerror(err));
3666                 goto skip_rtr;
3667         }
3668         mod = (struct ibv_exp_qp_attr){
3669                 .qp_state = IBV_QPS_RTR
3670         };
3671         err = ibv_exp_modify_qp(tmpl.qp, &mod, IBV_EXP_QP_STATE);
3672         if (err)
3673                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
3674                       (void *)dev, strerror(err));
3675 skip_rtr:
3676         *rxq = tmpl;
3677         assert(err >= 0);
3678         return err;
3679 }
3680
3681 /**
3682  * Configure a RX queue.
3683  *
3684  * @param dev
3685  *   Pointer to Ethernet device structure.
3686  * @param rxq
3687  *   Pointer to RX queue structure.
3688  * @param desc
3689  *   Number of descriptors to configure in queue.
3690  * @param socket
3691  *   NUMA socket on which memory must be allocated.
3692  * @param[in] conf
3693  *   Thresholds parameters.
3694  * @param mp
3695  *   Memory pool for buffer allocations.
3696  *
3697  * @return
3698  *   0 on success, errno value on failure.
3699  */
3700 static int
3701 rxq_setup(struct rte_eth_dev *dev, struct rxq *rxq, uint16_t desc,
3702           unsigned int socket, const struct rte_eth_rxconf *conf,
3703           struct rte_mempool *mp)
3704 {
3705         struct priv *priv = dev->data->dev_private;
3706         struct rxq tmpl = {
3707                 .priv = priv,
3708                 .mp = mp,
3709                 .socket = socket
3710         };
3711         struct ibv_exp_qp_attr mod;
3712         union {
3713                 struct ibv_exp_query_intf_params params;
3714                 struct ibv_exp_cq_init_attr cq;
3715                 struct ibv_exp_res_domain_init_attr rd;
3716         } attr;
3717         enum ibv_exp_query_intf_status status;
3718         struct ibv_recv_wr *bad_wr;
3719         struct rte_mbuf *buf;
3720         int ret = 0;
3721         int parent = (rxq == &priv->rxq_parent);
3722
3723         (void)conf; /* Thresholds configuration (ignored). */
3724         /*
3725          * If this is a parent queue, hardware must support RSS and
3726          * RSS must be enabled.
3727          */
3728         assert((!parent) || ((priv->hw_rss) && (priv->rss)));
3729         if (parent) {
3730                 /* Even if unused, ibv_create_cq() requires at least one
3731                  * descriptor. */
3732                 desc = 1;
3733                 goto skip_mr;
3734         }
3735         if ((desc == 0) || (desc % MLX4_PMD_SGE_WR_N)) {
3736                 ERROR("%p: invalid number of RX descriptors (must be a"
3737                       " multiple of %d)", (void *)dev, MLX4_PMD_SGE_WR_N);
3738                 return EINVAL;
3739         }
3740         /* Get mbuf length. */
3741         buf = rte_pktmbuf_alloc(mp);
3742         if (buf == NULL) {
3743                 ERROR("%p: unable to allocate mbuf", (void *)dev);
3744                 return ENOMEM;
3745         }
3746         tmpl.mb_len = buf->buf_len;
3747         assert((rte_pktmbuf_headroom(buf) +
3748                 rte_pktmbuf_tailroom(buf)) == tmpl.mb_len);
3749         assert(rte_pktmbuf_headroom(buf) == RTE_PKTMBUF_HEADROOM);
3750         rte_pktmbuf_free(buf);
3751         /* Toggle RX checksum offload if hardware supports it. */
3752         if (priv->hw_csum)
3753                 tmpl.csum = !!dev->data->dev_conf.rxmode.hw_ip_checksum;
3754         if (priv->hw_csum_l2tun)
3755                 tmpl.csum_l2tun = !!dev->data->dev_conf.rxmode.hw_ip_checksum;
3756         /* Enable scattered packets support for this queue if necessary. */
3757         if ((dev->data->dev_conf.rxmode.jumbo_frame) &&
3758             (dev->data->dev_conf.rxmode.max_rx_pkt_len >
3759              (tmpl.mb_len - RTE_PKTMBUF_HEADROOM))) {
3760                 tmpl.sp = 1;
3761                 desc /= MLX4_PMD_SGE_WR_N;
3762         }
3763         DEBUG("%p: %s scattered packets support (%u WRs)",
3764               (void *)dev, (tmpl.sp ? "enabling" : "disabling"), desc);
3765         /* Use the entire RX mempool as the memory region. */
3766         tmpl.mr = mlx4_mp2mr(priv->pd, mp);
3767         if (tmpl.mr == NULL) {
3768                 ret = EINVAL;
3769                 ERROR("%p: MR creation failure: %s",
3770                       (void *)dev, strerror(ret));
3771                 goto error;
3772         }
3773 skip_mr:
3774         attr.rd = (struct ibv_exp_res_domain_init_attr){
3775                 .comp_mask = (IBV_EXP_RES_DOMAIN_THREAD_MODEL |
3776                               IBV_EXP_RES_DOMAIN_MSG_MODEL),
3777                 .thread_model = IBV_EXP_THREAD_SINGLE,
3778                 .msg_model = IBV_EXP_MSG_HIGH_BW,
3779         };
3780         tmpl.rd = ibv_exp_create_res_domain(priv->ctx, &attr.rd);
3781         if (tmpl.rd == NULL) {
3782                 ret = ENOMEM;
3783                 ERROR("%p: RD creation failure: %s",
3784                       (void *)dev, strerror(ret));
3785                 goto error;
3786         }
3787         attr.cq = (struct ibv_exp_cq_init_attr){
3788                 .comp_mask = IBV_EXP_CQ_INIT_ATTR_RES_DOMAIN,
3789                 .res_domain = tmpl.rd,
3790         };
3791         tmpl.cq = ibv_exp_create_cq(priv->ctx, desc, NULL, NULL, 0, &attr.cq);
3792         if (tmpl.cq == NULL) {
3793                 ret = ENOMEM;
3794                 ERROR("%p: CQ creation failure: %s",
3795                       (void *)dev, strerror(ret));
3796                 goto error;
3797         }
3798         DEBUG("priv->device_attr.max_qp_wr is %d",
3799               priv->device_attr.max_qp_wr);
3800         DEBUG("priv->device_attr.max_sge is %d",
3801               priv->device_attr.max_sge);
3802 #ifdef RSS_SUPPORT
3803         if (priv->rss)
3804                 tmpl.qp = rxq_setup_qp_rss(priv, tmpl.cq, desc, parent,
3805                                            tmpl.rd);
3806         else
3807 #endif /* RSS_SUPPORT */
3808                 tmpl.qp = rxq_setup_qp(priv, tmpl.cq, desc, tmpl.rd);
3809         if (tmpl.qp == NULL) {
3810                 ret = (errno ? errno : EINVAL);
3811                 ERROR("%p: QP creation failure: %s",
3812                       (void *)dev, strerror(ret));
3813                 goto error;
3814         }
3815         mod = (struct ibv_exp_qp_attr){
3816                 /* Move the QP to this state. */
3817                 .qp_state = IBV_QPS_INIT,
3818                 /* Primary port number. */
3819                 .port_num = priv->port
3820         };
3821         ret = ibv_exp_modify_qp(tmpl.qp, &mod,
3822                                 (IBV_EXP_QP_STATE |
3823 #ifdef RSS_SUPPORT
3824                                  (parent ? IBV_EXP_QP_GROUP_RSS : 0) |
3825 #endif /* RSS_SUPPORT */
3826                                  IBV_EXP_QP_PORT));
3827         if (ret) {
3828                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
3829                       (void *)dev, strerror(ret));
3830                 goto error;
3831         }
3832         if ((parent) || (!priv->rss))  {
3833                 /* Configure MAC and broadcast addresses. */
3834                 ret = rxq_mac_addrs_add(&tmpl);
3835                 if (ret) {
3836                         ERROR("%p: QP flow attachment failed: %s",
3837                               (void *)dev, strerror(ret));
3838                         goto error;
3839                 }
3840         }
3841         /* Allocate descriptors for RX queues, except for the RSS parent. */
3842         if (parent)
3843                 goto skip_alloc;
3844         if (tmpl.sp)
3845                 ret = rxq_alloc_elts_sp(&tmpl, desc, NULL);
3846         else
3847                 ret = rxq_alloc_elts(&tmpl, desc, NULL);
3848         if (ret) {
3849                 ERROR("%p: RXQ allocation failed: %s",
3850                       (void *)dev, strerror(ret));
3851                 goto error;
3852         }
3853         ret = ibv_post_recv(tmpl.qp,
3854                             (tmpl.sp ?
3855                              &(*tmpl.elts.sp)[0].wr :
3856                              &(*tmpl.elts.no_sp)[0].wr),
3857                             &bad_wr);
3858         if (ret) {
3859                 ERROR("%p: ibv_post_recv() failed for WR %p: %s",
3860                       (void *)dev,
3861                       (void *)bad_wr,
3862                       strerror(ret));
3863                 goto error;
3864         }
3865 skip_alloc:
3866         mod = (struct ibv_exp_qp_attr){
3867                 .qp_state = IBV_QPS_RTR
3868         };
3869         ret = ibv_exp_modify_qp(tmpl.qp, &mod, IBV_EXP_QP_STATE);
3870         if (ret) {
3871                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
3872                       (void *)dev, strerror(ret));
3873                 goto error;
3874         }
3875         /* Save port ID. */
3876         tmpl.port_id = dev->data->port_id;
3877         DEBUG("%p: RTE port ID: %u", (void *)rxq, tmpl.port_id);
3878         attr.params = (struct ibv_exp_query_intf_params){
3879                 .intf_scope = IBV_EXP_INTF_GLOBAL,
3880                 .intf = IBV_EXP_INTF_CQ,
3881                 .obj = tmpl.cq,
3882         };
3883         tmpl.if_cq = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
3884         if (tmpl.if_cq == NULL) {
3885                 ERROR("%p: CQ interface family query failed with status %d",
3886                       (void *)dev, status);
3887                 goto error;
3888         }
3889         attr.params = (struct ibv_exp_query_intf_params){
3890                 .intf_scope = IBV_EXP_INTF_GLOBAL,
3891                 .intf = IBV_EXP_INTF_QP_BURST,
3892                 .obj = tmpl.qp,
3893         };
3894         tmpl.if_qp = ibv_exp_query_intf(priv->ctx, &attr.params, &status);
3895         if (tmpl.if_qp == NULL) {
3896                 ERROR("%p: QP interface family query failed with status %d",
3897                       (void *)dev, status);
3898                 goto error;
3899         }
3900         /* Clean up rxq in case we're reinitializing it. */
3901         DEBUG("%p: cleaning-up old rxq just in case", (void *)rxq);
3902         rxq_cleanup(rxq);
3903         *rxq = tmpl;
3904         DEBUG("%p: rxq updated with %p", (void *)rxq, (void *)&tmpl);
3905         assert(ret == 0);
3906         return 0;
3907 error:
3908         rxq_cleanup(&tmpl);
3909         assert(ret > 0);
3910         return ret;
3911 }
3912
3913 /**
3914  * DPDK callback to configure a RX queue.
3915  *
3916  * @param dev
3917  *   Pointer to Ethernet device structure.
3918  * @param idx
3919  *   RX queue index.
3920  * @param desc
3921  *   Number of descriptors to configure in queue.
3922  * @param socket
3923  *   NUMA socket on which memory must be allocated.
3924  * @param[in] conf
3925  *   Thresholds parameters.
3926  * @param mp
3927  *   Memory pool for buffer allocations.
3928  *
3929  * @return
3930  *   0 on success, negative errno value on failure.
3931  */
3932 static int
3933 mlx4_rx_queue_setup(struct rte_eth_dev *dev, uint16_t idx, uint16_t desc,
3934                     unsigned int socket, const struct rte_eth_rxconf *conf,
3935                     struct rte_mempool *mp)
3936 {
3937         struct priv *priv = dev->data->dev_private;
3938         struct rxq *rxq = (*priv->rxqs)[idx];
3939         int ret;
3940
3941         if (mlx4_is_secondary())
3942                 return -E_RTE_SECONDARY;
3943         priv_lock(priv);
3944         DEBUG("%p: configuring queue %u for %u descriptors",
3945               (void *)dev, idx, desc);
3946         if (idx >= priv->rxqs_n) {
3947                 ERROR("%p: queue index out of range (%u >= %u)",
3948                       (void *)dev, idx, priv->rxqs_n);
3949                 priv_unlock(priv);
3950                 return -EOVERFLOW;
3951         }
3952         if (rxq != NULL) {
3953                 DEBUG("%p: reusing already allocated queue index %u (%p)",
3954                       (void *)dev, idx, (void *)rxq);
3955                 if (priv->started) {
3956                         priv_unlock(priv);
3957                         return -EEXIST;
3958                 }
3959                 (*priv->rxqs)[idx] = NULL;
3960                 rxq_cleanup(rxq);
3961         } else {
3962                 rxq = rte_calloc_socket("RXQ", 1, sizeof(*rxq), 0, socket);
3963                 if (rxq == NULL) {
3964                         ERROR("%p: unable to allocate queue index %u",
3965                               (void *)dev, idx);
3966                         priv_unlock(priv);
3967                         return -ENOMEM;
3968                 }
3969         }
3970         ret = rxq_setup(dev, rxq, desc, socket, conf, mp);
3971         if (ret)
3972                 rte_free(rxq);
3973         else {
3974                 rxq->stats.idx = idx;
3975                 DEBUG("%p: adding RX queue %p to list",
3976                       (void *)dev, (void *)rxq);
3977                 (*priv->rxqs)[idx] = rxq;
3978                 /* Update receive callback. */
3979                 if (rxq->sp)
3980                         dev->rx_pkt_burst = mlx4_rx_burst_sp;
3981                 else
3982                         dev->rx_pkt_burst = mlx4_rx_burst;
3983         }
3984         priv_unlock(priv);
3985         return -ret;
3986 }
3987
3988 /**
3989  * DPDK callback to release a RX queue.
3990  *
3991  * @param dpdk_rxq
3992  *   Generic RX queue pointer.
3993  */
3994 static void
3995 mlx4_rx_queue_release(void *dpdk_rxq)
3996 {
3997         struct rxq *rxq = (struct rxq *)dpdk_rxq;
3998         struct priv *priv;
3999         unsigned int i;
4000
4001         if (mlx4_is_secondary())
4002                 return;
4003         if (rxq == NULL)
4004                 return;
4005         priv = rxq->priv;
4006         priv_lock(priv);
4007         assert(rxq != &priv->rxq_parent);
4008         for (i = 0; (i != priv->rxqs_n); ++i)
4009                 if ((*priv->rxqs)[i] == rxq) {
4010                         DEBUG("%p: removing RX queue %p from list",
4011                               (void *)priv->dev, (void *)rxq);
4012                         (*priv->rxqs)[i] = NULL;
4013                         break;
4014                 }
4015         rxq_cleanup(rxq);
4016         rte_free(rxq);
4017         priv_unlock(priv);
4018 }
4019
4020 static void
4021 priv_dev_interrupt_handler_install(struct priv *, struct rte_eth_dev *);
4022
4023 /**
4024  * DPDK callback to start the device.
4025  *
4026  * Simulate device start by attaching all configured flows.
4027  *
4028  * @param dev
4029  *   Pointer to Ethernet device structure.
4030  *
4031  * @return
4032  *   0 on success, negative errno value on failure.
4033  */
4034 static int
4035 mlx4_dev_start(struct rte_eth_dev *dev)
4036 {
4037         struct priv *priv = dev->data->dev_private;
4038         unsigned int i = 0;
4039         unsigned int r;
4040         struct rxq *rxq;
4041
4042         if (mlx4_is_secondary())
4043                 return -E_RTE_SECONDARY;
4044         priv_lock(priv);
4045         if (priv->started) {
4046                 priv_unlock(priv);
4047                 return 0;
4048         }
4049         DEBUG("%p: attaching configured flows to all RX queues", (void *)dev);
4050         priv->started = 1;
4051         if (priv->rss) {
4052                 rxq = &priv->rxq_parent;
4053                 r = 1;
4054         } else {
4055                 rxq = (*priv->rxqs)[0];
4056                 r = priv->rxqs_n;
4057         }
4058         /* Iterate only once when RSS is enabled. */
4059         do {
4060                 int ret;
4061
4062                 /* Ignore nonexistent RX queues. */
4063                 if (rxq == NULL)
4064                         continue;
4065                 ret = rxq_mac_addrs_add(rxq);
4066                 if (!ret && priv->promisc)
4067                         ret = rxq_promiscuous_enable(rxq);
4068                 if (!ret && priv->allmulti)
4069                         ret = rxq_allmulticast_enable(rxq);
4070                 if (!ret)
4071                         continue;
4072                 WARN("%p: QP flow attachment failed: %s",
4073                      (void *)dev, strerror(ret));
4074                 /* Rollback. */
4075                 while (i != 0) {
4076                         rxq = (*priv->rxqs)[--i];
4077                         if (rxq != NULL) {
4078                                 rxq_allmulticast_disable(rxq);
4079                                 rxq_promiscuous_disable(rxq);
4080                                 rxq_mac_addrs_del(rxq);
4081                         }
4082                 }
4083                 priv->started = 0;
4084                 priv_unlock(priv);
4085                 return -ret;
4086         } while ((--r) && ((rxq = (*priv->rxqs)[++i]), i));
4087         priv_dev_interrupt_handler_install(priv, dev);
4088         priv_unlock(priv);
4089         return 0;
4090 }
4091
4092 /**
4093  * DPDK callback to stop the device.
4094  *
4095  * Simulate device stop by detaching all configured flows.
4096  *
4097  * @param dev
4098  *   Pointer to Ethernet device structure.
4099  */
4100 static void
4101 mlx4_dev_stop(struct rte_eth_dev *dev)
4102 {
4103         struct priv *priv = dev->data->dev_private;
4104         unsigned int i = 0;
4105         unsigned int r;
4106         struct rxq *rxq;
4107
4108         if (mlx4_is_secondary())
4109                 return;
4110         priv_lock(priv);
4111         if (!priv->started) {
4112                 priv_unlock(priv);
4113                 return;
4114         }
4115         DEBUG("%p: detaching flows from all RX queues", (void *)dev);
4116         priv->started = 0;
4117         if (priv->rss) {
4118                 rxq = &priv->rxq_parent;
4119                 r = 1;
4120         } else {
4121                 rxq = (*priv->rxqs)[0];
4122                 r = priv->rxqs_n;
4123         }
4124         /* Iterate only once when RSS is enabled. */
4125         do {
4126                 /* Ignore nonexistent RX queues. */
4127                 if (rxq == NULL)
4128                         continue;
4129                 rxq_allmulticast_disable(rxq);
4130                 rxq_promiscuous_disable(rxq);
4131                 rxq_mac_addrs_del(rxq);
4132         } while ((--r) && ((rxq = (*priv->rxqs)[++i]), i));
4133         priv_unlock(priv);
4134 }
4135
4136 /**
4137  * Dummy DPDK callback for TX.
4138  *
4139  * This function is used to temporarily replace the real callback during
4140  * unsafe control operations on the queue, or in case of error.
4141  *
4142  * @param dpdk_txq
4143  *   Generic pointer to TX queue structure.
4144  * @param[in] pkts
4145  *   Packets to transmit.
4146  * @param pkts_n
4147  *   Number of packets in array.
4148  *
4149  * @return
4150  *   Number of packets successfully transmitted (<= pkts_n).
4151  */
4152 static uint16_t
4153 removed_tx_burst(void *dpdk_txq, struct rte_mbuf **pkts, uint16_t pkts_n)
4154 {
4155         (void)dpdk_txq;
4156         (void)pkts;
4157         (void)pkts_n;
4158         return 0;
4159 }
4160
4161 /**
4162  * Dummy DPDK callback for RX.
4163  *
4164  * This function is used to temporarily replace the real callback during
4165  * unsafe control operations on the queue, or in case of error.
4166  *
4167  * @param dpdk_rxq
4168  *   Generic pointer to RX queue structure.
4169  * @param[out] pkts
4170  *   Array to store received packets.
4171  * @param pkts_n
4172  *   Maximum number of packets in array.
4173  *
4174  * @return
4175  *   Number of packets successfully received (<= pkts_n).
4176  */
4177 static uint16_t
4178 removed_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
4179 {
4180         (void)dpdk_rxq;
4181         (void)pkts;
4182         (void)pkts_n;
4183         return 0;
4184 }
4185
4186 static void
4187 priv_dev_interrupt_handler_uninstall(struct priv *, struct rte_eth_dev *);
4188
4189 /**
4190  * DPDK callback to close the device.
4191  *
4192  * Destroy all queues and objects, free memory.
4193  *
4194  * @param dev
4195  *   Pointer to Ethernet device structure.
4196  */
4197 static void
4198 mlx4_dev_close(struct rte_eth_dev *dev)
4199 {
4200         struct priv *priv = mlx4_get_priv(dev);
4201         void *tmp;
4202         unsigned int i;
4203
4204         if (priv == NULL)
4205                 return;
4206         priv_lock(priv);
4207         DEBUG("%p: closing device \"%s\"",
4208               (void *)dev,
4209               ((priv->ctx != NULL) ? priv->ctx->device->name : ""));
4210         /* Prevent crashes when queues are still in use. This is unfortunately
4211          * still required for DPDK 1.3 because some programs (such as testpmd)
4212          * never release them before closing the device. */
4213         dev->rx_pkt_burst = removed_rx_burst;
4214         dev->tx_pkt_burst = removed_tx_burst;
4215         if (priv->rxqs != NULL) {
4216                 /* XXX race condition if mlx4_rx_burst() is still running. */
4217                 usleep(1000);
4218                 for (i = 0; (i != priv->rxqs_n); ++i) {
4219                         tmp = (*priv->rxqs)[i];
4220                         if (tmp == NULL)
4221                                 continue;
4222                         (*priv->rxqs)[i] = NULL;
4223                         rxq_cleanup(tmp);
4224                         rte_free(tmp);
4225                 }
4226                 priv->rxqs_n = 0;
4227                 priv->rxqs = NULL;
4228         }
4229         if (priv->txqs != NULL) {
4230                 /* XXX race condition if mlx4_tx_burst() is still running. */
4231                 usleep(1000);
4232                 for (i = 0; (i != priv->txqs_n); ++i) {
4233                         tmp = (*priv->txqs)[i];
4234                         if (tmp == NULL)
4235                                 continue;
4236                         (*priv->txqs)[i] = NULL;
4237                         txq_cleanup(tmp);
4238                         rte_free(tmp);
4239                 }
4240                 priv->txqs_n = 0;
4241                 priv->txqs = NULL;
4242         }
4243         if (priv->rss)
4244                 rxq_cleanup(&priv->rxq_parent);
4245         if (priv->pd != NULL) {
4246                 assert(priv->ctx != NULL);
4247                 claim_zero(ibv_dealloc_pd(priv->pd));
4248                 claim_zero(ibv_close_device(priv->ctx));
4249         } else
4250                 assert(priv->ctx == NULL);
4251         priv_dev_interrupt_handler_uninstall(priv, dev);
4252         priv_unlock(priv);
4253         memset(priv, 0, sizeof(*priv));
4254 }
4255
4256 /**
4257  * DPDK callback to get information about the device.
4258  *
4259  * @param dev
4260  *   Pointer to Ethernet device structure.
4261  * @param[out] info
4262  *   Info structure output buffer.
4263  */
4264 static void
4265 mlx4_dev_infos_get(struct rte_eth_dev *dev, struct rte_eth_dev_info *info)
4266 {
4267         struct priv *priv = mlx4_get_priv(dev);
4268         unsigned int max;
4269         char ifname[IF_NAMESIZE];
4270
4271         if (priv == NULL)
4272                 return;
4273         priv_lock(priv);
4274         /* FIXME: we should ask the device for these values. */
4275         info->min_rx_bufsize = 32;
4276         info->max_rx_pktlen = 65536;
4277         /*
4278          * Since we need one CQ per QP, the limit is the minimum number
4279          * between the two values.
4280          */
4281         max = ((priv->device_attr.max_cq > priv->device_attr.max_qp) ?
4282                priv->device_attr.max_qp : priv->device_attr.max_cq);
4283         /* If max >= 65535 then max = 0, max_rx_queues is uint16_t. */
4284         if (max >= 65535)
4285                 max = 65535;
4286         info->max_rx_queues = max;
4287         info->max_tx_queues = max;
4288         /* Last array entry is reserved for broadcast. */
4289         info->max_mac_addrs = (elemof(priv->mac) - 1);
4290         info->rx_offload_capa =
4291                 (priv->hw_csum ?
4292                  (DEV_RX_OFFLOAD_IPV4_CKSUM |
4293                   DEV_RX_OFFLOAD_UDP_CKSUM |
4294                   DEV_RX_OFFLOAD_TCP_CKSUM) :
4295                  0);
4296         info->tx_offload_capa =
4297                 (priv->hw_csum ?
4298                  (DEV_TX_OFFLOAD_IPV4_CKSUM |
4299                   DEV_TX_OFFLOAD_UDP_CKSUM |
4300                   DEV_TX_OFFLOAD_TCP_CKSUM) :
4301                  0);
4302         if (priv_get_ifname(priv, &ifname) == 0)
4303                 info->if_index = if_nametoindex(ifname);
4304         priv_unlock(priv);
4305 }
4306
4307 /**
4308  * DPDK callback to get device statistics.
4309  *
4310  * @param dev
4311  *   Pointer to Ethernet device structure.
4312  * @param[out] stats
4313  *   Stats structure output buffer.
4314  */
4315 static void
4316 mlx4_stats_get(struct rte_eth_dev *dev, struct rte_eth_stats *stats)
4317 {
4318         struct priv *priv = mlx4_get_priv(dev);
4319         struct rte_eth_stats tmp = {0};
4320         unsigned int i;
4321         unsigned int idx;
4322
4323         if (priv == NULL)
4324                 return;
4325         priv_lock(priv);
4326         /* Add software counters. */
4327         for (i = 0; (i != priv->rxqs_n); ++i) {
4328                 struct rxq *rxq = (*priv->rxqs)[i];
4329
4330                 if (rxq == NULL)
4331                         continue;
4332                 idx = rxq->stats.idx;
4333                 if (idx < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
4334 #ifdef MLX4_PMD_SOFT_COUNTERS
4335                         tmp.q_ipackets[idx] += rxq->stats.ipackets;
4336                         tmp.q_ibytes[idx] += rxq->stats.ibytes;
4337 #endif
4338                         tmp.q_errors[idx] += (rxq->stats.idropped +
4339                                               rxq->stats.rx_nombuf);
4340                 }
4341 #ifdef MLX4_PMD_SOFT_COUNTERS
4342                 tmp.ipackets += rxq->stats.ipackets;
4343                 tmp.ibytes += rxq->stats.ibytes;
4344 #endif
4345                 tmp.ierrors += rxq->stats.idropped;
4346                 tmp.rx_nombuf += rxq->stats.rx_nombuf;
4347         }
4348         for (i = 0; (i != priv->txqs_n); ++i) {
4349                 struct txq *txq = (*priv->txqs)[i];
4350
4351                 if (txq == NULL)
4352                         continue;
4353                 idx = txq->stats.idx;
4354                 if (idx < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
4355 #ifdef MLX4_PMD_SOFT_COUNTERS
4356                         tmp.q_opackets[idx] += txq->stats.opackets;
4357                         tmp.q_obytes[idx] += txq->stats.obytes;
4358 #endif
4359                         tmp.q_errors[idx] += txq->stats.odropped;
4360                 }
4361 #ifdef MLX4_PMD_SOFT_COUNTERS
4362                 tmp.opackets += txq->stats.opackets;
4363                 tmp.obytes += txq->stats.obytes;
4364 #endif
4365                 tmp.oerrors += txq->stats.odropped;
4366         }
4367 #ifndef MLX4_PMD_SOFT_COUNTERS
4368         /* FIXME: retrieve and add hardware counters. */
4369 #endif
4370         *stats = tmp;
4371         priv_unlock(priv);
4372 }
4373
4374 /**
4375  * DPDK callback to clear device statistics.
4376  *
4377  * @param dev
4378  *   Pointer to Ethernet device structure.
4379  */
4380 static void
4381 mlx4_stats_reset(struct rte_eth_dev *dev)
4382 {
4383         struct priv *priv = mlx4_get_priv(dev);
4384         unsigned int i;
4385         unsigned int idx;
4386
4387         if (priv == NULL)
4388                 return;
4389         priv_lock(priv);
4390         for (i = 0; (i != priv->rxqs_n); ++i) {
4391                 if ((*priv->rxqs)[i] == NULL)
4392                         continue;
4393                 idx = (*priv->rxqs)[i]->stats.idx;
4394                 (*priv->rxqs)[i]->stats =
4395                         (struct mlx4_rxq_stats){ .idx = idx };
4396         }
4397         for (i = 0; (i != priv->txqs_n); ++i) {
4398                 if ((*priv->txqs)[i] == NULL)
4399                         continue;
4400                 idx = (*priv->txqs)[i]->stats.idx;
4401                 (*priv->txqs)[i]->stats =
4402                         (struct mlx4_txq_stats){ .idx = idx };
4403         }
4404 #ifndef MLX4_PMD_SOFT_COUNTERS
4405         /* FIXME: reset hardware counters. */
4406 #endif
4407         priv_unlock(priv);
4408 }
4409
4410 /**
4411  * DPDK callback to remove a MAC address.
4412  *
4413  * @param dev
4414  *   Pointer to Ethernet device structure.
4415  * @param index
4416  *   MAC address index.
4417  */
4418 static void
4419 mlx4_mac_addr_remove(struct rte_eth_dev *dev, uint32_t index)
4420 {
4421         struct priv *priv = dev->data->dev_private;
4422
4423         if (mlx4_is_secondary())
4424                 return;
4425         priv_lock(priv);
4426         DEBUG("%p: removing MAC address from index %" PRIu32,
4427               (void *)dev, index);
4428         /* Last array entry is reserved for broadcast. */
4429         if (index >= (elemof(priv->mac) - 1))
4430                 goto end;
4431         priv_mac_addr_del(priv, index);
4432 end:
4433         priv_unlock(priv);
4434 }
4435
4436 /**
4437  * DPDK callback to add a MAC address.
4438  *
4439  * @param dev
4440  *   Pointer to Ethernet device structure.
4441  * @param mac_addr
4442  *   MAC address to register.
4443  * @param index
4444  *   MAC address index.
4445  * @param vmdq
4446  *   VMDq pool index to associate address with (ignored).
4447  */
4448 static void
4449 mlx4_mac_addr_add(struct rte_eth_dev *dev, struct ether_addr *mac_addr,
4450                   uint32_t index, uint32_t vmdq)
4451 {
4452         struct priv *priv = dev->data->dev_private;
4453
4454         if (mlx4_is_secondary())
4455                 return;
4456         (void)vmdq;
4457         priv_lock(priv);
4458         DEBUG("%p: adding MAC address at index %" PRIu32,
4459               (void *)dev, index);
4460         /* Last array entry is reserved for broadcast. */
4461         if (index >= (elemof(priv->mac) - 1))
4462                 goto end;
4463         priv_mac_addr_add(priv, index,
4464                           (const uint8_t (*)[ETHER_ADDR_LEN])
4465                           mac_addr->addr_bytes);
4466 end:
4467         priv_unlock(priv);
4468 }
4469
4470 /**
4471  * DPDK callback to set the primary MAC address.
4472  *
4473  * @param dev
4474  *   Pointer to Ethernet device structure.
4475  * @param mac_addr
4476  *   MAC address to register.
4477  */
4478 static void
4479 mlx4_mac_addr_set(struct rte_eth_dev *dev, struct ether_addr *mac_addr)
4480 {
4481         DEBUG("%p: setting primary MAC address", (void *)dev);
4482         mlx4_mac_addr_remove(dev, 0);
4483         mlx4_mac_addr_add(dev, mac_addr, 0, 0);
4484 }
4485
4486 /**
4487  * DPDK callback to enable promiscuous mode.
4488  *
4489  * @param dev
4490  *   Pointer to Ethernet device structure.
4491  */
4492 static void
4493 mlx4_promiscuous_enable(struct rte_eth_dev *dev)
4494 {
4495         struct priv *priv = dev->data->dev_private;
4496         unsigned int i;
4497         int ret;
4498
4499         if (mlx4_is_secondary())
4500                 return;
4501         priv_lock(priv);
4502         if (priv->promisc) {
4503                 priv_unlock(priv);
4504                 return;
4505         }
4506         /* If device isn't started, this is all we need to do. */
4507         if (!priv->started)
4508                 goto end;
4509         if (priv->rss) {
4510                 ret = rxq_promiscuous_enable(&priv->rxq_parent);
4511                 if (ret) {
4512                         priv_unlock(priv);
4513                         return;
4514                 }
4515                 goto end;
4516         }
4517         for (i = 0; (i != priv->rxqs_n); ++i) {
4518                 if ((*priv->rxqs)[i] == NULL)
4519                         continue;
4520                 ret = rxq_promiscuous_enable((*priv->rxqs)[i]);
4521                 if (!ret)
4522                         continue;
4523                 /* Failure, rollback. */
4524                 while (i != 0)
4525                         if ((*priv->rxqs)[--i] != NULL)
4526                                 rxq_promiscuous_disable((*priv->rxqs)[i]);
4527                 priv_unlock(priv);
4528                 return;
4529         }
4530 end:
4531         priv->promisc = 1;
4532         priv_unlock(priv);
4533 }
4534
4535 /**
4536  * DPDK callback to disable promiscuous mode.
4537  *
4538  * @param dev
4539  *   Pointer to Ethernet device structure.
4540  */
4541 static void
4542 mlx4_promiscuous_disable(struct rte_eth_dev *dev)
4543 {
4544         struct priv *priv = dev->data->dev_private;
4545         unsigned int i;
4546
4547         if (mlx4_is_secondary())
4548                 return;
4549         priv_lock(priv);
4550         if (!priv->promisc) {
4551                 priv_unlock(priv);
4552                 return;
4553         }
4554         if (priv->rss) {
4555                 rxq_promiscuous_disable(&priv->rxq_parent);
4556                 goto end;
4557         }
4558         for (i = 0; (i != priv->rxqs_n); ++i)
4559                 if ((*priv->rxqs)[i] != NULL)
4560                         rxq_promiscuous_disable((*priv->rxqs)[i]);
4561 end:
4562         priv->promisc = 0;
4563         priv_unlock(priv);
4564 }
4565
4566 /**
4567  * DPDK callback to enable allmulti mode.
4568  *
4569  * @param dev
4570  *   Pointer to Ethernet device structure.
4571  */
4572 static void
4573 mlx4_allmulticast_enable(struct rte_eth_dev *dev)
4574 {
4575         struct priv *priv = dev->data->dev_private;
4576         unsigned int i;
4577         int ret;
4578
4579         if (mlx4_is_secondary())
4580                 return;
4581         priv_lock(priv);
4582         if (priv->allmulti) {
4583                 priv_unlock(priv);
4584                 return;
4585         }
4586         /* If device isn't started, this is all we need to do. */
4587         if (!priv->started)
4588                 goto end;
4589         if (priv->rss) {
4590                 ret = rxq_allmulticast_enable(&priv->rxq_parent);
4591                 if (ret) {
4592                         priv_unlock(priv);
4593                         return;
4594                 }
4595                 goto end;
4596         }
4597         for (i = 0; (i != priv->rxqs_n); ++i) {
4598                 if ((*priv->rxqs)[i] == NULL)
4599                         continue;
4600                 ret = rxq_allmulticast_enable((*priv->rxqs)[i]);
4601                 if (!ret)
4602                         continue;
4603                 /* Failure, rollback. */
4604                 while (i != 0)
4605                         if ((*priv->rxqs)[--i] != NULL)
4606                                 rxq_allmulticast_disable((*priv->rxqs)[i]);
4607                 priv_unlock(priv);
4608                 return;
4609         }
4610 end:
4611         priv->allmulti = 1;
4612         priv_unlock(priv);
4613 }
4614
4615 /**
4616  * DPDK callback to disable allmulti mode.
4617  *
4618  * @param dev
4619  *   Pointer to Ethernet device structure.
4620  */
4621 static void
4622 mlx4_allmulticast_disable(struct rte_eth_dev *dev)
4623 {
4624         struct priv *priv = dev->data->dev_private;
4625         unsigned int i;
4626
4627         if (mlx4_is_secondary())
4628                 return;
4629         priv_lock(priv);
4630         if (!priv->allmulti) {
4631                 priv_unlock(priv);
4632                 return;
4633         }
4634         if (priv->rss) {
4635                 rxq_allmulticast_disable(&priv->rxq_parent);
4636                 goto end;
4637         }
4638         for (i = 0; (i != priv->rxqs_n); ++i)
4639                 if ((*priv->rxqs)[i] != NULL)
4640                         rxq_allmulticast_disable((*priv->rxqs)[i]);
4641 end:
4642         priv->allmulti = 0;
4643         priv_unlock(priv);
4644 }
4645
4646 /**
4647  * DPDK callback to retrieve physical link information (unlocked version).
4648  *
4649  * @param dev
4650  *   Pointer to Ethernet device structure.
4651  * @param wait_to_complete
4652  *   Wait for request completion (ignored).
4653  */
4654 static int
4655 mlx4_link_update_unlocked(struct rte_eth_dev *dev, int wait_to_complete)
4656 {
4657         struct priv *priv = mlx4_get_priv(dev);
4658         struct ethtool_cmd edata = {
4659                 .cmd = ETHTOOL_GSET
4660         };
4661         struct ifreq ifr;
4662         struct rte_eth_link dev_link;
4663         int link_speed = 0;
4664
4665         if (priv == NULL)
4666                 return -EINVAL;
4667         (void)wait_to_complete;
4668         if (priv_ifreq(priv, SIOCGIFFLAGS, &ifr)) {
4669                 WARN("ioctl(SIOCGIFFLAGS) failed: %s", strerror(errno));
4670                 return -1;
4671         }
4672         memset(&dev_link, 0, sizeof(dev_link));
4673         dev_link.link_status = ((ifr.ifr_flags & IFF_UP) &&
4674                                 (ifr.ifr_flags & IFF_RUNNING));
4675         ifr.ifr_data = &edata;
4676         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
4677                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_GSET) failed: %s",
4678                      strerror(errno));
4679                 return -1;
4680         }
4681         link_speed = ethtool_cmd_speed(&edata);
4682         if (link_speed == -1)
4683                 dev_link.link_speed = 0;
4684         else
4685                 dev_link.link_speed = link_speed;
4686         dev_link.link_duplex = ((edata.duplex == DUPLEX_HALF) ?
4687                                 ETH_LINK_HALF_DUPLEX : ETH_LINK_FULL_DUPLEX);
4688         if (memcmp(&dev_link, &dev->data->dev_link, sizeof(dev_link))) {
4689                 /* Link status changed. */
4690                 dev->data->dev_link = dev_link;
4691                 return 0;
4692         }
4693         /* Link status is still the same. */
4694         return -1;
4695 }
4696
4697 /**
4698  * DPDK callback to retrieve physical link information.
4699  *
4700  * @param dev
4701  *   Pointer to Ethernet device structure.
4702  * @param wait_to_complete
4703  *   Wait for request completion (ignored).
4704  */
4705 static int
4706 mlx4_link_update(struct rte_eth_dev *dev, int wait_to_complete)
4707 {
4708         struct priv *priv = mlx4_get_priv(dev);
4709         int ret;
4710
4711         if (priv == NULL)
4712                 return -EINVAL;
4713         priv_lock(priv);
4714         ret = mlx4_link_update_unlocked(dev, wait_to_complete);
4715         priv_unlock(priv);
4716         return ret;
4717 }
4718
4719 /**
4720  * DPDK callback to change the MTU.
4721  *
4722  * Setting the MTU affects hardware MRU (packets larger than the MTU cannot be
4723  * received). Use this as a hint to enable/disable scattered packets support
4724  * and improve performance when not needed.
4725  * Since failure is not an option, reconfiguring queues on the fly is not
4726  * recommended.
4727  *
4728  * @param dev
4729  *   Pointer to Ethernet device structure.
4730  * @param in_mtu
4731  *   New MTU.
4732  *
4733  * @return
4734  *   0 on success, negative errno value on failure.
4735  */
4736 static int
4737 mlx4_dev_set_mtu(struct rte_eth_dev *dev, uint16_t mtu)
4738 {
4739         struct priv *priv = dev->data->dev_private;
4740         int ret = 0;
4741         unsigned int i;
4742         uint16_t (*rx_func)(void *, struct rte_mbuf **, uint16_t) =
4743                 mlx4_rx_burst;
4744
4745         if (mlx4_is_secondary())
4746                 return -E_RTE_SECONDARY;
4747         priv_lock(priv);
4748         /* Set kernel interface MTU first. */
4749         if (priv_set_mtu(priv, mtu)) {
4750                 ret = errno;
4751                 WARN("cannot set port %u MTU to %u: %s", priv->port, mtu,
4752                      strerror(ret));
4753                 goto out;
4754         } else
4755                 DEBUG("adapter port %u MTU set to %u", priv->port, mtu);
4756         priv->mtu = mtu;
4757         /* Temporarily replace RX handler with a fake one, assuming it has not
4758          * been copied elsewhere. */
4759         dev->rx_pkt_burst = removed_rx_burst;
4760         /* Make sure everyone has left mlx4_rx_burst() and uses
4761          * removed_rx_burst() instead. */
4762         rte_wmb();
4763         usleep(1000);
4764         /* Reconfigure each RX queue. */
4765         for (i = 0; (i != priv->rxqs_n); ++i) {
4766                 struct rxq *rxq = (*priv->rxqs)[i];
4767                 unsigned int max_frame_len;
4768                 int sp;
4769
4770                 if (rxq == NULL)
4771                         continue;
4772                 /* Calculate new maximum frame length according to MTU and
4773                  * toggle scattered support (sp) if necessary. */
4774                 max_frame_len = (priv->mtu + ETHER_HDR_LEN +
4775                                  (ETHER_MAX_VLAN_FRAME_LEN - ETHER_MAX_LEN));
4776                 sp = (max_frame_len > (rxq->mb_len - RTE_PKTMBUF_HEADROOM));
4777                 /* Provide new values to rxq_setup(). */
4778                 dev->data->dev_conf.rxmode.jumbo_frame = sp;
4779                 dev->data->dev_conf.rxmode.max_rx_pkt_len = max_frame_len;
4780                 ret = rxq_rehash(dev, rxq);
4781                 if (ret) {
4782                         /* Force SP RX if that queue requires it and abort. */
4783                         if (rxq->sp)
4784                                 rx_func = mlx4_rx_burst_sp;
4785                         break;
4786                 }
4787                 /* Reenable non-RSS queue attributes. No need to check
4788                  * for errors at this stage. */
4789                 if (!priv->rss) {
4790                         rxq_mac_addrs_add(rxq);
4791                         if (priv->promisc)
4792                                 rxq_promiscuous_enable(rxq);
4793                         if (priv->allmulti)
4794                                 rxq_allmulticast_enable(rxq);
4795                 }
4796                 /* Scattered burst function takes priority. */
4797                 if (rxq->sp)
4798                         rx_func = mlx4_rx_burst_sp;
4799         }
4800         /* Burst functions can now be called again. */
4801         rte_wmb();
4802         dev->rx_pkt_burst = rx_func;
4803 out:
4804         priv_unlock(priv);
4805         assert(ret >= 0);
4806         return -ret;
4807 }
4808
4809 /**
4810  * DPDK callback to get flow control status.
4811  *
4812  * @param dev
4813  *   Pointer to Ethernet device structure.
4814  * @param[out] fc_conf
4815  *   Flow control output buffer.
4816  *
4817  * @return
4818  *   0 on success, negative errno value on failure.
4819  */
4820 static int
4821 mlx4_dev_get_flow_ctrl(struct rte_eth_dev *dev, struct rte_eth_fc_conf *fc_conf)
4822 {
4823         struct priv *priv = dev->data->dev_private;
4824         struct ifreq ifr;
4825         struct ethtool_pauseparam ethpause = {
4826                 .cmd = ETHTOOL_GPAUSEPARAM
4827         };
4828         int ret;
4829
4830         if (mlx4_is_secondary())
4831                 return -E_RTE_SECONDARY;
4832         ifr.ifr_data = &ethpause;
4833         priv_lock(priv);
4834         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
4835                 ret = errno;
4836                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_GPAUSEPARAM)"
4837                      " failed: %s",
4838                      strerror(ret));
4839                 goto out;
4840         }
4841
4842         fc_conf->autoneg = ethpause.autoneg;
4843         if (ethpause.rx_pause && ethpause.tx_pause)
4844                 fc_conf->mode = RTE_FC_FULL;
4845         else if (ethpause.rx_pause)
4846                 fc_conf->mode = RTE_FC_RX_PAUSE;
4847         else if (ethpause.tx_pause)
4848                 fc_conf->mode = RTE_FC_TX_PAUSE;
4849         else
4850                 fc_conf->mode = RTE_FC_NONE;
4851         ret = 0;
4852
4853 out:
4854         priv_unlock(priv);
4855         assert(ret >= 0);
4856         return -ret;
4857 }
4858
4859 /**
4860  * DPDK callback to modify flow control parameters.
4861  *
4862  * @param dev
4863  *   Pointer to Ethernet device structure.
4864  * @param[in] fc_conf
4865  *   Flow control parameters.
4866  *
4867  * @return
4868  *   0 on success, negative errno value on failure.
4869  */
4870 static int
4871 mlx4_dev_set_flow_ctrl(struct rte_eth_dev *dev, struct rte_eth_fc_conf *fc_conf)
4872 {
4873         struct priv *priv = dev->data->dev_private;
4874         struct ifreq ifr;
4875         struct ethtool_pauseparam ethpause = {
4876                 .cmd = ETHTOOL_SPAUSEPARAM
4877         };
4878         int ret;
4879
4880         if (mlx4_is_secondary())
4881                 return -E_RTE_SECONDARY;
4882         ifr.ifr_data = &ethpause;
4883         ethpause.autoneg = fc_conf->autoneg;
4884         if (((fc_conf->mode & RTE_FC_FULL) == RTE_FC_FULL) ||
4885             (fc_conf->mode & RTE_FC_RX_PAUSE))
4886                 ethpause.rx_pause = 1;
4887         else
4888                 ethpause.rx_pause = 0;
4889
4890         if (((fc_conf->mode & RTE_FC_FULL) == RTE_FC_FULL) ||
4891             (fc_conf->mode & RTE_FC_TX_PAUSE))
4892                 ethpause.tx_pause = 1;
4893         else
4894                 ethpause.tx_pause = 0;
4895
4896         priv_lock(priv);
4897         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
4898                 ret = errno;
4899                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_SPAUSEPARAM)"
4900                      " failed: %s",
4901                      strerror(ret));
4902                 goto out;
4903         }
4904         ret = 0;
4905
4906 out:
4907         priv_unlock(priv);
4908         assert(ret >= 0);
4909         return -ret;
4910 }
4911
4912 /**
4913  * Configure a VLAN filter.
4914  *
4915  * @param dev
4916  *   Pointer to Ethernet device structure.
4917  * @param vlan_id
4918  *   VLAN ID to filter.
4919  * @param on
4920  *   Toggle filter.
4921  *
4922  * @return
4923  *   0 on success, errno value on failure.
4924  */
4925 static int
4926 vlan_filter_set(struct rte_eth_dev *dev, uint16_t vlan_id, int on)
4927 {
4928         struct priv *priv = dev->data->dev_private;
4929         unsigned int i;
4930         unsigned int j = -1;
4931
4932         DEBUG("%p: %s VLAN filter ID %" PRIu16,
4933               (void *)dev, (on ? "enable" : "disable"), vlan_id);
4934         for (i = 0; (i != elemof(priv->vlan_filter)); ++i) {
4935                 if (!priv->vlan_filter[i].enabled) {
4936                         /* Unused index, remember it. */
4937                         j = i;
4938                         continue;
4939                 }
4940                 if (priv->vlan_filter[i].id != vlan_id)
4941                         continue;
4942                 /* This VLAN ID is already known, use its index. */
4943                 j = i;
4944                 break;
4945         }
4946         /* Check if there's room for another VLAN filter. */
4947         if (j == (unsigned int)-1)
4948                 return ENOMEM;
4949         /*
4950          * VLAN filters apply to all configured MAC addresses, flow
4951          * specifications must be reconfigured accordingly.
4952          */
4953         priv->vlan_filter[j].id = vlan_id;
4954         if ((on) && (!priv->vlan_filter[j].enabled)) {
4955                 /*
4956                  * Filter is disabled, enable it.
4957                  * Rehashing flows in all RX queues is necessary.
4958                  */
4959                 if (priv->rss)
4960                         rxq_mac_addrs_del(&priv->rxq_parent);
4961                 else
4962                         for (i = 0; (i != priv->rxqs_n); ++i)
4963                                 if ((*priv->rxqs)[i] != NULL)
4964                                         rxq_mac_addrs_del((*priv->rxqs)[i]);
4965                 priv->vlan_filter[j].enabled = 1;
4966                 if (priv->started) {
4967                         if (priv->rss)
4968                                 rxq_mac_addrs_add(&priv->rxq_parent);
4969                         else
4970                                 for (i = 0; (i != priv->rxqs_n); ++i) {
4971                                         if ((*priv->rxqs)[i] == NULL)
4972                                                 continue;
4973                                         rxq_mac_addrs_add((*priv->rxqs)[i]);
4974                                 }
4975                 }
4976         } else if ((!on) && (priv->vlan_filter[j].enabled)) {
4977                 /*
4978                  * Filter is enabled, disable it.
4979                  * Rehashing flows in all RX queues is necessary.
4980                  */
4981                 if (priv->rss)
4982                         rxq_mac_addrs_del(&priv->rxq_parent);
4983                 else
4984                         for (i = 0; (i != priv->rxqs_n); ++i)
4985                                 if ((*priv->rxqs)[i] != NULL)
4986                                         rxq_mac_addrs_del((*priv->rxqs)[i]);
4987                 priv->vlan_filter[j].enabled = 0;
4988                 if (priv->started) {
4989                         if (priv->rss)
4990                                 rxq_mac_addrs_add(&priv->rxq_parent);
4991                         else
4992                                 for (i = 0; (i != priv->rxqs_n); ++i) {
4993                                         if ((*priv->rxqs)[i] == NULL)
4994                                                 continue;
4995                                         rxq_mac_addrs_add((*priv->rxqs)[i]);
4996                                 }
4997                 }
4998         }
4999         return 0;
5000 }
5001
5002 /**
5003  * DPDK callback to configure a VLAN filter.
5004  *
5005  * @param dev
5006  *   Pointer to Ethernet device structure.
5007  * @param vlan_id
5008  *   VLAN ID to filter.
5009  * @param on
5010  *   Toggle filter.
5011  *
5012  * @return
5013  *   0 on success, negative errno value on failure.
5014  */
5015 static int
5016 mlx4_vlan_filter_set(struct rte_eth_dev *dev, uint16_t vlan_id, int on)
5017 {
5018         struct priv *priv = dev->data->dev_private;
5019         int ret;
5020
5021         if (mlx4_is_secondary())
5022                 return -E_RTE_SECONDARY;
5023         priv_lock(priv);
5024         ret = vlan_filter_set(dev, vlan_id, on);
5025         priv_unlock(priv);
5026         assert(ret >= 0);
5027         return -ret;
5028 }
5029
5030 static const struct eth_dev_ops mlx4_dev_ops = {
5031         .dev_configure = mlx4_dev_configure,
5032         .dev_start = mlx4_dev_start,
5033         .dev_stop = mlx4_dev_stop,
5034         .dev_close = mlx4_dev_close,
5035         .promiscuous_enable = mlx4_promiscuous_enable,
5036         .promiscuous_disable = mlx4_promiscuous_disable,
5037         .allmulticast_enable = mlx4_allmulticast_enable,
5038         .allmulticast_disable = mlx4_allmulticast_disable,
5039         .link_update = mlx4_link_update,
5040         .stats_get = mlx4_stats_get,
5041         .stats_reset = mlx4_stats_reset,
5042         .queue_stats_mapping_set = NULL,
5043         .dev_infos_get = mlx4_dev_infos_get,
5044         .vlan_filter_set = mlx4_vlan_filter_set,
5045         .vlan_tpid_set = NULL,
5046         .vlan_strip_queue_set = NULL,
5047         .vlan_offload_set = NULL,
5048         .rx_queue_setup = mlx4_rx_queue_setup,
5049         .tx_queue_setup = mlx4_tx_queue_setup,
5050         .rx_queue_release = mlx4_rx_queue_release,
5051         .tx_queue_release = mlx4_tx_queue_release,
5052         .dev_led_on = NULL,
5053         .dev_led_off = NULL,
5054         .flow_ctrl_get = mlx4_dev_get_flow_ctrl,
5055         .flow_ctrl_set = mlx4_dev_set_flow_ctrl,
5056         .priority_flow_ctrl_set = NULL,
5057         .mac_addr_remove = mlx4_mac_addr_remove,
5058         .mac_addr_add = mlx4_mac_addr_add,
5059         .mac_addr_set = mlx4_mac_addr_set,
5060         .mtu_set = mlx4_dev_set_mtu,
5061 };
5062
5063 /**
5064  * Get PCI information from struct ibv_device.
5065  *
5066  * @param device
5067  *   Pointer to Ethernet device structure.
5068  * @param[out] pci_addr
5069  *   PCI bus address output buffer.
5070  *
5071  * @return
5072  *   0 on success, -1 on failure and errno is set.
5073  */
5074 static int
5075 mlx4_ibv_device_to_pci_addr(const struct ibv_device *device,
5076                             struct rte_pci_addr *pci_addr)
5077 {
5078         FILE *file;
5079         char line[32];
5080         MKSTR(path, "%s/device/uevent", device->ibdev_path);
5081
5082         file = fopen(path, "rb");
5083         if (file == NULL)
5084                 return -1;
5085         while (fgets(line, sizeof(line), file) == line) {
5086                 size_t len = strlen(line);
5087                 int ret;
5088
5089                 /* Truncate long lines. */
5090                 if (len == (sizeof(line) - 1))
5091                         while (line[(len - 1)] != '\n') {
5092                                 ret = fgetc(file);
5093                                 if (ret == EOF)
5094                                         break;
5095                                 line[(len - 1)] = ret;
5096                         }
5097                 /* Extract information. */
5098                 if (sscanf(line,
5099                            "PCI_SLOT_NAME="
5100                            "%" SCNx16 ":%" SCNx8 ":%" SCNx8 ".%" SCNx8 "\n",
5101                            &pci_addr->domain,
5102                            &pci_addr->bus,
5103                            &pci_addr->devid,
5104                            &pci_addr->function) == 4) {
5105                         ret = 0;
5106                         break;
5107                 }
5108         }
5109         fclose(file);
5110         return 0;
5111 }
5112
5113 /**
5114  * Get MAC address by querying netdevice.
5115  *
5116  * @param[in] priv
5117  *   struct priv for the requested device.
5118  * @param[out] mac
5119  *   MAC address output buffer.
5120  *
5121  * @return
5122  *   0 on success, -1 on failure and errno is set.
5123  */
5124 static int
5125 priv_get_mac(struct priv *priv, uint8_t (*mac)[ETHER_ADDR_LEN])
5126 {
5127         struct ifreq request;
5128
5129         if (priv_ifreq(priv, SIOCGIFHWADDR, &request))
5130                 return -1;
5131         memcpy(mac, request.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
5132         return 0;
5133 }
5134
5135 /* Support up to 32 adapters. */
5136 static struct {
5137         struct rte_pci_addr pci_addr; /* associated PCI address */
5138         uint32_t ports; /* physical ports bitfield. */
5139 } mlx4_dev[32];
5140
5141 /**
5142  * Get device index in mlx4_dev[] from PCI bus address.
5143  *
5144  * @param[in] pci_addr
5145  *   PCI bus address to look for.
5146  *
5147  * @return
5148  *   mlx4_dev[] index on success, -1 on failure.
5149  */
5150 static int
5151 mlx4_dev_idx(struct rte_pci_addr *pci_addr)
5152 {
5153         unsigned int i;
5154         int ret = -1;
5155
5156         assert(pci_addr != NULL);
5157         for (i = 0; (i != elemof(mlx4_dev)); ++i) {
5158                 if ((mlx4_dev[i].pci_addr.domain == pci_addr->domain) &&
5159                     (mlx4_dev[i].pci_addr.bus == pci_addr->bus) &&
5160                     (mlx4_dev[i].pci_addr.devid == pci_addr->devid) &&
5161                     (mlx4_dev[i].pci_addr.function == pci_addr->function))
5162                         return i;
5163                 if ((mlx4_dev[i].ports == 0) && (ret == -1))
5164                         ret = i;
5165         }
5166         return ret;
5167 }
5168
5169 /**
5170  * Retrieve integer value from environment variable.
5171  *
5172  * @param[in] name
5173  *   Environment variable name.
5174  *
5175  * @return
5176  *   Integer value, 0 if the variable is not set.
5177  */
5178 static int
5179 mlx4_getenv_int(const char *name)
5180 {
5181         const char *val = getenv(name);
5182
5183         if (val == NULL)
5184                 return 0;
5185         return atoi(val);
5186 }
5187
5188 static void
5189 mlx4_dev_link_status_handler(void *);
5190 static void
5191 mlx4_dev_interrupt_handler(struct rte_intr_handle *, void *);
5192
5193 /**
5194  * Link status handler.
5195  *
5196  * @param priv
5197  *   Pointer to private structure.
5198  * @param dev
5199  *   Pointer to the rte_eth_dev structure.
5200  *
5201  * @return
5202  *   Nonzero if the callback process can be called immediately.
5203  */
5204 static int
5205 priv_dev_link_status_handler(struct priv *priv, struct rte_eth_dev *dev)
5206 {
5207         struct ibv_async_event event;
5208         int port_change = 0;
5209         int ret = 0;
5210
5211         /* Read all message and acknowledge them. */
5212         for (;;) {
5213                 if (ibv_get_async_event(priv->ctx, &event))
5214                         break;
5215
5216                 if (event.event_type == IBV_EVENT_PORT_ACTIVE ||
5217                     event.event_type == IBV_EVENT_PORT_ERR)
5218                         port_change = 1;
5219                 else
5220                         DEBUG("event type %d on port %d not handled",
5221                               event.event_type, event.element.port_num);
5222                 ibv_ack_async_event(&event);
5223         }
5224
5225         if (port_change ^ priv->pending_alarm) {
5226                 struct rte_eth_link *link = &dev->data->dev_link;
5227
5228                 priv->pending_alarm = 0;
5229                 mlx4_link_update_unlocked(dev, 0);
5230                 if (((link->link_speed == 0) && link->link_status) ||
5231                     ((link->link_speed != 0) && !link->link_status)) {
5232                         /* Inconsistent status, check again later. */
5233                         priv->pending_alarm = 1;
5234                         rte_eal_alarm_set(MLX4_ALARM_TIMEOUT_US,
5235                                           mlx4_dev_link_status_handler,
5236                                           dev);
5237                 } else
5238                         ret = 1;
5239         }
5240         return ret;
5241 }
5242
5243 /**
5244  * Handle delayed link status event.
5245  *
5246  * @param arg
5247  *   Registered argument.
5248  */
5249 static void
5250 mlx4_dev_link_status_handler(void *arg)
5251 {
5252         struct rte_eth_dev *dev = arg;
5253         struct priv *priv = dev->data->dev_private;
5254         int ret;
5255
5256         priv_lock(priv);
5257         assert(priv->pending_alarm == 1);
5258         ret = priv_dev_link_status_handler(priv, dev);
5259         priv_unlock(priv);
5260         if (ret)
5261                 _rte_eth_dev_callback_process(dev, RTE_ETH_EVENT_INTR_LSC);
5262 }
5263
5264 /**
5265  * Handle interrupts from the NIC.
5266  *
5267  * @param[in] intr_handle
5268  *   Interrupt handler.
5269  * @param cb_arg
5270  *   Callback argument.
5271  */
5272 static void
5273 mlx4_dev_interrupt_handler(struct rte_intr_handle *intr_handle, void *cb_arg)
5274 {
5275         struct rte_eth_dev *dev = cb_arg;
5276         struct priv *priv = dev->data->dev_private;
5277         int ret;
5278
5279         (void)intr_handle;
5280         priv_lock(priv);
5281         ret = priv_dev_link_status_handler(priv, dev);
5282         priv_unlock(priv);
5283         if (ret)
5284                 _rte_eth_dev_callback_process(dev, RTE_ETH_EVENT_INTR_LSC);
5285 }
5286
5287 /**
5288  * Uninstall interrupt handler.
5289  *
5290  * @param priv
5291  *   Pointer to private structure.
5292  * @param dev
5293  *   Pointer to the rte_eth_dev structure.
5294  */
5295 static void
5296 priv_dev_interrupt_handler_uninstall(struct priv *priv, struct rte_eth_dev *dev)
5297 {
5298         if (!dev->data->dev_conf.intr_conf.lsc)
5299                 return;
5300         rte_intr_callback_unregister(&priv->intr_handle,
5301                                      mlx4_dev_interrupt_handler,
5302                                      dev);
5303         if (priv->pending_alarm)
5304                 rte_eal_alarm_cancel(mlx4_dev_link_status_handler, dev);
5305         priv->pending_alarm = 0;
5306         priv->intr_handle.fd = 0;
5307         priv->intr_handle.type = 0;
5308 }
5309
5310 /**
5311  * Install interrupt handler.
5312  *
5313  * @param priv
5314  *   Pointer to private structure.
5315  * @param dev
5316  *   Pointer to the rte_eth_dev structure.
5317  */
5318 static void
5319 priv_dev_interrupt_handler_install(struct priv *priv, struct rte_eth_dev *dev)
5320 {
5321         int rc, flags;
5322
5323         if (!dev->data->dev_conf.intr_conf.lsc)
5324                 return;
5325         assert(priv->ctx->async_fd > 0);
5326         flags = fcntl(priv->ctx->async_fd, F_GETFL);
5327         rc = fcntl(priv->ctx->async_fd, F_SETFL, flags | O_NONBLOCK);
5328         if (rc < 0) {
5329                 INFO("failed to change file descriptor async event queue");
5330                 dev->data->dev_conf.intr_conf.lsc = 0;
5331         } else {
5332                 priv->intr_handle.fd = priv->ctx->async_fd;
5333                 priv->intr_handle.type = RTE_INTR_HANDLE_EXT;
5334                 rte_intr_callback_register(&priv->intr_handle,
5335                                            mlx4_dev_interrupt_handler,
5336                                            dev);
5337         }
5338 }
5339
5340 static struct eth_driver mlx4_driver;
5341
5342 /**
5343  * DPDK callback to register a PCI device.
5344  *
5345  * This function creates an Ethernet device for each port of a given
5346  * PCI device.
5347  *
5348  * @param[in] pci_drv
5349  *   PCI driver structure (mlx4_driver).
5350  * @param[in] pci_dev
5351  *   PCI device information.
5352  *
5353  * @return
5354  *   0 on success, negative errno value on failure.
5355  */
5356 static int
5357 mlx4_pci_devinit(struct rte_pci_driver *pci_drv, struct rte_pci_device *pci_dev)
5358 {
5359         struct ibv_device **list;
5360         struct ibv_device *ibv_dev;
5361         int err = 0;
5362         struct ibv_context *attr_ctx = NULL;
5363         struct ibv_device_attr device_attr;
5364         unsigned int vf;
5365         int idx;
5366         int i;
5367
5368         (void)pci_drv;
5369         assert(pci_drv == &mlx4_driver.pci_drv);
5370         /* Get mlx4_dev[] index. */
5371         idx = mlx4_dev_idx(&pci_dev->addr);
5372         if (idx == -1) {
5373                 ERROR("this driver cannot support any more adapters");
5374                 return -ENOMEM;
5375         }
5376         DEBUG("using driver device index %d", idx);
5377
5378         /* Save PCI address. */
5379         mlx4_dev[idx].pci_addr = pci_dev->addr;
5380         list = ibv_get_device_list(&i);
5381         if (list == NULL) {
5382                 assert(errno);
5383                 if (errno == ENOSYS) {
5384                         WARN("cannot list devices, is ib_uverbs loaded?");
5385                         return 0;
5386                 }
5387                 return -errno;
5388         }
5389         assert(i >= 0);
5390         /*
5391          * For each listed device, check related sysfs entry against
5392          * the provided PCI ID.
5393          */
5394         while (i != 0) {
5395                 struct rte_pci_addr pci_addr;
5396
5397                 --i;
5398                 DEBUG("checking device \"%s\"", list[i]->name);
5399                 if (mlx4_ibv_device_to_pci_addr(list[i], &pci_addr))
5400                         continue;
5401                 if ((pci_dev->addr.domain != pci_addr.domain) ||
5402                     (pci_dev->addr.bus != pci_addr.bus) ||
5403                     (pci_dev->addr.devid != pci_addr.devid) ||
5404                     (pci_dev->addr.function != pci_addr.function))
5405                         continue;
5406                 vf = (pci_dev->id.device_id ==
5407                       PCI_DEVICE_ID_MELLANOX_CONNECTX3VF);
5408                 INFO("PCI information matches, using device \"%s\" (VF: %s)",
5409                      list[i]->name, (vf ? "true" : "false"));
5410                 attr_ctx = ibv_open_device(list[i]);
5411                 err = errno;
5412                 break;
5413         }
5414         if (attr_ctx == NULL) {
5415                 ibv_free_device_list(list);
5416                 switch (err) {
5417                 case 0:
5418                         WARN("cannot access device, is mlx4_ib loaded?");
5419                         return 0;
5420                 case EINVAL:
5421                         WARN("cannot use device, are drivers up to date?");
5422                         return 0;
5423                 }
5424                 assert(err > 0);
5425                 return -err;
5426         }
5427         ibv_dev = list[i];
5428
5429         DEBUG("device opened");
5430         if (ibv_query_device(attr_ctx, &device_attr))
5431                 goto error;
5432         INFO("%u port(s) detected", device_attr.phys_port_cnt);
5433
5434         for (i = 0; i < device_attr.phys_port_cnt; i++) {
5435                 uint32_t port = i + 1; /* ports are indexed from one */
5436                 uint32_t test = (1 << i);
5437                 struct ibv_context *ctx = NULL;
5438                 struct ibv_port_attr port_attr;
5439                 struct ibv_pd *pd = NULL;
5440                 struct priv *priv = NULL;
5441                 struct rte_eth_dev *eth_dev = NULL;
5442 #ifdef HAVE_EXP_QUERY_DEVICE
5443                 struct ibv_exp_device_attr exp_device_attr;
5444 #endif /* HAVE_EXP_QUERY_DEVICE */
5445                 struct ether_addr mac;
5446
5447 #ifdef HAVE_EXP_QUERY_DEVICE
5448                 exp_device_attr.comp_mask = IBV_EXP_DEVICE_ATTR_EXP_CAP_FLAGS;
5449 #ifdef RSS_SUPPORT
5450                 exp_device_attr.comp_mask |= IBV_EXP_DEVICE_ATTR_RSS_TBL_SZ;
5451 #endif /* RSS_SUPPORT */
5452 #endif /* HAVE_EXP_QUERY_DEVICE */
5453
5454                 DEBUG("using port %u (%08" PRIx32 ")", port, test);
5455
5456                 ctx = ibv_open_device(ibv_dev);
5457                 if (ctx == NULL)
5458                         goto port_error;
5459
5460                 /* Check port status. */
5461                 err = ibv_query_port(ctx, port, &port_attr);
5462                 if (err) {
5463                         ERROR("port query failed: %s", strerror(err));
5464                         goto port_error;
5465                 }
5466                 if (port_attr.state != IBV_PORT_ACTIVE)
5467                         DEBUG("port %d is not active: \"%s\" (%d)",
5468                               port, ibv_port_state_str(port_attr.state),
5469                               port_attr.state);
5470
5471                 /* Allocate protection domain. */
5472                 pd = ibv_alloc_pd(ctx);
5473                 if (pd == NULL) {
5474                         ERROR("PD allocation failure");
5475                         err = ENOMEM;
5476                         goto port_error;
5477                 }
5478
5479                 mlx4_dev[idx].ports |= test;
5480
5481                 /* from rte_ethdev.c */
5482                 priv = rte_zmalloc("ethdev private structure",
5483                                    sizeof(*priv),
5484                                    RTE_CACHE_LINE_SIZE);
5485                 if (priv == NULL) {
5486                         ERROR("priv allocation failure");
5487                         err = ENOMEM;
5488                         goto port_error;
5489                 }
5490
5491                 priv->ctx = ctx;
5492                 priv->device_attr = device_attr;
5493                 priv->port = port;
5494                 priv->pd = pd;
5495                 priv->mtu = ETHER_MTU;
5496 #ifdef HAVE_EXP_QUERY_DEVICE
5497                 if (ibv_exp_query_device(ctx, &exp_device_attr)) {
5498                         ERROR("ibv_exp_query_device() failed");
5499                         goto port_error;
5500                 }
5501 #ifdef RSS_SUPPORT
5502                 if ((exp_device_attr.exp_device_cap_flags &
5503                      IBV_EXP_DEVICE_QPG) &&
5504                     (exp_device_attr.exp_device_cap_flags &
5505                      IBV_EXP_DEVICE_UD_RSS) &&
5506                     (exp_device_attr.comp_mask &
5507                      IBV_EXP_DEVICE_ATTR_RSS_TBL_SZ) &&
5508                     (exp_device_attr.max_rss_tbl_sz > 0)) {
5509                         priv->hw_qpg = 1;
5510                         priv->hw_rss = 1;
5511                         priv->max_rss_tbl_sz = exp_device_attr.max_rss_tbl_sz;
5512                 } else {
5513                         priv->hw_qpg = 0;
5514                         priv->hw_rss = 0;
5515                         priv->max_rss_tbl_sz = 0;
5516                 }
5517                 priv->hw_tss = !!(exp_device_attr.exp_device_cap_flags &
5518                                   IBV_EXP_DEVICE_UD_TSS);
5519                 DEBUG("device flags: %s%s%s",
5520                       (priv->hw_qpg ? "IBV_DEVICE_QPG " : ""),
5521                       (priv->hw_tss ? "IBV_DEVICE_TSS " : ""),
5522                       (priv->hw_rss ? "IBV_DEVICE_RSS " : ""));
5523                 if (priv->hw_rss)
5524                         DEBUG("maximum RSS indirection table size: %u",
5525                               exp_device_attr.max_rss_tbl_sz);
5526 #endif /* RSS_SUPPORT */
5527
5528                 priv->hw_csum =
5529                         ((exp_device_attr.exp_device_cap_flags &
5530                           IBV_EXP_DEVICE_RX_CSUM_TCP_UDP_PKT) &&
5531                          (exp_device_attr.exp_device_cap_flags &
5532                           IBV_EXP_DEVICE_RX_CSUM_IP_PKT));
5533                 DEBUG("checksum offloading is %ssupported",
5534                       (priv->hw_csum ? "" : "not "));
5535
5536                 priv->hw_csum_l2tun = !!(exp_device_attr.exp_device_cap_flags &
5537                                          IBV_EXP_DEVICE_VXLAN_SUPPORT);
5538                 DEBUG("L2 tunnel checksum offloads are %ssupported",
5539                       (priv->hw_csum_l2tun ? "" : "not "));
5540
5541 #ifdef INLINE_RECV
5542                 priv->inl_recv_size = mlx4_getenv_int("MLX4_INLINE_RECV_SIZE");
5543
5544                 if (priv->inl_recv_size) {
5545                         exp_device_attr.comp_mask =
5546                                 IBV_EXP_DEVICE_ATTR_INLINE_RECV_SZ;
5547                         if (ibv_exp_query_device(ctx, &exp_device_attr)) {
5548                                 INFO("Couldn't query device for inline-receive"
5549                                      " capabilities.");
5550                                 priv->inl_recv_size = 0;
5551                         } else {
5552                                 if ((unsigned)exp_device_attr.inline_recv_sz <
5553                                     priv->inl_recv_size) {
5554                                         INFO("Max inline-receive (%d) <"
5555                                              " requested inline-receive (%u)",
5556                                              exp_device_attr.inline_recv_sz,
5557                                              priv->inl_recv_size);
5558                                         priv->inl_recv_size =
5559                                                 exp_device_attr.inline_recv_sz;
5560                                 }
5561                         }
5562                         INFO("Set inline receive size to %u",
5563                              priv->inl_recv_size);
5564                 }
5565 #endif /* INLINE_RECV */
5566 #endif /* HAVE_EXP_QUERY_DEVICE */
5567
5568                 (void)mlx4_getenv_int;
5569                 priv->vf = vf;
5570                 /* Configure the first MAC address by default. */
5571                 if (priv_get_mac(priv, &mac.addr_bytes)) {
5572                         ERROR("cannot get MAC address, is mlx4_en loaded?"
5573                               " (errno: %s)", strerror(errno));
5574                         goto port_error;
5575                 }
5576                 INFO("port %u MAC address is %02x:%02x:%02x:%02x:%02x:%02x",
5577                      priv->port,
5578                      mac.addr_bytes[0], mac.addr_bytes[1],
5579                      mac.addr_bytes[2], mac.addr_bytes[3],
5580                      mac.addr_bytes[4], mac.addr_bytes[5]);
5581                 /* Register MAC and broadcast addresses. */
5582                 claim_zero(priv_mac_addr_add(priv, 0,
5583                                              (const uint8_t (*)[ETHER_ADDR_LEN])
5584                                              mac.addr_bytes));
5585                 claim_zero(priv_mac_addr_add(priv, (elemof(priv->mac) - 1),
5586                                              &(const uint8_t [ETHER_ADDR_LEN])
5587                                              { "\xff\xff\xff\xff\xff\xff" }));
5588 #ifndef NDEBUG
5589                 {
5590                         char ifname[IF_NAMESIZE];
5591
5592                         if (priv_get_ifname(priv, &ifname) == 0)
5593                                 DEBUG("port %u ifname is \"%s\"",
5594                                       priv->port, ifname);
5595                         else
5596                                 DEBUG("port %u ifname is unknown", priv->port);
5597                 }
5598 #endif
5599                 /* Get actual MTU if possible. */
5600                 priv_get_mtu(priv, &priv->mtu);
5601                 DEBUG("port %u MTU is %u", priv->port, priv->mtu);
5602
5603                 /* from rte_ethdev.c */
5604                 {
5605                         char name[RTE_ETH_NAME_MAX_LEN];
5606
5607                         snprintf(name, sizeof(name), "%s port %u",
5608                                  ibv_get_device_name(ibv_dev), port);
5609                         eth_dev = rte_eth_dev_allocate(name, RTE_ETH_DEV_PCI);
5610                 }
5611                 if (eth_dev == NULL) {
5612                         ERROR("can not allocate rte ethdev");
5613                         err = ENOMEM;
5614                         goto port_error;
5615                 }
5616
5617                 /* Secondary processes have to use local storage for their
5618                  * private data as well as a copy of eth_dev->data, but this
5619                  * pointer must not be modified before burst functions are
5620                  * actually called. */
5621                 if (mlx4_is_secondary()) {
5622                         struct mlx4_secondary_data *sd =
5623                                 &mlx4_secondary_data[eth_dev->data->port_id];
5624
5625                         sd->primary_priv = eth_dev->data->dev_private;
5626                         if (sd->primary_priv == NULL) {
5627                                 ERROR("no private data for port %u",
5628                                       eth_dev->data->port_id);
5629                                 err = EINVAL;
5630                                 goto port_error;
5631                         }
5632                         sd->shared_dev_data = eth_dev->data;
5633                         rte_spinlock_init(&sd->lock);
5634                         memcpy(sd->data.name, sd->shared_dev_data->name,
5635                                sizeof(sd->data.name));
5636                         sd->data.dev_private = priv;
5637                         sd->data.rx_mbuf_alloc_failed = 0;
5638                         sd->data.mtu = ETHER_MTU;
5639                         sd->data.port_id = sd->shared_dev_data->port_id;
5640                         sd->data.mac_addrs = priv->mac;
5641                         eth_dev->tx_pkt_burst = mlx4_tx_burst_secondary_setup;
5642                         eth_dev->rx_pkt_burst = mlx4_rx_burst_secondary_setup;
5643                 } else {
5644                         eth_dev->data->dev_private = priv;
5645                         eth_dev->data->rx_mbuf_alloc_failed = 0;
5646                         eth_dev->data->mtu = ETHER_MTU;
5647                         eth_dev->data->mac_addrs = priv->mac;
5648                 }
5649                 eth_dev->pci_dev = pci_dev;
5650
5651                 rte_eth_copy_pci_info(eth_dev, pci_dev);
5652
5653                 eth_dev->driver = &mlx4_driver;
5654
5655                 priv->dev = eth_dev;
5656                 eth_dev->dev_ops = &mlx4_dev_ops;
5657                 TAILQ_INIT(&eth_dev->link_intr_cbs);
5658
5659                 /* Bring Ethernet device up. */
5660                 DEBUG("forcing Ethernet interface up");
5661                 priv_set_flags(priv, ~IFF_UP, IFF_UP);
5662                 continue;
5663
5664 port_error:
5665                 rte_free(priv);
5666                 if (pd)
5667                         claim_zero(ibv_dealloc_pd(pd));
5668                 if (ctx)
5669                         claim_zero(ibv_close_device(ctx));
5670                 if (eth_dev)
5671                         rte_eth_dev_release_port(eth_dev);
5672                 break;
5673         }
5674
5675         /*
5676          * XXX if something went wrong in the loop above, there is a resource
5677          * leak (ctx, pd, priv, dpdk ethdev) but we can do nothing about it as
5678          * long as the dpdk does not provide a way to deallocate a ethdev and a
5679          * way to enumerate the registered ethdevs to free the previous ones.
5680          */
5681
5682         /* no port found, complain */
5683         if (!mlx4_dev[idx].ports) {
5684                 err = ENODEV;
5685                 goto error;
5686         }
5687
5688 error:
5689         if (attr_ctx)
5690                 claim_zero(ibv_close_device(attr_ctx));
5691         if (list)
5692                 ibv_free_device_list(list);
5693         assert(err >= 0);
5694         return -err;
5695 }
5696
5697 static const struct rte_pci_id mlx4_pci_id_map[] = {
5698         {
5699                 .vendor_id = PCI_VENDOR_ID_MELLANOX,
5700                 .device_id = PCI_DEVICE_ID_MELLANOX_CONNECTX3,
5701                 .subsystem_vendor_id = PCI_ANY_ID,
5702                 .subsystem_device_id = PCI_ANY_ID
5703         },
5704         {
5705                 .vendor_id = PCI_VENDOR_ID_MELLANOX,
5706                 .device_id = PCI_DEVICE_ID_MELLANOX_CONNECTX3PRO,
5707                 .subsystem_vendor_id = PCI_ANY_ID,
5708                 .subsystem_device_id = PCI_ANY_ID
5709         },
5710         {
5711                 .vendor_id = PCI_VENDOR_ID_MELLANOX,
5712                 .device_id = PCI_DEVICE_ID_MELLANOX_CONNECTX3VF,
5713                 .subsystem_vendor_id = PCI_ANY_ID,
5714                 .subsystem_device_id = PCI_ANY_ID
5715         },
5716         {
5717                 .vendor_id = 0
5718         }
5719 };
5720
5721 static struct eth_driver mlx4_driver = {
5722         .pci_drv = {
5723                 .name = MLX4_DRIVER_NAME,
5724                 .id_table = mlx4_pci_id_map,
5725                 .devinit = mlx4_pci_devinit,
5726                 .drv_flags = RTE_PCI_DRV_INTR_LSC,
5727         },
5728         .dev_private_size = sizeof(struct priv)
5729 };
5730
5731 /**
5732  * Driver initialization routine.
5733  */
5734 static int
5735 rte_mlx4_pmd_init(const char *name, const char *args)
5736 {
5737         (void)name;
5738         (void)args;
5739
5740         RTE_BUILD_BUG_ON(sizeof(wr_id_t) != sizeof(uint64_t));
5741         /*
5742          * RDMAV_HUGEPAGES_SAFE tells ibv_fork_init() we intend to use
5743          * huge pages. Calling ibv_fork_init() during init allows
5744          * applications to use fork() safely for purposes other than
5745          * using this PMD, which is not supported in forked processes.
5746          */
5747         setenv("RDMAV_HUGEPAGES_SAFE", "1", 1);
5748         ibv_fork_init();
5749         rte_eal_pci_register(&mlx4_driver.pci_drv);
5750         return 0;
5751 }
5752
5753 static struct rte_driver rte_mlx4_driver = {
5754         .type = PMD_PDEV,
5755         .name = MLX4_DRIVER_NAME,
5756         .init = rte_mlx4_pmd_init,
5757 };
5758
5759 PMD_REGISTER_DRIVER(rte_mlx4_driver)