tailq: remove unused macros
[dpdk.git] / lib / librte_pmd_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  * - Multiple RX VLAN filters can be configured, but only the first one
37  *   works properly.
38  * - RSS hash key and options cannot be modified.
39  * - Hardware counters aren't implemented.
40  */
41
42 /* System headers. */
43 #include <stddef.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <stdint.h>
47 #include <inttypes.h>
48 #include <string.h>
49 #include <errno.h>
50 #include <unistd.h>
51 #include <limits.h>
52 #include <assert.h>
53 #include <arpa/inet.h>
54 #include <net/if.h>
55 #include <dirent.h>
56 #include <sys/ioctl.h>
57 #include <sys/socket.h>
58 #include <netinet/in.h>
59 #include <linux/if.h>
60 #include <linux/ethtool.h>
61 #include <linux/sockios.h>
62
63 /* Verbs header. */
64 /* ISO C doesn't support unnamed structs/unions, disabling -pedantic. */
65 #ifdef PEDANTIC
66 #pragma GCC diagnostic ignored "-pedantic"
67 #endif
68 #include <infiniband/verbs.h>
69 #ifdef PEDANTIC
70 #pragma GCC diagnostic error "-pedantic"
71 #endif
72
73 /* DPDK headers don't like -pedantic. */
74 #ifdef PEDANTIC
75 #pragma GCC diagnostic ignored "-pedantic"
76 #endif
77 #include <rte_config.h>
78 #include <rte_ether.h>
79 #include <rte_ethdev.h>
80 #include <rte_dev.h>
81 #include <rte_mbuf.h>
82 #include <rte_errno.h>
83 #include <rte_mempool.h>
84 #include <rte_prefetch.h>
85 #include <rte_malloc.h>
86 #include <rte_spinlock.h>
87 #include <rte_atomic.h>
88 #include <rte_version.h>
89 #include <rte_log.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 /* Compile-time check. */
136 static inline void wr_id_t_check(void)
137 {
138         wr_id_t check[1 + (2 * -!(sizeof(wr_id_t) == sizeof(uint64_t)))];
139
140         (void)check;
141         (void)wr_id_t_check;
142 }
143
144 /* If raw send operations are available, use them since they are faster. */
145 #ifdef SEND_RAW_WR_SUPPORT
146 typedef struct ibv_send_wr_raw mlx4_send_wr_t;
147 #define mlx4_post_send ibv_post_send_raw
148 #else
149 typedef struct ibv_send_wr mlx4_send_wr_t;
150 #define mlx4_post_send ibv_post_send
151 #endif
152
153 struct mlx4_rxq_stats {
154         unsigned int idx; /**< Mapping index. */
155 #ifdef MLX4_PMD_SOFT_COUNTERS
156         uint64_t ipackets;  /**< Total of successfully received packets. */
157         uint64_t ibytes;    /**< Total of successfully received bytes. */
158 #endif
159         uint64_t idropped;  /**< Total of packets dropped when RX ring full. */
160         uint64_t rx_nombuf; /**< Total of RX mbuf allocation failures. */
161 };
162
163 struct mlx4_txq_stats {
164         unsigned int idx; /**< Mapping index. */
165 #ifdef MLX4_PMD_SOFT_COUNTERS
166         uint64_t opackets; /**< Total of successfully sent packets. */
167         uint64_t obytes;   /**< Total of successfully sent bytes. */
168 #endif
169         uint64_t odropped; /**< Total of packets not sent when TX ring full. */
170 };
171
172 /* RX element (scattered packets). */
173 struct rxq_elt_sp {
174         struct ibv_recv_wr wr; /* Work Request. */
175         struct ibv_sge sges[MLX4_PMD_SGE_WR_N]; /* Scatter/Gather Elements. */
176         struct rte_mbuf *bufs[MLX4_PMD_SGE_WR_N]; /* SGEs buffers. */
177 };
178
179 /* RX element. */
180 struct rxq_elt {
181         struct ibv_recv_wr wr; /* Work Request. */
182         struct ibv_sge sge; /* Scatter/Gather Element. */
183         /* mbuf pointer is derived from WR_ID(wr.wr_id).offset. */
184 };
185
186 /* RX queue descriptor. */
187 struct rxq {
188         struct priv *priv; /* Back pointer to private data. */
189         struct rte_mempool *mp; /* Memory Pool for allocations. */
190         struct ibv_mr *mr; /* Memory Region (for mp). */
191         struct ibv_cq *cq; /* Completion Queue. */
192         struct ibv_qp *qp; /* Queue Pair. */
193         /*
194          * There is exactly one flow configured per MAC address. Each flow
195          * may contain several specifications, one per configured VLAN ID.
196          */
197         BITFIELD_DECLARE(mac_configured, uint32_t, MLX4_MAX_MAC_ADDRESSES);
198         struct ibv_exp_flow *mac_flow[MLX4_MAX_MAC_ADDRESSES];
199         struct ibv_exp_flow *promisc_flow; /* Promiscuous flow. */
200         struct ibv_exp_flow *allmulti_flow; /* Multicast flow. */
201         unsigned int port_id; /* Port ID for incoming packets. */
202         unsigned int elts_n; /* (*elts)[] length. */
203         union {
204                 struct rxq_elt_sp (*sp)[]; /* Scattered RX elements. */
205                 struct rxq_elt (*no_sp)[]; /* RX elements. */
206         } elts;
207         unsigned int sp:1; /* Use scattered RX elements. */
208         uint32_t mb_len; /* Length of a mp-issued mbuf. */
209         struct mlx4_rxq_stats stats; /* RX queue counters. */
210         unsigned int socket; /* CPU socket ID for allocations. */
211 };
212
213 /* TX element. */
214 struct txq_elt {
215         mlx4_send_wr_t wr; /* Work Request. */
216         struct ibv_sge sges[MLX4_PMD_SGE_WR_N]; /* Scatter/Gather Elements. */
217         /* mbuf pointer is derived from WR_ID(wr.wr_id).offset. */
218 };
219
220 /* Linear buffer type. It is used when transmitting buffers with too many
221  * segments that do not fit the hardware queue (see max_send_sge).
222  * Extra segments are copied (linearized) in such buffers, replacing the
223  * last SGE during TX.
224  * The size is arbitrary but large enough to hold a jumbo frame with
225  * 8 segments considering mbuf.buf_len is about 2048 bytes. */
226 typedef uint8_t linear_t[16384];
227
228 /* TX queue descriptor. */
229 struct txq {
230         struct priv *priv; /* Back pointer to private data. */
231         struct {
232                 struct rte_mempool *mp; /* Cached Memory Pool. */
233                 struct ibv_mr *mr; /* Memory Region (for mp). */
234                 uint32_t lkey; /* mr->lkey */
235         } mp2mr[MLX4_PMD_TX_MP_CACHE]; /* MP to MR translation table. */
236         struct ibv_cq *cq; /* Completion Queue. */
237         struct ibv_qp *qp; /* Queue Pair. */
238 #if MLX4_PMD_MAX_INLINE > 0
239         uint32_t max_inline; /* Max inline send size <= MLX4_PMD_MAX_INLINE. */
240 #endif
241         unsigned int elts_n; /* (*elts)[] length. */
242         struct txq_elt (*elts)[]; /* TX elements. */
243         unsigned int elts_head; /* Current index in (*elts)[]. */
244         unsigned int elts_tail; /* First element awaiting completion. */
245         unsigned int elts_comp; /* Number of completion requests. */
246         struct mlx4_txq_stats stats; /* TX queue counters. */
247         linear_t (*elts_linear)[]; /* Linearized buffers. */
248         struct ibv_mr *mr_linear; /* Memory Region for linearized buffers. */
249         unsigned int socket; /* CPU socket ID for allocations. */
250 };
251
252 struct priv {
253         struct rte_eth_dev *dev; /* Ethernet device. */
254         struct ibv_context *ctx; /* Verbs context. */
255         struct ibv_device_attr device_attr; /* Device properties. */
256         struct ibv_port_attr port_attr; /* Physical port properties. */
257         struct ibv_pd *pd; /* Protection Domain. */
258         /*
259          * MAC addresses array and configuration bit-field.
260          * An extra entry that cannot be modified by the DPDK is reserved
261          * for broadcast frames (destination MAC address ff:ff:ff:ff:ff:ff).
262          */
263         struct ether_addr mac[MLX4_MAX_MAC_ADDRESSES];
264         BITFIELD_DECLARE(mac_configured, uint32_t, MLX4_MAX_MAC_ADDRESSES);
265         /* VLAN filters. */
266         struct {
267                 unsigned int enabled:1; /* If enabled. */
268                 unsigned int id:12; /* VLAN ID (0-4095). */
269         } vlan_filter[MLX4_MAX_VLAN_IDS]; /* VLAN filters table. */
270         /* Device properties. */
271         uint16_t mtu; /* Configured MTU. */
272         uint8_t port; /* Physical port number. */
273         unsigned int started:1; /* Device started, flows enabled. */
274         unsigned int promisc:1; /* Device in promiscuous mode. */
275         unsigned int promisc_ok:1; /* Promiscuous flow is supported. */
276         unsigned int allmulti:1; /* Device receives all multicast packets. */
277         unsigned int hw_qpg:1; /* QP groups are supported. */
278         unsigned int hw_tss:1; /* TSS is supported. */
279         unsigned int hw_rss:1; /* RSS is supported. */
280         unsigned int rss:1; /* RSS is enabled. */
281 #ifdef MLX4_COMPAT_VMWARE
282         unsigned int vmware:1; /* Use VMware compatibility. */
283 #endif
284         unsigned int vf:1; /* This is a VF device. */
285 #ifdef INLINE_RECV
286         unsigned int inl_recv_size; /* Inline recv size */
287 #endif
288         unsigned int max_rss_tbl_sz; /* Maximum number of RSS queues. */
289         /* RX/TX queues. */
290         struct rxq rxq_parent; /* Parent queue when RSS is enabled. */
291         unsigned int rxqs_n; /* RX queues array size. */
292         unsigned int txqs_n; /* TX queues array size. */
293         struct rxq *(*rxqs)[]; /* RX queues. */
294         struct txq *(*txqs)[]; /* TX queues. */
295         rte_spinlock_t lock; /* Lock for control functions. */
296 };
297
298 /**
299  * Lock private structure to protect it from concurrent access in the
300  * control path.
301  *
302  * @param priv
303  *   Pointer to private structure.
304  */
305 static void
306 priv_lock(struct priv *priv)
307 {
308         rte_spinlock_lock(&priv->lock);
309 }
310
311 /**
312  * Unlock private structure.
313  *
314  * @param priv
315  *   Pointer to private structure.
316  */
317 static void
318 priv_unlock(struct priv *priv)
319 {
320         rte_spinlock_unlock(&priv->lock);
321 }
322
323 /* Allocate a buffer on the stack and fill it with a printf format string. */
324 #define MKSTR(name, ...) \
325         char name[snprintf(NULL, 0, __VA_ARGS__) + 1]; \
326         \
327         snprintf(name, sizeof(name), __VA_ARGS__)
328
329 /**
330  * Get interface name from private structure.
331  *
332  * @param[in] priv
333  *   Pointer to private structure.
334  * @param[out] ifname
335  *   Interface name output buffer.
336  *
337  * @return
338  *   0 on success, -1 on failure and errno is set.
339  */
340 static int
341 priv_get_ifname(const struct priv *priv, char (*ifname)[IF_NAMESIZE])
342 {
343         int ret = -1;
344         DIR *dir;
345         struct dirent *dent;
346
347         {
348                 MKSTR(path, "%s/device/net", priv->ctx->device->ibdev_path);
349
350                 dir = opendir(path);
351                 if (dir == NULL)
352                         return -1;
353         }
354         while ((dent = readdir(dir)) != NULL) {
355                 char *name = dent->d_name;
356                 FILE *file;
357                 unsigned int dev_id;
358                 int r;
359
360                 if ((name[0] == '.') &&
361                     ((name[1] == '\0') ||
362                      ((name[1] == '.') && (name[2] == '\0'))))
363                         continue;
364
365                 MKSTR(path, "%s/device/net/%s/dev_id",
366                       priv->ctx->device->ibdev_path, name);
367
368                 file = fopen(path, "rb");
369                 if (file == NULL)
370                         continue;
371                 r = fscanf(file, "%x", &dev_id);
372                 fclose(file);
373                 if ((r == 1) && (dev_id == (priv->port - 1u))) {
374                         snprintf(*ifname, sizeof(*ifname), "%s", name);
375                         ret = 0;
376                         break;
377                 }
378         }
379         closedir(dir);
380         return ret;
381 }
382
383 /**
384  * Read from sysfs entry.
385  *
386  * @param[in] priv
387  *   Pointer to private structure.
388  * @param[in] entry
389  *   Entry name relative to sysfs path.
390  * @param[out] buf
391  *   Data output buffer.
392  * @param size
393  *   Buffer size.
394  *
395  * @return
396  *   0 on success, -1 on failure and errno is set.
397  */
398 static int
399 priv_sysfs_read(const struct priv *priv, const char *entry,
400                 char *buf, size_t size)
401 {
402         char ifname[IF_NAMESIZE];
403         FILE *file;
404         int ret;
405         int err;
406
407         if (priv_get_ifname(priv, &ifname))
408                 return -1;
409
410         MKSTR(path, "%s/device/net/%s/%s", priv->ctx->device->ibdev_path,
411               ifname, entry);
412
413         file = fopen(path, "rb");
414         if (file == NULL)
415                 return -1;
416         ret = fread(buf, 1, size, file);
417         err = errno;
418         if (((size_t)ret < size) && (ferror(file)))
419                 ret = -1;
420         else
421                 ret = size;
422         fclose(file);
423         errno = err;
424         return ret;
425 }
426
427 /**
428  * Write to sysfs entry.
429  *
430  * @param[in] priv
431  *   Pointer to private structure.
432  * @param[in] entry
433  *   Entry name relative to sysfs path.
434  * @param[in] buf
435  *   Data buffer.
436  * @param size
437  *   Buffer size.
438  *
439  * @return
440  *   0 on success, -1 on failure and errno is set.
441  */
442 static int
443 priv_sysfs_write(const struct priv *priv, const char *entry,
444                  char *buf, size_t size)
445 {
446         char ifname[IF_NAMESIZE];
447         FILE *file;
448         int ret;
449         int err;
450
451         if (priv_get_ifname(priv, &ifname))
452                 return -1;
453
454         MKSTR(path, "%s/device/net/%s/%s", priv->ctx->device->ibdev_path,
455               ifname, entry);
456
457         file = fopen(path, "wb");
458         if (file == NULL)
459                 return -1;
460         ret = fwrite(buf, 1, size, file);
461         err = errno;
462         if (((size_t)ret < size) || (ferror(file)))
463                 ret = -1;
464         else
465                 ret = size;
466         fclose(file);
467         errno = err;
468         return ret;
469 }
470
471 /**
472  * Get unsigned long sysfs property.
473  *
474  * @param priv
475  *   Pointer to private structure.
476  * @param[in] name
477  *   Entry name relative to sysfs path.
478  * @param[out] value
479  *   Value output buffer.
480  *
481  * @return
482  *   0 on success, -1 on failure and errno is set.
483  */
484 static int
485 priv_get_sysfs_ulong(struct priv *priv, const char *name, unsigned long *value)
486 {
487         int ret;
488         unsigned long value_ret;
489         char value_str[32];
490
491         ret = priv_sysfs_read(priv, name, value_str, (sizeof(value_str) - 1));
492         if (ret == -1) {
493                 DEBUG("cannot read %s value from sysfs: %s",
494                       name, strerror(errno));
495                 return -1;
496         }
497         value_str[ret] = '\0';
498         errno = 0;
499         value_ret = strtoul(value_str, NULL, 0);
500         if (errno) {
501                 DEBUG("invalid %s value `%s': %s", name, value_str,
502                       strerror(errno));
503                 return -1;
504         }
505         *value = value_ret;
506         return 0;
507 }
508
509 /**
510  * Set unsigned long sysfs property.
511  *
512  * @param priv
513  *   Pointer to private structure.
514  * @param[in] name
515  *   Entry name relative to sysfs path.
516  * @param value
517  *   Value to set.
518  *
519  * @return
520  *   0 on success, -1 on failure and errno is set.
521  */
522 static int
523 priv_set_sysfs_ulong(struct priv *priv, const char *name, unsigned long value)
524 {
525         int ret;
526         MKSTR(value_str, "%lu", value);
527
528         ret = priv_sysfs_write(priv, name, value_str, (sizeof(value_str) - 1));
529         if (ret == -1) {
530                 DEBUG("cannot write %s `%s' (%lu) to sysfs: %s",
531                       name, value_str, value, strerror(errno));
532                 return -1;
533         }
534         return 0;
535 }
536
537 /**
538  * Perform ifreq ioctl() on associated Ethernet device.
539  *
540  * @param[in] priv
541  *   Pointer to private structure.
542  * @param req
543  *   Request number to pass to ioctl().
544  * @param[out] ifr
545  *   Interface request structure output buffer.
546  *
547  * @return
548  *   0 on success, -1 on failure and errno is set.
549  */
550 static int
551 priv_ifreq(const struct priv *priv, int req, struct ifreq *ifr)
552 {
553         int sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
554         int ret = -1;
555
556         if (sock == -1)
557                 return ret;
558         if (priv_get_ifname(priv, &ifr->ifr_name) == 0)
559                 ret = ioctl(sock, req, ifr);
560         close(sock);
561         return ret;
562 }
563
564 /**
565  * Get device MTU.
566  *
567  * @param priv
568  *   Pointer to private structure.
569  * @param[out] mtu
570  *   MTU value output buffer.
571  *
572  * @return
573  *   0 on success, -1 on failure and errno is set.
574  */
575 static int
576 priv_get_mtu(struct priv *priv, uint16_t *mtu)
577 {
578         unsigned long ulong_mtu;
579
580         if (priv_get_sysfs_ulong(priv, "mtu", &ulong_mtu) == -1)
581                 return -1;
582         *mtu = ulong_mtu;
583         return 0;
584 }
585
586 /**
587  * Set device MTU.
588  *
589  * @param priv
590  *   Pointer to private structure.
591  * @param mtu
592  *   MTU value to set.
593  *
594  * @return
595  *   0 on success, -1 on failure and errno is set.
596  */
597 static int
598 priv_set_mtu(struct priv *priv, uint16_t mtu)
599 {
600         return priv_set_sysfs_ulong(priv, "mtu", mtu);
601 }
602
603 /**
604  * Set device flags.
605  *
606  * @param priv
607  *   Pointer to private structure.
608  * @param keep
609  *   Bitmask for flags that must remain untouched.
610  * @param flags
611  *   Bitmask for flags to modify.
612  *
613  * @return
614  *   0 on success, -1 on failure and errno is set.
615  */
616 static int
617 priv_set_flags(struct priv *priv, unsigned int keep, unsigned int flags)
618 {
619         unsigned long tmp;
620
621         if (priv_get_sysfs_ulong(priv, "flags", &tmp) == -1)
622                 return -1;
623         tmp &= keep;
624         tmp |= flags;
625         return priv_set_sysfs_ulong(priv, "flags", tmp);
626 }
627
628 /* Device configuration. */
629
630 static int
631 rxq_setup(struct rte_eth_dev *dev, struct rxq *rxq, uint16_t desc,
632           unsigned int socket, const struct rte_eth_rxconf *conf,
633           struct rte_mempool *mp);
634
635 static void
636 rxq_cleanup(struct rxq *rxq);
637
638 /**
639  * Ethernet device configuration.
640  *
641  * Prepare the driver for a given number of TX and RX queues.
642  * Allocate parent RSS queue when several RX queues are requested.
643  *
644  * @param dev
645  *   Pointer to Ethernet device structure.
646  *
647  * @return
648  *   0 on success, errno value on failure.
649  */
650 static int
651 dev_configure(struct rte_eth_dev *dev)
652 {
653         struct priv *priv = dev->data->dev_private;
654         unsigned int rxqs_n = dev->data->nb_rx_queues;
655         unsigned int txqs_n = dev->data->nb_tx_queues;
656         unsigned int tmp;
657         int ret;
658
659         priv->rxqs = (void *)dev->data->rx_queues;
660         priv->txqs = (void *)dev->data->tx_queues;
661         if (txqs_n != priv->txqs_n) {
662                 INFO("%p: TX queues number update: %u -> %u",
663                      (void *)dev, priv->txqs_n, txqs_n);
664                 priv->txqs_n = txqs_n;
665         }
666         if (rxqs_n == priv->rxqs_n)
667                 return 0;
668         INFO("%p: RX queues number update: %u -> %u",
669              (void *)dev, priv->rxqs_n, rxqs_n);
670         /* If RSS is enabled, disable it first. */
671         if (priv->rss) {
672                 unsigned int i;
673
674                 /* Only if there are no remaining child RX queues. */
675                 for (i = 0; (i != priv->rxqs_n); ++i)
676                         if ((*priv->rxqs)[i] != NULL)
677                                 return EINVAL;
678                 rxq_cleanup(&priv->rxq_parent);
679                 priv->rss = 0;
680                 priv->rxqs_n = 0;
681         }
682         if (rxqs_n <= 1) {
683                 /* Nothing else to do. */
684                 priv->rxqs_n = rxqs_n;
685                 return 0;
686         }
687         /* Allocate a new RSS parent queue if supported by hardware. */
688         if (!priv->hw_rss) {
689                 ERROR("%p: only a single RX queue can be configured when"
690                       " hardware doesn't support RSS",
691                       (void *)dev);
692                 return EINVAL;
693         }
694         /* Fail if hardware doesn't support that many RSS queues. */
695         if (rxqs_n >= priv->max_rss_tbl_sz) {
696                 ERROR("%p: only %u RX queues can be configured for RSS",
697                       (void *)dev, priv->max_rss_tbl_sz);
698                 return EINVAL;
699         }
700         priv->rss = 1;
701         tmp = priv->rxqs_n;
702         priv->rxqs_n = rxqs_n;
703         ret = rxq_setup(dev, &priv->rxq_parent, 0, 0, NULL, NULL);
704         if (!ret)
705                 return 0;
706         /* Failure, rollback. */
707         priv->rss = 0;
708         priv->rxqs_n = tmp;
709         assert(ret > 0);
710         return ret;
711 }
712
713 /**
714  * DPDK callback for Ethernet device configuration.
715  *
716  * @param dev
717  *   Pointer to Ethernet device structure.
718  *
719  * @return
720  *   0 on success, negative errno value on failure.
721  */
722 static int
723 mlx4_dev_configure(struct rte_eth_dev *dev)
724 {
725         struct priv *priv = dev->data->dev_private;
726         int ret;
727
728         priv_lock(priv);
729         ret = dev_configure(dev);
730         assert(ret >= 0);
731         priv_unlock(priv);
732         return -ret;
733 }
734
735 /* TX queues handling. */
736
737 /**
738  * Allocate TX queue elements.
739  *
740  * @param txq
741  *   Pointer to TX queue structure.
742  * @param elts_n
743  *   Number of elements to allocate.
744  *
745  * @return
746  *   0 on success, errno value on failure.
747  */
748 static int
749 txq_alloc_elts(struct txq *txq, unsigned int elts_n)
750 {
751         unsigned int i;
752         struct txq_elt (*elts)[elts_n] =
753                 rte_calloc_socket("TXQ", 1, sizeof(*elts), 0, txq->socket);
754         linear_t (*elts_linear)[elts_n] =
755                 rte_calloc_socket("TXQ", 1, sizeof(*elts_linear), 0,
756                                   txq->socket);
757         struct ibv_mr *mr_linear = NULL;
758         int ret = 0;
759
760         if ((elts == NULL) || (elts_linear == NULL)) {
761                 ERROR("%p: can't allocate packets array", (void *)txq);
762                 ret = ENOMEM;
763                 goto error;
764         }
765         mr_linear =
766                 ibv_reg_mr(txq->priv->pd, elts_linear, sizeof(*elts_linear),
767                            (IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE));
768         if (mr_linear == NULL) {
769                 ERROR("%p: unable to configure MR, ibv_reg_mr() failed",
770                       (void *)txq);
771                 ret = EINVAL;
772                 goto error;
773         }
774         for (i = 0; (i != elts_n); ++i) {
775                 struct txq_elt *elt = &(*elts)[i];
776                 mlx4_send_wr_t *wr = &elt->wr;
777
778                 /* Configure WR. */
779                 WR_ID(wr->wr_id).id = i;
780                 WR_ID(wr->wr_id).offset = 0;
781                 wr->sg_list = &elt->sges[0];
782                 wr->opcode = IBV_WR_SEND;
783                 /* Other fields are updated during TX. */
784         }
785         DEBUG("%p: allocated and configured %u WRs", (void *)txq, elts_n);
786         txq->elts_n = elts_n;
787         txq->elts = elts;
788         txq->elts_head = 0;
789         txq->elts_tail = 0;
790         txq->elts_comp = 0;
791         txq->elts_linear = elts_linear;
792         txq->mr_linear = mr_linear;
793         assert(ret == 0);
794         return 0;
795 error:
796         if (mr_linear != NULL)
797                 claim_zero(ibv_dereg_mr(mr_linear));
798         if (elts_linear != NULL)
799                 rte_free(elts_linear);
800         if (elts != NULL)
801                 rte_free(elts);
802         DEBUG("%p: failed, freed everything", (void *)txq);
803         assert(ret > 0);
804         return ret;
805 }
806
807 /**
808  * Free TX queue elements.
809  *
810  * @param txq
811  *   Pointer to TX queue structure.
812  */
813 static void
814 txq_free_elts(struct txq *txq)
815 {
816         unsigned int i;
817         unsigned int elts_n = txq->elts_n;
818         struct txq_elt (*elts)[elts_n] = txq->elts;
819         linear_t (*elts_linear)[elts_n] = txq->elts_linear;
820         struct ibv_mr *mr_linear = txq->mr_linear;
821
822         DEBUG("%p: freeing WRs", (void *)txq);
823         txq->elts_n = 0;
824         txq->elts = NULL;
825         txq->elts_linear = NULL;
826         txq->mr_linear = NULL;
827         if (mr_linear != NULL)
828                 claim_zero(ibv_dereg_mr(mr_linear));
829         if (elts_linear != NULL)
830                 rte_free(elts_linear);
831         if (elts == NULL)
832                 return;
833         for (i = 0; (i != elemof(*elts)); ++i) {
834                 struct txq_elt *elt = &(*elts)[i];
835
836                 if (WR_ID(elt->wr.wr_id).offset == 0)
837                         continue;
838                 rte_pktmbuf_free((void *)(elt->sges[0].addr -
839                                           WR_ID(elt->wr.wr_id).offset));
840         }
841         rte_free(elts);
842 }
843
844
845 /**
846  * Clean up a TX queue.
847  *
848  * Destroy objects, free allocated memory and reset the structure for reuse.
849  *
850  * @param txq
851  *   Pointer to TX queue structure.
852  */
853 static void
854 txq_cleanup(struct txq *txq)
855 {
856         size_t i;
857
858         DEBUG("cleaning up %p", (void *)txq);
859         txq_free_elts(txq);
860         if (txq->qp != NULL)
861                 claim_zero(ibv_destroy_qp(txq->qp));
862         if (txq->cq != NULL)
863                 claim_zero(ibv_destroy_cq(txq->cq));
864         for (i = 0; (i != elemof(txq->mp2mr)); ++i) {
865                 if (txq->mp2mr[i].mp == NULL)
866                         break;
867                 assert(txq->mp2mr[i].mr != NULL);
868                 claim_zero(ibv_dereg_mr(txq->mp2mr[i].mr));
869         }
870         memset(txq, 0, sizeof(*txq));
871 }
872
873 /**
874  * Manage TX completions.
875  *
876  * When sending a burst, mlx4_tx_burst() posts several WRs.
877  * To improve performance, a completion event is only required for the last of
878  * them. Doing so discards completion information for other WRs, but this
879  * information would not be used anyway.
880  *
881  * @param txq
882  *   Pointer to TX queue structure.
883  *
884  * @return
885  *   0 on success, -1 on failure.
886  */
887 static int
888 txq_complete(struct txq *txq)
889 {
890         unsigned int elts_comp = txq->elts_comp;
891         unsigned int elts_tail;
892         const unsigned int elts_n = txq->elts_n;
893         struct ibv_wc wcs[elts_comp];
894         int wcs_n;
895
896         if (unlikely(elts_comp == 0))
897                 return 0;
898 #ifdef DEBUG_SEND
899         DEBUG("%p: processing %u work requests completions",
900               (void *)txq, elts_comp);
901 #endif
902         wcs_n = ibv_poll_cq(txq->cq, elts_comp, wcs);
903         if (unlikely(wcs_n == 0))
904                 return 0;
905         if (unlikely(wcs_n < 0)) {
906                 DEBUG("%p: ibv_poll_cq() failed (wcs_n=%d)",
907                       (void *)txq, wcs_n);
908                 return -1;
909         }
910         elts_comp -= wcs_n;
911         assert(elts_comp <= txq->elts_comp);
912         /*
913          * Work Completion ID contains the associated element index in
914          * (*txq->elts)[]. Since WCs are returned in order, we only need to
915          * look at the last WC to clear older Work Requests.
916          *
917          * Assume WC status is successful as nothing can be done about it
918          * anyway.
919          */
920         elts_tail = WR_ID(wcs[wcs_n - 1].wr_id).id;
921         /* Consume the last WC. */
922         if (++elts_tail >= elts_n)
923                 elts_tail = 0;
924         txq->elts_tail = elts_tail;
925         txq->elts_comp = elts_comp;
926         return 0;
927 }
928
929 /**
930  * Get Memory Region (MR) <-> Memory Pool (MP) association from txq->mp2mr[].
931  * Add MP to txq->mp2mr[] if it's not registered yet. If mp2mr[] is full,
932  * remove an entry first.
933  *
934  * @param txq
935  *   Pointer to TX queue structure.
936  * @param[in] mp
937  *   Memory Pool for which a Memory Region lkey must be returned.
938  *
939  * @return
940  *   mr->lkey on success, (uint32_t)-1 on failure.
941  */
942 static uint32_t
943 txq_mp2mr(struct txq *txq, struct rte_mempool *mp)
944 {
945         unsigned int i;
946         struct ibv_mr *mr;
947
948         for (i = 0; (i != elemof(txq->mp2mr)); ++i) {
949                 if (unlikely(txq->mp2mr[i].mp == NULL)) {
950                         /* Unknown MP, add a new MR for it. */
951                         break;
952                 }
953                 if (txq->mp2mr[i].mp == mp) {
954                         assert(txq->mp2mr[i].lkey != (uint32_t)-1);
955                         assert(txq->mp2mr[i].mr->lkey == txq->mp2mr[i].lkey);
956                         return txq->mp2mr[i].lkey;
957                 }
958         }
959         /* Add a new entry, register MR first. */
960         DEBUG("%p: discovered new memory pool %p", (void *)txq, (void *)mp);
961         mr = ibv_reg_mr(txq->priv->pd,
962                         (void *)mp->elt_va_start,
963                         (mp->elt_va_end - mp->elt_va_start),
964                         (IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE));
965         if (unlikely(mr == NULL)) {
966                 DEBUG("%p: unable to configure MR, ibv_reg_mr() failed.",
967                       (void *)txq);
968                 return (uint32_t)-1;
969         }
970         if (unlikely(i == elemof(txq->mp2mr))) {
971                 /* Table is full, remove oldest entry. */
972                 DEBUG("%p: MR <-> MP table full, dropping oldest entry.",
973                       (void *)txq);
974                 --i;
975                 claim_zero(ibv_dereg_mr(txq->mp2mr[i].mr));
976                 memmove(&txq->mp2mr[0], &txq->mp2mr[1],
977                         (sizeof(txq->mp2mr) - sizeof(txq->mp2mr[0])));
978         }
979         /* Store the new entry. */
980         txq->mp2mr[i].mp = mp;
981         txq->mp2mr[i].mr = mr;
982         txq->mp2mr[i].lkey = mr->lkey;
983         DEBUG("%p: new MR lkey for MP %p: 0x%08" PRIu32,
984               (void *)txq, (void *)mp, txq->mp2mr[i].lkey);
985         return txq->mp2mr[i].lkey;
986 }
987
988 /**
989  * Copy scattered mbuf contents to a single linear buffer.
990  *
991  * @param[out] linear
992  *   Linear output buffer.
993  * @param[in] buf
994  *   Scattered input buffer.
995  *
996  * @return
997  *   Number of bytes copied to the output buffer or 0 if not large enough.
998  */
999 static unsigned int
1000 linearize_mbuf(linear_t *linear, struct rte_mbuf *buf)
1001 {
1002         unsigned int size = 0;
1003         unsigned int offset;
1004
1005         do {
1006                 unsigned int len = DATA_LEN(buf);
1007
1008                 offset = size;
1009                 size += len;
1010                 if (unlikely(size > sizeof(*linear)))
1011                         return 0;
1012                 memcpy(&(*linear)[offset],
1013                        rte_pktmbuf_mtod(buf, uint8_t *),
1014                        len);
1015                 buf = NEXT(buf);
1016         } while (buf != NULL);
1017         return size;
1018 }
1019
1020 /**
1021  * DPDK callback for TX.
1022  *
1023  * @param dpdk_txq
1024  *   Generic pointer to TX queue structure.
1025  * @param[in] pkts
1026  *   Packets to transmit.
1027  * @param pkts_n
1028  *   Number of packets in array.
1029  *
1030  * @return
1031  *   Number of packets successfully transmitted (<= pkts_n).
1032  */
1033 static uint16_t
1034 mlx4_tx_burst(void *dpdk_txq, struct rte_mbuf **pkts, uint16_t pkts_n)
1035 {
1036         struct txq *txq = (struct txq *)dpdk_txq;
1037         mlx4_send_wr_t head;
1038         mlx4_send_wr_t **wr_next = &head.next;
1039         mlx4_send_wr_t *bad_wr;
1040         unsigned int elts_head = txq->elts_head;
1041         const unsigned int elts_tail = txq->elts_tail;
1042         const unsigned int elts_n = txq->elts_n;
1043         unsigned int i;
1044         unsigned int max;
1045         int err;
1046
1047         txq_complete(txq);
1048         max = (elts_n - (elts_head - elts_tail));
1049         if (max > elts_n)
1050                 max -= elts_n;
1051         assert(max >= 1);
1052         assert(max <= elts_n);
1053         /* Always leave one free entry in the ring. */
1054         --max;
1055         if (max == 0)
1056                 return 0;
1057         if (max > pkts_n)
1058                 max = pkts_n;
1059         for (i = 0; (i != max); ++i) {
1060                 struct rte_mbuf *buf = pkts[i];
1061                 struct txq_elt *elt = &(*txq->elts)[elts_head];
1062                 mlx4_send_wr_t *wr = &elt->wr;
1063                 unsigned int segs = NB_SEGS(buf);
1064 #if (MLX4_PMD_MAX_INLINE > 0) || defined(MLX4_PMD_SOFT_COUNTERS)
1065                 unsigned int sent_size = 0;
1066 #endif
1067                 unsigned int j;
1068                 int linearize = 0;
1069
1070                 /* Clean up old buffer. */
1071                 if (likely(WR_ID(wr->wr_id).offset != 0)) {
1072                         struct rte_mbuf *tmp = (void *)
1073                                 (elt->sges[0].addr - WR_ID(wr->wr_id).offset);
1074
1075                         /* Faster than rte_pktmbuf_free(). */
1076                         do {
1077                                 struct rte_mbuf *next = NEXT(tmp);
1078
1079                                 rte_pktmbuf_free_seg(tmp);
1080                                 tmp = next;
1081                         } while (tmp != NULL);
1082                 }
1083 #ifndef NDEBUG
1084                 /* For assert(). */
1085                 WR_ID(wr->wr_id).offset = 0;
1086                 for (j = 0; ((int)j < wr->num_sge); ++j) {
1087                         elt->sges[j].addr = 0;
1088                         elt->sges[j].length = 0;
1089                         elt->sges[j].lkey = 0;
1090                 }
1091                 wr->next = NULL;
1092                 wr->num_sge = 0;
1093 #endif
1094                 /* Sanity checks, most of which are only relevant with
1095                  * debugging enabled. */
1096                 assert(WR_ID(wr->wr_id).id == elts_head);
1097                 assert(WR_ID(wr->wr_id).offset == 0);
1098                 assert(wr->next == NULL);
1099                 assert(wr->sg_list == &elt->sges[0]);
1100                 assert(wr->num_sge == 0);
1101                 assert(wr->opcode == IBV_WR_SEND);
1102                 /* When there are too many segments, extra segments are
1103                  * linearized in the last SGE. */
1104                 if (unlikely(segs > elemof(elt->sges))) {
1105                         segs = (elemof(elt->sges) - 1);
1106                         linearize = 1;
1107                 }
1108                 /* Set WR fields. */
1109                 assert(((uintptr_t)rte_pktmbuf_mtod(buf, char *) -
1110                         (uintptr_t)buf) <= 0xffff);
1111                 WR_ID(wr->wr_id).offset =
1112                         ((uintptr_t)rte_pktmbuf_mtod(buf, char *) -
1113                          (uintptr_t)buf);
1114                 wr->num_sge = segs;
1115                 /* Register segments as SGEs. */
1116                 for (j = 0; (j != segs); ++j) {
1117                         struct ibv_sge *sge = &elt->sges[j];
1118                         uint32_t lkey;
1119
1120                         /* Retrieve Memory Region key for this memory pool. */
1121                         lkey = txq_mp2mr(txq, buf->pool);
1122                         if (unlikely(lkey == (uint32_t)-1)) {
1123                                 /* MR does not exist. */
1124                                 DEBUG("%p: unable to get MP <-> MR"
1125                                       " association", (void *)txq);
1126                                 /* Clean up TX element. */
1127                                 WR_ID(elt->wr.wr_id).offset = 0;
1128 #ifndef NDEBUG
1129                                 /* For assert(). */
1130                                 while (j) {
1131                                         --j;
1132                                         --sge;
1133                                         sge->addr = 0;
1134                                         sge->length = 0;
1135                                         sge->lkey = 0;
1136                                 }
1137                                 wr->num_sge = 0;
1138 #endif
1139                                 goto stop;
1140                         }
1141                         /* Sanity checks, only relevant with debugging
1142                          * enabled. */
1143                         assert(sge->addr == 0);
1144                         assert(sge->length == 0);
1145                         assert(sge->lkey == 0);
1146                         /* Update SGE. */
1147                         sge->addr = (uintptr_t)rte_pktmbuf_mtod(buf, char *);
1148                         if (txq->priv->vf)
1149                                 rte_prefetch0((volatile void *)sge->addr);
1150                         sge->length = DATA_LEN(buf);
1151                         sge->lkey = lkey;
1152 #if (MLX4_PMD_MAX_INLINE > 0) || defined(MLX4_PMD_SOFT_COUNTERS)
1153                         sent_size += sge->length;
1154 #endif
1155                         buf = NEXT(buf);
1156                 }
1157                 /* If buf is not NULL here and is not going to be linearized,
1158                  * nb_segs is not valid. */
1159                 assert(j == segs);
1160                 assert((buf == NULL) || (linearize));
1161                 /* Linearize extra segments. */
1162                 if (linearize) {
1163                         struct ibv_sge *sge = &elt->sges[segs];
1164                         linear_t *linear = &(*txq->elts_linear)[elts_head];
1165                         unsigned int size = linearize_mbuf(linear, buf);
1166
1167                         assert(segs == (elemof(elt->sges) - 1));
1168                         if (size == 0) {
1169                                 /* Invalid packet. */
1170                                 DEBUG("%p: packet too large to be linearized.",
1171                                       (void *)txq);
1172                                 /* Clean up TX element. */
1173                                 WR_ID(elt->wr.wr_id).offset = 0;
1174 #ifndef NDEBUG
1175                                 /* For assert(). */
1176                                 while (j) {
1177                                         --j;
1178                                         --sge;
1179                                         sge->addr = 0;
1180                                         sge->length = 0;
1181                                         sge->lkey = 0;
1182                                 }
1183                                 wr->num_sge = 0;
1184 #endif
1185                                 goto stop;
1186                         }
1187                         /* If MLX4_PMD_SGE_WR_N is 1, free mbuf immediately
1188                          * and clear offset from WR ID. */
1189                         if (elemof(elt->sges) == 1) {
1190                                 do {
1191                                         struct rte_mbuf *next = NEXT(buf);
1192
1193                                         rte_pktmbuf_free_seg(buf);
1194                                         buf = next;
1195                                 } while (buf != NULL);
1196                                 WR_ID(wr->wr_id).offset = 0;
1197                         }
1198                         /* Set WR fields and fill SGE with linear buffer. */
1199                         ++wr->num_sge;
1200                         /* Sanity checks, only relevant with debugging
1201                          * enabled. */
1202                         assert(sge->addr == 0);
1203                         assert(sge->length == 0);
1204                         assert(sge->lkey == 0);
1205                         /* Update SGE. */
1206                         sge->addr = (uintptr_t)&(*linear)[0];
1207                         sge->length = size;
1208                         sge->lkey = txq->mr_linear->lkey;
1209 #if (MLX4_PMD_MAX_INLINE > 0) || defined(MLX4_PMD_SOFT_COUNTERS)
1210                         sent_size += size;
1211 #endif
1212                 }
1213                 /* Link WRs together for ibv_post_send(). */
1214                 *wr_next = wr;
1215                 wr_next = &wr->next;
1216 #if MLX4_PMD_MAX_INLINE > 0
1217                 if (sent_size <= txq->max_inline)
1218                         wr->send_flags = IBV_SEND_INLINE;
1219                 else
1220 #endif
1221                         wr->send_flags = 0;
1222                 if (++elts_head >= elts_n)
1223                         elts_head = 0;
1224 #ifdef MLX4_PMD_SOFT_COUNTERS
1225                 /* Increment sent bytes counter. */
1226                 txq->stats.obytes += sent_size;
1227 #endif
1228         }
1229 stop:
1230         /* Take a shortcut if nothing must be sent. */
1231         if (unlikely(i == 0))
1232                 return 0;
1233 #ifdef MLX4_PMD_SOFT_COUNTERS
1234         /* Increment sent packets counter. */
1235         txq->stats.opackets += i;
1236 #endif
1237         *wr_next = NULL;
1238         /* The last WR is the only one asking for a completion event. */
1239         containerof(wr_next, mlx4_send_wr_t, next)->
1240                 send_flags |= IBV_SEND_SIGNALED;
1241         err = mlx4_post_send(txq->qp, head.next, &bad_wr);
1242         if (unlikely(err)) {
1243                 unsigned int unsent = 0;
1244
1245                 /* An error occurred, completion event is lost. Fix counters. */
1246                 while (bad_wr != NULL) {
1247                         struct txq_elt *elt =
1248                                 containerof(bad_wr, struct txq_elt, wr);
1249                         mlx4_send_wr_t *wr = &elt->wr;
1250                         mlx4_send_wr_t *next = wr->next;
1251 #if defined(MLX4_PMD_SOFT_COUNTERS) || !defined(NDEBUG)
1252                         unsigned int j;
1253 #endif
1254
1255                         assert(wr == bad_wr);
1256                         /* Clean up TX element without freeing it, caller
1257                          * should take care of this. */
1258                         WR_ID(elt->wr.wr_id).offset = 0;
1259 #ifdef MLX4_PMD_SOFT_COUNTERS
1260                         for (j = 0; ((int)j < wr->num_sge); ++j)
1261                                 txq->stats.obytes -= wr->sg_list[j].length;
1262 #endif
1263                         ++unsent;
1264 #ifndef NDEBUG
1265                         /* For assert(). */
1266                         for (j = 0; ((int)j < wr->num_sge); ++j) {
1267                                 elt->sges[j].addr = 0;
1268                                 elt->sges[j].length = 0;
1269                                 elt->sges[j].lkey = 0;
1270                         }
1271                         wr->next = NULL;
1272                         wr->num_sge = 0;
1273 #endif
1274                         bad_wr = next;
1275                 }
1276 #ifdef MLX4_PMD_SOFT_COUNTERS
1277                 txq->stats.opackets -= unsent;
1278 #endif
1279                 assert(i >= unsent);
1280                 i -= unsent;
1281                 /* "Unsend" remaining packets. */
1282                 elts_head -= unsent;
1283                 if (elts_head >= elts_n)
1284                         elts_head += elts_n;
1285                 assert(elts_head < elts_n);
1286                 DEBUG("%p: mlx4_post_send() failed, %u unprocessed WRs: %s",
1287                       (void *)txq, unsent,
1288                       ((err <= -1) ? "Internal error" : strerror(err)));
1289         } else
1290                 ++txq->elts_comp;
1291         txq->elts_head = elts_head;
1292         return i;
1293 }
1294
1295 /**
1296  * Configure a TX queue.
1297  *
1298  * @param dev
1299  *   Pointer to Ethernet device structure.
1300  * @param txq
1301  *   Pointer to TX queue structure.
1302  * @param desc
1303  *   Number of descriptors to configure in queue.
1304  * @param socket
1305  *   NUMA socket on which memory must be allocated.
1306  * @param[in] conf
1307  *   Thresholds parameters.
1308  *
1309  * @return
1310  *   0 on success, errno value on failure.
1311  */
1312 static int
1313 txq_setup(struct rte_eth_dev *dev, struct txq *txq, uint16_t desc,
1314           unsigned int socket, const struct rte_eth_txconf *conf)
1315 {
1316         struct priv *priv = dev->data->dev_private;
1317         struct txq tmpl = {
1318                 .priv = priv,
1319                 .socket = socket
1320         };
1321         union {
1322                 struct ibv_qp_init_attr init;
1323                 struct ibv_exp_qp_attr mod;
1324         } attr;
1325         int ret = 0;
1326
1327         (void)conf; /* Thresholds configuration (ignored). */
1328         if ((desc == 0) || (desc % MLX4_PMD_SGE_WR_N)) {
1329                 ERROR("%p: invalid number of TX descriptors (must be a"
1330                       " multiple of %d)", (void *)dev, desc);
1331                 return EINVAL;
1332         }
1333         desc /= MLX4_PMD_SGE_WR_N;
1334         /* MRs will be registered in mp2mr[] later. */
1335         tmpl.cq = ibv_create_cq(priv->ctx, desc, NULL, NULL, 0);
1336         if (tmpl.cq == NULL) {
1337                 ret = ENOMEM;
1338                 ERROR("%p: CQ creation failure: %s",
1339                       (void *)dev, strerror(ret));
1340                 goto error;
1341         }
1342         DEBUG("priv->device_attr.max_qp_wr is %d",
1343               priv->device_attr.max_qp_wr);
1344         DEBUG("priv->device_attr.max_sge is %d",
1345               priv->device_attr.max_sge);
1346         attr.init = (struct ibv_qp_init_attr){
1347                 /* CQ to be associated with the send queue. */
1348                 .send_cq = tmpl.cq,
1349                 /* CQ to be associated with the receive queue. */
1350                 .recv_cq = tmpl.cq,
1351                 .cap = {
1352                         /* Max number of outstanding WRs. */
1353                         .max_send_wr = ((priv->device_attr.max_qp_wr < desc) ?
1354                                         priv->device_attr.max_qp_wr :
1355                                         desc),
1356                         /* Max number of scatter/gather elements in a WR. */
1357                         .max_send_sge = ((priv->device_attr.max_sge <
1358                                           MLX4_PMD_SGE_WR_N) ?
1359                                          priv->device_attr.max_sge :
1360                                          MLX4_PMD_SGE_WR_N),
1361 #if MLX4_PMD_MAX_INLINE > 0
1362                         .max_inline_data = MLX4_PMD_MAX_INLINE,
1363 #endif
1364                 },
1365                 .qp_type = IBV_QPT_RAW_PACKET,
1366                 /* Do *NOT* enable this, completions events are managed per
1367                  * TX burst. */
1368                 .sq_sig_all = 0
1369         };
1370         tmpl.qp = ibv_create_qp(priv->pd, &attr.init);
1371         if (tmpl.qp == NULL) {
1372                 ret = (errno ? errno : EINVAL);
1373                 ERROR("%p: QP creation failure: %s",
1374                       (void *)dev, strerror(ret));
1375                 goto error;
1376         }
1377 #if MLX4_PMD_MAX_INLINE > 0
1378         /* ibv_create_qp() updates this value. */
1379         tmpl.max_inline = attr.init.cap.max_inline_data;
1380 #endif
1381         attr.mod = (struct ibv_exp_qp_attr){
1382                 /* Move the QP to this state. */
1383                 .qp_state = IBV_QPS_INIT,
1384                 /* Primary port number. */
1385                 .port_num = priv->port
1386         };
1387         ret = ibv_exp_modify_qp(tmpl.qp, &attr.mod,
1388                                 (IBV_EXP_QP_STATE | IBV_EXP_QP_PORT));
1389         if (ret) {
1390                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
1391                       (void *)dev, strerror(ret));
1392                 goto error;
1393         }
1394         ret = txq_alloc_elts(&tmpl, desc);
1395         if (ret) {
1396                 ERROR("%p: TXQ allocation failed: %s",
1397                       (void *)dev, strerror(ret));
1398                 goto error;
1399         }
1400         attr.mod = (struct ibv_exp_qp_attr){
1401                 .qp_state = IBV_QPS_RTR
1402         };
1403         ret = ibv_exp_modify_qp(tmpl.qp, &attr.mod, IBV_EXP_QP_STATE);
1404         if (ret) {
1405                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
1406                       (void *)dev, strerror(ret));
1407                 goto error;
1408         }
1409         attr.mod.qp_state = IBV_QPS_RTS;
1410         ret = ibv_exp_modify_qp(tmpl.qp, &attr.mod, IBV_EXP_QP_STATE);
1411         if (ret) {
1412                 ERROR("%p: QP state to IBV_QPS_RTS failed: %s",
1413                       (void *)dev, strerror(ret));
1414                 goto error;
1415         }
1416         /* Clean up txq in case we're reinitializing it. */
1417         DEBUG("%p: cleaning-up old txq just in case", (void *)txq);
1418         txq_cleanup(txq);
1419         *txq = tmpl;
1420         DEBUG("%p: txq updated with %p", (void *)txq, (void *)&tmpl);
1421         assert(ret == 0);
1422         return 0;
1423 error:
1424         txq_cleanup(&tmpl);
1425         assert(ret > 0);
1426         return ret;
1427 }
1428
1429 /**
1430  * DPDK callback to configure a TX queue.
1431  *
1432  * @param dev
1433  *   Pointer to Ethernet device structure.
1434  * @param idx
1435  *   TX queue index.
1436  * @param desc
1437  *   Number of descriptors to configure in queue.
1438  * @param socket
1439  *   NUMA socket on which memory must be allocated.
1440  * @param[in] conf
1441  *   Thresholds parameters.
1442  *
1443  * @return
1444  *   0 on success, negative errno value on failure.
1445  */
1446 static int
1447 mlx4_tx_queue_setup(struct rte_eth_dev *dev, uint16_t idx, uint16_t desc,
1448                     unsigned int socket, const struct rte_eth_txconf *conf)
1449 {
1450         struct priv *priv = dev->data->dev_private;
1451         struct txq *txq = (*priv->txqs)[idx];
1452         int ret;
1453
1454         priv_lock(priv);
1455         DEBUG("%p: configuring queue %u for %u descriptors",
1456               (void *)dev, idx, desc);
1457         if (idx >= priv->txqs_n) {
1458                 ERROR("%p: queue index out of range (%u >= %u)",
1459                       (void *)dev, idx, priv->txqs_n);
1460                 priv_unlock(priv);
1461                 return -EOVERFLOW;
1462         }
1463         if (txq != NULL) {
1464                 DEBUG("%p: reusing already allocated queue index %u (%p)",
1465                       (void *)dev, idx, (void *)txq);
1466                 if (priv->started) {
1467                         priv_unlock(priv);
1468                         return -EEXIST;
1469                 }
1470                 (*priv->txqs)[idx] = NULL;
1471                 txq_cleanup(txq);
1472         } else {
1473                 txq = rte_calloc_socket("TXQ", 1, sizeof(*txq), 0, socket);
1474                 if (txq == NULL) {
1475                         ERROR("%p: unable to allocate queue index %u",
1476                               (void *)dev, idx);
1477                         priv_unlock(priv);
1478                         return -ENOMEM;
1479                 }
1480         }
1481         ret = txq_setup(dev, txq, desc, socket, conf);
1482         if (ret)
1483                 rte_free(txq);
1484         else {
1485                 txq->stats.idx = idx;
1486                 DEBUG("%p: adding TX queue %p to list",
1487                       (void *)dev, (void *)txq);
1488                 (*priv->txqs)[idx] = txq;
1489                 /* Update send callback. */
1490                 dev->tx_pkt_burst = mlx4_tx_burst;
1491         }
1492         priv_unlock(priv);
1493         return -ret;
1494 }
1495
1496 /**
1497  * DPDK callback to release a TX queue.
1498  *
1499  * @param dpdk_txq
1500  *   Generic TX queue pointer.
1501  */
1502 static void
1503 mlx4_tx_queue_release(void *dpdk_txq)
1504 {
1505         struct txq *txq = (struct txq *)dpdk_txq;
1506         struct priv *priv;
1507         unsigned int i;
1508
1509         if (txq == NULL)
1510                 return;
1511         priv = txq->priv;
1512         priv_lock(priv);
1513         for (i = 0; (i != priv->txqs_n); ++i)
1514                 if ((*priv->txqs)[i] == txq) {
1515                         DEBUG("%p: removing TX queue %p from list",
1516                               (void *)priv->dev, (void *)txq);
1517                         (*priv->txqs)[i] = NULL;
1518                         break;
1519                 }
1520         txq_cleanup(txq);
1521         rte_free(txq);
1522         priv_unlock(priv);
1523 }
1524
1525 /* RX queues handling. */
1526
1527 /**
1528  * Allocate RX queue elements with scattered packets support.
1529  *
1530  * @param rxq
1531  *   Pointer to RX queue structure.
1532  * @param elts_n
1533  *   Number of elements to allocate.
1534  * @param[in] pool
1535  *   If not NULL, fetch buffers from this array instead of allocating them
1536  *   with rte_pktmbuf_alloc().
1537  *
1538  * @return
1539  *   0 on success, errno value on failure.
1540  */
1541 static int
1542 rxq_alloc_elts_sp(struct rxq *rxq, unsigned int elts_n,
1543                   struct rte_mbuf **pool)
1544 {
1545         unsigned int i;
1546         struct rxq_elt_sp (*elts)[elts_n] =
1547                 rte_calloc_socket("RXQ elements", 1, sizeof(*elts), 0,
1548                                   rxq->socket);
1549         int ret = 0;
1550
1551         if (elts == NULL) {
1552                 ERROR("%p: can't allocate packets array", (void *)rxq);
1553                 ret = ENOMEM;
1554                 goto error;
1555         }
1556         /* For each WR (packet). */
1557         for (i = 0; (i != elts_n); ++i) {
1558                 unsigned int j;
1559                 struct rxq_elt_sp *elt = &(*elts)[i];
1560                 struct ibv_recv_wr *wr = &elt->wr;
1561                 struct ibv_sge (*sges)[(elemof(elt->sges))] = &elt->sges;
1562
1563                 /* These two arrays must have the same size. */
1564                 assert(elemof(elt->sges) == elemof(elt->bufs));
1565                 /* Configure WR. */
1566                 wr->wr_id = i;
1567                 wr->next = &(*elts)[(i + 1)].wr;
1568                 wr->sg_list = &(*sges)[0];
1569                 wr->num_sge = elemof(*sges);
1570                 /* For each SGE (segment). */
1571                 for (j = 0; (j != elemof(elt->bufs)); ++j) {
1572                         struct ibv_sge *sge = &(*sges)[j];
1573                         struct rte_mbuf *buf;
1574
1575                         if (pool != NULL) {
1576                                 buf = *(pool++);
1577                                 assert(buf != NULL);
1578                                 rte_pktmbuf_reset(buf);
1579                         } else
1580                                 buf = rte_pktmbuf_alloc(rxq->mp);
1581                         if (buf == NULL) {
1582                                 assert(pool == NULL);
1583                                 ERROR("%p: empty mbuf pool", (void *)rxq);
1584                                 ret = ENOMEM;
1585                                 goto error;
1586                         }
1587                         elt->bufs[j] = buf;
1588                         /* Headroom is reserved by rte_pktmbuf_alloc(). */
1589                         assert(DATA_OFF(buf) == RTE_PKTMBUF_HEADROOM);
1590                         /* Buffer is supposed to be empty. */
1591                         assert(rte_pktmbuf_data_len(buf) == 0);
1592                         assert(rte_pktmbuf_pkt_len(buf) == 0);
1593                         /* sge->addr must be able to store a pointer. */
1594                         assert(sizeof(sge->addr) >= sizeof(uintptr_t));
1595                         if (j == 0) {
1596                                 /* The first SGE keeps its headroom. */
1597                                 sge->addr = (uintptr_t)rte_pktmbuf_mtod(buf,
1598                                                                         char *);
1599                                 sge->length = (buf->buf_len -
1600                                                RTE_PKTMBUF_HEADROOM);
1601                         } else {
1602                                 /* Subsequent SGEs lose theirs. */
1603                                 assert(DATA_OFF(buf) == RTE_PKTMBUF_HEADROOM);
1604                                 SET_DATA_OFF(buf, 0);
1605                                 sge->addr = (uintptr_t)buf->buf_addr;
1606                                 sge->length = buf->buf_len;
1607                         }
1608                         sge->lkey = rxq->mr->lkey;
1609                         /* Redundant check for tailroom. */
1610                         assert(sge->length == rte_pktmbuf_tailroom(buf));
1611                 }
1612         }
1613         /* The last WR pointer must be NULL. */
1614         (*elts)[(i - 1)].wr.next = NULL;
1615         DEBUG("%p: allocated and configured %u WRs (%zu segments)",
1616               (void *)rxq, elts_n, (elts_n * elemof((*elts)[0].sges)));
1617         rxq->elts_n = elts_n;
1618         rxq->elts.sp = elts;
1619         assert(ret == 0);
1620         return 0;
1621 error:
1622         if (elts != NULL) {
1623                 assert(pool == NULL);
1624                 for (i = 0; (i != elemof(*elts)); ++i) {
1625                         unsigned int j;
1626                         struct rxq_elt_sp *elt = &(*elts)[i];
1627
1628                         for (j = 0; (j != elemof(elt->bufs)); ++j) {
1629                                 struct rte_mbuf *buf = elt->bufs[j];
1630
1631                                 if (buf != NULL)
1632                                         rte_pktmbuf_free_seg(buf);
1633                         }
1634                 }
1635                 rte_free(elts);
1636         }
1637         DEBUG("%p: failed, freed everything", (void *)rxq);
1638         assert(ret > 0);
1639         return ret;
1640 }
1641
1642 /**
1643  * Free RX queue elements with scattered packets support.
1644  *
1645  * @param rxq
1646  *   Pointer to RX queue structure.
1647  */
1648 static void
1649 rxq_free_elts_sp(struct rxq *rxq)
1650 {
1651         unsigned int i;
1652         unsigned int elts_n = rxq->elts_n;
1653         struct rxq_elt_sp (*elts)[elts_n] = rxq->elts.sp;
1654
1655         DEBUG("%p: freeing WRs", (void *)rxq);
1656         rxq->elts_n = 0;
1657         rxq->elts.sp = NULL;
1658         if (elts == NULL)
1659                 return;
1660         for (i = 0; (i != elemof(*elts)); ++i) {
1661                 unsigned int j;
1662                 struct rxq_elt_sp *elt = &(*elts)[i];
1663
1664                 for (j = 0; (j != elemof(elt->bufs)); ++j) {
1665                         struct rte_mbuf *buf = elt->bufs[j];
1666
1667                         if (buf != NULL)
1668                                 rte_pktmbuf_free_seg(buf);
1669                 }
1670         }
1671         rte_free(elts);
1672 }
1673
1674 /**
1675  * Allocate RX queue elements.
1676  *
1677  * @param rxq
1678  *   Pointer to RX queue structure.
1679  * @param elts_n
1680  *   Number of elements to allocate.
1681  * @param[in] pool
1682  *   If not NULL, fetch buffers from this array instead of allocating them
1683  *   with rte_pktmbuf_alloc().
1684  *
1685  * @return
1686  *   0 on success, errno value on failure.
1687  */
1688 static int
1689 rxq_alloc_elts(struct rxq *rxq, unsigned int elts_n, struct rte_mbuf **pool)
1690 {
1691         unsigned int i;
1692         struct rxq_elt (*elts)[elts_n] =
1693                 rte_calloc_socket("RXQ elements", 1, sizeof(*elts), 0,
1694                                   rxq->socket);
1695         int ret = 0;
1696
1697         if (elts == NULL) {
1698                 ERROR("%p: can't allocate packets array", (void *)rxq);
1699                 ret = ENOMEM;
1700                 goto error;
1701         }
1702         /* For each WR (packet). */
1703         for (i = 0; (i != elts_n); ++i) {
1704                 struct rxq_elt *elt = &(*elts)[i];
1705                 struct ibv_recv_wr *wr = &elt->wr;
1706                 struct ibv_sge *sge = &(*elts)[i].sge;
1707                 struct rte_mbuf *buf;
1708
1709                 if (pool != NULL) {
1710                         buf = *(pool++);
1711                         assert(buf != NULL);
1712                         rte_pktmbuf_reset(buf);
1713                 } else
1714                         buf = rte_pktmbuf_alloc(rxq->mp);
1715                 if (buf == NULL) {
1716                         assert(pool == NULL);
1717                         ERROR("%p: empty mbuf pool", (void *)rxq);
1718                         ret = ENOMEM;
1719                         goto error;
1720                 }
1721                 /* Configure WR. Work request ID contains its own index in
1722                  * the elts array and the offset between SGE buffer header and
1723                  * its data. */
1724                 WR_ID(wr->wr_id).id = i;
1725                 WR_ID(wr->wr_id).offset =
1726                         (((uintptr_t)buf->buf_addr + RTE_PKTMBUF_HEADROOM) -
1727                          (uintptr_t)buf);
1728                 wr->next = &(*elts)[(i + 1)].wr;
1729                 wr->sg_list = sge;
1730                 wr->num_sge = 1;
1731                 /* Headroom is reserved by rte_pktmbuf_alloc(). */
1732                 assert(DATA_OFF(buf) == RTE_PKTMBUF_HEADROOM);
1733                 /* Buffer is supposed to be empty. */
1734                 assert(rte_pktmbuf_data_len(buf) == 0);
1735                 assert(rte_pktmbuf_pkt_len(buf) == 0);
1736                 /* sge->addr must be able to store a pointer. */
1737                 assert(sizeof(sge->addr) >= sizeof(uintptr_t));
1738                 /* SGE keeps its headroom. */
1739                 sge->addr = (uintptr_t)
1740                         ((uint8_t *)buf->buf_addr + RTE_PKTMBUF_HEADROOM);
1741                 sge->length = (buf->buf_len - RTE_PKTMBUF_HEADROOM);
1742                 sge->lkey = rxq->mr->lkey;
1743                 /* Redundant check for tailroom. */
1744                 assert(sge->length == rte_pktmbuf_tailroom(buf));
1745                 /* Make sure elts index and SGE mbuf pointer can be deduced
1746                  * from WR ID. */
1747                 if ((WR_ID(wr->wr_id).id != i) ||
1748                     ((void *)(sge->addr - WR_ID(wr->wr_id).offset) != buf)) {
1749                         ERROR("%p: cannot store index and offset in WR ID",
1750                               (void *)rxq);
1751                         sge->addr = 0;
1752                         rte_pktmbuf_free(buf);
1753                         ret = EOVERFLOW;
1754                         goto error;
1755                 }
1756         }
1757         /* The last WR pointer must be NULL. */
1758         (*elts)[(i - 1)].wr.next = NULL;
1759         DEBUG("%p: allocated and configured %u single-segment WRs",
1760               (void *)rxq, elts_n);
1761         rxq->elts_n = elts_n;
1762         rxq->elts.no_sp = elts;
1763         assert(ret == 0);
1764         return 0;
1765 error:
1766         if (elts != NULL) {
1767                 assert(pool == NULL);
1768                 for (i = 0; (i != elemof(*elts)); ++i) {
1769                         struct rxq_elt *elt = &(*elts)[i];
1770                         struct rte_mbuf *buf;
1771
1772                         if (elt->sge.addr == 0)
1773                                 continue;
1774                         assert(WR_ID(elt->wr.wr_id).id == i);
1775                         buf = (void *)
1776                                 (elt->sge.addr - WR_ID(elt->wr.wr_id).offset);
1777                         rte_pktmbuf_free_seg(buf);
1778                 }
1779                 rte_free(elts);
1780         }
1781         DEBUG("%p: failed, freed everything", (void *)rxq);
1782         assert(ret > 0);
1783         return ret;
1784 }
1785
1786 /**
1787  * Free RX queue elements.
1788  *
1789  * @param rxq
1790  *   Pointer to RX queue structure.
1791  */
1792 static void
1793 rxq_free_elts(struct rxq *rxq)
1794 {
1795         unsigned int i;
1796         unsigned int elts_n = rxq->elts_n;
1797         struct rxq_elt (*elts)[elts_n] = rxq->elts.no_sp;
1798
1799         DEBUG("%p: freeing WRs", (void *)rxq);
1800         rxq->elts_n = 0;
1801         rxq->elts.no_sp = NULL;
1802         if (elts == NULL)
1803                 return;
1804         for (i = 0; (i != elemof(*elts)); ++i) {
1805                 struct rxq_elt *elt = &(*elts)[i];
1806                 struct rte_mbuf *buf;
1807
1808                 if (elt->sge.addr == 0)
1809                         continue;
1810                 assert(WR_ID(elt->wr.wr_id).id == i);
1811                 buf = (void *)(elt->sge.addr - WR_ID(elt->wr.wr_id).offset);
1812                 rte_pktmbuf_free_seg(buf);
1813         }
1814         rte_free(elts);
1815 }
1816
1817 /**
1818  * Unregister a MAC address from a RX queue.
1819  *
1820  * @param rxq
1821  *   Pointer to RX queue structure.
1822  * @param mac_index
1823  *   MAC address index.
1824  */
1825 static void
1826 rxq_mac_addr_del(struct rxq *rxq, unsigned int mac_index)
1827 {
1828 #if defined(NDEBUG) || defined(MLX4_COMPAT_VMWARE)
1829         struct priv *priv = rxq->priv;
1830         const uint8_t (*mac)[ETHER_ADDR_LEN] =
1831                 (const uint8_t (*)[ETHER_ADDR_LEN])
1832                 priv->mac[mac_index].addr_bytes;
1833 #endif
1834
1835         assert(mac_index < elemof(priv->mac));
1836         if (!BITFIELD_ISSET(rxq->mac_configured, mac_index)) {
1837                 assert(rxq->mac_flow[mac_index] == NULL);
1838                 return;
1839         }
1840         DEBUG("%p: removing MAC address %02x:%02x:%02x:%02x:%02x:%02x"
1841               " index %u",
1842               (void *)rxq,
1843               (*mac)[0], (*mac)[1], (*mac)[2], (*mac)[3], (*mac)[4], (*mac)[5],
1844               mac_index);
1845 #ifdef MLX4_COMPAT_VMWARE
1846         if (priv->vmware) {
1847                 union ibv_gid gid = { .raw = { 0 } };
1848
1849                 memcpy(&gid.raw[10], *mac, sizeof(*mac));
1850                 claim_zero(ibv_detach_mcast(rxq->qp, &gid, 0));
1851                 BITFIELD_RESET(rxq->mac_configured, mac_index);
1852                 return;
1853         }
1854 #endif
1855         assert(rxq->mac_flow[mac_index] != NULL);
1856         claim_zero(ibv_exp_destroy_flow(rxq->mac_flow[mac_index]));
1857         rxq->mac_flow[mac_index] = NULL;
1858         BITFIELD_RESET(rxq->mac_configured, mac_index);
1859 }
1860
1861 /**
1862  * Unregister all MAC addresses from a RX queue.
1863  *
1864  * @param rxq
1865  *   Pointer to RX queue structure.
1866  */
1867 static void
1868 rxq_mac_addrs_del(struct rxq *rxq)
1869 {
1870         struct priv *priv = rxq->priv;
1871         unsigned int i;
1872
1873         for (i = 0; (i != elemof(priv->mac)); ++i)
1874                 rxq_mac_addr_del(rxq, i);
1875 }
1876
1877 static int rxq_promiscuous_enable(struct rxq *);
1878 static void rxq_promiscuous_disable(struct rxq *);
1879
1880 /**
1881  * Register a MAC address in a RX queue.
1882  *
1883  * @param rxq
1884  *   Pointer to RX queue structure.
1885  * @param mac_index
1886  *   MAC address index to register.
1887  *
1888  * @return
1889  *   0 on success, errno value on failure.
1890  */
1891 static int
1892 rxq_mac_addr_add(struct rxq *rxq, unsigned int mac_index)
1893 {
1894         struct priv *priv = rxq->priv;
1895         const uint8_t (*mac)[ETHER_ADDR_LEN] =
1896                 (const uint8_t (*)[ETHER_ADDR_LEN])
1897                 priv->mac[mac_index].addr_bytes;
1898         unsigned int vlans = 0;
1899         unsigned int specs = 0;
1900         unsigned int i, j;
1901         struct ibv_exp_flow *flow;
1902
1903         assert(mac_index < elemof(priv->mac));
1904         if (BITFIELD_ISSET(rxq->mac_configured, mac_index))
1905                 rxq_mac_addr_del(rxq, mac_index);
1906         /* Number of configured VLANs. */
1907         for (i = 0; (i != elemof(priv->vlan_filter)); ++i)
1908                 if (priv->vlan_filter[i].enabled)
1909                         ++vlans;
1910         specs = (vlans ? vlans : 1);
1911
1912         /* Allocate flow specification on the stack. */
1913         struct ibv_exp_flow_attr data
1914                 [1 +
1915                  (sizeof(struct ibv_exp_flow_spec_eth[specs]) /
1916                   sizeof(struct ibv_exp_flow_attr)) +
1917                  !!(sizeof(struct ibv_exp_flow_spec_eth[specs]) %
1918                     sizeof(struct ibv_exp_flow_attr))];
1919         struct ibv_exp_flow_attr *attr = (void *)&data[0];
1920         struct ibv_exp_flow_spec_eth *spec = (void *)&data[1];
1921
1922         /*
1923          * No padding must be inserted by the compiler between attr and spec.
1924          * This layout is expected by libibverbs.
1925          */
1926         assert(((uint8_t *)attr + sizeof(*attr)) == (uint8_t *)spec);
1927         *attr = (struct ibv_exp_flow_attr){
1928                 .type = IBV_EXP_FLOW_ATTR_NORMAL,
1929                 .num_of_specs = specs,
1930                 .port = priv->port,
1931                 .flags = 0
1932         };
1933         *spec = (struct ibv_exp_flow_spec_eth){
1934                 .type = IBV_EXP_FLOW_SPEC_ETH,
1935                 .size = sizeof(*spec),
1936                 .val = {
1937                         .dst_mac = {
1938                                 (*mac)[0], (*mac)[1], (*mac)[2],
1939                                 (*mac)[3], (*mac)[4], (*mac)[5]
1940                         }
1941                 },
1942                 .mask = {
1943                         .dst_mac = "\xff\xff\xff\xff\xff\xff",
1944                         .vlan_tag = (vlans ? htons(0xfff) : 0)
1945                 }
1946         };
1947         /* Fill VLAN specifications. */
1948         for (i = 0, j = 0; (i != elemof(priv->vlan_filter)); ++i) {
1949                 if (!priv->vlan_filter[i].enabled)
1950                         continue;
1951                 assert(j != vlans);
1952                 if (j)
1953                         spec[j] = spec[0];
1954                 spec[j].val.vlan_tag = htons(priv->vlan_filter[i].id);
1955                 ++j;
1956         }
1957         DEBUG("%p: adding MAC address %02x:%02x:%02x:%02x:%02x:%02x index %u"
1958               " (%u VLAN(s) configured)",
1959               (void *)rxq,
1960               (*mac)[0], (*mac)[1], (*mac)[2], (*mac)[3], (*mac)[4], (*mac)[5],
1961               mac_index,
1962               vlans);
1963 #ifdef MLX4_COMPAT_VMWARE
1964         if (priv->vmware) {
1965                 union ibv_gid gid = { .raw = { 0 } };
1966
1967                 /* Call multicast attach with unicast mac to get traffic. */
1968                 memcpy(&gid.raw[10], *mac, sizeof(*mac));
1969                 errno = 0;
1970                 if (ibv_attach_mcast(rxq->qp, &gid, 0)) {
1971                         if (errno)
1972                                 return errno;
1973                         return EINVAL;
1974                 }
1975                 BITFIELD_SET(rxq->mac_configured, mac_index);
1976                 return 0;
1977         }
1978 #endif
1979         /* Create related flow. */
1980         errno = 0;
1981         flow = ibv_exp_create_flow(rxq->qp, attr);
1982         if (flow == NULL) {
1983                 int err = errno;
1984
1985                 /* Flow creation failure is not fatal when in DMFS A0 mode.
1986                  * Ignore error if promiscuity is already enabled or can be
1987                  * enabled. */
1988                 if (priv->promisc_ok)
1989                         return 0;
1990                 if ((rxq->promisc_flow != NULL) ||
1991                     (rxq_promiscuous_enable(rxq) == 0)) {
1992                         if (rxq->promisc_flow != NULL)
1993                                 rxq_promiscuous_disable(rxq);
1994                         WARN("cannot configure normal flow but promiscuous"
1995                              " mode is fine, assuming promiscuous optimization"
1996                              " is enabled"
1997                              " (options mlx4_core log_num_mgm_entry_size=-7)");
1998                         priv->promisc_ok = 1;
1999                         return 0;
2000                 }
2001                 errno = err;
2002                 /* It's not clear whether errno is always set in this case. */
2003                 ERROR("%p: flow configuration failed, errno=%d: %s",
2004                       (void *)rxq, errno,
2005                       (errno ? strerror(errno) : "Unknown error"));
2006                 if (errno)
2007                         return errno;
2008                 return EINVAL;
2009         }
2010         assert(rxq->mac_flow[mac_index] == NULL);
2011         rxq->mac_flow[mac_index] = flow;
2012         BITFIELD_SET(rxq->mac_configured, mac_index);
2013         return 0;
2014 }
2015
2016 /**
2017  * Register all MAC addresses in a RX queue.
2018  *
2019  * @param rxq
2020  *   Pointer to RX queue structure.
2021  *
2022  * @return
2023  *   0 on success, errno value on failure.
2024  */
2025 static int
2026 rxq_mac_addrs_add(struct rxq *rxq)
2027 {
2028         struct priv *priv = rxq->priv;
2029         unsigned int i;
2030         int ret;
2031
2032         for (i = 0; (i != elemof(priv->mac)); ++i) {
2033                 if (!BITFIELD_ISSET(priv->mac_configured, i))
2034                         continue;
2035                 ret = rxq_mac_addr_add(rxq, i);
2036                 if (!ret)
2037                         continue;
2038                 /* Failure, rollback. */
2039                 while (i != 0)
2040                         rxq_mac_addr_del(rxq, --i);
2041                 assert(ret > 0);
2042                 return ret;
2043         }
2044         return 0;
2045 }
2046
2047 /**
2048  * Unregister a MAC address.
2049  *
2050  * In RSS mode, the MAC address is unregistered from the parent queue,
2051  * otherwise it is unregistered from each queue directly.
2052  *
2053  * @param priv
2054  *   Pointer to private structure.
2055  * @param mac_index
2056  *   MAC address index.
2057  */
2058 static void
2059 priv_mac_addr_del(struct priv *priv, unsigned int mac_index)
2060 {
2061         unsigned int i;
2062
2063         assert(mac_index < elemof(priv->mac));
2064         if (!BITFIELD_ISSET(priv->mac_configured, mac_index))
2065                 return;
2066         if (priv->rss) {
2067                 rxq_mac_addr_del(&priv->rxq_parent, mac_index);
2068                 goto end;
2069         }
2070         for (i = 0; (i != priv->dev->data->nb_rx_queues); ++i)
2071                 rxq_mac_addr_del((*priv->rxqs)[i], mac_index);
2072 end:
2073         BITFIELD_RESET(priv->mac_configured, mac_index);
2074 }
2075
2076 /**
2077  * Register a MAC address.
2078  *
2079  * In RSS mode, the MAC address is registered in the parent queue,
2080  * otherwise it is registered in each queue directly.
2081  *
2082  * @param priv
2083  *   Pointer to private structure.
2084  * @param mac_index
2085  *   MAC address index to use.
2086  * @param mac
2087  *   MAC address to register.
2088  *
2089  * @return
2090  *   0 on success, errno value on failure.
2091  */
2092 static int
2093 priv_mac_addr_add(struct priv *priv, unsigned int mac_index,
2094                   const uint8_t (*mac)[ETHER_ADDR_LEN])
2095 {
2096         unsigned int i;
2097         int ret;
2098
2099         assert(mac_index < elemof(priv->mac));
2100         /* First, make sure this address isn't already configured. */
2101         for (i = 0; (i != elemof(priv->mac)); ++i) {
2102                 /* Skip this index, it's going to be reconfigured. */
2103                 if (i == mac_index)
2104                         continue;
2105                 if (!BITFIELD_ISSET(priv->mac_configured, i))
2106                         continue;
2107                 if (memcmp(priv->mac[i].addr_bytes, *mac, sizeof(*mac)))
2108                         continue;
2109                 /* Address already configured elsewhere, return with error. */
2110                 return EADDRINUSE;
2111         }
2112         if (BITFIELD_ISSET(priv->mac_configured, mac_index))
2113                 priv_mac_addr_del(priv, mac_index);
2114         priv->mac[mac_index] = (struct ether_addr){
2115                 {
2116                         (*mac)[0], (*mac)[1], (*mac)[2],
2117                         (*mac)[3], (*mac)[4], (*mac)[5]
2118                 }
2119         };
2120         /* If device isn't started, this is all we need to do. */
2121         if (!priv->started) {
2122 #ifndef NDEBUG
2123                 /* Verify that all queues have this index disabled. */
2124                 for (i = 0; (i != priv->rxqs_n); ++i) {
2125                         if ((*priv->rxqs)[i] == NULL)
2126                                 continue;
2127                         assert(!BITFIELD_ISSET
2128                                ((*priv->rxqs)[i]->mac_configured, mac_index));
2129                 }
2130 #endif
2131                 goto end;
2132         }
2133         if (priv->rss) {
2134                 ret = rxq_mac_addr_add(&priv->rxq_parent, mac_index);
2135                 if (ret)
2136                         return ret;
2137                 goto end;
2138         }
2139         for (i = 0; (i != priv->rxqs_n); ++i) {
2140                 if ((*priv->rxqs)[i] == NULL)
2141                         continue;
2142                 ret = rxq_mac_addr_add((*priv->rxqs)[i], mac_index);
2143                 if (!ret)
2144                         continue;
2145                 /* Failure, rollback. */
2146                 while (i != 0)
2147                         if ((*priv->rxqs)[(--i)] != NULL)
2148                                 rxq_mac_addr_del((*priv->rxqs)[i], mac_index);
2149                 return ret;
2150         }
2151 end:
2152         BITFIELD_SET(priv->mac_configured, mac_index);
2153         return 0;
2154 }
2155
2156 /**
2157  * Enable allmulti mode in a RX queue.
2158  *
2159  * @param rxq
2160  *   Pointer to RX queue structure.
2161  *
2162  * @return
2163  *   0 on success, errno value on failure.
2164  */
2165 static int
2166 rxq_allmulticast_enable(struct rxq *rxq)
2167 {
2168         struct ibv_exp_flow *flow;
2169         struct ibv_exp_flow_attr attr = {
2170                 .type = IBV_EXP_FLOW_ATTR_MC_DEFAULT,
2171                 .num_of_specs = 0,
2172                 .port = rxq->priv->port,
2173                 .flags = 0
2174         };
2175
2176 #ifdef MLX4_COMPAT_VMWARE
2177         if (rxq->priv->vmware) {
2178                 ERROR("%p: allmulticast mode is not supported in VMware",
2179                       (void *)rxq);
2180                 return EINVAL;
2181         }
2182 #endif
2183         DEBUG("%p: enabling allmulticast mode", (void *)rxq);
2184         if (rxq->allmulti_flow != NULL)
2185                 return EBUSY;
2186         errno = 0;
2187         flow = ibv_exp_create_flow(rxq->qp, &attr);
2188         if (flow == NULL) {
2189                 /* It's not clear whether errno is always set in this case. */
2190                 ERROR("%p: flow configuration failed, errno=%d: %s",
2191                       (void *)rxq, errno,
2192                       (errno ? strerror(errno) : "Unknown error"));
2193                 if (errno)
2194                         return errno;
2195                 return EINVAL;
2196         }
2197         rxq->allmulti_flow = flow;
2198         DEBUG("%p: allmulticast mode enabled", (void *)rxq);
2199         return 0;
2200 }
2201
2202 /**
2203  * Disable allmulti mode in a RX queue.
2204  *
2205  * @param rxq
2206  *   Pointer to RX queue structure.
2207  */
2208 static void
2209 rxq_allmulticast_disable(struct rxq *rxq)
2210 {
2211 #ifdef MLX4_COMPAT_VMWARE
2212         if (rxq->priv->vmware) {
2213                 ERROR("%p: allmulticast mode is not supported in VMware",
2214                       (void *)rxq);
2215                 return;
2216         }
2217 #endif
2218         DEBUG("%p: disabling allmulticast mode", (void *)rxq);
2219         if (rxq->allmulti_flow == NULL)
2220                 return;
2221         claim_zero(ibv_exp_destroy_flow(rxq->allmulti_flow));
2222         rxq->allmulti_flow = NULL;
2223         DEBUG("%p: allmulticast mode disabled", (void *)rxq);
2224 }
2225
2226 /**
2227  * Enable promiscuous mode in a RX queue.
2228  *
2229  * @param rxq
2230  *   Pointer to RX queue structure.
2231  *
2232  * @return
2233  *   0 on success, errno value on failure.
2234  */
2235 static int
2236 rxq_promiscuous_enable(struct rxq *rxq)
2237 {
2238         struct ibv_exp_flow *flow;
2239         struct ibv_exp_flow_attr attr = {
2240                 .type = IBV_EXP_FLOW_ATTR_ALL_DEFAULT,
2241                 .num_of_specs = 0,
2242                 .port = rxq->priv->port,
2243                 .flags = 0
2244         };
2245
2246 #ifdef MLX4_COMPAT_VMWARE
2247         if (rxq->priv->vmware) {
2248                 ERROR("%p: promiscuous mode is not supported in VMware",
2249                       (void *)rxq);
2250                 return EINVAL;
2251         }
2252 #endif
2253         if (rxq->priv->vf)
2254                 return 0;
2255         DEBUG("%p: enabling promiscuous mode", (void *)rxq);
2256         if (rxq->promisc_flow != NULL)
2257                 return EBUSY;
2258         errno = 0;
2259         flow = ibv_exp_create_flow(rxq->qp, &attr);
2260         if (flow == NULL) {
2261                 /* It's not clear whether errno is always set in this case. */
2262                 ERROR("%p: flow configuration failed, errno=%d: %s",
2263                       (void *)rxq, errno,
2264                       (errno ? strerror(errno) : "Unknown error"));
2265                 if (errno)
2266                         return errno;
2267                 return EINVAL;
2268         }
2269         rxq->promisc_flow = flow;
2270         DEBUG("%p: promiscuous mode enabled", (void *)rxq);
2271         return 0;
2272 }
2273
2274 /**
2275  * Disable promiscuous mode in a RX queue.
2276  *
2277  * @param rxq
2278  *   Pointer to RX queue structure.
2279  */
2280 static void
2281 rxq_promiscuous_disable(struct rxq *rxq)
2282 {
2283 #ifdef MLX4_COMPAT_VMWARE
2284         if (rxq->priv->vmware) {
2285                 ERROR("%p: promiscuous mode is not supported in VMware",
2286                       (void *)rxq);
2287                 return;
2288         }
2289 #endif
2290         if (rxq->priv->vf)
2291                 return;
2292         DEBUG("%p: disabling promiscuous mode", (void *)rxq);
2293         if (rxq->promisc_flow == NULL)
2294                 return;
2295         claim_zero(ibv_exp_destroy_flow(rxq->promisc_flow));
2296         rxq->promisc_flow = NULL;
2297         DEBUG("%p: promiscuous mode disabled", (void *)rxq);
2298 }
2299
2300 /**
2301  * Clean up a RX queue.
2302  *
2303  * Destroy objects, free allocated memory and reset the structure for reuse.
2304  *
2305  * @param rxq
2306  *   Pointer to RX queue structure.
2307  */
2308 static void
2309 rxq_cleanup(struct rxq *rxq)
2310 {
2311         DEBUG("cleaning up %p", (void *)rxq);
2312         if (rxq->sp)
2313                 rxq_free_elts_sp(rxq);
2314         else
2315                 rxq_free_elts(rxq);
2316         if (rxq->qp != NULL) {
2317                 rxq_promiscuous_disable(rxq);
2318                 rxq_allmulticast_disable(rxq);
2319                 rxq_mac_addrs_del(rxq);
2320                 claim_zero(ibv_destroy_qp(rxq->qp));
2321         }
2322         if (rxq->cq != NULL)
2323                 claim_zero(ibv_destroy_cq(rxq->cq));
2324         if (rxq->mr != NULL)
2325                 claim_zero(ibv_dereg_mr(rxq->mr));
2326         memset(rxq, 0, sizeof(*rxq));
2327 }
2328
2329 static uint16_t
2330 mlx4_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n);
2331
2332 /**
2333  * DPDK callback for RX with scattered packets support.
2334  *
2335  * @param dpdk_rxq
2336  *   Generic pointer to RX queue structure.
2337  * @param[out] pkts
2338  *   Array to store received packets.
2339  * @param pkts_n
2340  *   Maximum number of packets in array.
2341  *
2342  * @return
2343  *   Number of packets successfully received (<= pkts_n).
2344  */
2345 static uint16_t
2346 mlx4_rx_burst_sp(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
2347 {
2348         struct rxq *rxq = (struct rxq *)dpdk_rxq;
2349         struct rxq_elt_sp (*elts)[rxq->elts_n] = rxq->elts.sp;
2350         struct ibv_wc wcs[pkts_n];
2351         struct ibv_recv_wr head;
2352         struct ibv_recv_wr **next = &head.next;
2353         struct ibv_recv_wr *bad_wr;
2354         int ret = 0;
2355         int wcs_n;
2356         int i;
2357
2358         if (unlikely(!rxq->sp))
2359                 return mlx4_rx_burst(dpdk_rxq, pkts, pkts_n);
2360         if (unlikely(elts == NULL)) /* See RTE_DEV_CMD_SET_MTU. */
2361                 return 0;
2362         wcs_n = ibv_poll_cq(rxq->cq, pkts_n, wcs);
2363         if (unlikely(wcs_n == 0))
2364                 return 0;
2365         if (unlikely(wcs_n < 0)) {
2366                 DEBUG("rxq=%p, ibv_poll_cq() failed (wc_n=%d)",
2367                       (void *)rxq, wcs_n);
2368                 return 0;
2369         }
2370         assert(wcs_n <= (int)pkts_n);
2371         /* For each work completion. */
2372         for (i = 0; (i != wcs_n); ++i) {
2373                 struct ibv_wc *wc = &wcs[i];
2374                 uint64_t wr_id = wc->wr_id;
2375                 uint32_t len = wc->byte_len;
2376                 struct rxq_elt_sp *elt = &(*elts)[wr_id];
2377                 struct ibv_recv_wr *wr = &elt->wr;
2378                 struct rte_mbuf *pkt_buf = NULL; /* Buffer returned in pkts. */
2379                 struct rte_mbuf **pkt_buf_next = &pkt_buf;
2380                 unsigned int seg_headroom = RTE_PKTMBUF_HEADROOM;
2381                 unsigned int j = 0;
2382
2383                 /* Sanity checks. */
2384                 assert(wr_id < rxq->elts_n);
2385                 assert(wr_id == wr->wr_id);
2386                 assert(wr->sg_list == elt->sges);
2387                 assert(wr->num_sge == elemof(elt->sges));
2388                 /* Link completed WRs together for repost. */
2389                 *next = wr;
2390                 next = &wr->next;
2391                 if (unlikely(wc->status != IBV_WC_SUCCESS)) {
2392                         /* Whatever, just repost the offending WR. */
2393                         DEBUG("rxq=%p, wr_id=%" PRIu64 ": bad work completion"
2394                               " status (%d): %s",
2395                               (void *)rxq, wc->wr_id, wc->status,
2396                               ibv_wc_status_str(wc->status));
2397 #ifdef MLX4_PMD_SOFT_COUNTERS
2398                         /* Increase dropped packets counter. */
2399                         ++rxq->stats.idropped;
2400 #endif
2401                         goto repost;
2402                 }
2403                 /*
2404                  * Replace spent segments with new ones, concatenate and
2405                  * return them as pkt_buf.
2406                  */
2407                 while (1) {
2408                         struct ibv_sge *sge = &elt->sges[j];
2409                         struct rte_mbuf *seg = elt->bufs[j];
2410                         struct rte_mbuf *rep;
2411                         unsigned int seg_tailroom;
2412
2413                         /*
2414                          * Fetch initial bytes of packet descriptor into a
2415                          * cacheline while allocating rep.
2416                          */
2417                         rte_prefetch0(seg);
2418                         rep = __rte_mbuf_raw_alloc(rxq->mp);
2419                         if (unlikely(rep == NULL)) {
2420                                 /*
2421                                  * Unable to allocate a replacement mbuf,
2422                                  * repost WR.
2423                                  */
2424                                 DEBUG("rxq=%p, wr_id=%" PRIu64 ":"
2425                                       " can't allocate a new mbuf",
2426                                       (void *)rxq, wr_id);
2427                                 if (pkt_buf != NULL)
2428                                         rte_pktmbuf_free(pkt_buf);
2429                                 /* Increase out of memory counters. */
2430                                 ++rxq->stats.rx_nombuf;
2431                                 ++rxq->priv->dev->data->rx_mbuf_alloc_failed;
2432                                 goto repost;
2433                         }
2434 #ifndef NDEBUG
2435                         /* Poison user-modifiable fields in rep. */
2436                         NEXT(rep) = (void *)((uintptr_t)-1);
2437                         SET_DATA_OFF(rep, 0xdead);
2438                         DATA_LEN(rep) = 0xd00d;
2439                         PKT_LEN(rep) = 0xdeadd00d;
2440                         NB_SEGS(rep) = 0x2a;
2441                         PORT(rep) = 0x2a;
2442                         rep->ol_flags = -1;
2443 #endif
2444                         assert(rep->buf_len == seg->buf_len);
2445                         assert(rep->buf_len == rxq->mb_len);
2446                         /* Reconfigure sge to use rep instead of seg. */
2447                         assert(sge->lkey == rxq->mr->lkey);
2448                         sge->addr = ((uintptr_t)rep->buf_addr + seg_headroom);
2449                         elt->bufs[j] = rep;
2450                         ++j;
2451                         /* Update pkt_buf if it's the first segment, or link
2452                          * seg to the previous one and update pkt_buf_next. */
2453                         *pkt_buf_next = seg;
2454                         pkt_buf_next = &NEXT(seg);
2455                         /* Update seg information. */
2456                         seg_tailroom = (seg->buf_len - seg_headroom);
2457                         assert(sge->length == seg_tailroom);
2458                         SET_DATA_OFF(seg, seg_headroom);
2459                         if (likely(len <= seg_tailroom)) {
2460                                 /* Last segment. */
2461                                 DATA_LEN(seg) = len;
2462                                 PKT_LEN(seg) = len;
2463                                 /* Sanity check. */
2464                                 assert(rte_pktmbuf_headroom(seg) ==
2465                                        seg_headroom);
2466                                 assert(rte_pktmbuf_tailroom(seg) ==
2467                                        (seg_tailroom - len));
2468                                 break;
2469                         }
2470                         DATA_LEN(seg) = seg_tailroom;
2471                         PKT_LEN(seg) = seg_tailroom;
2472                         /* Sanity check. */
2473                         assert(rte_pktmbuf_headroom(seg) == seg_headroom);
2474                         assert(rte_pktmbuf_tailroom(seg) == 0);
2475                         /* Fix len and clear headroom for next segments. */
2476                         len -= seg_tailroom;
2477                         seg_headroom = 0;
2478                 }
2479                 /* Update head and tail segments. */
2480                 *pkt_buf_next = NULL;
2481                 assert(pkt_buf != NULL);
2482                 assert(j != 0);
2483                 NB_SEGS(pkt_buf) = j;
2484                 PORT(pkt_buf) = rxq->port_id;
2485                 PKT_LEN(pkt_buf) = wc->byte_len;
2486                 pkt_buf->ol_flags = 0;
2487
2488                 /* Return packet. */
2489                 *(pkts++) = pkt_buf;
2490                 ++ret;
2491 #ifdef MLX4_PMD_SOFT_COUNTERS
2492                 /* Increase bytes counter. */
2493                 rxq->stats.ibytes += wc->byte_len;
2494 #endif
2495 repost:
2496                 continue;
2497         }
2498         *next = NULL;
2499         /* Repost WRs. */
2500 #ifdef DEBUG_RECV
2501         DEBUG("%p: reposting %d WRs starting from %" PRIu64 " (%p)",
2502               (void *)rxq, wcs_n, wcs[0].wr_id, (void *)head.next);
2503 #endif
2504         i = ibv_post_recv(rxq->qp, head.next, &bad_wr);
2505         if (unlikely(i)) {
2506                 /* Inability to repost WRs is fatal. */
2507                 DEBUG("%p: ibv_post_recv(): failed for WR %p: %s",
2508                       (void *)rxq->priv,
2509                       (void *)bad_wr,
2510                       strerror(i));
2511                 abort();
2512         }
2513 #ifdef MLX4_PMD_SOFT_COUNTERS
2514         /* Increase packets counter. */
2515         rxq->stats.ipackets += ret;
2516 #endif
2517         return ret;
2518 }
2519
2520 /**
2521  * DPDK callback for RX.
2522  *
2523  * The following function is the same as mlx4_rx_burst_sp(), except it doesn't
2524  * manage scattered packets. Improves performance when MRU is lower than the
2525  * size of the first segment.
2526  *
2527  * @param dpdk_rxq
2528  *   Generic pointer to RX queue structure.
2529  * @param[out] pkts
2530  *   Array to store received packets.
2531  * @param pkts_n
2532  *   Maximum number of packets in array.
2533  *
2534  * @return
2535  *   Number of packets successfully received (<= pkts_n).
2536  */
2537 static uint16_t
2538 mlx4_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
2539 {
2540         struct rxq *rxq = (struct rxq *)dpdk_rxq;
2541         struct rxq_elt (*elts)[rxq->elts_n] = rxq->elts.no_sp;
2542         struct ibv_wc wcs[pkts_n];
2543         struct ibv_recv_wr head;
2544         struct ibv_recv_wr **next = &head.next;
2545         struct ibv_recv_wr *bad_wr;
2546         int ret = 0;
2547         int wcs_n;
2548         int i;
2549
2550         if (unlikely(rxq->sp))
2551                 return mlx4_rx_burst_sp(dpdk_rxq, pkts, pkts_n);
2552         wcs_n = ibv_poll_cq(rxq->cq, pkts_n, wcs);
2553         if (unlikely(wcs_n == 0))
2554                 return 0;
2555         if (unlikely(wcs_n < 0)) {
2556                 DEBUG("rxq=%p, ibv_poll_cq() failed (wc_n=%d)",
2557                       (void *)rxq, wcs_n);
2558                 return 0;
2559         }
2560         assert(wcs_n <= (int)pkts_n);
2561         /* For each work completion. */
2562         for (i = 0; (i != wcs_n); ++i) {
2563                 struct ibv_wc *wc = &wcs[i];
2564                 uint64_t wr_id = wc->wr_id;
2565                 uint32_t len = wc->byte_len;
2566                 struct rxq_elt *elt = &(*elts)[WR_ID(wr_id).id];
2567                 struct ibv_recv_wr *wr = &elt->wr;
2568                 struct rte_mbuf *seg =
2569                         (void *)(elt->sge.addr - WR_ID(wr_id).offset);
2570                 struct rte_mbuf *rep;
2571
2572                 /* Sanity checks. */
2573                 assert(WR_ID(wr_id).id < rxq->elts_n);
2574                 assert(wr_id == wr->wr_id);
2575                 assert(wr->sg_list == &elt->sge);
2576                 assert(wr->num_sge == 1);
2577                 /* Link completed WRs together for repost. */
2578                 *next = wr;
2579                 next = &wr->next;
2580                 if (unlikely(wc->status != IBV_WC_SUCCESS)) {
2581                         /* Whatever, just repost the offending WR. */
2582                         DEBUG("rxq=%p, wr_id=%" PRIu32 ": bad work completion"
2583                               " status (%d): %s",
2584                               (void *)rxq, WR_ID(wr_id).id, wc->status,
2585                               ibv_wc_status_str(wc->status));
2586 #ifdef MLX4_PMD_SOFT_COUNTERS
2587                         /* Increase dropped packets counter. */
2588                         ++rxq->stats.idropped;
2589 #endif
2590                         goto repost;
2591                 }
2592                 /*
2593                  * Fetch initial bytes of packet descriptor into a
2594                  * cacheline while allocating rep.
2595                  */
2596                 rte_prefetch0(seg);
2597                 rep = __rte_mbuf_raw_alloc(rxq->mp);
2598                 if (unlikely(rep == NULL)) {
2599                         /*
2600                          * Unable to allocate a replacement mbuf,
2601                          * repost WR.
2602                          */
2603                         DEBUG("rxq=%p, wr_id=%" PRIu32 ":"
2604                               " can't allocate a new mbuf",
2605                               (void *)rxq, WR_ID(wr_id).id);
2606                         /* Increase out of memory counters. */
2607                         ++rxq->stats.rx_nombuf;
2608                         ++rxq->priv->dev->data->rx_mbuf_alloc_failed;
2609                         goto repost;
2610                 }
2611
2612                 /* Reconfigure sge to use rep instead of seg. */
2613                 elt->sge.addr = (uintptr_t)rep->buf_addr + RTE_PKTMBUF_HEADROOM;
2614                 assert(elt->sge.lkey == rxq->mr->lkey);
2615                 WR_ID(wr->wr_id).offset =
2616                         (((uintptr_t)rep->buf_addr + RTE_PKTMBUF_HEADROOM) -
2617                          (uintptr_t)rep);
2618                 assert(WR_ID(wr->wr_id).id == WR_ID(wr_id).id);
2619
2620                 /* Update seg information. */
2621                 SET_DATA_OFF(seg, RTE_PKTMBUF_HEADROOM);
2622                 NB_SEGS(seg) = 1;
2623                 PORT(seg) = rxq->port_id;
2624                 NEXT(seg) = NULL;
2625                 PKT_LEN(seg) = len;
2626                 DATA_LEN(seg) = len;
2627                 seg->ol_flags = 0;
2628
2629                 /* Return packet. */
2630                 *(pkts++) = seg;
2631                 ++ret;
2632 #ifdef MLX4_PMD_SOFT_COUNTERS
2633                 /* Increase bytes counter. */
2634                 rxq->stats.ibytes += wc->byte_len;
2635 #endif
2636 repost:
2637                 continue;
2638         }
2639         *next = NULL;
2640         /* Repost WRs. */
2641 #ifdef DEBUG_RECV
2642         DEBUG("%p: reposting %d WRs starting from %" PRIu32 " (%p)",
2643               (void *)rxq, wcs_n, WR_ID(wcs[0].wr_id).id, (void *)head.next);
2644 #endif
2645         i = ibv_post_recv(rxq->qp, head.next, &bad_wr);
2646         if (unlikely(i)) {
2647                 /* Inability to repost WRs is fatal. */
2648                 DEBUG("%p: ibv_post_recv(): failed for WR %p: %s",
2649                       (void *)rxq->priv,
2650                       (void *)bad_wr,
2651                       strerror(i));
2652                 abort();
2653         }
2654 #ifdef MLX4_PMD_SOFT_COUNTERS
2655         /* Increase packets counter. */
2656         rxq->stats.ipackets += ret;
2657 #endif
2658         return ret;
2659 }
2660
2661 #ifdef INLINE_RECV
2662
2663 /**
2664  * Allocate a Queue Pair in case inline receive is supported.
2665  *
2666  * @param priv
2667  *   Pointer to private structure.
2668  * @param cq
2669  *   Completion queue to associate with QP.
2670  * @param desc
2671  *   Number of descriptors in QP (hint only).
2672  *
2673  * @return
2674  *   QP pointer or NULL in case of error.
2675  */
2676 static struct ibv_qp *
2677 rxq_setup_qp(struct priv *priv, struct ibv_cq *cq, uint16_t desc)
2678 {
2679         struct ibv_exp_qp_init_attr attr = {
2680                 /* CQ to be associated with the send queue. */
2681                 .send_cq = cq,
2682                 /* CQ to be associated with the receive queue. */
2683                 .recv_cq = cq,
2684                 .max_inl_recv = priv->inl_recv_size,
2685                 .cap = {
2686                         /* Max number of outstanding WRs. */
2687                         .max_recv_wr = ((priv->device_attr.max_qp_wr < desc) ?
2688                                         priv->device_attr.max_qp_wr :
2689                                         desc),
2690                         /* Max number of scatter/gather elements in a WR. */
2691                         .max_recv_sge = ((priv->device_attr.max_sge <
2692                                           MLX4_PMD_SGE_WR_N) ?
2693                                          priv->device_attr.max_sge :
2694                                          MLX4_PMD_SGE_WR_N),
2695                 },
2696                 .qp_type = IBV_QPT_RAW_PACKET,
2697                 .pd = priv->pd
2698         };
2699
2700         attr.comp_mask = IBV_EXP_QP_INIT_ATTR_PD;
2701         attr.comp_mask |= IBV_EXP_QP_INIT_ATTR_INL_RECV;
2702
2703         return ibv_exp_create_qp(priv->ctx, &attr);
2704 }
2705
2706 #else /* INLINE_RECV */
2707
2708 /**
2709  * Allocate a Queue Pair.
2710  *
2711  * @param priv
2712  *   Pointer to private structure.
2713  * @param cq
2714  *   Completion queue to associate with QP.
2715  * @param desc
2716  *   Number of descriptors in QP (hint only).
2717  *
2718  * @return
2719  *   QP pointer or NULL in case of error.
2720  */
2721 static struct ibv_qp *
2722 rxq_setup_qp(struct priv *priv, struct ibv_cq *cq, uint16_t desc)
2723 {
2724         struct ibv_qp_init_attr attr = {
2725                 /* CQ to be associated with the send queue. */
2726                 .send_cq = cq,
2727                 /* CQ to be associated with the receive queue. */
2728                 .recv_cq = cq,
2729                 .cap = {
2730                         /* Max number of outstanding WRs. */
2731                         .max_recv_wr = ((priv->device_attr.max_qp_wr < desc) ?
2732                                         priv->device_attr.max_qp_wr :
2733                                         desc),
2734                         /* Max number of scatter/gather elements in a WR. */
2735                         .max_recv_sge = ((priv->device_attr.max_sge <
2736                                           MLX4_PMD_SGE_WR_N) ?
2737                                          priv->device_attr.max_sge :
2738                                          MLX4_PMD_SGE_WR_N),
2739                 },
2740                 .qp_type = IBV_QPT_RAW_PACKET
2741         };
2742
2743         return ibv_create_qp(priv->pd, &attr);
2744 }
2745
2746 #endif /* INLINE_RECV */
2747
2748 #ifdef RSS_SUPPORT
2749
2750 /**
2751  * Allocate a RSS Queue Pair.
2752  *
2753  * @param priv
2754  *   Pointer to private structure.
2755  * @param cq
2756  *   Completion queue to associate with QP.
2757  * @param desc
2758  *   Number of descriptors in QP (hint only).
2759  * @param parent
2760  *   If nonzero, create a parent QP, otherwise a child.
2761  *
2762  * @return
2763  *   QP pointer or NULL in case of error.
2764  */
2765 static struct ibv_qp *
2766 rxq_setup_qp_rss(struct priv *priv, struct ibv_cq *cq, uint16_t desc,
2767                  int parent)
2768 {
2769         struct ibv_exp_qp_init_attr attr = {
2770                 /* CQ to be associated with the send queue. */
2771                 .send_cq = cq,
2772                 /* CQ to be associated with the receive queue. */
2773                 .recv_cq = cq,
2774 #ifdef INLINE_RECV
2775                 .max_inl_recv = priv->inl_recv_size,
2776 #endif
2777                 .cap = {
2778                         /* Max number of outstanding WRs. */
2779                         .max_recv_wr = ((priv->device_attr.max_qp_wr < desc) ?
2780                                         priv->device_attr.max_qp_wr :
2781                                         desc),
2782                         /* Max number of scatter/gather elements in a WR. */
2783                         .max_recv_sge = ((priv->device_attr.max_sge <
2784                                           MLX4_PMD_SGE_WR_N) ?
2785                                          priv->device_attr.max_sge :
2786                                          MLX4_PMD_SGE_WR_N),
2787                 },
2788                 .qp_type = IBV_QPT_RAW_PACKET,
2789                 .comp_mask = (IBV_EXP_QP_INIT_ATTR_PD |
2790                               IBV_EXP_QP_INIT_ATTR_QPG),
2791                 .pd = priv->pd
2792         };
2793
2794 #ifdef INLINE_RECV
2795         attr.comp_mask |= IBV_EXP_QP_INIT_ATTR_INL_RECV;
2796 #endif
2797         if (parent) {
2798                 attr.qpg.qpg_type = IBV_EXP_QPG_PARENT;
2799                 /* TSS isn't necessary. */
2800                 attr.qpg.parent_attrib.tss_child_count = 0;
2801                 attr.qpg.parent_attrib.rss_child_count = priv->rxqs_n;
2802                 DEBUG("initializing parent RSS queue");
2803         } else {
2804                 attr.qpg.qpg_type = IBV_EXP_QPG_CHILD_RX;
2805                 attr.qpg.qpg_parent = priv->rxq_parent.qp;
2806                 DEBUG("initializing child RSS queue");
2807         }
2808         return ibv_exp_create_qp(priv->ctx, &attr);
2809 }
2810
2811 #endif /* RSS_SUPPORT */
2812
2813 /**
2814  * Reconfigure a RX queue with new parameters.
2815  *
2816  * rxq_rehash() does not allocate mbufs, which, if not done from the right
2817  * thread (such as a control thread), may corrupt the pool.
2818  * In case of failure, the queue is left untouched.
2819  *
2820  * @param dev
2821  *   Pointer to Ethernet device structure.
2822  * @param rxq
2823  *   RX queue pointer.
2824  *
2825  * @return
2826  *   0 on success, errno value on failure.
2827  */
2828 static int
2829 rxq_rehash(struct rte_eth_dev *dev, struct rxq *rxq)
2830 {
2831         struct priv *priv = rxq->priv;
2832         struct rxq tmpl = *rxq;
2833         unsigned int mbuf_n;
2834         unsigned int desc_n;
2835         struct rte_mbuf **pool;
2836         unsigned int i, k;
2837         struct ibv_exp_qp_attr mod;
2838         struct ibv_recv_wr *bad_wr;
2839         int err;
2840         int parent = (rxq == &priv->rxq_parent);
2841
2842         if (parent) {
2843                 ERROR("%p: cannot rehash parent queue %p",
2844                       (void *)dev, (void *)rxq);
2845                 return EINVAL;
2846         }
2847         DEBUG("%p: rehashing queue %p", (void *)dev, (void *)rxq);
2848         /* Number of descriptors and mbufs currently allocated. */
2849         desc_n = (tmpl.elts_n * (tmpl.sp ? MLX4_PMD_SGE_WR_N : 1));
2850         mbuf_n = desc_n;
2851         /* Enable scattered packets support for this queue if necessary. */
2852         if ((dev->data->dev_conf.rxmode.jumbo_frame) &&
2853             (dev->data->dev_conf.rxmode.max_rx_pkt_len >
2854              (tmpl.mb_len - RTE_PKTMBUF_HEADROOM))) {
2855                 tmpl.sp = 1;
2856                 desc_n /= MLX4_PMD_SGE_WR_N;
2857         } else
2858                 tmpl.sp = 0;
2859         DEBUG("%p: %s scattered packets support (%u WRs)",
2860               (void *)dev, (tmpl.sp ? "enabling" : "disabling"), desc_n);
2861         /* If scatter mode is the same as before, nothing to do. */
2862         if (tmpl.sp == rxq->sp) {
2863                 DEBUG("%p: nothing to do", (void *)dev);
2864                 return 0;
2865         }
2866         /* Remove attached flows if RSS is disabled (no parent queue). */
2867         if (!priv->rss) {
2868                 rxq_allmulticast_disable(&tmpl);
2869                 rxq_promiscuous_disable(&tmpl);
2870                 rxq_mac_addrs_del(&tmpl);
2871                 /* Update original queue in case of failure. */
2872                 rxq->allmulti_flow = tmpl.allmulti_flow;
2873                 rxq->promisc_flow = tmpl.promisc_flow;
2874                 memcpy(rxq->mac_configured, tmpl.mac_configured,
2875                        sizeof(rxq->mac_configured));
2876                 memcpy(rxq->mac_flow, tmpl.mac_flow, sizeof(rxq->mac_flow));
2877         }
2878         /* From now on, any failure will render the queue unusable.
2879          * Reinitialize QP. */
2880         mod = (struct ibv_exp_qp_attr){ .qp_state = IBV_QPS_RESET };
2881         err = ibv_exp_modify_qp(tmpl.qp, &mod, IBV_EXP_QP_STATE);
2882         if (err) {
2883                 ERROR("%p: cannot reset QP: %s", (void *)dev, strerror(err));
2884                 assert(err > 0);
2885                 return err;
2886         }
2887         err = ibv_resize_cq(tmpl.cq, desc_n);
2888         if (err) {
2889                 ERROR("%p: cannot resize CQ: %s", (void *)dev, strerror(err));
2890                 assert(err > 0);
2891                 return err;
2892         }
2893         mod = (struct ibv_exp_qp_attr){
2894                 /* Move the QP to this state. */
2895                 .qp_state = IBV_QPS_INIT,
2896                 /* Primary port number. */
2897                 .port_num = priv->port
2898         };
2899         err = ibv_exp_modify_qp(tmpl.qp, &mod,
2900                                 (IBV_EXP_QP_STATE |
2901 #ifdef RSS_SUPPORT
2902                                  (parent ? IBV_EXP_QP_GROUP_RSS : 0) |
2903 #endif /* RSS_SUPPORT */
2904                                  IBV_EXP_QP_PORT));
2905         if (err) {
2906                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
2907                       (void *)dev, strerror(err));
2908                 assert(err > 0);
2909                 return err;
2910         };
2911         /* Reconfigure flows. Do not care for errors. */
2912         if (!priv->rss) {
2913                 rxq_mac_addrs_add(&tmpl);
2914                 if (priv->promisc)
2915                         rxq_promiscuous_enable(&tmpl);
2916                 if (priv->allmulti)
2917                         rxq_allmulticast_enable(&tmpl);
2918                 /* Update original queue in case of failure. */
2919                 rxq->allmulti_flow = tmpl.allmulti_flow;
2920                 rxq->promisc_flow = tmpl.promisc_flow;
2921                 memcpy(rxq->mac_configured, tmpl.mac_configured,
2922                        sizeof(rxq->mac_configured));
2923                 memcpy(rxq->mac_flow, tmpl.mac_flow, sizeof(rxq->mac_flow));
2924         }
2925         /* Allocate pool. */
2926         pool = rte_malloc(__func__, (mbuf_n * sizeof(*pool)), 0);
2927         if (pool == NULL) {
2928                 ERROR("%p: cannot allocate memory", (void *)dev);
2929                 return ENOBUFS;
2930         }
2931         /* Snatch mbufs from original queue. */
2932         k = 0;
2933         if (rxq->sp) {
2934                 struct rxq_elt_sp (*elts)[rxq->elts_n] = rxq->elts.sp;
2935
2936                 for (i = 0; (i != elemof(*elts)); ++i) {
2937                         struct rxq_elt_sp *elt = &(*elts)[i];
2938                         unsigned int j;
2939
2940                         for (j = 0; (j != elemof(elt->bufs)); ++j) {
2941                                 assert(elt->bufs[j] != NULL);
2942                                 pool[k++] = elt->bufs[j];
2943                         }
2944                 }
2945         } else {
2946                 struct rxq_elt (*elts)[rxq->elts_n] = rxq->elts.no_sp;
2947
2948                 for (i = 0; (i != elemof(*elts)); ++i) {
2949                         struct rxq_elt *elt = &(*elts)[i];
2950                         struct rte_mbuf *buf = (void *)
2951                                 (elt->sge.addr - WR_ID(elt->wr.wr_id).offset);
2952
2953                         assert(WR_ID(elt->wr.wr_id).id == i);
2954                         pool[k++] = buf;
2955                 }
2956         }
2957         assert(k == mbuf_n);
2958         tmpl.elts_n = 0;
2959         tmpl.elts.sp = NULL;
2960         assert((void *)&tmpl.elts.sp == (void *)&tmpl.elts.no_sp);
2961         err = ((tmpl.sp) ?
2962                rxq_alloc_elts_sp(&tmpl, desc_n, pool) :
2963                rxq_alloc_elts(&tmpl, desc_n, pool));
2964         if (err) {
2965                 ERROR("%p: cannot reallocate WRs, aborting", (void *)dev);
2966                 rte_free(pool);
2967                 assert(err > 0);
2968                 return err;
2969         }
2970         assert(tmpl.elts_n == desc_n);
2971         assert(tmpl.elts.sp != NULL);
2972         rte_free(pool);
2973         /* Clean up original data. */
2974         rxq->elts_n = 0;
2975         rte_free(rxq->elts.sp);
2976         rxq->elts.sp = NULL;
2977         /* Post WRs. */
2978         err = ibv_post_recv(tmpl.qp,
2979                             (tmpl.sp ?
2980                              &(*tmpl.elts.sp)[0].wr :
2981                              &(*tmpl.elts.no_sp)[0].wr),
2982                             &bad_wr);
2983         if (err) {
2984                 ERROR("%p: ibv_post_recv() failed for WR %p: %s",
2985                       (void *)dev,
2986                       (void *)bad_wr,
2987                       strerror(err));
2988                 goto skip_rtr;
2989         }
2990         mod = (struct ibv_exp_qp_attr){
2991                 .qp_state = IBV_QPS_RTR
2992         };
2993         err = ibv_exp_modify_qp(tmpl.qp, &mod, IBV_EXP_QP_STATE);
2994         if (err)
2995                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
2996                       (void *)dev, strerror(err));
2997 skip_rtr:
2998         *rxq = tmpl;
2999         assert(err >= 0);
3000         return err;
3001 }
3002
3003 /**
3004  * Configure a RX queue.
3005  *
3006  * @param dev
3007  *   Pointer to Ethernet device structure.
3008  * @param rxq
3009  *   Pointer to RX queue structure.
3010  * @param desc
3011  *   Number of descriptors to configure in queue.
3012  * @param socket
3013  *   NUMA socket on which memory must be allocated.
3014  * @param[in] conf
3015  *   Thresholds parameters.
3016  * @param mp
3017  *   Memory pool for buffer allocations.
3018  *
3019  * @return
3020  *   0 on success, errno value on failure.
3021  */
3022 static int
3023 rxq_setup(struct rte_eth_dev *dev, struct rxq *rxq, uint16_t desc,
3024           unsigned int socket, const struct rte_eth_rxconf *conf,
3025           struct rte_mempool *mp)
3026 {
3027         struct priv *priv = dev->data->dev_private;
3028         struct rxq tmpl = {
3029                 .priv = priv,
3030                 .mp = mp,
3031                 .socket = socket
3032         };
3033         struct ibv_exp_qp_attr mod;
3034         struct ibv_recv_wr *bad_wr;
3035         struct rte_mbuf *buf;
3036         int ret = 0;
3037         int parent = (rxq == &priv->rxq_parent);
3038
3039         (void)conf; /* Thresholds configuration (ignored). */
3040         /*
3041          * If this is a parent queue, hardware must support RSS and
3042          * RSS must be enabled.
3043          */
3044         assert((!parent) || ((priv->hw_rss) && (priv->rss)));
3045         if (parent) {
3046                 /* Even if unused, ibv_create_cq() requires at least one
3047                  * descriptor. */
3048                 desc = 1;
3049                 goto skip_mr;
3050         }
3051         if ((desc == 0) || (desc % MLX4_PMD_SGE_WR_N)) {
3052                 ERROR("%p: invalid number of RX descriptors (must be a"
3053                       " multiple of %d)", (void *)dev, desc);
3054                 return EINVAL;
3055         }
3056         /* Get mbuf length. */
3057         buf = rte_pktmbuf_alloc(mp);
3058         if (buf == NULL) {
3059                 ERROR("%p: unable to allocate mbuf", (void *)dev);
3060                 return ENOMEM;
3061         }
3062         tmpl.mb_len = buf->buf_len;
3063         assert((rte_pktmbuf_headroom(buf) +
3064                 rte_pktmbuf_tailroom(buf)) == tmpl.mb_len);
3065         assert(rte_pktmbuf_headroom(buf) == RTE_PKTMBUF_HEADROOM);
3066         rte_pktmbuf_free(buf);
3067         /* Enable scattered packets support for this queue if necessary. */
3068         if ((dev->data->dev_conf.rxmode.jumbo_frame) &&
3069             (dev->data->dev_conf.rxmode.max_rx_pkt_len >
3070              (tmpl.mb_len - RTE_PKTMBUF_HEADROOM))) {
3071                 tmpl.sp = 1;
3072                 desc /= MLX4_PMD_SGE_WR_N;
3073         }
3074         DEBUG("%p: %s scattered packets support (%u WRs)",
3075               (void *)dev, (tmpl.sp ? "enabling" : "disabling"), desc);
3076         /* Use the entire RX mempool as the memory region. */
3077         tmpl.mr = ibv_reg_mr(priv->pd,
3078                              (void *)mp->elt_va_start,
3079                              (mp->elt_va_end - mp->elt_va_start),
3080                              (IBV_ACCESS_LOCAL_WRITE |
3081                               IBV_ACCESS_REMOTE_WRITE));
3082         if (tmpl.mr == NULL) {
3083                 ret = EINVAL;
3084                 ERROR("%p: MR creation failure: %s",
3085                       (void *)dev, strerror(ret));
3086                 goto error;
3087         }
3088 skip_mr:
3089         tmpl.cq = ibv_create_cq(priv->ctx, desc, NULL, NULL, 0);
3090         if (tmpl.cq == NULL) {
3091                 ret = ENOMEM;
3092                 ERROR("%p: CQ creation failure: %s",
3093                       (void *)dev, strerror(ret));
3094                 goto error;
3095         }
3096         DEBUG("priv->device_attr.max_qp_wr is %d",
3097               priv->device_attr.max_qp_wr);
3098         DEBUG("priv->device_attr.max_sge is %d",
3099               priv->device_attr.max_sge);
3100 #ifdef RSS_SUPPORT
3101         if (priv->rss)
3102                 tmpl.qp = rxq_setup_qp_rss(priv, tmpl.cq, desc, parent);
3103         else
3104 #endif /* RSS_SUPPORT */
3105                 tmpl.qp = rxq_setup_qp(priv, tmpl.cq, desc);
3106         if (tmpl.qp == NULL) {
3107                 ret = (errno ? errno : EINVAL);
3108                 ERROR("%p: QP creation failure: %s",
3109                       (void *)dev, strerror(ret));
3110                 goto error;
3111         }
3112         mod = (struct ibv_exp_qp_attr){
3113                 /* Move the QP to this state. */
3114                 .qp_state = IBV_QPS_INIT,
3115                 /* Primary port number. */
3116                 .port_num = priv->port
3117         };
3118         ret = ibv_exp_modify_qp(tmpl.qp, &mod,
3119                                 (IBV_EXP_QP_STATE |
3120 #ifdef RSS_SUPPORT
3121                                  (parent ? IBV_EXP_QP_GROUP_RSS : 0) |
3122 #endif /* RSS_SUPPORT */
3123                                  IBV_EXP_QP_PORT));
3124         if (ret) {
3125                 ERROR("%p: QP state to IBV_QPS_INIT failed: %s",
3126                       (void *)dev, strerror(ret));
3127                 goto error;
3128         }
3129         if ((parent) || (!priv->rss))  {
3130                 /* Configure MAC and broadcast addresses. */
3131                 ret = rxq_mac_addrs_add(&tmpl);
3132                 if (ret) {
3133                         ERROR("%p: QP flow attachment failed: %s",
3134                               (void *)dev, strerror(ret));
3135                         goto error;
3136                 }
3137         }
3138         /* Allocate descriptors for RX queues, except for the RSS parent. */
3139         if (parent)
3140                 goto skip_alloc;
3141         if (tmpl.sp)
3142                 ret = rxq_alloc_elts_sp(&tmpl, desc, NULL);
3143         else
3144                 ret = rxq_alloc_elts(&tmpl, desc, NULL);
3145         if (ret) {
3146                 ERROR("%p: RXQ allocation failed: %s",
3147                       (void *)dev, strerror(ret));
3148                 goto error;
3149         }
3150         ret = ibv_post_recv(tmpl.qp,
3151                             (tmpl.sp ?
3152                              &(*tmpl.elts.sp)[0].wr :
3153                              &(*tmpl.elts.no_sp)[0].wr),
3154                             &bad_wr);
3155         if (ret) {
3156                 ERROR("%p: ibv_post_recv() failed for WR %p: %s",
3157                       (void *)dev,
3158                       (void *)bad_wr,
3159                       strerror(ret));
3160                 goto error;
3161         }
3162 skip_alloc:
3163         mod = (struct ibv_exp_qp_attr){
3164                 .qp_state = IBV_QPS_RTR
3165         };
3166         ret = ibv_exp_modify_qp(tmpl.qp, &mod, IBV_EXP_QP_STATE);
3167         if (ret) {
3168                 ERROR("%p: QP state to IBV_QPS_RTR failed: %s",
3169                       (void *)dev, strerror(ret));
3170                 goto error;
3171         }
3172         /* Save port ID. */
3173         tmpl.port_id = dev->data->port_id;
3174         DEBUG("%p: RTE port ID: %u", (void *)rxq, tmpl.port_id);
3175         /* Clean up rxq in case we're reinitializing it. */
3176         DEBUG("%p: cleaning-up old rxq just in case", (void *)rxq);
3177         rxq_cleanup(rxq);
3178         *rxq = tmpl;
3179         DEBUG("%p: rxq updated with %p", (void *)rxq, (void *)&tmpl);
3180         assert(ret == 0);
3181         return 0;
3182 error:
3183         rxq_cleanup(&tmpl);
3184         assert(ret > 0);
3185         return ret;
3186 }
3187
3188 /**
3189  * DPDK callback to configure a RX queue.
3190  *
3191  * @param dev
3192  *   Pointer to Ethernet device structure.
3193  * @param idx
3194  *   RX queue index.
3195  * @param desc
3196  *   Number of descriptors to configure in queue.
3197  * @param socket
3198  *   NUMA socket on which memory must be allocated.
3199  * @param[in] conf
3200  *   Thresholds parameters.
3201  * @param mp
3202  *   Memory pool for buffer allocations.
3203  *
3204  * @return
3205  *   0 on success, negative errno value on failure.
3206  */
3207 static int
3208 mlx4_rx_queue_setup(struct rte_eth_dev *dev, uint16_t idx, uint16_t desc,
3209                     unsigned int socket, const struct rte_eth_rxconf *conf,
3210                     struct rte_mempool *mp)
3211 {
3212         struct priv *priv = dev->data->dev_private;
3213         struct rxq *rxq = (*priv->rxqs)[idx];
3214         int ret;
3215
3216         priv_lock(priv);
3217         DEBUG("%p: configuring queue %u for %u descriptors",
3218               (void *)dev, idx, desc);
3219         if (idx >= priv->rxqs_n) {
3220                 ERROR("%p: queue index out of range (%u >= %u)",
3221                       (void *)dev, idx, priv->rxqs_n);
3222                 priv_unlock(priv);
3223                 return -EOVERFLOW;
3224         }
3225         if (rxq != NULL) {
3226                 DEBUG("%p: reusing already allocated queue index %u (%p)",
3227                       (void *)dev, idx, (void *)rxq);
3228                 if (priv->started) {
3229                         priv_unlock(priv);
3230                         return -EEXIST;
3231                 }
3232                 (*priv->rxqs)[idx] = NULL;
3233                 rxq_cleanup(rxq);
3234         } else {
3235                 rxq = rte_calloc_socket("RXQ", 1, sizeof(*rxq), 0, socket);
3236                 if (rxq == NULL) {
3237                         ERROR("%p: unable to allocate queue index %u",
3238                               (void *)dev, idx);
3239                         priv_unlock(priv);
3240                         return -ENOMEM;
3241                 }
3242         }
3243         ret = rxq_setup(dev, rxq, desc, socket, conf, mp);
3244         if (ret)
3245                 rte_free(rxq);
3246         else {
3247                 rxq->stats.idx = idx;
3248                 DEBUG("%p: adding RX queue %p to list",
3249                       (void *)dev, (void *)rxq);
3250                 (*priv->rxqs)[idx] = rxq;
3251                 /* Update receive callback. */
3252                 if (rxq->sp)
3253                         dev->rx_pkt_burst = mlx4_rx_burst_sp;
3254                 else
3255                         dev->rx_pkt_burst = mlx4_rx_burst;
3256         }
3257         priv_unlock(priv);
3258         return -ret;
3259 }
3260
3261 /**
3262  * DPDK callback to release a RX queue.
3263  *
3264  * @param dpdk_rxq
3265  *   Generic RX queue pointer.
3266  */
3267 static void
3268 mlx4_rx_queue_release(void *dpdk_rxq)
3269 {
3270         struct rxq *rxq = (struct rxq *)dpdk_rxq;
3271         struct priv *priv;
3272         unsigned int i;
3273
3274         if (rxq == NULL)
3275                 return;
3276         priv = rxq->priv;
3277         priv_lock(priv);
3278         assert(rxq != &priv->rxq_parent);
3279         for (i = 0; (i != priv->rxqs_n); ++i)
3280                 if ((*priv->rxqs)[i] == rxq) {
3281                         DEBUG("%p: removing RX queue %p from list",
3282                               (void *)priv->dev, (void *)rxq);
3283                         (*priv->rxqs)[i] = NULL;
3284                         break;
3285                 }
3286         rxq_cleanup(rxq);
3287         rte_free(rxq);
3288         priv_unlock(priv);
3289 }
3290
3291 /**
3292  * DPDK callback to start the device.
3293  *
3294  * Simulate device start by attaching all configured flows.
3295  *
3296  * @param dev
3297  *   Pointer to Ethernet device structure.
3298  *
3299  * @return
3300  *   0 on success, negative errno value on failure.
3301  */
3302 static int
3303 mlx4_dev_start(struct rte_eth_dev *dev)
3304 {
3305         struct priv *priv = dev->data->dev_private;
3306         unsigned int i = 0;
3307         unsigned int r;
3308         struct rxq *rxq;
3309
3310         priv_lock(priv);
3311         if (priv->started) {
3312                 priv_unlock(priv);
3313                 return 0;
3314         }
3315         DEBUG("%p: attaching configured flows to all RX queues", (void *)dev);
3316         priv->started = 1;
3317         if (priv->rss) {
3318                 rxq = &priv->rxq_parent;
3319                 r = 1;
3320         } else {
3321                 rxq = (*priv->rxqs)[0];
3322                 r = priv->rxqs_n;
3323         }
3324         /* Iterate only once when RSS is enabled. */
3325         do {
3326                 int ret;
3327
3328                 /* Ignore nonexistent RX queues. */
3329                 if (rxq == NULL)
3330                         continue;
3331                 ret = rxq_mac_addrs_add(rxq);
3332                 if (!ret && priv->promisc)
3333                         ret = rxq_promiscuous_enable(rxq);
3334                 if (!ret && priv->allmulti)
3335                         ret = rxq_allmulticast_enable(rxq);
3336                 if (!ret)
3337                         continue;
3338                 WARN("%p: QP flow attachment failed: %s",
3339                      (void *)dev, strerror(ret));
3340                 /* Rollback. */
3341                 while (i != 0) {
3342                         rxq = (*priv->rxqs)[--i];
3343                         if (rxq != NULL) {
3344                                 rxq_allmulticast_disable(rxq);
3345                                 rxq_promiscuous_disable(rxq);
3346                                 rxq_mac_addrs_del(rxq);
3347                         }
3348                 }
3349                 priv->started = 0;
3350                 return -ret;
3351         } while ((--r) && ((rxq = (*priv->rxqs)[++i]), i));
3352         priv_unlock(priv);
3353         return 0;
3354 }
3355
3356 /**
3357  * DPDK callback to stop the device.
3358  *
3359  * Simulate device stop by detaching all configured flows.
3360  *
3361  * @param dev
3362  *   Pointer to Ethernet device structure.
3363  */
3364 static void
3365 mlx4_dev_stop(struct rte_eth_dev *dev)
3366 {
3367         struct priv *priv = dev->data->dev_private;
3368         unsigned int i = 0;
3369         unsigned int r;
3370         struct rxq *rxq;
3371
3372         priv_lock(priv);
3373         if (!priv->started) {
3374                 priv_unlock(priv);
3375                 return;
3376         }
3377         DEBUG("%p: detaching flows from all RX queues", (void *)dev);
3378         priv->started = 0;
3379         if (priv->rss) {
3380                 rxq = &priv->rxq_parent;
3381                 r = 1;
3382         } else {
3383                 rxq = (*priv->rxqs)[0];
3384                 r = priv->rxqs_n;
3385         }
3386         /* Iterate only once when RSS is enabled. */
3387         do {
3388                 /* Ignore nonexistent RX queues. */
3389                 if (rxq == NULL)
3390                         continue;
3391                 rxq_allmulticast_disable(rxq);
3392                 rxq_promiscuous_disable(rxq);
3393                 rxq_mac_addrs_del(rxq);
3394         } while ((--r) && ((rxq = (*priv->rxqs)[++i]), i));
3395         priv_unlock(priv);
3396 }
3397
3398 /**
3399  * Dummy DPDK callback for TX.
3400  *
3401  * This function is used to temporarily replace the real callback during
3402  * unsafe control operations on the queue, or in case of error.
3403  *
3404  * @param dpdk_txq
3405  *   Generic pointer to TX queue structure.
3406  * @param[in] pkts
3407  *   Packets to transmit.
3408  * @param pkts_n
3409  *   Number of packets in array.
3410  *
3411  * @return
3412  *   Number of packets successfully transmitted (<= pkts_n).
3413  */
3414 static uint16_t
3415 removed_tx_burst(void *dpdk_txq, struct rte_mbuf **pkts, uint16_t pkts_n)
3416 {
3417         (void)dpdk_txq;
3418         (void)pkts;
3419         (void)pkts_n;
3420         return 0;
3421 }
3422
3423 /**
3424  * Dummy DPDK callback for RX.
3425  *
3426  * This function is used to temporarily replace the real callback during
3427  * unsafe control operations on the queue, or in case of error.
3428  *
3429  * @param dpdk_rxq
3430  *   Generic pointer to RX queue structure.
3431  * @param[out] pkts
3432  *   Array to store received packets.
3433  * @param pkts_n
3434  *   Maximum number of packets in array.
3435  *
3436  * @return
3437  *   Number of packets successfully received (<= pkts_n).
3438  */
3439 static uint16_t
3440 removed_rx_burst(void *dpdk_rxq, struct rte_mbuf **pkts, uint16_t pkts_n)
3441 {
3442         (void)dpdk_rxq;
3443         (void)pkts;
3444         (void)pkts_n;
3445         return 0;
3446 }
3447
3448 /**
3449  * DPDK callback to close the device.
3450  *
3451  * Destroy all queues and objects, free memory.
3452  *
3453  * @param dev
3454  *   Pointer to Ethernet device structure.
3455  */
3456 static void
3457 mlx4_dev_close(struct rte_eth_dev *dev)
3458 {
3459         struct priv *priv = dev->data->dev_private;
3460         void *tmp;
3461         unsigned int i;
3462
3463         priv_lock(priv);
3464         DEBUG("%p: closing device \"%s\"",
3465               (void *)dev,
3466               ((priv->ctx != NULL) ? priv->ctx->device->name : ""));
3467         /* Prevent crashes when queues are still in use. This is unfortunately
3468          * still required for DPDK 1.3 because some programs (such as testpmd)
3469          * never release them before closing the device. */
3470         dev->rx_pkt_burst = removed_rx_burst;
3471         dev->tx_pkt_burst = removed_tx_burst;
3472         if (priv->rxqs != NULL) {
3473                 /* XXX race condition if mlx4_rx_burst() is still running. */
3474                 usleep(1000);
3475                 for (i = 0; (i != priv->rxqs_n); ++i) {
3476                         tmp = (*priv->rxqs)[i];
3477                         if (tmp == NULL)
3478                                 continue;
3479                         (*priv->rxqs)[i] = NULL;
3480                         rxq_cleanup(tmp);
3481                         rte_free(tmp);
3482                 }
3483                 priv->rxqs_n = 0;
3484                 priv->rxqs = NULL;
3485         }
3486         if (priv->txqs != NULL) {
3487                 /* XXX race condition if mlx4_tx_burst() is still running. */
3488                 usleep(1000);
3489                 for (i = 0; (i != priv->txqs_n); ++i) {
3490                         tmp = (*priv->txqs)[i];
3491                         if (tmp == NULL)
3492                                 continue;
3493                         (*priv->txqs)[i] = NULL;
3494                         txq_cleanup(tmp);
3495                         rte_free(tmp);
3496                 }
3497                 priv->txqs_n = 0;
3498                 priv->txqs = NULL;
3499         }
3500         if (priv->rss)
3501                 rxq_cleanup(&priv->rxq_parent);
3502         if (priv->pd != NULL) {
3503                 assert(priv->ctx != NULL);
3504                 claim_zero(ibv_dealloc_pd(priv->pd));
3505                 claim_zero(ibv_close_device(priv->ctx));
3506         } else
3507                 assert(priv->ctx == NULL);
3508         priv_unlock(priv);
3509         memset(priv, 0, sizeof(*priv));
3510 }
3511
3512 /**
3513  * DPDK callback to get information about the device.
3514  *
3515  * @param dev
3516  *   Pointer to Ethernet device structure.
3517  * @param[out] info
3518  *   Info structure output buffer.
3519  */
3520 static void
3521 mlx4_dev_infos_get(struct rte_eth_dev *dev, struct rte_eth_dev_info *info)
3522 {
3523         struct priv *priv = dev->data->dev_private;
3524         unsigned int max;
3525
3526         priv_lock(priv);
3527         /* FIXME: we should ask the device for these values. */
3528         info->min_rx_bufsize = 32;
3529         info->max_rx_pktlen = 65536;
3530         /*
3531          * Since we need one CQ per QP, the limit is the minimum number
3532          * between the two values.
3533          */
3534         max = ((priv->device_attr.max_cq > priv->device_attr.max_qp) ?
3535                priv->device_attr.max_qp : priv->device_attr.max_cq);
3536         /* If max >= 65535 then max = 0, max_rx_queues is uint16_t. */
3537         if (max >= 65535)
3538                 max = 65535;
3539         info->max_rx_queues = max;
3540         info->max_tx_queues = max;
3541         info->max_mac_addrs = elemof(priv->mac);
3542         priv_unlock(priv);
3543 }
3544
3545 /**
3546  * DPDK callback to get device statistics.
3547  *
3548  * @param dev
3549  *   Pointer to Ethernet device structure.
3550  * @param[out] stats
3551  *   Stats structure output buffer.
3552  */
3553 static void
3554 mlx4_stats_get(struct rte_eth_dev *dev, struct rte_eth_stats *stats)
3555 {
3556         struct priv *priv = dev->data->dev_private;
3557         struct rte_eth_stats tmp = { .ipackets = 0 };
3558         unsigned int i;
3559         unsigned int idx;
3560
3561         priv_lock(priv);
3562         /* Add software counters. */
3563         for (i = 0; (i != priv->rxqs_n); ++i) {
3564                 struct rxq *rxq = (*priv->rxqs)[i];
3565
3566                 if (rxq == NULL)
3567                         continue;
3568                 idx = rxq->stats.idx;
3569                 if (idx < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
3570 #ifdef MLX4_PMD_SOFT_COUNTERS
3571                         tmp.q_ipackets[idx] += rxq->stats.ipackets;
3572                         tmp.q_ibytes[idx] += rxq->stats.ibytes;
3573 #endif
3574                         tmp.q_errors[idx] += (rxq->stats.idropped +
3575                                               rxq->stats.rx_nombuf);
3576                 }
3577 #ifdef MLX4_PMD_SOFT_COUNTERS
3578                 tmp.ipackets += rxq->stats.ipackets;
3579                 tmp.ibytes += rxq->stats.ibytes;
3580 #endif
3581                 tmp.ierrors += rxq->stats.idropped;
3582                 tmp.rx_nombuf += rxq->stats.rx_nombuf;
3583         }
3584         for (i = 0; (i != priv->txqs_n); ++i) {
3585                 struct txq *txq = (*priv->txqs)[i];
3586
3587                 if (txq == NULL)
3588                         continue;
3589                 idx = txq->stats.idx;
3590                 if (idx < RTE_ETHDEV_QUEUE_STAT_CNTRS) {
3591 #ifdef MLX4_PMD_SOFT_COUNTERS
3592                         tmp.q_opackets[idx] += txq->stats.opackets;
3593                         tmp.q_obytes[idx] += txq->stats.obytes;
3594 #endif
3595                         tmp.q_errors[idx] += txq->stats.odropped;
3596                 }
3597 #ifdef MLX4_PMD_SOFT_COUNTERS
3598                 tmp.opackets += txq->stats.opackets;
3599                 tmp.obytes += txq->stats.obytes;
3600 #endif
3601                 tmp.oerrors += txq->stats.odropped;
3602         }
3603 #ifndef MLX4_PMD_SOFT_COUNTERS
3604         /* FIXME: retrieve and add hardware counters. */
3605 #endif
3606         *stats = tmp;
3607         priv_unlock(priv);
3608 }
3609
3610 /**
3611  * DPDK callback to clear device statistics.
3612  *
3613  * @param dev
3614  *   Pointer to Ethernet device structure.
3615  */
3616 static void
3617 mlx4_stats_reset(struct rte_eth_dev *dev)
3618 {
3619         struct priv *priv = dev->data->dev_private;
3620         unsigned int i;
3621         unsigned int idx;
3622
3623         priv_lock(priv);
3624         for (i = 0; (i != priv->rxqs_n); ++i) {
3625                 if ((*priv->rxqs)[i] == NULL)
3626                         continue;
3627                 idx = (*priv->rxqs)[i]->stats.idx;
3628                 (*priv->rxqs)[i]->stats =
3629                         (struct mlx4_rxq_stats){ .idx = idx };
3630         }
3631         for (i = 0; (i != priv->txqs_n); ++i) {
3632                 if ((*priv->txqs)[i] == NULL)
3633                         continue;
3634                 idx = (*priv->rxqs)[i]->stats.idx;
3635                 (*priv->txqs)[i]->stats =
3636                         (struct mlx4_txq_stats){ .idx = idx };
3637         }
3638 #ifndef MLX4_PMD_SOFT_COUNTERS
3639         /* FIXME: reset hardware counters. */
3640 #endif
3641         priv_unlock(priv);
3642 }
3643
3644 /**
3645  * DPDK callback to remove a MAC address.
3646  *
3647  * @param dev
3648  *   Pointer to Ethernet device structure.
3649  * @param index
3650  *   MAC address index.
3651  */
3652 static void
3653 mlx4_mac_addr_remove(struct rte_eth_dev *dev, uint32_t index)
3654 {
3655         struct priv *priv = dev->data->dev_private;
3656
3657         priv_lock(priv);
3658         DEBUG("%p: removing MAC address from index %" PRIu32,
3659               (void *)dev, index);
3660         if (index >= MLX4_MAX_MAC_ADDRESSES)
3661                 goto end;
3662         /* Refuse to remove the broadcast address, this one is special. */
3663         if (!memcmp(priv->mac[index].addr_bytes, "\xff\xff\xff\xff\xff\xff",
3664                     ETHER_ADDR_LEN))
3665                 goto end;
3666         priv_mac_addr_del(priv, index);
3667 end:
3668         priv_unlock(priv);
3669 }
3670
3671 /**
3672  * DPDK callback to add a MAC address.
3673  *
3674  * @param dev
3675  *   Pointer to Ethernet device structure.
3676  * @param mac_addr
3677  *   MAC address to register.
3678  * @param index
3679  *   MAC address index.
3680  * @param vmdq
3681  *   VMDq pool index to associate address with (ignored).
3682  */
3683 static void
3684 mlx4_mac_addr_add(struct rte_eth_dev *dev, struct ether_addr *mac_addr,
3685                   uint32_t index, uint32_t vmdq)
3686 {
3687         struct priv *priv = dev->data->dev_private;
3688
3689         (void)vmdq;
3690         priv_lock(priv);
3691         DEBUG("%p: adding MAC address at index %" PRIu32,
3692               (void *)dev, index);
3693         if (index >= MLX4_MAX_MAC_ADDRESSES)
3694                 goto end;
3695         /* Refuse to add the broadcast address, this one is special. */
3696         if (!memcmp(mac_addr->addr_bytes, "\xff\xff\xff\xff\xff\xff",
3697                     ETHER_ADDR_LEN))
3698                 goto end;
3699         priv_mac_addr_add(priv, index,
3700                           (const uint8_t (*)[ETHER_ADDR_LEN])
3701                           mac_addr->addr_bytes);
3702 end:
3703         priv_unlock(priv);
3704 }
3705
3706 /**
3707  * DPDK callback to enable promiscuous mode.
3708  *
3709  * @param dev
3710  *   Pointer to Ethernet device structure.
3711  */
3712 static void
3713 mlx4_promiscuous_enable(struct rte_eth_dev *dev)
3714 {
3715         struct priv *priv = dev->data->dev_private;
3716         unsigned int i;
3717         int ret;
3718
3719         priv_lock(priv);
3720         if (priv->promisc) {
3721                 priv_unlock(priv);
3722                 return;
3723         }
3724         /* If device isn't started, this is all we need to do. */
3725         if (!priv->started)
3726                 goto end;
3727         if (priv->rss) {
3728                 ret = rxq_promiscuous_enable(&priv->rxq_parent);
3729                 if (ret) {
3730                         priv_unlock(priv);
3731                         return;
3732                 }
3733                 goto end;
3734         }
3735         for (i = 0; (i != priv->rxqs_n); ++i) {
3736                 if ((*priv->rxqs)[i] == NULL)
3737                         continue;
3738                 ret = rxq_promiscuous_enable((*priv->rxqs)[i]);
3739                 if (!ret)
3740                         continue;
3741                 /* Failure, rollback. */
3742                 while (i != 0)
3743                         if ((*priv->rxqs)[--i] != NULL)
3744                                 rxq_promiscuous_disable((*priv->rxqs)[i]);
3745                 priv_unlock(priv);
3746                 return;
3747         }
3748 end:
3749         priv->promisc = 1;
3750         priv_unlock(priv);
3751 }
3752
3753 /**
3754  * DPDK callback to disable promiscuous mode.
3755  *
3756  * @param dev
3757  *   Pointer to Ethernet device structure.
3758  */
3759 static void
3760 mlx4_promiscuous_disable(struct rte_eth_dev *dev)
3761 {
3762         struct priv *priv = dev->data->dev_private;
3763         unsigned int i;
3764
3765         priv_lock(priv);
3766         if (!priv->promisc) {
3767                 priv_unlock(priv);
3768                 return;
3769         }
3770         if (priv->rss) {
3771                 rxq_promiscuous_disable(&priv->rxq_parent);
3772                 goto end;
3773         }
3774         for (i = 0; (i != priv->rxqs_n); ++i)
3775                 if ((*priv->rxqs)[i] != NULL)
3776                         rxq_promiscuous_disable((*priv->rxqs)[i]);
3777 end:
3778         priv->promisc = 0;
3779         priv_unlock(priv);
3780 }
3781
3782 /**
3783  * DPDK callback to enable allmulti mode.
3784  *
3785  * @param dev
3786  *   Pointer to Ethernet device structure.
3787  */
3788 static void
3789 mlx4_allmulticast_enable(struct rte_eth_dev *dev)
3790 {
3791         struct priv *priv = dev->data->dev_private;
3792         unsigned int i;
3793         int ret;
3794
3795         priv_lock(priv);
3796         if (priv->allmulti) {
3797                 priv_unlock(priv);
3798                 return;
3799         }
3800         /* If device isn't started, this is all we need to do. */
3801         if (!priv->started)
3802                 goto end;
3803         if (priv->rss) {
3804                 ret = rxq_allmulticast_enable(&priv->rxq_parent);
3805                 if (ret) {
3806                         priv_unlock(priv);
3807                         return;
3808                 }
3809                 goto end;
3810         }
3811         for (i = 0; (i != priv->rxqs_n); ++i) {
3812                 if ((*priv->rxqs)[i] == NULL)
3813                         continue;
3814                 ret = rxq_allmulticast_enable((*priv->rxqs)[i]);
3815                 if (!ret)
3816                         continue;
3817                 /* Failure, rollback. */
3818                 while (i != 0)
3819                         if ((*priv->rxqs)[--i] != NULL)
3820                                 rxq_allmulticast_disable((*priv->rxqs)[i]);
3821                 priv_unlock(priv);
3822                 return;
3823         }
3824 end:
3825         priv->allmulti = 1;
3826         priv_unlock(priv);
3827 }
3828
3829 /**
3830  * DPDK callback to disable allmulti mode.
3831  *
3832  * @param dev
3833  *   Pointer to Ethernet device structure.
3834  */
3835 static void
3836 mlx4_allmulticast_disable(struct rte_eth_dev *dev)
3837 {
3838         struct priv *priv = dev->data->dev_private;
3839         unsigned int i;
3840
3841         priv_lock(priv);
3842         if (!priv->allmulti) {
3843                 priv_unlock(priv);
3844                 return;
3845         }
3846         if (priv->rss) {
3847                 rxq_allmulticast_disable(&priv->rxq_parent);
3848                 goto end;
3849         }
3850         for (i = 0; (i != priv->rxqs_n); ++i)
3851                 if ((*priv->rxqs)[i] != NULL)
3852                         rxq_allmulticast_disable((*priv->rxqs)[i]);
3853 end:
3854         priv->allmulti = 0;
3855         priv_unlock(priv);
3856 }
3857
3858 /**
3859  * DPDK callback to retrieve physical link information (unlocked version).
3860  *
3861  * @param dev
3862  *   Pointer to Ethernet device structure.
3863  * @param wait_to_complete
3864  *   Wait for request completion (ignored).
3865  */
3866 static int
3867 mlx4_link_update_unlocked(struct rte_eth_dev *dev, int wait_to_complete)
3868 {
3869         struct priv *priv = dev->data->dev_private;
3870         struct ibv_port_attr port_attr;
3871         static const uint8_t width_mult[] = {
3872                 /* Multiplier values taken from devinfo.c in libibverbs. */
3873                 0, 1, 4, 0, 8, 0, 0, 0, 12, 0
3874         };
3875
3876         (void)wait_to_complete;
3877         errno = ibv_query_port(priv->ctx, priv->port, &port_attr);
3878         if (errno) {
3879                 WARN("port query failed: %s", strerror(errno));
3880                 return -1;
3881         }
3882         dev->data->dev_link = (struct rte_eth_link){
3883                 .link_speed = (ibv_rate_to_mbps(mult_to_ibv_rate
3884                                                 (port_attr.active_speed)) *
3885                                width_mult[(port_attr.active_width %
3886                                            sizeof(width_mult))]),
3887                 .link_duplex = ETH_LINK_FULL_DUPLEX,
3888                 .link_status = (port_attr.state == IBV_PORT_ACTIVE)
3889         };
3890         if (memcmp(&port_attr, &priv->port_attr, sizeof(port_attr))) {
3891                 /* Link status changed. */
3892                 priv->port_attr = port_attr;
3893                 return 0;
3894         }
3895         /* Link status is still the same. */
3896         return -1;
3897 }
3898
3899 /**
3900  * DPDK callback to retrieve physical link information.
3901  *
3902  * @param dev
3903  *   Pointer to Ethernet device structure.
3904  * @param wait_to_complete
3905  *   Wait for request completion (ignored).
3906  */
3907 static int
3908 mlx4_link_update(struct rte_eth_dev *dev, int wait_to_complete)
3909 {
3910         struct priv *priv = dev->data->dev_private;
3911         int ret;
3912
3913         priv_lock(priv);
3914         ret = mlx4_link_update_unlocked(dev, wait_to_complete);
3915         priv_unlock(priv);
3916         return ret;
3917 }
3918
3919 /**
3920  * DPDK callback to change the MTU.
3921  *
3922  * Setting the MTU affects hardware MRU (packets larger than the MTU cannot be
3923  * received). Use this as a hint to enable/disable scattered packets support
3924  * and improve performance when not needed.
3925  * Since failure is not an option, reconfiguring queues on the fly is not
3926  * recommended.
3927  *
3928  * @param dev
3929  *   Pointer to Ethernet device structure.
3930  * @param in_mtu
3931  *   New MTU.
3932  *
3933  * @return
3934  *   0 on success, negative errno value on failure.
3935  */
3936 static int
3937 mlx4_dev_set_mtu(struct rte_eth_dev *dev, uint16_t mtu)
3938 {
3939         struct priv *priv = dev->data->dev_private;
3940         int ret = 0;
3941         unsigned int i;
3942         uint16_t (*rx_func)(void *, struct rte_mbuf **, uint16_t) =
3943                 mlx4_rx_burst;
3944
3945         priv_lock(priv);
3946         /* Set kernel interface MTU first. */
3947         if (priv_set_mtu(priv, mtu)) {
3948                 ret = errno;
3949                 WARN("cannot set port %u MTU to %u: %s", priv->port, mtu,
3950                      strerror(ret));
3951                 goto out;
3952         } else
3953                 DEBUG("adapter port %u MTU set to %u", priv->port, mtu);
3954         priv->mtu = mtu;
3955         /* Temporarily replace RX handler with a fake one, assuming it has not
3956          * been copied elsewhere. */
3957         dev->rx_pkt_burst = removed_rx_burst;
3958         /* Make sure everyone has left mlx4_rx_burst() and uses
3959          * removed_rx_burst() instead. */
3960         rte_wmb();
3961         usleep(1000);
3962         /* Reconfigure each RX queue. */
3963         for (i = 0; (i != priv->rxqs_n); ++i) {
3964                 struct rxq *rxq = (*priv->rxqs)[i];
3965                 unsigned int max_frame_len;
3966                 int sp;
3967
3968                 if (rxq == NULL)
3969                         continue;
3970                 /* Calculate new maximum frame length according to MTU and
3971                  * toggle scattered support (sp) if necessary. */
3972                 max_frame_len = (priv->mtu + ETHER_HDR_LEN +
3973                                  (ETHER_MAX_VLAN_FRAME_LEN - ETHER_MAX_LEN));
3974                 sp = (max_frame_len > (rxq->mb_len - RTE_PKTMBUF_HEADROOM));
3975                 /* Provide new values to rxq_setup(). */
3976                 dev->data->dev_conf.rxmode.jumbo_frame = sp;
3977                 dev->data->dev_conf.rxmode.max_rx_pkt_len = max_frame_len;
3978                 ret = rxq_rehash(dev, rxq);
3979                 if (ret) {
3980                         /* Force SP RX if that queue requires it and abort. */
3981                         if (rxq->sp)
3982                                 rx_func = mlx4_rx_burst_sp;
3983                         break;
3984                 }
3985                 /* Reenable non-RSS queue attributes. No need to check
3986                  * for errors at this stage. */
3987                 if (!priv->rss) {
3988                         rxq_mac_addrs_add(rxq);
3989                         if (priv->promisc)
3990                                 rxq_promiscuous_enable(rxq);
3991                         if (priv->allmulti)
3992                                 rxq_allmulticast_enable(rxq);
3993                 }
3994                 /* Scattered burst function takes priority. */
3995                 if (rxq->sp)
3996                         rx_func = mlx4_rx_burst_sp;
3997         }
3998         /* Burst functions can now be called again. */
3999         rte_wmb();
4000         dev->rx_pkt_burst = rx_func;
4001 out:
4002         priv_unlock(priv);
4003         assert(ret >= 0);
4004         return -ret;
4005 }
4006
4007 /**
4008  * DPDK callback to get flow control status.
4009  *
4010  * @param dev
4011  *   Pointer to Ethernet device structure.
4012  * @param[out] fc_conf
4013  *   Flow control output buffer.
4014  *
4015  * @return
4016  *   0 on success, negative errno value on failure.
4017  */
4018 static int
4019 mlx4_dev_get_flow_ctrl(struct rte_eth_dev *dev, struct rte_eth_fc_conf *fc_conf)
4020 {
4021         struct priv *priv = dev->data->dev_private;
4022         struct ifreq ifr;
4023         struct ethtool_pauseparam ethpause = {
4024                 .cmd = ETHTOOL_GPAUSEPARAM
4025         };
4026         int ret;
4027
4028         ifr.ifr_data = &ethpause;
4029         priv_lock(priv);
4030         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
4031                 ret = errno;
4032                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_GPAUSEPARAM)"
4033                      " failed: %s",
4034                      strerror(ret));
4035                 goto out;
4036         }
4037
4038         fc_conf->autoneg = ethpause.autoneg;
4039         if (ethpause.rx_pause && ethpause.tx_pause)
4040                 fc_conf->mode = RTE_FC_FULL;
4041         else if (ethpause.rx_pause)
4042                 fc_conf->mode = RTE_FC_RX_PAUSE;
4043         else if (ethpause.tx_pause)
4044                 fc_conf->mode = RTE_FC_TX_PAUSE;
4045         else
4046                 fc_conf->mode = RTE_FC_NONE;
4047         ret = 0;
4048
4049 out:
4050         priv_unlock(priv);
4051         assert(ret >= 0);
4052         return -ret;
4053 }
4054
4055 /**
4056  * DPDK callback to modify flow control parameters.
4057  *
4058  * @param dev
4059  *   Pointer to Ethernet device structure.
4060  * @param[in] fc_conf
4061  *   Flow control parameters.
4062  *
4063  * @return
4064  *   0 on success, negative errno value on failure.
4065  */
4066 static int
4067 mlx4_dev_set_flow_ctrl(struct rte_eth_dev *dev, struct rte_eth_fc_conf *fc_conf)
4068 {
4069         struct priv *priv = dev->data->dev_private;
4070         struct ifreq ifr;
4071         struct ethtool_pauseparam ethpause = {
4072                 .cmd = ETHTOOL_SPAUSEPARAM
4073         };
4074         int ret;
4075
4076         ifr.ifr_data = &ethpause;
4077         ethpause.autoneg = fc_conf->autoneg;
4078         if (((fc_conf->mode & RTE_FC_FULL) == RTE_FC_FULL) ||
4079             (fc_conf->mode & RTE_FC_RX_PAUSE))
4080                 ethpause.rx_pause = 1;
4081         else
4082                 ethpause.rx_pause = 0;
4083
4084         if (((fc_conf->mode & RTE_FC_FULL) == RTE_FC_FULL) ||
4085             (fc_conf->mode & RTE_FC_TX_PAUSE))
4086                 ethpause.tx_pause = 1;
4087         else
4088                 ethpause.tx_pause = 0;
4089
4090         priv_lock(priv);
4091         if (priv_ifreq(priv, SIOCETHTOOL, &ifr)) {
4092                 ret = errno;
4093                 WARN("ioctl(SIOCETHTOOL, ETHTOOL_SPAUSEPARAM)"
4094                      " failed: %s",
4095                      strerror(ret));
4096                 goto out;
4097         }
4098         ret = 0;
4099
4100 out:
4101         priv_unlock(priv);
4102         assert(ret >= 0);
4103         return -ret;
4104 }
4105
4106 /**
4107  * Configure a VLAN filter.
4108  *
4109  * @param dev
4110  *   Pointer to Ethernet device structure.
4111  * @param vlan_id
4112  *   VLAN ID to filter.
4113  * @param on
4114  *   Toggle filter.
4115  *
4116  * @return
4117  *   0 on success, errno value on failure.
4118  */
4119 static int
4120 vlan_filter_set(struct rte_eth_dev *dev, uint16_t vlan_id, int on)
4121 {
4122         struct priv *priv = dev->data->dev_private;
4123         unsigned int i;
4124         unsigned int j = -1;
4125
4126         DEBUG("%p: %s VLAN filter ID %" PRIu16,
4127               (void *)dev, (on ? "enable" : "disable"), vlan_id);
4128         for (i = 0; (i != elemof(priv->vlan_filter)); ++i) {
4129                 if (!priv->vlan_filter[i].enabled) {
4130                         /* Unused index, remember it. */
4131                         j = i;
4132                         continue;
4133                 }
4134                 if (priv->vlan_filter[i].id != vlan_id)
4135                         continue;
4136                 /* This VLAN ID is already known, use its index. */
4137                 j = i;
4138                 break;
4139         }
4140         /* Check if there's room for another VLAN filter. */
4141         if (j == (unsigned int)-1)
4142                 return ENOMEM;
4143         /*
4144          * VLAN filters apply to all configured MAC addresses, flow
4145          * specifications must be reconfigured accordingly.
4146          */
4147         priv->vlan_filter[j].id = vlan_id;
4148         if ((on) && (!priv->vlan_filter[j].enabled)) {
4149                 /*
4150                  * Filter is disabled, enable it.
4151                  * Rehashing flows in all RX queues is necessary.
4152                  */
4153                 if (priv->rss)
4154                         rxq_mac_addrs_del(&priv->rxq_parent);
4155                 else
4156                         for (i = 0; (i != priv->rxqs_n); ++i)
4157                                 if ((*priv->rxqs)[i] != NULL)
4158                                         rxq_mac_addrs_del((*priv->rxqs)[i]);
4159                 priv->vlan_filter[j].enabled = 1;
4160                 if (priv->started) {
4161                         if (priv->rss)
4162                                 rxq_mac_addrs_add(&priv->rxq_parent);
4163                         else
4164                                 for (i = 0; (i != priv->rxqs_n); ++i) {
4165                                         if ((*priv->rxqs)[i] == NULL)
4166                                                 continue;
4167                                         rxq_mac_addrs_add((*priv->rxqs)[i]);
4168                                 }
4169                 }
4170         } else if ((!on) && (priv->vlan_filter[j].enabled)) {
4171                 /*
4172                  * Filter is enabled, disable it.
4173                  * Rehashing flows in all RX queues is necessary.
4174                  */
4175                 if (priv->rss)
4176                         rxq_mac_addrs_del(&priv->rxq_parent);
4177                 else
4178                         for (i = 0; (i != priv->rxqs_n); ++i)
4179                                 if ((*priv->rxqs)[i] != NULL)
4180                                         rxq_mac_addrs_del((*priv->rxqs)[i]);
4181                 priv->vlan_filter[j].enabled = 0;
4182                 if (priv->started) {
4183                         if (priv->rss)
4184                                 rxq_mac_addrs_add(&priv->rxq_parent);
4185                         else
4186                                 for (i = 0; (i != priv->rxqs_n); ++i) {
4187                                         if ((*priv->rxqs)[i] == NULL)
4188                                                 continue;
4189                                         rxq_mac_addrs_add((*priv->rxqs)[i]);
4190                                 }
4191                 }
4192         }
4193         return 0;
4194 }
4195
4196 /**
4197  * DPDK callback to configure a VLAN filter.
4198  *
4199  * @param dev
4200  *   Pointer to Ethernet device structure.
4201  * @param vlan_id
4202  *   VLAN ID to filter.
4203  * @param on
4204  *   Toggle filter.
4205  *
4206  * @return
4207  *   0 on success, negative errno value on failure.
4208  */
4209 static int
4210 mlx4_vlan_filter_set(struct rte_eth_dev *dev, uint16_t vlan_id, int on)
4211 {
4212         struct priv *priv = dev->data->dev_private;
4213         int ret;
4214
4215         priv_lock(priv);
4216         ret = vlan_filter_set(dev, vlan_id, on);
4217         priv_unlock(priv);
4218         assert(ret >= 0);
4219         return -ret;
4220 }
4221
4222 static struct eth_dev_ops mlx4_dev_ops = {
4223         .dev_configure = mlx4_dev_configure,
4224         .dev_start = mlx4_dev_start,
4225         .dev_stop = mlx4_dev_stop,
4226         .dev_close = mlx4_dev_close,
4227         .promiscuous_enable = mlx4_promiscuous_enable,
4228         .promiscuous_disable = mlx4_promiscuous_disable,
4229         .allmulticast_enable = mlx4_allmulticast_enable,
4230         .allmulticast_disable = mlx4_allmulticast_disable,
4231         .link_update = mlx4_link_update,
4232         .stats_get = mlx4_stats_get,
4233         .stats_reset = mlx4_stats_reset,
4234         .queue_stats_mapping_set = NULL,
4235         .dev_infos_get = mlx4_dev_infos_get,
4236         .vlan_filter_set = mlx4_vlan_filter_set,
4237         .vlan_tpid_set = NULL,
4238         .vlan_strip_queue_set = NULL,
4239         .vlan_offload_set = NULL,
4240         .rx_queue_setup = mlx4_rx_queue_setup,
4241         .tx_queue_setup = mlx4_tx_queue_setup,
4242         .rx_queue_release = mlx4_rx_queue_release,
4243         .tx_queue_release = mlx4_tx_queue_release,
4244         .dev_led_on = NULL,
4245         .dev_led_off = NULL,
4246         .flow_ctrl_get = mlx4_dev_get_flow_ctrl,
4247         .flow_ctrl_set = mlx4_dev_set_flow_ctrl,
4248         .priority_flow_ctrl_set = NULL,
4249         .mac_addr_remove = mlx4_mac_addr_remove,
4250         .mac_addr_add = mlx4_mac_addr_add,
4251         .mtu_set = mlx4_dev_set_mtu,
4252         .fdir_add_signature_filter = NULL,
4253         .fdir_update_signature_filter = NULL,
4254         .fdir_remove_signature_filter = NULL,
4255         .fdir_add_perfect_filter = NULL,
4256         .fdir_update_perfect_filter = NULL,
4257         .fdir_remove_perfect_filter = NULL,
4258         .fdir_set_masks = NULL
4259 };
4260
4261 /**
4262  * Get PCI information from struct ibv_device.
4263  *
4264  * @param device
4265  *   Pointer to Ethernet device structure.
4266  * @param[out] pci_addr
4267  *   PCI bus address output buffer.
4268  *
4269  * @return
4270  *   0 on success, -1 on failure and errno is set.
4271  */
4272 static int
4273 mlx4_ibv_device_to_pci_addr(const struct ibv_device *device,
4274                             struct rte_pci_addr *pci_addr)
4275 {
4276         FILE *file;
4277         char line[32];
4278         MKSTR(path, "%s/device/uevent", device->ibdev_path);
4279
4280         file = fopen(path, "rb");
4281         if (file == NULL)
4282                 return -1;
4283         while (fgets(line, sizeof(line), file) == line) {
4284                 size_t len = strlen(line);
4285                 int ret;
4286
4287                 /* Truncate long lines. */
4288                 if (len == (sizeof(line) - 1))
4289                         while (line[(len - 1)] != '\n') {
4290                                 ret = fgetc(file);
4291                                 if (ret == EOF)
4292                                         break;
4293                                 line[(len - 1)] = ret;
4294                         }
4295                 /* Extract information. */
4296                 if (sscanf(line,
4297                            "PCI_SLOT_NAME="
4298                            "%" SCNx16 ":%" SCNx8 ":%" SCNx8 ".%" SCNx8 "\n",
4299                            &pci_addr->domain,
4300                            &pci_addr->bus,
4301                            &pci_addr->devid,
4302                            &pci_addr->function) == 4) {
4303                         ret = 0;
4304                         break;
4305                 }
4306         }
4307         fclose(file);
4308         return 0;
4309 }
4310
4311 /**
4312  * Derive MAC address from port GID.
4313  *
4314  * @param[out] mac
4315  *   MAC address output buffer.
4316  * @param port
4317  *   Physical port number.
4318  * @param[in] gid
4319  *   Port GID.
4320  */
4321 static void
4322 mac_from_gid(uint8_t (*mac)[ETHER_ADDR_LEN], uint32_t port, uint8_t *gid)
4323 {
4324         memcpy(&(*mac)[0], gid + 8, 3);
4325         memcpy(&(*mac)[3], gid + 13, 3);
4326         if (port == 1)
4327                 (*mac)[0] ^= 2;
4328 }
4329
4330 /* Support up to 32 adapters. */
4331 static struct {
4332         struct rte_pci_addr pci_addr; /* associated PCI address */
4333         uint32_t ports; /* physical ports bitfield. */
4334 } mlx4_dev[32];
4335
4336 /**
4337  * Get device index in mlx4_dev[] from PCI bus address.
4338  *
4339  * @param[in] pci_addr
4340  *   PCI bus address to look for.
4341  *
4342  * @return
4343  *   mlx4_dev[] index on success, -1 on failure.
4344  */
4345 static int
4346 mlx4_dev_idx(struct rte_pci_addr *pci_addr)
4347 {
4348         unsigned int i;
4349         int ret = -1;
4350
4351         assert(pci_addr != NULL);
4352         for (i = 0; (i != elemof(mlx4_dev)); ++i) {
4353                 if ((mlx4_dev[i].pci_addr.domain == pci_addr->domain) &&
4354                     (mlx4_dev[i].pci_addr.bus == pci_addr->bus) &&
4355                     (mlx4_dev[i].pci_addr.devid == pci_addr->devid) &&
4356                     (mlx4_dev[i].pci_addr.function == pci_addr->function))
4357                         return i;
4358                 if ((mlx4_dev[i].ports == 0) && (ret == -1))
4359                         ret = i;
4360         }
4361         return ret;
4362 }
4363
4364 /**
4365  * Retrieve integer value from environment variable.
4366  *
4367  * @param[in] name
4368  *   Environment variable name.
4369  *
4370  * @return
4371  *   Integer value, 0 if the variable is not set.
4372  */
4373 static int
4374 mlx4_getenv_int(const char *name)
4375 {
4376         const char *val = getenv(name);
4377
4378         if (val == NULL)
4379                 return 0;
4380         return atoi(val);
4381 }
4382
4383 static struct eth_driver mlx4_driver;
4384
4385 /**
4386  * DPDK callback to register a PCI device.
4387  *
4388  * This function creates an Ethernet device for each port of a given
4389  * PCI device.
4390  *
4391  * @param[in] pci_drv
4392  *   PCI driver structure (mlx4_driver).
4393  * @param[in] pci_dev
4394  *   PCI device information.
4395  *
4396  * @return
4397  *   0 on success, negative errno value on failure.
4398  */
4399 static int
4400 mlx4_pci_devinit(struct rte_pci_driver *pci_drv, struct rte_pci_device *pci_dev)
4401 {
4402         struct ibv_device **list;
4403         struct ibv_device *ibv_dev;
4404         int err = 0;
4405         struct ibv_context *attr_ctx = NULL;
4406         struct ibv_device_attr device_attr;
4407         unsigned int vf;
4408         int idx;
4409         int i;
4410
4411         (void)pci_drv;
4412         assert(pci_drv == &mlx4_driver.pci_drv);
4413         /* Get mlx4_dev[] index. */
4414         idx = mlx4_dev_idx(&pci_dev->addr);
4415         if (idx == -1) {
4416                 ERROR("this driver cannot support any more adapters");
4417                 return -ENOMEM;
4418         }
4419         DEBUG("using driver device index %d", idx);
4420
4421         /* Save PCI address. */
4422         mlx4_dev[idx].pci_addr = pci_dev->addr;
4423         list = ibv_get_device_list(&i);
4424         if (list == NULL) {
4425                 assert(errno);
4426                 return -errno;
4427         }
4428         assert(i >= 0);
4429         /*
4430          * For each listed device, check related sysfs entry against
4431          * the provided PCI ID.
4432          */
4433         while (i != 0) {
4434                 struct rte_pci_addr pci_addr;
4435
4436                 --i;
4437                 DEBUG("checking device \"%s\"", list[i]->name);
4438                 if (mlx4_ibv_device_to_pci_addr(list[i], &pci_addr))
4439                         continue;
4440                 if ((pci_dev->addr.domain != pci_addr.domain) ||
4441                     (pci_dev->addr.bus != pci_addr.bus) ||
4442                     (pci_dev->addr.devid != pci_addr.devid) ||
4443                     (pci_dev->addr.function != pci_addr.function))
4444                         continue;
4445                 vf = (pci_dev->id.device_id ==
4446                       PCI_DEVICE_ID_MELLANOX_CONNECTX3VF);
4447                 INFO("PCI information matches, using device \"%s\" (VF: %s)",
4448                      list[i]->name, (vf ? "true" : "false"));
4449                 attr_ctx = ibv_open_device(list[i]);
4450                 err = errno;
4451                 break;
4452         }
4453         if (attr_ctx == NULL) {
4454                 if (err == 0)
4455                         err = ENODEV;
4456                 ibv_free_device_list(list);
4457                 assert(err > 0);
4458                 return -err;
4459         }
4460         ibv_dev = list[i];
4461
4462         DEBUG("device opened");
4463         if (ibv_query_device(attr_ctx, &device_attr))
4464                 goto error;
4465         INFO("%u port(s) detected", device_attr.phys_port_cnt);
4466
4467         for (i = 0; i < device_attr.phys_port_cnt; i++) {
4468                 uint32_t port = i + 1; /* ports are indexed from one */
4469                 uint32_t test = (1 << i);
4470                 struct ibv_context *ctx = NULL;
4471                 struct ibv_port_attr port_attr;
4472                 struct ibv_pd *pd = NULL;
4473                 struct priv *priv = NULL;
4474                 struct rte_eth_dev *eth_dev;
4475 #if defined(INLINE_RECV) || defined(RSS_SUPPORT)
4476                 struct ibv_exp_device_attr exp_device_attr;
4477 #endif
4478                 struct ether_addr mac;
4479                 union ibv_gid temp_gid;
4480
4481 #ifdef RSS_SUPPORT
4482                 exp_device_attr.comp_mask =
4483                         (IBV_EXP_DEVICE_ATTR_EXP_CAP_FLAGS |
4484                          IBV_EXP_DEVICE_ATTR_RSS_TBL_SZ);
4485 #endif /* RSS_SUPPORT */
4486
4487                 DEBUG("using port %u (%08" PRIx32 ")", port, test);
4488
4489                 ctx = ibv_open_device(ibv_dev);
4490                 if (ctx == NULL)
4491                         goto port_error;
4492
4493                 /* Check port status. */
4494                 err = ibv_query_port(ctx, port, &port_attr);
4495                 if (err) {
4496                         ERROR("port query failed: %s", strerror(err));
4497                         goto port_error;
4498                 }
4499                 if (port_attr.state != IBV_PORT_ACTIVE)
4500                         WARN("bad state for port %d: \"%s\" (%d)",
4501                              port, ibv_port_state_str(port_attr.state),
4502                              port_attr.state);
4503
4504                 /* Allocate protection domain. */
4505                 pd = ibv_alloc_pd(ctx);
4506                 if (pd == NULL) {
4507                         ERROR("PD allocation failure");
4508                         err = ENOMEM;
4509                         goto port_error;
4510                 }
4511
4512                 mlx4_dev[idx].ports |= test;
4513
4514                 /* from rte_ethdev.c */
4515                 priv = rte_zmalloc("ethdev private structure",
4516                                    sizeof(*priv),
4517                                    RTE_CACHE_LINE_SIZE);
4518                 if (priv == NULL) {
4519                         ERROR("priv allocation failure");
4520                         err = ENOMEM;
4521                         goto port_error;
4522                 }
4523
4524                 priv->ctx = ctx;
4525                 priv->device_attr = device_attr;
4526                 priv->port_attr = port_attr;
4527                 priv->port = port;
4528                 priv->pd = pd;
4529                 priv->mtu = ETHER_MTU;
4530 #ifdef RSS_SUPPORT
4531                 if (ibv_exp_query_device(ctx, &exp_device_attr)) {
4532                         INFO("experimental ibv_exp_query_device");
4533                         goto port_error;
4534                 }
4535                 if ((exp_device_attr.exp_device_cap_flags &
4536                      IBV_EXP_DEVICE_QPG) &&
4537                     (exp_device_attr.exp_device_cap_flags &
4538                      IBV_EXP_DEVICE_UD_RSS) &&
4539                     (exp_device_attr.comp_mask &
4540                      IBV_EXP_DEVICE_ATTR_RSS_TBL_SZ) &&
4541                     (exp_device_attr.max_rss_tbl_sz > 0)) {
4542                         priv->hw_qpg = 1;
4543                         priv->hw_rss = 1;
4544                         priv->max_rss_tbl_sz = exp_device_attr.max_rss_tbl_sz;
4545                 } else {
4546                         priv->hw_qpg = 0;
4547                         priv->hw_rss = 0;
4548                         priv->max_rss_tbl_sz = 0;
4549                 }
4550                 priv->hw_tss = !!(exp_device_attr.exp_device_cap_flags &
4551                                   IBV_EXP_DEVICE_UD_TSS);
4552                 DEBUG("device flags: %s%s%s",
4553                       (priv->hw_qpg ? "IBV_DEVICE_QPG " : ""),
4554                       (priv->hw_tss ? "IBV_DEVICE_TSS " : ""),
4555                       (priv->hw_rss ? "IBV_DEVICE_RSS " : ""));
4556                 if (priv->hw_rss)
4557                         DEBUG("maximum RSS indirection table size: %u",
4558                               exp_device_attr.max_rss_tbl_sz);
4559 #endif /* RSS_SUPPORT */
4560
4561 #ifdef INLINE_RECV
4562                 priv->inl_recv_size = mlx4_getenv_int("MLX4_INLINE_RECV_SIZE");
4563
4564                 if (priv->inl_recv_size) {
4565                         exp_device_attr.comp_mask =
4566                                 IBV_EXP_DEVICE_ATTR_INLINE_RECV_SZ;
4567                         if (ibv_exp_query_device(ctx, &exp_device_attr)) {
4568                                 INFO("Couldn't query device for inline-receive"
4569                                      " capabilities.");
4570                                 priv->inl_recv_size = 0;
4571                         } else {
4572                                 if ((unsigned)exp_device_attr.inline_recv_sz <
4573                                     priv->inl_recv_size) {
4574                                         INFO("Max inline-receive (%d) <"
4575                                              " requested inline-receive (%u)",
4576                                              exp_device_attr.inline_recv_sz,
4577                                              priv->inl_recv_size);
4578                                         priv->inl_recv_size =
4579                                                 exp_device_attr.inline_recv_sz;
4580                                 }
4581                         }
4582                         INFO("Set inline receive size to %u",
4583                              priv->inl_recv_size);
4584                 }
4585 #endif /* INLINE_RECV */
4586
4587 #ifdef MLX4_COMPAT_VMWARE
4588                 if (mlx4_getenv_int("MLX4_COMPAT_VMWARE"))
4589                         priv->vmware = 1;
4590 #else /* MLX4_COMPAT_VMWARE */
4591                 (void)mlx4_getenv_int;
4592 #endif /* MLX4_COMPAT_VMWARE */
4593                 priv->vf = vf;
4594                 if (ibv_query_gid(ctx, port, 0, &temp_gid)) {
4595                         ERROR("ibv_query_gid() failure");
4596                         goto port_error;
4597                 }
4598                 /* Configure the first MAC address by default. */
4599                 mac_from_gid(&mac.addr_bytes, port, temp_gid.raw);
4600                 INFO("port %u MAC address is %02x:%02x:%02x:%02x:%02x:%02x",
4601                      priv->port,
4602                      mac.addr_bytes[0], mac.addr_bytes[1],
4603                      mac.addr_bytes[2], mac.addr_bytes[3],
4604                      mac.addr_bytes[4], mac.addr_bytes[5]);
4605                 /* Register MAC and broadcast addresses. */
4606                 claim_zero(priv_mac_addr_add(priv, 0,
4607                                              (const uint8_t (*)[ETHER_ADDR_LEN])
4608                                              mac.addr_bytes));
4609                 claim_zero(priv_mac_addr_add(priv, 1,
4610                                              &(const uint8_t [ETHER_ADDR_LEN])
4611                                              { "\xff\xff\xff\xff\xff\xff" }));
4612 #ifndef NDEBUG
4613                 {
4614                         char ifname[IF_NAMESIZE];
4615
4616                         if (priv_get_ifname(priv, &ifname) == 0)
4617                                 DEBUG("port %u ifname is \"%s\"",
4618                                       priv->port, ifname);
4619                         else
4620                                 DEBUG("port %u ifname is unknown", priv->port);
4621                 }
4622 #endif
4623                 /* Get actual MTU if possible. */
4624                 priv_get_mtu(priv, &priv->mtu);
4625                 DEBUG("port %u MTU is %u", priv->port, priv->mtu);
4626
4627                 /* from rte_ethdev.c */
4628                 {
4629                         char name[RTE_ETH_NAME_MAX_LEN];
4630
4631                         snprintf(name, sizeof(name), "%s port %u",
4632                                  ibv_get_device_name(ibv_dev), port);
4633                         eth_dev = rte_eth_dev_allocate(name, RTE_ETH_DEV_PCI);
4634                 }
4635                 if (eth_dev == NULL) {
4636                         ERROR("can not allocate rte ethdev");
4637                         err = ENOMEM;
4638                         goto port_error;
4639                 }
4640
4641                 eth_dev->data->dev_private = priv;
4642                 eth_dev->pci_dev = pci_dev;
4643                 eth_dev->driver = &mlx4_driver;
4644                 eth_dev->data->rx_mbuf_alloc_failed = 0;
4645                 eth_dev->data->mtu = ETHER_MTU;
4646
4647                 priv->dev = eth_dev;
4648                 eth_dev->dev_ops = &mlx4_dev_ops;
4649                 eth_dev->data->mac_addrs = priv->mac;
4650
4651                 /* Bring Ethernet device up. */
4652                 DEBUG("forcing Ethernet interface up");
4653                 priv_set_flags(priv, ~IFF_UP, IFF_UP);
4654                 continue;
4655
4656 port_error:
4657                 if (priv)
4658                         rte_free(priv);
4659                 if (pd)
4660                         claim_zero(ibv_dealloc_pd(pd));
4661                 if (ctx)
4662                         claim_zero(ibv_close_device(ctx));
4663                 break;
4664         }
4665
4666         /*
4667          * XXX if something went wrong in the loop above, there is a resource
4668          * leak (ctx, pd, priv, dpdk ethdev) but we can do nothing about it as
4669          * long as the dpdk does not provide a way to deallocate a ethdev and a
4670          * way to enumerate the registered ethdevs to free the previous ones.
4671          */
4672
4673         /* no port found, complain */
4674         if (!mlx4_dev[idx].ports) {
4675                 err = ENODEV;
4676                 goto error;
4677         }
4678
4679 error:
4680         if (attr_ctx)
4681                 claim_zero(ibv_close_device(attr_ctx));
4682         if (list)
4683                 ibv_free_device_list(list);
4684         assert(err >= 0);
4685         return -err;
4686 }
4687
4688 static struct rte_pci_id mlx4_pci_id_map[] = {
4689         {
4690                 .vendor_id = PCI_VENDOR_ID_MELLANOX,
4691                 .device_id = PCI_DEVICE_ID_MELLANOX_CONNECTX3,
4692                 .subsystem_vendor_id = PCI_ANY_ID,
4693                 .subsystem_device_id = PCI_ANY_ID
4694         },
4695         {
4696                 .vendor_id = PCI_VENDOR_ID_MELLANOX,
4697                 .device_id = PCI_DEVICE_ID_MELLANOX_CONNECTX3PRO,
4698                 .subsystem_vendor_id = PCI_ANY_ID,
4699                 .subsystem_device_id = PCI_ANY_ID
4700         },
4701         {
4702                 .vendor_id = PCI_VENDOR_ID_MELLANOX,
4703                 .device_id = PCI_DEVICE_ID_MELLANOX_CONNECTX3VF,
4704                 .subsystem_vendor_id = PCI_ANY_ID,
4705                 .subsystem_device_id = PCI_ANY_ID
4706         },
4707         {
4708                 .vendor_id = 0
4709         }
4710 };
4711
4712 static struct eth_driver mlx4_driver = {
4713         .pci_drv = {
4714                 .name = MLX4_DRIVER_NAME,
4715                 .id_table = mlx4_pci_id_map,
4716                 .devinit = mlx4_pci_devinit,
4717         },
4718         .dev_private_size = sizeof(struct priv)
4719 };
4720
4721 /**
4722  * Driver initialization routine.
4723  */
4724 static int
4725 rte_mlx4_pmd_init(const char *name, const char *args)
4726 {
4727         (void)name;
4728         (void)args;
4729         rte_eal_pci_register(&mlx4_driver.pci_drv);
4730         return 0;
4731 }
4732
4733 static struct rte_driver rte_mlx4_driver = {
4734         .type = PMD_PDEV,
4735         .name = MLX4_DRIVER_NAME,
4736         .init = rte_mlx4_pmd_init,
4737 };
4738
4739 PMD_REGISTER_DRIVER(rte_mlx4_driver)