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