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