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