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