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