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