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