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