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