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