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