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