net/mlx5: fix allocation when no memory on device NUMA node
[dpdk.git] / drivers / net / mlx5 / mlx5.c
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright 2015 6WIND S.A.
5  *   Copyright 2015 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 #include <stddef.h>
35 #include <unistd.h>
36 #include <string.h>
37 #include <assert.h>
38 #include <stdint.h>
39 #include <stdlib.h>
40 #include <errno.h>
41 #include <net/if.h>
42
43 /* Verbs header. */
44 /* ISO C doesn't support unnamed structs/unions, disabling -pedantic. */
45 #ifdef PEDANTIC
46 #pragma GCC diagnostic ignored "-Wpedantic"
47 #endif
48 #include <infiniband/verbs.h>
49 #ifdef PEDANTIC
50 #pragma GCC diagnostic error "-Wpedantic"
51 #endif
52
53 #include <rte_malloc.h>
54 #include <rte_ethdev_driver.h>
55 #include <rte_ethdev_pci.h>
56 #include <rte_pci.h>
57 #include <rte_bus_pci.h>
58 #include <rte_common.h>
59 #include <rte_kvargs.h>
60
61 #include "mlx5.h"
62 #include "mlx5_utils.h"
63 #include "mlx5_rxtx.h"
64 #include "mlx5_autoconf.h"
65 #include "mlx5_defs.h"
66
67 /* Device parameter to enable RX completion queue compression. */
68 #define MLX5_RXQ_CQE_COMP_EN "rxq_cqe_comp_en"
69
70 /* Device parameter to configure inline send. */
71 #define MLX5_TXQ_INLINE "txq_inline"
72
73 /*
74  * Device parameter to configure the number of TX queues threshold for
75  * enabling inline send.
76  */
77 #define MLX5_TXQS_MIN_INLINE "txqs_min_inline"
78
79 /* Device parameter to enable multi-packet send WQEs. */
80 #define MLX5_TXQ_MPW_EN "txq_mpw_en"
81
82 /* Device parameter to include 2 dsegs in the title WQEBB. */
83 #define MLX5_TXQ_MPW_HDR_DSEG_EN "txq_mpw_hdr_dseg_en"
84
85 /* Device parameter to limit the size of inlining packet. */
86 #define MLX5_TXQ_MAX_INLINE_LEN "txq_max_inline_len"
87
88 /* Device parameter to enable hardware Tx vector. */
89 #define MLX5_TX_VEC_EN "tx_vec_en"
90
91 /* Device parameter to enable hardware Rx vector. */
92 #define MLX5_RX_VEC_EN "rx_vec_en"
93
94 #ifndef HAVE_IBV_MLX5_MOD_MPW
95 #define MLX5DV_CONTEXT_FLAGS_MPW_ALLOWED (1 << 2)
96 #define MLX5DV_CONTEXT_FLAGS_ENHANCED_MPW (1 << 3)
97 #endif
98
99 #ifndef HAVE_IBV_MLX5_MOD_CQE_128B_COMP
100 #define MLX5DV_CONTEXT_FLAGS_CQE_128B_COMP (1 << 4)
101 #endif
102
103 /**
104  * Retrieve integer value from environment variable.
105  *
106  * @param[in] name
107  *   Environment variable name.
108  *
109  * @return
110  *   Integer value, 0 if the variable is not set.
111  */
112 int
113 mlx5_getenv_int(const char *name)
114 {
115         const char *val = getenv(name);
116
117         if (val == NULL)
118                 return 0;
119         return atoi(val);
120 }
121
122 /**
123  * Verbs callback to allocate a memory. This function should allocate the space
124  * according to the size provided residing inside a huge page.
125  * Please note that all allocation must respect the alignment from libmlx5
126  * (i.e. currently sysconf(_SC_PAGESIZE)).
127  *
128  * @param[in] size
129  *   The size in bytes of the memory to allocate.
130  * @param[in] data
131  *   A pointer to the callback data.
132  *
133  * @return
134  *   a pointer to the allocate space.
135  */
136 static void *
137 mlx5_alloc_verbs_buf(size_t size, void *data)
138 {
139         struct priv *priv = data;
140         void *ret;
141         size_t alignment = sysconf(_SC_PAGESIZE);
142         unsigned int socket = SOCKET_ID_ANY;
143
144         if (priv->verbs_alloc_ctx.type == MLX5_VERBS_ALLOC_TYPE_TX_QUEUE) {
145                 const struct mlx5_txq_ctrl *ctrl = priv->verbs_alloc_ctx.obj;
146
147                 socket = ctrl->socket;
148         } else if (priv->verbs_alloc_ctx.type ==
149                    MLX5_VERBS_ALLOC_TYPE_RX_QUEUE) {
150                 const struct mlx5_rxq_ctrl *ctrl = priv->verbs_alloc_ctx.obj;
151
152                 socket = ctrl->socket;
153         }
154         assert(data != NULL);
155         ret = rte_malloc_socket(__func__, size, alignment, socket);
156         DEBUG("Extern alloc size: %lu, align: %lu: %p", size, alignment, ret);
157         return ret;
158 }
159
160 /**
161  * Verbs callback to free a memory.
162  *
163  * @param[in] ptr
164  *   A pointer to the memory to free.
165  * @param[in] data
166  *   A pointer to the callback data.
167  */
168 static void
169 mlx5_free_verbs_buf(void *ptr, void *data __rte_unused)
170 {
171         assert(data != NULL);
172         DEBUG("Extern free request: %p", ptr);
173         rte_free(ptr);
174 }
175
176 /**
177  * DPDK callback to close the device.
178  *
179  * Destroy all queues and objects, free memory.
180  *
181  * @param dev
182  *   Pointer to Ethernet device structure.
183  */
184 static void
185 mlx5_dev_close(struct rte_eth_dev *dev)
186 {
187         struct priv *priv = dev->data->dev_private;
188         unsigned int i;
189         int ret;
190
191         priv_lock(priv);
192         DEBUG("%p: closing device \"%s\"",
193               (void *)dev,
194               ((priv->ctx != NULL) ? priv->ctx->device->name : ""));
195         /* In case mlx5_dev_stop() has not been called. */
196         priv_dev_interrupt_handler_uninstall(priv, dev);
197         priv_dev_traffic_disable(priv, dev);
198         /* Prevent crashes when queues are still in use. */
199         dev->rx_pkt_burst = removed_rx_burst;
200         dev->tx_pkt_burst = removed_tx_burst;
201         if (priv->rxqs != NULL) {
202                 /* XXX race condition if mlx5_rx_burst() is still running. */
203                 usleep(1000);
204                 for (i = 0; (i != priv->rxqs_n); ++i)
205                         mlx5_priv_rxq_release(priv, i);
206                 priv->rxqs_n = 0;
207                 priv->rxqs = NULL;
208         }
209         if (priv->txqs != NULL) {
210                 /* XXX race condition if mlx5_tx_burst() is still running. */
211                 usleep(1000);
212                 for (i = 0; (i != priv->txqs_n); ++i)
213                         mlx5_priv_txq_release(priv, i);
214                 priv->txqs_n = 0;
215                 priv->txqs = NULL;
216         }
217         if (priv->pd != NULL) {
218                 assert(priv->ctx != NULL);
219                 claim_zero(ibv_dealloc_pd(priv->pd));
220                 claim_zero(ibv_close_device(priv->ctx));
221         } else
222                 assert(priv->ctx == NULL);
223         if (priv->rss_conf.rss_key != NULL)
224                 rte_free(priv->rss_conf.rss_key);
225         if (priv->reta_idx != NULL)
226                 rte_free(priv->reta_idx);
227         priv_socket_uninit(priv);
228         ret = mlx5_priv_hrxq_ibv_verify(priv);
229         if (ret)
230                 WARN("%p: some Hash Rx queue still remain", (void *)priv);
231         ret = mlx5_priv_ind_table_ibv_verify(priv);
232         if (ret)
233                 WARN("%p: some Indirection table still remain", (void *)priv);
234         ret = mlx5_priv_rxq_ibv_verify(priv);
235         if (ret)
236                 WARN("%p: some Verbs Rx queue still remain", (void *)priv);
237         ret = mlx5_priv_rxq_verify(priv);
238         if (ret)
239                 WARN("%p: some Rx Queues still remain", (void *)priv);
240         ret = mlx5_priv_txq_ibv_verify(priv);
241         if (ret)
242                 WARN("%p: some Verbs Tx queue still remain", (void *)priv);
243         ret = mlx5_priv_txq_verify(priv);
244         if (ret)
245                 WARN("%p: some Tx Queues still remain", (void *)priv);
246         ret = priv_flow_verify(priv);
247         if (ret)
248                 WARN("%p: some flows still remain", (void *)priv);
249         ret = priv_mr_verify(priv);
250         if (ret)
251                 WARN("%p: some Memory Region still remain", (void *)priv);
252         priv_unlock(priv);
253         memset(priv, 0, sizeof(*priv));
254 }
255
256 const struct eth_dev_ops mlx5_dev_ops = {
257         .dev_configure = mlx5_dev_configure,
258         .dev_start = mlx5_dev_start,
259         .dev_stop = mlx5_dev_stop,
260         .dev_set_link_down = mlx5_set_link_down,
261         .dev_set_link_up = mlx5_set_link_up,
262         .dev_close = mlx5_dev_close,
263         .promiscuous_enable = mlx5_promiscuous_enable,
264         .promiscuous_disable = mlx5_promiscuous_disable,
265         .allmulticast_enable = mlx5_allmulticast_enable,
266         .allmulticast_disable = mlx5_allmulticast_disable,
267         .link_update = mlx5_link_update,
268         .stats_get = mlx5_stats_get,
269         .stats_reset = mlx5_stats_reset,
270         .xstats_get = mlx5_xstats_get,
271         .xstats_reset = mlx5_xstats_reset,
272         .xstats_get_names = mlx5_xstats_get_names,
273         .dev_infos_get = mlx5_dev_infos_get,
274         .dev_supported_ptypes_get = mlx5_dev_supported_ptypes_get,
275         .vlan_filter_set = mlx5_vlan_filter_set,
276         .rx_queue_setup = mlx5_rx_queue_setup,
277         .tx_queue_setup = mlx5_tx_queue_setup,
278         .rx_queue_release = mlx5_rx_queue_release,
279         .tx_queue_release = mlx5_tx_queue_release,
280         .flow_ctrl_get = mlx5_dev_get_flow_ctrl,
281         .flow_ctrl_set = mlx5_dev_set_flow_ctrl,
282         .mac_addr_remove = mlx5_mac_addr_remove,
283         .mac_addr_add = mlx5_mac_addr_add,
284         .mac_addr_set = mlx5_mac_addr_set,
285         .mtu_set = mlx5_dev_set_mtu,
286         .vlan_strip_queue_set = mlx5_vlan_strip_queue_set,
287         .vlan_offload_set = mlx5_vlan_offload_set,
288         .reta_update = mlx5_dev_rss_reta_update,
289         .reta_query = mlx5_dev_rss_reta_query,
290         .rss_hash_update = mlx5_rss_hash_update,
291         .rss_hash_conf_get = mlx5_rss_hash_conf_get,
292         .filter_ctrl = mlx5_dev_filter_ctrl,
293         .rx_descriptor_status = mlx5_rx_descriptor_status,
294         .tx_descriptor_status = mlx5_tx_descriptor_status,
295         .rx_queue_intr_enable = mlx5_rx_intr_enable,
296         .rx_queue_intr_disable = mlx5_rx_intr_disable,
297         .is_removed = mlx5_is_removed,
298 };
299
300 static const struct eth_dev_ops mlx5_dev_sec_ops = {
301         .stats_get = mlx5_stats_get,
302         .stats_reset = mlx5_stats_reset,
303         .xstats_get = mlx5_xstats_get,
304         .xstats_reset = mlx5_xstats_reset,
305         .xstats_get_names = mlx5_xstats_get_names,
306         .dev_infos_get = mlx5_dev_infos_get,
307         .rx_descriptor_status = mlx5_rx_descriptor_status,
308         .tx_descriptor_status = mlx5_tx_descriptor_status,
309 };
310
311 /* Available operators in flow isolated mode. */
312 const struct eth_dev_ops mlx5_dev_ops_isolate = {
313         .dev_configure = mlx5_dev_configure,
314         .dev_start = mlx5_dev_start,
315         .dev_stop = mlx5_dev_stop,
316         .dev_set_link_down = mlx5_set_link_down,
317         .dev_set_link_up = mlx5_set_link_up,
318         .dev_close = mlx5_dev_close,
319         .link_update = mlx5_link_update,
320         .stats_get = mlx5_stats_get,
321         .stats_reset = mlx5_stats_reset,
322         .xstats_get = mlx5_xstats_get,
323         .xstats_reset = mlx5_xstats_reset,
324         .xstats_get_names = mlx5_xstats_get_names,
325         .dev_infos_get = mlx5_dev_infos_get,
326         .dev_supported_ptypes_get = mlx5_dev_supported_ptypes_get,
327         .vlan_filter_set = mlx5_vlan_filter_set,
328         .rx_queue_setup = mlx5_rx_queue_setup,
329         .tx_queue_setup = mlx5_tx_queue_setup,
330         .rx_queue_release = mlx5_rx_queue_release,
331         .tx_queue_release = mlx5_tx_queue_release,
332         .flow_ctrl_get = mlx5_dev_get_flow_ctrl,
333         .flow_ctrl_set = mlx5_dev_set_flow_ctrl,
334         .mac_addr_remove = mlx5_mac_addr_remove,
335         .mac_addr_add = mlx5_mac_addr_add,
336         .mac_addr_set = mlx5_mac_addr_set,
337         .mtu_set = mlx5_dev_set_mtu,
338         .vlan_strip_queue_set = mlx5_vlan_strip_queue_set,
339         .vlan_offload_set = mlx5_vlan_offload_set,
340         .filter_ctrl = mlx5_dev_filter_ctrl,
341         .rx_descriptor_status = mlx5_rx_descriptor_status,
342         .tx_descriptor_status = mlx5_tx_descriptor_status,
343         .rx_queue_intr_enable = mlx5_rx_intr_enable,
344         .rx_queue_intr_disable = mlx5_rx_intr_disable,
345         .is_removed = mlx5_is_removed,
346 };
347
348 static struct {
349         struct rte_pci_addr pci_addr; /* associated PCI address */
350         uint32_t ports; /* physical ports bitfield. */
351 } mlx5_dev[32];
352
353 /**
354  * Get device index in mlx5_dev[] from PCI bus address.
355  *
356  * @param[in] pci_addr
357  *   PCI bus address to look for.
358  *
359  * @return
360  *   mlx5_dev[] index on success, -1 on failure.
361  */
362 static int
363 mlx5_dev_idx(struct rte_pci_addr *pci_addr)
364 {
365         unsigned int i;
366         int ret = -1;
367
368         assert(pci_addr != NULL);
369         for (i = 0; (i != RTE_DIM(mlx5_dev)); ++i) {
370                 if ((mlx5_dev[i].pci_addr.domain == pci_addr->domain) &&
371                     (mlx5_dev[i].pci_addr.bus == pci_addr->bus) &&
372                     (mlx5_dev[i].pci_addr.devid == pci_addr->devid) &&
373                     (mlx5_dev[i].pci_addr.function == pci_addr->function))
374                         return i;
375                 if ((mlx5_dev[i].ports == 0) && (ret == -1))
376                         ret = i;
377         }
378         return ret;
379 }
380
381 /**
382  * Verify and store value for device argument.
383  *
384  * @param[in] key
385  *   Key argument to verify.
386  * @param[in] val
387  *   Value associated with key.
388  * @param opaque
389  *   User data.
390  *
391  * @return
392  *   0 on success, negative errno value on failure.
393  */
394 static int
395 mlx5_args_check(const char *key, const char *val, void *opaque)
396 {
397         struct mlx5_dev_config *config = opaque;
398         unsigned long tmp;
399
400         errno = 0;
401         tmp = strtoul(val, NULL, 0);
402         if (errno) {
403                 WARN("%s: \"%s\" is not a valid integer", key, val);
404                 return errno;
405         }
406         if (strcmp(MLX5_RXQ_CQE_COMP_EN, key) == 0) {
407                 config->cqe_comp = !!tmp;
408         } else if (strcmp(MLX5_TXQ_INLINE, key) == 0) {
409                 config->txq_inline = tmp;
410         } else if (strcmp(MLX5_TXQS_MIN_INLINE, key) == 0) {
411                 config->txqs_inline = tmp;
412         } else if (strcmp(MLX5_TXQ_MPW_EN, key) == 0) {
413                 config->mps = !!tmp ? config->mps : 0;
414         } else if (strcmp(MLX5_TXQ_MPW_HDR_DSEG_EN, key) == 0) {
415                 config->mpw_hdr_dseg = !!tmp;
416         } else if (strcmp(MLX5_TXQ_MAX_INLINE_LEN, key) == 0) {
417                 config->inline_max_packet_sz = tmp;
418         } else if (strcmp(MLX5_TX_VEC_EN, key) == 0) {
419                 config->tx_vec_en = !!tmp;
420         } else if (strcmp(MLX5_RX_VEC_EN, key) == 0) {
421                 config->rx_vec_en = !!tmp;
422         } else {
423                 WARN("%s: unknown parameter", key);
424                 return -EINVAL;
425         }
426         return 0;
427 }
428
429 /**
430  * Parse device parameters.
431  *
432  * @param config
433  *   Pointer to device configuration structure.
434  * @param devargs
435  *   Device arguments structure.
436  *
437  * @return
438  *   0 on success, errno value on failure.
439  */
440 static int
441 mlx5_args(struct mlx5_dev_config *config, struct rte_devargs *devargs)
442 {
443         const char **params = (const char *[]){
444                 MLX5_RXQ_CQE_COMP_EN,
445                 MLX5_TXQ_INLINE,
446                 MLX5_TXQS_MIN_INLINE,
447                 MLX5_TXQ_MPW_EN,
448                 MLX5_TXQ_MPW_HDR_DSEG_EN,
449                 MLX5_TXQ_MAX_INLINE_LEN,
450                 MLX5_TX_VEC_EN,
451                 MLX5_RX_VEC_EN,
452                 NULL,
453         };
454         struct rte_kvargs *kvlist;
455         int ret = 0;
456         int i;
457
458         if (devargs == NULL)
459                 return 0;
460         /* Following UGLY cast is done to pass checkpatch. */
461         kvlist = rte_kvargs_parse(devargs->args, params);
462         if (kvlist == NULL)
463                 return 0;
464         /* Process parameters. */
465         for (i = 0; (params[i] != NULL); ++i) {
466                 if (rte_kvargs_count(kvlist, params[i])) {
467                         ret = rte_kvargs_process(kvlist, params[i],
468                                                  mlx5_args_check, config);
469                         if (ret != 0) {
470                                 rte_kvargs_free(kvlist);
471                                 return ret;
472                         }
473                 }
474         }
475         rte_kvargs_free(kvlist);
476         return 0;
477 }
478
479 static struct rte_pci_driver mlx5_driver;
480
481 /**
482  * DPDK callback to register a PCI device.
483  *
484  * This function creates an Ethernet device for each port of a given
485  * PCI device.
486  *
487  * @param[in] pci_drv
488  *   PCI driver structure (mlx5_driver).
489  * @param[in] pci_dev
490  *   PCI device information.
491  *
492  * @return
493  *   0 on success, negative errno value on failure.
494  */
495 static int
496 mlx5_pci_probe(struct rte_pci_driver *pci_drv, struct rte_pci_device *pci_dev)
497 {
498         struct ibv_device **list;
499         struct ibv_device *ibv_dev;
500         int err = 0;
501         struct ibv_context *attr_ctx = NULL;
502         struct ibv_device_attr_ex device_attr;
503         unsigned int sriov;
504         unsigned int mps;
505         unsigned int cqe_comp;
506         unsigned int tunnel_en = 0;
507         int idx;
508         int i;
509         struct mlx5dv_context attrs_out;
510 #ifdef HAVE_IBV_DEVICE_COUNTERS_SET_SUPPORT
511         struct ibv_counter_set_description cs_desc;
512 #endif
513
514         (void)pci_drv;
515         assert(pci_drv == &mlx5_driver);
516         /* Get mlx5_dev[] index. */
517         idx = mlx5_dev_idx(&pci_dev->addr);
518         if (idx == -1) {
519                 ERROR("this driver cannot support any more adapters");
520                 return -ENOMEM;
521         }
522         DEBUG("using driver device index %d", idx);
523
524         /* Save PCI address. */
525         mlx5_dev[idx].pci_addr = pci_dev->addr;
526         list = ibv_get_device_list(&i);
527         if (list == NULL) {
528                 assert(errno);
529                 if (errno == ENOSYS)
530                         ERROR("cannot list devices, is ib_uverbs loaded?");
531                 return -errno;
532         }
533         assert(i >= 0);
534         /*
535          * For each listed device, check related sysfs entry against
536          * the provided PCI ID.
537          */
538         while (i != 0) {
539                 struct rte_pci_addr pci_addr;
540
541                 --i;
542                 DEBUG("checking device \"%s\"", list[i]->name);
543                 if (mlx5_ibv_device_to_pci_addr(list[i], &pci_addr))
544                         continue;
545                 if ((pci_dev->addr.domain != pci_addr.domain) ||
546                     (pci_dev->addr.bus != pci_addr.bus) ||
547                     (pci_dev->addr.devid != pci_addr.devid) ||
548                     (pci_dev->addr.function != pci_addr.function))
549                         continue;
550                 sriov = ((pci_dev->id.device_id ==
551                        PCI_DEVICE_ID_MELLANOX_CONNECTX4VF) ||
552                       (pci_dev->id.device_id ==
553                        PCI_DEVICE_ID_MELLANOX_CONNECTX4LXVF) ||
554                       (pci_dev->id.device_id ==
555                        PCI_DEVICE_ID_MELLANOX_CONNECTX5VF) ||
556                       (pci_dev->id.device_id ==
557                        PCI_DEVICE_ID_MELLANOX_CONNECTX5EXVF));
558                 switch (pci_dev->id.device_id) {
559                 case PCI_DEVICE_ID_MELLANOX_CONNECTX4:
560                         tunnel_en = 1;
561                         break;
562                 case PCI_DEVICE_ID_MELLANOX_CONNECTX4LX:
563                 case PCI_DEVICE_ID_MELLANOX_CONNECTX5:
564                 case PCI_DEVICE_ID_MELLANOX_CONNECTX5VF:
565                 case PCI_DEVICE_ID_MELLANOX_CONNECTX5EX:
566                 case PCI_DEVICE_ID_MELLANOX_CONNECTX5EXVF:
567                         tunnel_en = 1;
568                         break;
569                 default:
570                         break;
571                 }
572                 INFO("PCI information matches, using device \"%s\""
573                      " (SR-IOV: %s)",
574                      list[i]->name,
575                      sriov ? "true" : "false");
576                 attr_ctx = ibv_open_device(list[i]);
577                 err = errno;
578                 break;
579         }
580         if (attr_ctx == NULL) {
581                 ibv_free_device_list(list);
582                 switch (err) {
583                 case 0:
584                         ERROR("cannot access device, is mlx5_ib loaded?");
585                         return -ENODEV;
586                 case EINVAL:
587                         ERROR("cannot use device, are drivers up to date?");
588                         return -EINVAL;
589                 }
590                 assert(err > 0);
591                 return -err;
592         }
593         ibv_dev = list[i];
594
595         DEBUG("device opened");
596         /*
597          * Multi-packet send is supported by ConnectX-4 Lx PF as well
598          * as all ConnectX-5 devices.
599          */
600         mlx5dv_query_device(attr_ctx, &attrs_out);
601         if (attrs_out.flags & MLX5DV_CONTEXT_FLAGS_MPW_ALLOWED) {
602                 if (attrs_out.flags & MLX5DV_CONTEXT_FLAGS_ENHANCED_MPW) {
603                         DEBUG("Enhanced MPW is supported");
604                         mps = MLX5_MPW_ENHANCED;
605                 } else {
606                         DEBUG("MPW is supported");
607                         mps = MLX5_MPW;
608                 }
609         } else {
610                 DEBUG("MPW isn't supported");
611                 mps = MLX5_MPW_DISABLED;
612         }
613         if (RTE_CACHE_LINE_SIZE == 128 &&
614             !(attrs_out.flags & MLX5DV_CONTEXT_FLAGS_CQE_128B_COMP))
615                 cqe_comp = 0;
616         else
617                 cqe_comp = 1;
618         if (ibv_query_device_ex(attr_ctx, NULL, &device_attr))
619                 goto error;
620         INFO("%u port(s) detected", device_attr.orig_attr.phys_port_cnt);
621
622         for (i = 0; i < device_attr.orig_attr.phys_port_cnt; i++) {
623                 uint32_t port = i + 1; /* ports are indexed from one */
624                 uint32_t test = (1 << i);
625                 struct ibv_context *ctx = NULL;
626                 struct ibv_port_attr port_attr;
627                 struct ibv_pd *pd = NULL;
628                 struct priv *priv = NULL;
629                 struct rte_eth_dev *eth_dev;
630                 struct ibv_device_attr_ex device_attr_ex;
631                 struct ether_addr mac;
632                 uint16_t num_vfs = 0;
633                 struct ibv_device_attr_ex device_attr;
634                 struct mlx5_dev_config config = {
635                         .cqe_comp = cqe_comp,
636                         .mps = mps,
637                         .tunnel_en = tunnel_en,
638                         .tx_vec_en = 1,
639                         .rx_vec_en = 1,
640                         .mpw_hdr_dseg = 0,
641                         .txq_inline = MLX5_ARG_UNSET,
642                         .txqs_inline = MLX5_ARG_UNSET,
643                         .inline_max_packet_sz = MLX5_ARG_UNSET,
644                 };
645
646                 mlx5_dev[idx].ports |= test;
647
648                 if (rte_eal_process_type() == RTE_PROC_SECONDARY) {
649                         /* from rte_ethdev.c */
650                         char name[RTE_ETH_NAME_MAX_LEN];
651
652                         snprintf(name, sizeof(name), "%s port %u",
653                                  ibv_get_device_name(ibv_dev), port);
654                         eth_dev = rte_eth_dev_attach_secondary(name);
655                         if (eth_dev == NULL) {
656                                 ERROR("can not attach rte ethdev");
657                                 err = ENOMEM;
658                                 goto error;
659                         }
660                         eth_dev->device = &pci_dev->device;
661                         eth_dev->dev_ops = &mlx5_dev_sec_ops;
662                         priv = eth_dev->data->dev_private;
663                         /* Receive command fd from primary process */
664                         err = priv_socket_connect(priv);
665                         if (err < 0) {
666                                 err = -err;
667                                 goto error;
668                         }
669                         /* Remap UAR for Tx queues. */
670                         err = priv_tx_uar_remap(priv, err);
671                         if (err < 0) {
672                                 err = -err;
673                                 goto error;
674                         }
675                         /*
676                          * Ethdev pointer is still required as input since
677                          * the primary device is not accessible from the
678                          * secondary process.
679                          */
680                         eth_dev->rx_pkt_burst =
681                                 priv_select_rx_function(priv, eth_dev);
682                         eth_dev->tx_pkt_burst =
683                                 priv_select_tx_function(priv, eth_dev);
684                         continue;
685                 }
686
687                 DEBUG("using port %u (%08" PRIx32 ")", port, test);
688
689                 ctx = ibv_open_device(ibv_dev);
690                 if (ctx == NULL) {
691                         err = ENODEV;
692                         goto port_error;
693                 }
694
695                 ibv_query_device_ex(ctx, NULL, &device_attr);
696                 /* Check port status. */
697                 err = ibv_query_port(ctx, port, &port_attr);
698                 if (err) {
699                         ERROR("port query failed: %s", strerror(err));
700                         goto port_error;
701                 }
702
703                 if (port_attr.link_layer != IBV_LINK_LAYER_ETHERNET) {
704                         ERROR("port %d is not configured in Ethernet mode",
705                               port);
706                         err = EINVAL;
707                         goto port_error;
708                 }
709
710                 if (port_attr.state != IBV_PORT_ACTIVE)
711                         DEBUG("port %d is not active: \"%s\" (%d)",
712                               port, ibv_port_state_str(port_attr.state),
713                               port_attr.state);
714
715                 /* Allocate protection domain. */
716                 pd = ibv_alloc_pd(ctx);
717                 if (pd == NULL) {
718                         ERROR("PD allocation failure");
719                         err = ENOMEM;
720                         goto port_error;
721                 }
722
723                 mlx5_dev[idx].ports |= test;
724
725                 /* from rte_ethdev.c */
726                 priv = rte_zmalloc("ethdev private structure",
727                                    sizeof(*priv),
728                                    RTE_CACHE_LINE_SIZE);
729                 if (priv == NULL) {
730                         ERROR("priv allocation failure");
731                         err = ENOMEM;
732                         goto port_error;
733                 }
734
735                 priv->ctx = ctx;
736                 strncpy(priv->ibdev_path, priv->ctx->device->ibdev_path,
737                         sizeof(priv->ibdev_path));
738                 priv->device_attr = device_attr;
739                 priv->port = port;
740                 priv->pd = pd;
741                 priv->mtu = ETHER_MTU;
742                 err = mlx5_args(&config, pci_dev->device.devargs);
743                 if (err) {
744                         ERROR("failed to process device arguments: %s",
745                               strerror(err));
746                         goto port_error;
747                 }
748                 if (ibv_query_device_ex(ctx, NULL, &device_attr_ex)) {
749                         ERROR("ibv_query_device_ex() failed");
750                         goto port_error;
751                 }
752
753                 config.hw_csum = !!(device_attr_ex.device_cap_flags_ex &
754                                     IBV_DEVICE_RAW_IP_CSUM);
755                 DEBUG("checksum offloading is %ssupported",
756                       (config.hw_csum ? "" : "not "));
757
758 #ifdef HAVE_IBV_DEVICE_VXLAN_SUPPORT
759                 config.hw_csum_l2tun =
760                                 !!(exp_device_attr.exp_device_cap_flags &
761                                    IBV_DEVICE_VXLAN_SUPPORT);
762 #endif
763                 DEBUG("Rx L2 tunnel checksum offloads are %ssupported",
764                       (config.hw_csum_l2tun ? "" : "not "));
765
766 #ifdef HAVE_IBV_DEVICE_COUNTERS_SET_SUPPORT
767                 config.flow_counter_en = !!(device_attr.max_counter_sets);
768                 ibv_describe_counter_set(ctx, 0, &cs_desc);
769                 DEBUG("counter type = %d, num of cs = %ld, attributes = %d",
770                       cs_desc.counter_type, cs_desc.num_of_cs,
771                       cs_desc.attributes);
772 #endif
773                 config.ind_table_max_size =
774                         device_attr_ex.rss_caps.max_rwq_indirection_table_size;
775                 /* Remove this check once DPDK supports larger/variable
776                  * indirection tables. */
777                 if (config.ind_table_max_size >
778                                 (unsigned int)ETH_RSS_RETA_SIZE_512)
779                         config.ind_table_max_size = ETH_RSS_RETA_SIZE_512;
780                 DEBUG("maximum RX indirection table size is %u",
781                       config.ind_table_max_size);
782                 config.hw_vlan_strip = !!(device_attr_ex.raw_packet_caps &
783                                          IBV_RAW_PACKET_CAP_CVLAN_STRIPPING);
784                 DEBUG("VLAN stripping is %ssupported",
785                       (config.hw_vlan_strip ? "" : "not "));
786
787                 config.hw_fcs_strip =
788                                 !!(device_attr_ex.orig_attr.device_cap_flags &
789                                 IBV_WQ_FLAGS_SCATTER_FCS);
790                 DEBUG("FCS stripping configuration is %ssupported",
791                       (config.hw_fcs_strip ? "" : "not "));
792
793 #ifdef HAVE_IBV_WQ_FLAG_RX_END_PADDING
794                 config.hw_padding = !!device_attr_ex.rx_pad_end_addr_align;
795 #endif
796                 DEBUG("hardware RX end alignment padding is %ssupported",
797                       (config.hw_padding ? "" : "not "));
798
799                 priv_get_num_vfs(priv, &num_vfs);
800                 config.sriov = (num_vfs || sriov);
801                 config.tso = ((device_attr_ex.tso_caps.max_tso > 0) &&
802                               (device_attr_ex.tso_caps.supported_qpts &
803                               (1 << IBV_QPT_RAW_PACKET)));
804                 if (config.tso)
805                         config.tso_max_payload_sz =
806                                         device_attr_ex.tso_caps.max_tso;
807                 if (config.mps && !mps) {
808                         ERROR("multi-packet send not supported on this device"
809                               " (" MLX5_TXQ_MPW_EN ")");
810                         err = ENOTSUP;
811                         goto port_error;
812                 }
813                 INFO("%sMPS is %s",
814                      config.mps == MLX5_MPW_ENHANCED ? "Enhanced " : "",
815                      config.mps != MLX5_MPW_DISABLED ? "enabled" : "disabled");
816                 if (config.cqe_comp && !cqe_comp) {
817                         WARN("Rx CQE compression isn't supported");
818                         config.cqe_comp = 0;
819                 }
820                 /* Configure the first MAC address by default. */
821                 if (priv_get_mac(priv, &mac.addr_bytes)) {
822                         ERROR("cannot get MAC address, is mlx5_en loaded?"
823                               " (errno: %s)", strerror(errno));
824                         err = ENODEV;
825                         goto port_error;
826                 }
827                 INFO("port %u MAC address is %02x:%02x:%02x:%02x:%02x:%02x",
828                      priv->port,
829                      mac.addr_bytes[0], mac.addr_bytes[1],
830                      mac.addr_bytes[2], mac.addr_bytes[3],
831                      mac.addr_bytes[4], mac.addr_bytes[5]);
832 #ifndef NDEBUG
833                 {
834                         char ifname[IF_NAMESIZE];
835
836                         if (priv_get_ifname(priv, &ifname) == 0)
837                                 DEBUG("port %u ifname is \"%s\"",
838                                       priv->port, ifname);
839                         else
840                                 DEBUG("port %u ifname is unknown", priv->port);
841                 }
842 #endif
843                 /* Get actual MTU if possible. */
844                 priv_get_mtu(priv, &priv->mtu);
845                 DEBUG("port %u MTU is %u", priv->port, priv->mtu);
846
847                 /* from rte_ethdev.c */
848                 {
849                         char name[RTE_ETH_NAME_MAX_LEN];
850
851                         snprintf(name, sizeof(name), "%s port %u",
852                                  ibv_get_device_name(ibv_dev), port);
853                         eth_dev = rte_eth_dev_allocate(name);
854                 }
855                 if (eth_dev == NULL) {
856                         ERROR("can not allocate rte ethdev");
857                         err = ENOMEM;
858                         goto port_error;
859                 }
860                 eth_dev->data->dev_private = priv;
861                 eth_dev->data->mac_addrs = priv->mac;
862                 eth_dev->device = &pci_dev->device;
863                 rte_eth_copy_pci_info(eth_dev, pci_dev);
864                 eth_dev->device->driver = &mlx5_driver.driver;
865                 priv->dev = eth_dev;
866                 eth_dev->dev_ops = &mlx5_dev_ops;
867                 /* Register MAC address. */
868                 claim_zero(mlx5_mac_addr_add(eth_dev, &mac, 0, 0));
869                 TAILQ_INIT(&priv->flows);
870                 TAILQ_INIT(&priv->ctrl_flows);
871
872                 /* Hint libmlx5 to use PMD allocator for data plane resources */
873                 struct mlx5dv_ctx_allocators alctr = {
874                         .alloc = &mlx5_alloc_verbs_buf,
875                         .free = &mlx5_free_verbs_buf,
876                         .data = priv,
877                 };
878                 mlx5dv_set_context_attr(ctx, MLX5DV_CTX_ATTR_BUF_ALLOCATORS,
879                                         (void *)((uintptr_t)&alctr));
880
881                 /* Bring Ethernet device up. */
882                 DEBUG("forcing Ethernet interface up");
883                 priv_set_flags(priv, ~IFF_UP, IFF_UP);
884                 /* Store device configuration on private structure. */
885                 priv->config = config;
886                 continue;
887
888 port_error:
889                 if (priv)
890                         rte_free(priv);
891                 if (pd)
892                         claim_zero(ibv_dealloc_pd(pd));
893                 if (ctx)
894                         claim_zero(ibv_close_device(ctx));
895                 break;
896         }
897
898         /*
899          * XXX if something went wrong in the loop above, there is a resource
900          * leak (ctx, pd, priv, dpdk ethdev) but we can do nothing about it as
901          * long as the dpdk does not provide a way to deallocate a ethdev and a
902          * way to enumerate the registered ethdevs to free the previous ones.
903          */
904
905         /* no port found, complain */
906         if (!mlx5_dev[idx].ports) {
907                 err = ENODEV;
908                 goto error;
909         }
910
911 error:
912         if (attr_ctx)
913                 claim_zero(ibv_close_device(attr_ctx));
914         if (list)
915                 ibv_free_device_list(list);
916         assert(err >= 0);
917         return -err;
918 }
919
920 static const struct rte_pci_id mlx5_pci_id_map[] = {
921         {
922                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
923                                PCI_DEVICE_ID_MELLANOX_CONNECTX4)
924         },
925         {
926                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
927                                PCI_DEVICE_ID_MELLANOX_CONNECTX4VF)
928         },
929         {
930                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
931                                PCI_DEVICE_ID_MELLANOX_CONNECTX4LX)
932         },
933         {
934                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
935                                PCI_DEVICE_ID_MELLANOX_CONNECTX4LXVF)
936         },
937         {
938                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
939                                PCI_DEVICE_ID_MELLANOX_CONNECTX5)
940         },
941         {
942                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
943                                PCI_DEVICE_ID_MELLANOX_CONNECTX5VF)
944         },
945         {
946                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
947                                PCI_DEVICE_ID_MELLANOX_CONNECTX5EX)
948         },
949         {
950                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
951                                PCI_DEVICE_ID_MELLANOX_CONNECTX5EXVF)
952         },
953         {
954                 .vendor_id = 0
955         }
956 };
957
958 static struct rte_pci_driver mlx5_driver = {
959         .driver = {
960                 .name = MLX5_DRIVER_NAME
961         },
962         .id_table = mlx5_pci_id_map,
963         .probe = mlx5_pci_probe,
964         .drv_flags = RTE_PCI_DRV_INTR_LSC | RTE_PCI_DRV_INTR_RMV,
965 };
966
967 /**
968  * Driver initialization routine.
969  */
970 RTE_INIT(rte_mlx5_pmd_init);
971 static void
972 rte_mlx5_pmd_init(void)
973 {
974         /* Build the static table for ptype conversion. */
975         mlx5_set_ptype_table();
976         /*
977          * RDMAV_HUGEPAGES_SAFE tells ibv_fork_init() we intend to use
978          * huge pages. Calling ibv_fork_init() during init allows
979          * applications to use fork() safely for purposes other than
980          * using this PMD, which is not supported in forked processes.
981          */
982         setenv("RDMAV_HUGEPAGES_SAFE", "1", 1);
983         /* Match the size of Rx completion entry to the size of a cacheline. */
984         if (RTE_CACHE_LINE_SIZE == 128)
985                 setenv("MLX5_CQE_SIZE", "128", 0);
986         ibv_fork_init();
987         rte_pci_register(&mlx5_driver);
988 }
989
990 RTE_PMD_EXPORT_NAME(net_mlx5, __COUNTER__);
991 RTE_PMD_REGISTER_PCI_TABLE(net_mlx5, mlx5_pci_id_map);
992 RTE_PMD_REGISTER_KMOD_DEP(net_mlx5, "* ib_uverbs & mlx5_core & mlx5_ib");