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