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