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