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