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