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