net/mlx5: add parameter for port representors
[dpdk.git] / drivers / net / mlx5 / mlx5.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright 2015 6WIND S.A.
3  * Copyright 2015 Mellanox Technologies, Ltd
4  */
5
6 #include <stddef.h>
7 #include <unistd.h>
8 #include <string.h>
9 #include <assert.h>
10 #include <dlfcn.h>
11 #include <stdint.h>
12 #include <stdlib.h>
13 #include <errno.h>
14 #include <net/if.h>
15 #include <sys/mman.h>
16 #include <linux/netlink.h>
17 #include <linux/rtnetlink.h>
18
19 /* Verbs header. */
20 /* ISO C doesn't support unnamed structs/unions, disabling -pedantic. */
21 #ifdef PEDANTIC
22 #pragma GCC diagnostic ignored "-Wpedantic"
23 #endif
24 #include <infiniband/verbs.h>
25 #ifdef PEDANTIC
26 #pragma GCC diagnostic error "-Wpedantic"
27 #endif
28
29 #include <rte_malloc.h>
30 #include <rte_ethdev_driver.h>
31 #include <rte_ethdev_pci.h>
32 #include <rte_pci.h>
33 #include <rte_bus_pci.h>
34 #include <rte_common.h>
35 #include <rte_config.h>
36 #include <rte_eal_memconfig.h>
37 #include <rte_kvargs.h>
38 #include <rte_rwlock.h>
39 #include <rte_spinlock.h>
40 #include <rte_string_fns.h>
41
42 #include "mlx5.h"
43 #include "mlx5_utils.h"
44 #include "mlx5_rxtx.h"
45 #include "mlx5_autoconf.h"
46 #include "mlx5_defs.h"
47 #include "mlx5_glue.h"
48 #include "mlx5_mr.h"
49
50 /* Device parameter to enable RX completion queue compression. */
51 #define MLX5_RXQ_CQE_COMP_EN "rxq_cqe_comp_en"
52
53 /* Device parameter to enable Multi-Packet Rx queue. */
54 #define MLX5_RX_MPRQ_EN "mprq_en"
55
56 /* Device parameter to configure log 2 of the number of strides for MPRQ. */
57 #define MLX5_RX_MPRQ_LOG_STRIDE_NUM "mprq_log_stride_num"
58
59 /* Device parameter to limit the size of memcpy'd packet for MPRQ. */
60 #define MLX5_RX_MPRQ_MAX_MEMCPY_LEN "mprq_max_memcpy_len"
61
62 /* Device parameter to set the minimum number of Rx queues to enable MPRQ. */
63 #define MLX5_RXQS_MIN_MPRQ "rxqs_min_mprq"
64
65 /* Device parameter to configure inline send. */
66 #define MLX5_TXQ_INLINE "txq_inline"
67
68 /*
69  * Device parameter to configure the number of TX queues threshold for
70  * enabling inline send.
71  */
72 #define MLX5_TXQS_MIN_INLINE "txqs_min_inline"
73
74 /* Device parameter to enable multi-packet send WQEs. */
75 #define MLX5_TXQ_MPW_EN "txq_mpw_en"
76
77 /* Device parameter to include 2 dsegs in the title WQEBB. */
78 #define MLX5_TXQ_MPW_HDR_DSEG_EN "txq_mpw_hdr_dseg_en"
79
80 /* Device parameter to limit the size of inlining packet. */
81 #define MLX5_TXQ_MAX_INLINE_LEN "txq_max_inline_len"
82
83 /* Device parameter to enable hardware Tx vector. */
84 #define MLX5_TX_VEC_EN "tx_vec_en"
85
86 /* Device parameter to enable hardware Rx vector. */
87 #define MLX5_RX_VEC_EN "rx_vec_en"
88
89 /* Allow L3 VXLAN flow creation. */
90 #define MLX5_L3_VXLAN_EN "l3_vxlan_en"
91
92 /* Activate Netlink support in VF mode. */
93 #define MLX5_VF_NL_EN "vf_nl_en"
94
95 /* Select port representors to instantiate. */
96 #define MLX5_REPRESENTOR "representor"
97
98 #ifndef HAVE_IBV_MLX5_MOD_MPW
99 #define MLX5DV_CONTEXT_FLAGS_MPW_ALLOWED (1 << 2)
100 #define MLX5DV_CONTEXT_FLAGS_ENHANCED_MPW (1 << 3)
101 #endif
102
103 #ifndef HAVE_IBV_MLX5_MOD_CQE_128B_COMP
104 #define MLX5DV_CONTEXT_FLAGS_CQE_128B_COMP (1 << 4)
105 #endif
106
107 static const char *MZ_MLX5_PMD_SHARED_DATA = "mlx5_pmd_shared_data";
108
109 /* Shared memory between primary and secondary processes. */
110 struct mlx5_shared_data *mlx5_shared_data;
111
112 /* Spinlock for mlx5_shared_data allocation. */
113 static rte_spinlock_t mlx5_shared_data_lock = RTE_SPINLOCK_INITIALIZER;
114
115 /** Driver-specific log messages type. */
116 int mlx5_logtype;
117
118 /**
119  * Prepare shared data between primary and secondary process.
120  */
121 static void
122 mlx5_prepare_shared_data(void)
123 {
124         const struct rte_memzone *mz;
125
126         rte_spinlock_lock(&mlx5_shared_data_lock);
127         if (mlx5_shared_data == NULL) {
128                 if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
129                         /* Allocate shared memory. */
130                         mz = rte_memzone_reserve(MZ_MLX5_PMD_SHARED_DATA,
131                                                  sizeof(*mlx5_shared_data),
132                                                  SOCKET_ID_ANY, 0);
133                 } else {
134                         /* Lookup allocated shared memory. */
135                         mz = rte_memzone_lookup(MZ_MLX5_PMD_SHARED_DATA);
136                 }
137                 if (mz == NULL)
138                         rte_panic("Cannot allocate mlx5 shared data\n");
139                 mlx5_shared_data = mz->addr;
140                 /* Initialize shared data. */
141                 if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
142                         LIST_INIT(&mlx5_shared_data->mem_event_cb_list);
143                         rte_rwlock_init(&mlx5_shared_data->mem_event_rwlock);
144                 }
145                 rte_mem_event_callback_register("MLX5_MEM_EVENT_CB",
146                                                 mlx5_mr_mem_event_cb, NULL);
147         }
148         rte_spinlock_unlock(&mlx5_shared_data_lock);
149 }
150
151 /**
152  * Retrieve integer value from environment variable.
153  *
154  * @param[in] name
155  *   Environment variable name.
156  *
157  * @return
158  *   Integer value, 0 if the variable is not set.
159  */
160 int
161 mlx5_getenv_int(const char *name)
162 {
163         const char *val = getenv(name);
164
165         if (val == NULL)
166                 return 0;
167         return atoi(val);
168 }
169
170 /**
171  * Verbs callback to allocate a memory. This function should allocate the space
172  * according to the size provided residing inside a huge page.
173  * Please note that all allocation must respect the alignment from libmlx5
174  * (i.e. currently sysconf(_SC_PAGESIZE)).
175  *
176  * @param[in] size
177  *   The size in bytes of the memory to allocate.
178  * @param[in] data
179  *   A pointer to the callback data.
180  *
181  * @return
182  *   Allocated buffer, NULL otherwise and rte_errno is set.
183  */
184 static void *
185 mlx5_alloc_verbs_buf(size_t size, void *data)
186 {
187         struct priv *priv = data;
188         void *ret;
189         size_t alignment = sysconf(_SC_PAGESIZE);
190         unsigned int socket = SOCKET_ID_ANY;
191
192         if (priv->verbs_alloc_ctx.type == MLX5_VERBS_ALLOC_TYPE_TX_QUEUE) {
193                 const struct mlx5_txq_ctrl *ctrl = priv->verbs_alloc_ctx.obj;
194
195                 socket = ctrl->socket;
196         } else if (priv->verbs_alloc_ctx.type ==
197                    MLX5_VERBS_ALLOC_TYPE_RX_QUEUE) {
198                 const struct mlx5_rxq_ctrl *ctrl = priv->verbs_alloc_ctx.obj;
199
200                 socket = ctrl->socket;
201         }
202         assert(data != NULL);
203         ret = rte_malloc_socket(__func__, size, alignment, socket);
204         if (!ret && size)
205                 rte_errno = ENOMEM;
206         return ret;
207 }
208
209 /**
210  * Verbs callback to free a memory.
211  *
212  * @param[in] ptr
213  *   A pointer to the memory to free.
214  * @param[in] data
215  *   A pointer to the callback data.
216  */
217 static void
218 mlx5_free_verbs_buf(void *ptr, void *data __rte_unused)
219 {
220         assert(data != NULL);
221         rte_free(ptr);
222 }
223
224 /**
225  * DPDK callback to close the device.
226  *
227  * Destroy all queues and objects, free memory.
228  *
229  * @param dev
230  *   Pointer to Ethernet device structure.
231  */
232 static void
233 mlx5_dev_close(struct rte_eth_dev *dev)
234 {
235         struct priv *priv = dev->data->dev_private;
236         unsigned int i;
237         int ret;
238
239         DRV_LOG(DEBUG, "port %u closing device \"%s\"",
240                 dev->data->port_id,
241                 ((priv->ctx != NULL) ? priv->ctx->device->name : ""));
242         /* In case mlx5_dev_stop() has not been called. */
243         mlx5_dev_interrupt_handler_uninstall(dev);
244         mlx5_traffic_disable(dev);
245         /* Prevent crashes when queues are still in use. */
246         dev->rx_pkt_burst = removed_rx_burst;
247         dev->tx_pkt_burst = removed_tx_burst;
248         if (priv->rxqs != NULL) {
249                 /* XXX race condition if mlx5_rx_burst() is still running. */
250                 usleep(1000);
251                 for (i = 0; (i != priv->rxqs_n); ++i)
252                         mlx5_rxq_release(dev, i);
253                 priv->rxqs_n = 0;
254                 priv->rxqs = NULL;
255         }
256         if (priv->txqs != NULL) {
257                 /* XXX race condition if mlx5_tx_burst() is still running. */
258                 usleep(1000);
259                 for (i = 0; (i != priv->txqs_n); ++i)
260                         mlx5_txq_release(dev, i);
261                 priv->txqs_n = 0;
262                 priv->txqs = NULL;
263         }
264         mlx5_flow_delete_drop_queue(dev);
265         mlx5_mprq_free_mp(dev);
266         mlx5_mr_release(dev);
267         if (priv->pd != NULL) {
268                 assert(priv->ctx != NULL);
269                 claim_zero(mlx5_glue->dealloc_pd(priv->pd));
270                 claim_zero(mlx5_glue->close_device(priv->ctx));
271         } else
272                 assert(priv->ctx == NULL);
273         if (priv->rss_conf.rss_key != NULL)
274                 rte_free(priv->rss_conf.rss_key);
275         if (priv->reta_idx != NULL)
276                 rte_free(priv->reta_idx);
277         if (priv->primary_socket)
278                 mlx5_socket_uninit(dev);
279         if (priv->config.vf)
280                 mlx5_nl_mac_addr_flush(dev);
281         if (priv->nl_socket_route >= 0)
282                 close(priv->nl_socket_route);
283         if (priv->nl_socket_rdma >= 0)
284                 close(priv->nl_socket_rdma);
285         ret = mlx5_hrxq_ibv_verify(dev);
286         if (ret)
287                 DRV_LOG(WARNING, "port %u some hash Rx queue still remain",
288                         dev->data->port_id);
289         ret = mlx5_ind_table_ibv_verify(dev);
290         if (ret)
291                 DRV_LOG(WARNING, "port %u some indirection table still remain",
292                         dev->data->port_id);
293         ret = mlx5_rxq_ibv_verify(dev);
294         if (ret)
295                 DRV_LOG(WARNING, "port %u some Verbs Rx queue still remain",
296                         dev->data->port_id);
297         ret = mlx5_rxq_verify(dev);
298         if (ret)
299                 DRV_LOG(WARNING, "port %u some Rx queues still remain",
300                         dev->data->port_id);
301         ret = mlx5_txq_ibv_verify(dev);
302         if (ret)
303                 DRV_LOG(WARNING, "port %u some Verbs Tx queue still remain",
304                         dev->data->port_id);
305         ret = mlx5_txq_verify(dev);
306         if (ret)
307                 DRV_LOG(WARNING, "port %u some Tx queues still remain",
308                         dev->data->port_id);
309         ret = mlx5_flow_verify(dev);
310         if (ret)
311                 DRV_LOG(WARNING, "port %u some flows still remain",
312                         dev->data->port_id);
313         if (priv->domain_id != RTE_ETH_DEV_SWITCH_DOMAIN_ID_INVALID) {
314                 unsigned int c = 0;
315                 unsigned int i = mlx5_dev_to_port_id(dev->device, NULL, 0);
316                 uint16_t port_id[i];
317
318                 i = RTE_MIN(mlx5_dev_to_port_id(dev->device, port_id, i), i);
319                 while (i--) {
320                         struct priv *opriv =
321                                 rte_eth_devices[port_id[i]].data->dev_private;
322
323                         if (!opriv ||
324                             opriv->domain_id != priv->domain_id ||
325                             &rte_eth_devices[port_id[i]] == dev)
326                                 continue;
327                         ++c;
328                 }
329                 if (!c)
330                         claim_zero(rte_eth_switch_domain_free(priv->domain_id));
331         }
332         memset(priv, 0, sizeof(*priv));
333         priv->domain_id = RTE_ETH_DEV_SWITCH_DOMAIN_ID_INVALID;
334 }
335
336 const struct eth_dev_ops mlx5_dev_ops = {
337         .dev_configure = mlx5_dev_configure,
338         .dev_start = mlx5_dev_start,
339         .dev_stop = mlx5_dev_stop,
340         .dev_set_link_down = mlx5_set_link_down,
341         .dev_set_link_up = mlx5_set_link_up,
342         .dev_close = mlx5_dev_close,
343         .promiscuous_enable = mlx5_promiscuous_enable,
344         .promiscuous_disable = mlx5_promiscuous_disable,
345         .allmulticast_enable = mlx5_allmulticast_enable,
346         .allmulticast_disable = mlx5_allmulticast_disable,
347         .link_update = mlx5_link_update,
348         .stats_get = mlx5_stats_get,
349         .stats_reset = mlx5_stats_reset,
350         .xstats_get = mlx5_xstats_get,
351         .xstats_reset = mlx5_xstats_reset,
352         .xstats_get_names = mlx5_xstats_get_names,
353         .dev_infos_get = mlx5_dev_infos_get,
354         .dev_supported_ptypes_get = mlx5_dev_supported_ptypes_get,
355         .vlan_filter_set = mlx5_vlan_filter_set,
356         .rx_queue_setup = mlx5_rx_queue_setup,
357         .tx_queue_setup = mlx5_tx_queue_setup,
358         .rx_queue_release = mlx5_rx_queue_release,
359         .tx_queue_release = mlx5_tx_queue_release,
360         .flow_ctrl_get = mlx5_dev_get_flow_ctrl,
361         .flow_ctrl_set = mlx5_dev_set_flow_ctrl,
362         .mac_addr_remove = mlx5_mac_addr_remove,
363         .mac_addr_add = mlx5_mac_addr_add,
364         .mac_addr_set = mlx5_mac_addr_set,
365         .set_mc_addr_list = mlx5_set_mc_addr_list,
366         .mtu_set = mlx5_dev_set_mtu,
367         .vlan_strip_queue_set = mlx5_vlan_strip_queue_set,
368         .vlan_offload_set = mlx5_vlan_offload_set,
369         .reta_update = mlx5_dev_rss_reta_update,
370         .reta_query = mlx5_dev_rss_reta_query,
371         .rss_hash_update = mlx5_rss_hash_update,
372         .rss_hash_conf_get = mlx5_rss_hash_conf_get,
373         .filter_ctrl = mlx5_dev_filter_ctrl,
374         .rx_descriptor_status = mlx5_rx_descriptor_status,
375         .tx_descriptor_status = mlx5_tx_descriptor_status,
376         .rx_queue_intr_enable = mlx5_rx_intr_enable,
377         .rx_queue_intr_disable = mlx5_rx_intr_disable,
378         .is_removed = mlx5_is_removed,
379 };
380
381 static const struct eth_dev_ops mlx5_dev_sec_ops = {
382         .stats_get = mlx5_stats_get,
383         .stats_reset = mlx5_stats_reset,
384         .xstats_get = mlx5_xstats_get,
385         .xstats_reset = mlx5_xstats_reset,
386         .xstats_get_names = mlx5_xstats_get_names,
387         .dev_infos_get = mlx5_dev_infos_get,
388         .rx_descriptor_status = mlx5_rx_descriptor_status,
389         .tx_descriptor_status = mlx5_tx_descriptor_status,
390 };
391
392 /* Available operators in flow isolated mode. */
393 const struct eth_dev_ops mlx5_dev_ops_isolate = {
394         .dev_configure = mlx5_dev_configure,
395         .dev_start = mlx5_dev_start,
396         .dev_stop = mlx5_dev_stop,
397         .dev_set_link_down = mlx5_set_link_down,
398         .dev_set_link_up = mlx5_set_link_up,
399         .dev_close = mlx5_dev_close,
400         .link_update = mlx5_link_update,
401         .stats_get = mlx5_stats_get,
402         .stats_reset = mlx5_stats_reset,
403         .xstats_get = mlx5_xstats_get,
404         .xstats_reset = mlx5_xstats_reset,
405         .xstats_get_names = mlx5_xstats_get_names,
406         .dev_infos_get = mlx5_dev_infos_get,
407         .dev_supported_ptypes_get = mlx5_dev_supported_ptypes_get,
408         .vlan_filter_set = mlx5_vlan_filter_set,
409         .rx_queue_setup = mlx5_rx_queue_setup,
410         .tx_queue_setup = mlx5_tx_queue_setup,
411         .rx_queue_release = mlx5_rx_queue_release,
412         .tx_queue_release = mlx5_tx_queue_release,
413         .flow_ctrl_get = mlx5_dev_get_flow_ctrl,
414         .flow_ctrl_set = mlx5_dev_set_flow_ctrl,
415         .mac_addr_remove = mlx5_mac_addr_remove,
416         .mac_addr_add = mlx5_mac_addr_add,
417         .mac_addr_set = mlx5_mac_addr_set,
418         .set_mc_addr_list = mlx5_set_mc_addr_list,
419         .mtu_set = mlx5_dev_set_mtu,
420         .vlan_strip_queue_set = mlx5_vlan_strip_queue_set,
421         .vlan_offload_set = mlx5_vlan_offload_set,
422         .filter_ctrl = mlx5_dev_filter_ctrl,
423         .rx_descriptor_status = mlx5_rx_descriptor_status,
424         .tx_descriptor_status = mlx5_tx_descriptor_status,
425         .rx_queue_intr_enable = mlx5_rx_intr_enable,
426         .rx_queue_intr_disable = mlx5_rx_intr_disable,
427         .is_removed = mlx5_is_removed,
428 };
429
430 /**
431  * Verify and store value for device argument.
432  *
433  * @param[in] key
434  *   Key argument to verify.
435  * @param[in] val
436  *   Value associated with key.
437  * @param opaque
438  *   User data.
439  *
440  * @return
441  *   0 on success, a negative errno value otherwise and rte_errno is set.
442  */
443 static int
444 mlx5_args_check(const char *key, const char *val, void *opaque)
445 {
446         struct mlx5_dev_config *config = opaque;
447         unsigned long tmp;
448
449         /* No-op, port representors are processed in mlx5_dev_spawn(). */
450         if (!strcmp(MLX5_REPRESENTOR, key))
451                 return 0;
452         errno = 0;
453         tmp = strtoul(val, NULL, 0);
454         if (errno) {
455                 rte_errno = errno;
456                 DRV_LOG(WARNING, "%s: \"%s\" is not a valid integer", key, val);
457                 return -rte_errno;
458         }
459         if (strcmp(MLX5_RXQ_CQE_COMP_EN, key) == 0) {
460                 config->cqe_comp = !!tmp;
461         } else if (strcmp(MLX5_RX_MPRQ_EN, key) == 0) {
462                 config->mprq.enabled = !!tmp;
463         } else if (strcmp(MLX5_RX_MPRQ_LOG_STRIDE_NUM, key) == 0) {
464                 config->mprq.stride_num_n = tmp;
465         } else if (strcmp(MLX5_RX_MPRQ_MAX_MEMCPY_LEN, key) == 0) {
466                 config->mprq.max_memcpy_len = tmp;
467         } else if (strcmp(MLX5_RXQS_MIN_MPRQ, key) == 0) {
468                 config->mprq.min_rxqs_num = tmp;
469         } else if (strcmp(MLX5_TXQ_INLINE, key) == 0) {
470                 config->txq_inline = tmp;
471         } else if (strcmp(MLX5_TXQS_MIN_INLINE, key) == 0) {
472                 config->txqs_inline = tmp;
473         } else if (strcmp(MLX5_TXQ_MPW_EN, key) == 0) {
474                 config->mps = !!tmp ? config->mps : 0;
475         } else if (strcmp(MLX5_TXQ_MPW_HDR_DSEG_EN, key) == 0) {
476                 config->mpw_hdr_dseg = !!tmp;
477         } else if (strcmp(MLX5_TXQ_MAX_INLINE_LEN, key) == 0) {
478                 config->inline_max_packet_sz = tmp;
479         } else if (strcmp(MLX5_TX_VEC_EN, key) == 0) {
480                 config->tx_vec_en = !!tmp;
481         } else if (strcmp(MLX5_RX_VEC_EN, key) == 0) {
482                 config->rx_vec_en = !!tmp;
483         } else if (strcmp(MLX5_L3_VXLAN_EN, key) == 0) {
484                 config->l3_vxlan_en = !!tmp;
485         } else if (strcmp(MLX5_VF_NL_EN, key) == 0) {
486                 config->vf_nl_en = !!tmp;
487         } else {
488                 DRV_LOG(WARNING, "%s: unknown parameter", key);
489                 rte_errno = EINVAL;
490                 return -rte_errno;
491         }
492         return 0;
493 }
494
495 /**
496  * Parse device parameters.
497  *
498  * @param config
499  *   Pointer to device configuration structure.
500  * @param devargs
501  *   Device arguments structure.
502  *
503  * @return
504  *   0 on success, a negative errno value otherwise and rte_errno is set.
505  */
506 static int
507 mlx5_args(struct mlx5_dev_config *config, struct rte_devargs *devargs)
508 {
509         const char **params = (const char *[]){
510                 MLX5_RXQ_CQE_COMP_EN,
511                 MLX5_RX_MPRQ_EN,
512                 MLX5_RX_MPRQ_LOG_STRIDE_NUM,
513                 MLX5_RX_MPRQ_MAX_MEMCPY_LEN,
514                 MLX5_RXQS_MIN_MPRQ,
515                 MLX5_TXQ_INLINE,
516                 MLX5_TXQS_MIN_INLINE,
517                 MLX5_TXQ_MPW_EN,
518                 MLX5_TXQ_MPW_HDR_DSEG_EN,
519                 MLX5_TXQ_MAX_INLINE_LEN,
520                 MLX5_TX_VEC_EN,
521                 MLX5_RX_VEC_EN,
522                 MLX5_L3_VXLAN_EN,
523                 MLX5_VF_NL_EN,
524                 MLX5_REPRESENTOR,
525                 NULL,
526         };
527         struct rte_kvargs *kvlist;
528         int ret = 0;
529         int i;
530
531         if (devargs == NULL)
532                 return 0;
533         /* Following UGLY cast is done to pass checkpatch. */
534         kvlist = rte_kvargs_parse(devargs->args, params);
535         if (kvlist == NULL)
536                 return 0;
537         /* Process parameters. */
538         for (i = 0; (params[i] != NULL); ++i) {
539                 if (rte_kvargs_count(kvlist, params[i])) {
540                         ret = rte_kvargs_process(kvlist, params[i],
541                                                  mlx5_args_check, config);
542                         if (ret) {
543                                 rte_errno = EINVAL;
544                                 rte_kvargs_free(kvlist);
545                                 return -rte_errno;
546                         }
547                 }
548         }
549         rte_kvargs_free(kvlist);
550         return 0;
551 }
552
553 static struct rte_pci_driver mlx5_driver;
554
555 /*
556  * Reserved UAR address space for TXQ UAR(hw doorbell) mapping, process
557  * local resource used by both primary and secondary to avoid duplicate
558  * reservation.
559  * The space has to be available on both primary and secondary process,
560  * TXQ UAR maps to this area using fixed mmap w/o double check.
561  */
562 static void *uar_base;
563
564 static int
565 find_lower_va_bound(const struct rte_memseg_list *msl __rte_unused,
566                 const struct rte_memseg *ms, void *arg)
567 {
568         void **addr = arg;
569
570         if (*addr == NULL)
571                 *addr = ms->addr;
572         else
573                 *addr = RTE_MIN(*addr, ms->addr);
574
575         return 0;
576 }
577
578 /**
579  * Reserve UAR address space for primary process.
580  *
581  * @param[in] dev
582  *   Pointer to Ethernet device.
583  *
584  * @return
585  *   0 on success, a negative errno value otherwise and rte_errno is set.
586  */
587 static int
588 mlx5_uar_init_primary(struct rte_eth_dev *dev)
589 {
590         struct priv *priv = dev->data->dev_private;
591         void *addr = (void *)0;
592
593         if (uar_base) { /* UAR address space mapped. */
594                 priv->uar_base = uar_base;
595                 return 0;
596         }
597         /* find out lower bound of hugepage segments */
598         rte_memseg_walk(find_lower_va_bound, &addr);
599
600         /* keep distance to hugepages to minimize potential conflicts. */
601         addr = RTE_PTR_SUB(addr, MLX5_UAR_OFFSET + MLX5_UAR_SIZE);
602         /* anonymous mmap, no real memory consumption. */
603         addr = mmap(addr, MLX5_UAR_SIZE,
604                     PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
605         if (addr == MAP_FAILED) {
606                 DRV_LOG(ERR,
607                         "port %u failed to reserve UAR address space, please"
608                         " adjust MLX5_UAR_SIZE or try --base-virtaddr",
609                         dev->data->port_id);
610                 rte_errno = ENOMEM;
611                 return -rte_errno;
612         }
613         /* Accept either same addr or a new addr returned from mmap if target
614          * range occupied.
615          */
616         DRV_LOG(INFO, "port %u reserved UAR address space: %p",
617                 dev->data->port_id, addr);
618         priv->uar_base = addr; /* for primary and secondary UAR re-mmap. */
619         uar_base = addr; /* process local, don't reserve again. */
620         return 0;
621 }
622
623 /**
624  * Reserve UAR address space for secondary process, align with
625  * primary process.
626  *
627  * @param[in] dev
628  *   Pointer to Ethernet device.
629  *
630  * @return
631  *   0 on success, a negative errno value otherwise and rte_errno is set.
632  */
633 static int
634 mlx5_uar_init_secondary(struct rte_eth_dev *dev)
635 {
636         struct priv *priv = dev->data->dev_private;
637         void *addr;
638
639         assert(priv->uar_base);
640         if (uar_base) { /* already reserved. */
641                 assert(uar_base == priv->uar_base);
642                 return 0;
643         }
644         /* anonymous mmap, no real memory consumption. */
645         addr = mmap(priv->uar_base, MLX5_UAR_SIZE,
646                     PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
647         if (addr == MAP_FAILED) {
648                 DRV_LOG(ERR, "port %u UAR mmap failed: %p size: %llu",
649                         dev->data->port_id, priv->uar_base, MLX5_UAR_SIZE);
650                 rte_errno = ENXIO;
651                 return -rte_errno;
652         }
653         if (priv->uar_base != addr) {
654                 DRV_LOG(ERR,
655                         "port %u UAR address %p size %llu occupied, please"
656                         " adjust MLX5_UAR_OFFSET or try EAL parameter"
657                         " --base-virtaddr",
658                         dev->data->port_id, priv->uar_base, MLX5_UAR_SIZE);
659                 rte_errno = ENXIO;
660                 return -rte_errno;
661         }
662         uar_base = addr; /* process local, don't reserve again */
663         DRV_LOG(INFO, "port %u reserved UAR address space: %p",
664                 dev->data->port_id, addr);
665         return 0;
666 }
667
668 /**
669  * Spawn an Ethernet device from Verbs information.
670  *
671  * @param dpdk_dev
672  *   Backing DPDK device.
673  * @param ibv_dev
674  *   Verbs device.
675  * @param vf
676  *   If nonzero, enable VF-specific features.
677  * @param[in] switch_info
678  *   Switch properties of Ethernet device.
679  *
680  * @return
681  *   A valid Ethernet device object on success, NULL otherwise and rte_errno
682  *   is set. The following error is defined:
683  *
684  *   EBUSY: device is not supposed to be spawned.
685  */
686 static struct rte_eth_dev *
687 mlx5_dev_spawn(struct rte_device *dpdk_dev,
688                struct ibv_device *ibv_dev,
689                int vf,
690                const struct mlx5_switch_info *switch_info)
691 {
692         struct ibv_context *ctx;
693         struct ibv_device_attr_ex attr;
694         struct ibv_port_attr port_attr;
695         struct ibv_pd *pd = NULL;
696         struct mlx5dv_context dv_attr = { .comp_mask = 0 };
697         struct mlx5_dev_config config = {
698                 .vf = !!vf,
699                 .tx_vec_en = 1,
700                 .rx_vec_en = 1,
701                 .mpw_hdr_dseg = 0,
702                 .txq_inline = MLX5_ARG_UNSET,
703                 .txqs_inline = MLX5_ARG_UNSET,
704                 .inline_max_packet_sz = MLX5_ARG_UNSET,
705                 .vf_nl_en = 1,
706                 .mprq = {
707                         .enabled = 0,
708                         .stride_num_n = MLX5_MPRQ_STRIDE_NUM_N,
709                         .max_memcpy_len = MLX5_MPRQ_MEMCPY_DEFAULT_LEN,
710                         .min_rxqs_num = MLX5_MPRQ_MIN_RXQS,
711                 },
712         };
713         struct rte_eth_dev *eth_dev = NULL;
714         struct priv *priv = NULL;
715         int err = 0;
716         unsigned int mps;
717         unsigned int cqe_comp;
718         unsigned int tunnel_en = 0;
719         unsigned int mpls_en = 0;
720         unsigned int swp = 0;
721         unsigned int verb_priorities = 0;
722         unsigned int mprq = 0;
723         unsigned int mprq_min_stride_size_n = 0;
724         unsigned int mprq_max_stride_size_n = 0;
725         unsigned int mprq_min_stride_num_n = 0;
726         unsigned int mprq_max_stride_num_n = 0;
727 #ifdef HAVE_IBV_DEVICE_COUNTERS_SET_SUPPORT
728         struct ibv_counter_set_description cs_desc = { .counter_type = 0 };
729 #endif
730         struct ether_addr mac;
731         char name[RTE_ETH_NAME_MAX_LEN];
732         int own_domain_id = 0;
733         unsigned int i;
734
735         /* Determine if this port representor is supposed to be spawned. */
736         if (switch_info->representor && dpdk_dev->devargs) {
737                 struct rte_eth_devargs eth_da;
738
739                 err = rte_eth_devargs_parse(dpdk_dev->devargs->args, &eth_da);
740                 if (err) {
741                         rte_errno = -err;
742                         DRV_LOG(ERR, "failed to process device arguments: %s",
743                                 strerror(rte_errno));
744                         return NULL;
745                 }
746                 for (i = 0; i < eth_da.nb_representor_ports; ++i)
747                         if (eth_da.representor_ports[i] ==
748                             (uint16_t)switch_info->port_name)
749                                 break;
750                 if (i == eth_da.nb_representor_ports) {
751                         rte_errno = EBUSY;
752                         return NULL;
753                 }
754         }
755         /* Prepare shared data between primary and secondary process. */
756         mlx5_prepare_shared_data();
757         errno = 0;
758         ctx = mlx5_glue->open_device(ibv_dev);
759         if (!ctx) {
760                 rte_errno = errno ? errno : ENODEV;
761                 return NULL;
762         }
763 #ifdef HAVE_IBV_MLX5_MOD_SWP
764         dv_attr.comp_mask |= MLX5DV_CONTEXT_MASK_SWP;
765 #endif
766         /*
767          * Multi-packet send is supported by ConnectX-4 Lx PF as well
768          * as all ConnectX-5 devices.
769          */
770 #ifdef HAVE_IBV_DEVICE_TUNNEL_SUPPORT
771         dv_attr.comp_mask |= MLX5DV_CONTEXT_MASK_TUNNEL_OFFLOADS;
772 #endif
773 #ifdef HAVE_IBV_DEVICE_STRIDING_RQ_SUPPORT
774         dv_attr.comp_mask |= MLX5DV_CONTEXT_MASK_STRIDING_RQ;
775 #endif
776         mlx5_glue->dv_query_device(ctx, &dv_attr);
777         if (dv_attr.flags & MLX5DV_CONTEXT_FLAGS_MPW_ALLOWED) {
778                 if (dv_attr.flags & MLX5DV_CONTEXT_FLAGS_ENHANCED_MPW) {
779                         DRV_LOG(DEBUG, "enhanced MPW is supported");
780                         mps = MLX5_MPW_ENHANCED;
781                 } else {
782                         DRV_LOG(DEBUG, "MPW is supported");
783                         mps = MLX5_MPW;
784                 }
785         } else {
786                 DRV_LOG(DEBUG, "MPW isn't supported");
787                 mps = MLX5_MPW_DISABLED;
788         }
789         config.mps = mps;
790 #ifdef HAVE_IBV_MLX5_MOD_SWP
791         if (dv_attr.comp_mask & MLX5DV_CONTEXT_MASK_SWP)
792                 swp = dv_attr.sw_parsing_caps.sw_parsing_offloads;
793         DRV_LOG(DEBUG, "SWP support: %u", swp);
794 #endif
795         config.swp = !!swp;
796 #ifdef HAVE_IBV_DEVICE_STRIDING_RQ_SUPPORT
797         if (dv_attr.comp_mask & MLX5DV_CONTEXT_MASK_STRIDING_RQ) {
798                 struct mlx5dv_striding_rq_caps mprq_caps =
799                         dv_attr.striding_rq_caps;
800
801                 DRV_LOG(DEBUG, "\tmin_single_stride_log_num_of_bytes: %d",
802                         mprq_caps.min_single_stride_log_num_of_bytes);
803                 DRV_LOG(DEBUG, "\tmax_single_stride_log_num_of_bytes: %d",
804                         mprq_caps.max_single_stride_log_num_of_bytes);
805                 DRV_LOG(DEBUG, "\tmin_single_wqe_log_num_of_strides: %d",
806                         mprq_caps.min_single_wqe_log_num_of_strides);
807                 DRV_LOG(DEBUG, "\tmax_single_wqe_log_num_of_strides: %d",
808                         mprq_caps.max_single_wqe_log_num_of_strides);
809                 DRV_LOG(DEBUG, "\tsupported_qpts: %d",
810                         mprq_caps.supported_qpts);
811                 DRV_LOG(DEBUG, "device supports Multi-Packet RQ");
812                 mprq = 1;
813                 mprq_min_stride_size_n =
814                         mprq_caps.min_single_stride_log_num_of_bytes;
815                 mprq_max_stride_size_n =
816                         mprq_caps.max_single_stride_log_num_of_bytes;
817                 mprq_min_stride_num_n =
818                         mprq_caps.min_single_wqe_log_num_of_strides;
819                 mprq_max_stride_num_n =
820                         mprq_caps.max_single_wqe_log_num_of_strides;
821                 config.mprq.stride_num_n = RTE_MAX(MLX5_MPRQ_STRIDE_NUM_N,
822                                                    mprq_min_stride_num_n);
823         }
824 #endif
825         if (RTE_CACHE_LINE_SIZE == 128 &&
826             !(dv_attr.flags & MLX5DV_CONTEXT_FLAGS_CQE_128B_COMP))
827                 cqe_comp = 0;
828         else
829                 cqe_comp = 1;
830         config.cqe_comp = cqe_comp;
831 #ifdef HAVE_IBV_DEVICE_TUNNEL_SUPPORT
832         if (dv_attr.comp_mask & MLX5DV_CONTEXT_MASK_TUNNEL_OFFLOADS) {
833                 tunnel_en = ((dv_attr.tunnel_offloads_caps &
834                               MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_VXLAN) &&
835                              (dv_attr.tunnel_offloads_caps &
836                               MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_GRE));
837         }
838         DRV_LOG(DEBUG, "tunnel offloading is %ssupported",
839                 tunnel_en ? "" : "not ");
840 #else
841         DRV_LOG(WARNING,
842                 "tunnel offloading disabled due to old OFED/rdma-core version");
843 #endif
844         config.tunnel_en = tunnel_en;
845 #ifdef HAVE_IBV_DEVICE_MPLS_SUPPORT
846         mpls_en = ((dv_attr.tunnel_offloads_caps &
847                     MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_CW_MPLS_OVER_GRE) &&
848                    (dv_attr.tunnel_offloads_caps &
849                     MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_CW_MPLS_OVER_UDP));
850         DRV_LOG(DEBUG, "MPLS over GRE/UDP tunnel offloading is %ssupported",
851                 mpls_en ? "" : "not ");
852 #else
853         DRV_LOG(WARNING, "MPLS over GRE/UDP tunnel offloading disabled due to"
854                 " old OFED/rdma-core version or firmware configuration");
855 #endif
856         config.mpls_en = mpls_en;
857         err = mlx5_glue->query_device_ex(ctx, NULL, &attr);
858         if (err) {
859                 DEBUG("ibv_query_device_ex() failed");
860                 goto error;
861         }
862         if (!switch_info->representor)
863                 rte_strlcpy(name, dpdk_dev->name, sizeof(name));
864         else
865                 snprintf(name, sizeof(name), "%s_representor_%u",
866                          dpdk_dev->name, switch_info->port_name);
867         DRV_LOG(DEBUG, "naming Ethernet device \"%s\"", name);
868         if (rte_eal_process_type() == RTE_PROC_SECONDARY) {
869                 eth_dev = rte_eth_dev_attach_secondary(name);
870                 if (eth_dev == NULL) {
871                         DRV_LOG(ERR, "can not attach rte ethdev");
872                         rte_errno = ENOMEM;
873                         err = rte_errno;
874                         goto error;
875                 }
876                 eth_dev->device = dpdk_dev;
877                 eth_dev->dev_ops = &mlx5_dev_sec_ops;
878                 err = mlx5_uar_init_secondary(eth_dev);
879                 if (err) {
880                         err = rte_errno;
881                         goto error;
882                 }
883                 /* Receive command fd from primary process */
884                 err = mlx5_socket_connect(eth_dev);
885                 if (err < 0) {
886                         err = rte_errno;
887                         goto error;
888                 }
889                 /* Remap UAR for Tx queues. */
890                 err = mlx5_tx_uar_remap(eth_dev, err);
891                 if (err) {
892                         err = rte_errno;
893                         goto error;
894                 }
895                 /*
896                  * Ethdev pointer is still required as input since
897                  * the primary device is not accessible from the
898                  * secondary process.
899                  */
900                 eth_dev->rx_pkt_burst = mlx5_select_rx_function(eth_dev);
901                 eth_dev->tx_pkt_burst = mlx5_select_tx_function(eth_dev);
902                 claim_zero(mlx5_glue->close_device(ctx));
903                 return eth_dev;
904         }
905         /* Check port status. */
906         err = mlx5_glue->query_port(ctx, 1, &port_attr);
907         if (err) {
908                 DRV_LOG(ERR, "port query failed: %s", strerror(err));
909                 goto error;
910         }
911         if (port_attr.link_layer != IBV_LINK_LAYER_ETHERNET) {
912                 DRV_LOG(ERR, "port is not configured in Ethernet mode");
913                 err = EINVAL;
914                 goto error;
915         }
916         if (port_attr.state != IBV_PORT_ACTIVE)
917                 DRV_LOG(DEBUG, "port is not active: \"%s\" (%d)",
918                         mlx5_glue->port_state_str(port_attr.state),
919                         port_attr.state);
920         /* Allocate protection domain. */
921         pd = mlx5_glue->alloc_pd(ctx);
922         if (pd == NULL) {
923                 DRV_LOG(ERR, "PD allocation failure");
924                 err = ENOMEM;
925                 goto error;
926         }
927         priv = rte_zmalloc("ethdev private structure",
928                            sizeof(*priv),
929                            RTE_CACHE_LINE_SIZE);
930         if (priv == NULL) {
931                 DRV_LOG(ERR, "priv allocation failure");
932                 err = ENOMEM;
933                 goto error;
934         }
935         priv->ctx = ctx;
936         strncpy(priv->ibdev_name, priv->ctx->device->name,
937                 sizeof(priv->ibdev_name));
938         strncpy(priv->ibdev_path, priv->ctx->device->ibdev_path,
939                 sizeof(priv->ibdev_path));
940         priv->device_attr = attr;
941         priv->pd = pd;
942         priv->mtu = ETHER_MTU;
943         /* Some internal functions rely on Netlink sockets, open them now. */
944         priv->nl_socket_rdma = mlx5_nl_init(0, NETLINK_RDMA);
945         priv->nl_socket_route = mlx5_nl_init(RTMGRP_LINK, NETLINK_ROUTE);
946         priv->nl_sn = 0;
947         priv->representor = !!switch_info->representor;
948         priv->domain_id = RTE_ETH_DEV_SWITCH_DOMAIN_ID_INVALID;
949         priv->representor_id =
950                 switch_info->representor ? switch_info->port_name : -1;
951         /*
952          * Look for sibling devices in order to reuse their switch domain
953          * if any, otherwise allocate one.
954          */
955         i = mlx5_dev_to_port_id(dpdk_dev, NULL, 0);
956         if (i > 0) {
957                 uint16_t port_id[i];
958
959                 i = RTE_MIN(mlx5_dev_to_port_id(dpdk_dev, port_id, i), i);
960                 while (i--) {
961                         const struct priv *opriv =
962                                 rte_eth_devices[port_id[i]].data->dev_private;
963
964                         if (!opriv ||
965                             opriv->domain_id ==
966                             RTE_ETH_DEV_SWITCH_DOMAIN_ID_INVALID)
967                                 continue;
968                         priv->domain_id = opriv->domain_id;
969                         break;
970                 }
971         }
972         if (priv->domain_id == RTE_ETH_DEV_SWITCH_DOMAIN_ID_INVALID) {
973                 err = rte_eth_switch_domain_alloc(&priv->domain_id);
974                 if (err) {
975                         err = rte_errno;
976                         DRV_LOG(ERR, "unable to allocate switch domain: %s",
977                                 strerror(rte_errno));
978                         goto error;
979                 }
980                 own_domain_id = 1;
981         }
982         err = mlx5_args(&config, dpdk_dev->devargs);
983         if (err) {
984                 err = rte_errno;
985                 DRV_LOG(ERR, "failed to process device arguments: %s",
986                         strerror(rte_errno));
987                 goto error;
988         }
989         config.hw_csum = !!(attr.device_cap_flags_ex & IBV_DEVICE_RAW_IP_CSUM);
990         DRV_LOG(DEBUG, "checksum offloading is %ssupported",
991                 (config.hw_csum ? "" : "not "));
992 #ifdef HAVE_IBV_DEVICE_COUNTERS_SET_SUPPORT
993         config.flow_counter_en = !!attr.max_counter_sets;
994         mlx5_glue->describe_counter_set(ctx, 0, &cs_desc);
995         DRV_LOG(DEBUG, "counter type = %d, num of cs = %ld, attributes = %d",
996                 cs_desc.counter_type, cs_desc.num_of_cs,
997                 cs_desc.attributes);
998 #endif
999         config.ind_table_max_size =
1000                 attr.rss_caps.max_rwq_indirection_table_size;
1001         /*
1002          * Remove this check once DPDK supports larger/variable
1003          * indirection tables.
1004          */
1005         if (config.ind_table_max_size > (unsigned int)ETH_RSS_RETA_SIZE_512)
1006                 config.ind_table_max_size = ETH_RSS_RETA_SIZE_512;
1007         DRV_LOG(DEBUG, "maximum Rx indirection table size is %u",
1008                 config.ind_table_max_size);
1009         config.hw_vlan_strip = !!(attr.raw_packet_caps &
1010                                   IBV_RAW_PACKET_CAP_CVLAN_STRIPPING);
1011         DRV_LOG(DEBUG, "VLAN stripping is %ssupported",
1012                 (config.hw_vlan_strip ? "" : "not "));
1013         config.hw_fcs_strip = !!(attr.raw_packet_caps &
1014                                  IBV_RAW_PACKET_CAP_SCATTER_FCS);
1015         DRV_LOG(DEBUG, "FCS stripping configuration is %ssupported",
1016                 (config.hw_fcs_strip ? "" : "not "));
1017 #ifdef HAVE_IBV_WQ_FLAG_RX_END_PADDING
1018         config.hw_padding = !!attr.rx_pad_end_addr_align;
1019 #endif
1020         DRV_LOG(DEBUG, "hardware Rx end alignment padding is %ssupported",
1021                 (config.hw_padding ? "" : "not "));
1022         config.tso = (attr.tso_caps.max_tso > 0 &&
1023                       (attr.tso_caps.supported_qpts &
1024                        (1 << IBV_QPT_RAW_PACKET)));
1025         if (config.tso)
1026                 config.tso_max_payload_sz = attr.tso_caps.max_tso;
1027         if (config.mps && !mps) {
1028                 DRV_LOG(ERR,
1029                         "multi-packet send not supported on this device"
1030                         " (" MLX5_TXQ_MPW_EN ")");
1031                 err = ENOTSUP;
1032                 goto error;
1033         }
1034         DRV_LOG(INFO, "%sMPS is %s",
1035                 config.mps == MLX5_MPW_ENHANCED ? "enhanced " : "",
1036                 config.mps != MLX5_MPW_DISABLED ? "enabled" : "disabled");
1037         if (config.cqe_comp && !cqe_comp) {
1038                 DRV_LOG(WARNING, "Rx CQE compression isn't supported");
1039                 config.cqe_comp = 0;
1040         }
1041         if (config.mprq.enabled && mprq) {
1042                 if (config.mprq.stride_num_n > mprq_max_stride_num_n ||
1043                     config.mprq.stride_num_n < mprq_min_stride_num_n) {
1044                         config.mprq.stride_num_n =
1045                                 RTE_MAX(MLX5_MPRQ_STRIDE_NUM_N,
1046                                         mprq_min_stride_num_n);
1047                         DRV_LOG(WARNING,
1048                                 "the number of strides"
1049                                 " for Multi-Packet RQ is out of range,"
1050                                 " setting default value (%u)",
1051                                 1 << config.mprq.stride_num_n);
1052                 }
1053                 config.mprq.min_stride_size_n = mprq_min_stride_size_n;
1054                 config.mprq.max_stride_size_n = mprq_max_stride_size_n;
1055         } else if (config.mprq.enabled && !mprq) {
1056                 DRV_LOG(WARNING, "Multi-Packet RQ isn't supported");
1057                 config.mprq.enabled = 0;
1058         }
1059         eth_dev = rte_eth_dev_allocate(name);
1060         if (eth_dev == NULL) {
1061                 DRV_LOG(ERR, "can not allocate rte ethdev");
1062                 err = ENOMEM;
1063                 goto error;
1064         }
1065         if (priv->representor)
1066                 eth_dev->data->dev_flags |= RTE_ETH_DEV_REPRESENTOR;
1067         eth_dev->data->dev_private = priv;
1068         priv->dev_data = eth_dev->data;
1069         eth_dev->data->mac_addrs = priv->mac;
1070         eth_dev->device = dpdk_dev;
1071         eth_dev->device->driver = &mlx5_driver.driver;
1072         err = mlx5_uar_init_primary(eth_dev);
1073         if (err) {
1074                 err = rte_errno;
1075                 goto error;
1076         }
1077         /* Configure the first MAC address by default. */
1078         if (mlx5_get_mac(eth_dev, &mac.addr_bytes)) {
1079                 DRV_LOG(ERR,
1080                         "port %u cannot get MAC address, is mlx5_en"
1081                         " loaded? (errno: %s)",
1082                         eth_dev->data->port_id, strerror(rte_errno));
1083                 err = ENODEV;
1084                 goto error;
1085         }
1086         DRV_LOG(INFO,
1087                 "port %u MAC address is %02x:%02x:%02x:%02x:%02x:%02x",
1088                 eth_dev->data->port_id,
1089                 mac.addr_bytes[0], mac.addr_bytes[1],
1090                 mac.addr_bytes[2], mac.addr_bytes[3],
1091                 mac.addr_bytes[4], mac.addr_bytes[5]);
1092 #ifndef NDEBUG
1093         {
1094                 char ifname[IF_NAMESIZE];
1095
1096                 if (mlx5_get_ifname(eth_dev, &ifname) == 0)
1097                         DRV_LOG(DEBUG, "port %u ifname is \"%s\"",
1098                                 eth_dev->data->port_id, ifname);
1099                 else
1100                         DRV_LOG(DEBUG, "port %u ifname is unknown",
1101                                 eth_dev->data->port_id);
1102         }
1103 #endif
1104         /* Get actual MTU if possible. */
1105         err = mlx5_get_mtu(eth_dev, &priv->mtu);
1106         if (err) {
1107                 err = rte_errno;
1108                 goto error;
1109         }
1110         DRV_LOG(DEBUG, "port %u MTU is %u", eth_dev->data->port_id,
1111                 priv->mtu);
1112         /* Initialize burst functions to prevent crashes before link-up. */
1113         eth_dev->rx_pkt_burst = removed_rx_burst;
1114         eth_dev->tx_pkt_burst = removed_tx_burst;
1115         eth_dev->dev_ops = &mlx5_dev_ops;
1116         /* Register MAC address. */
1117         claim_zero(mlx5_mac_addr_add(eth_dev, &mac, 0, 0));
1118         if (vf && config.vf_nl_en)
1119                 mlx5_nl_mac_addr_sync(eth_dev);
1120         TAILQ_INIT(&priv->flows);
1121         TAILQ_INIT(&priv->ctrl_flows);
1122         /* Hint libmlx5 to use PMD allocator for data plane resources */
1123         struct mlx5dv_ctx_allocators alctr = {
1124                 .alloc = &mlx5_alloc_verbs_buf,
1125                 .free = &mlx5_free_verbs_buf,
1126                 .data = priv,
1127         };
1128         mlx5_glue->dv_set_context_attr(ctx, MLX5DV_CTX_ATTR_BUF_ALLOCATORS,
1129                                        (void *)((uintptr_t)&alctr));
1130         /* Bring Ethernet device up. */
1131         DRV_LOG(DEBUG, "port %u forcing Ethernet interface up",
1132                 eth_dev->data->port_id);
1133         mlx5_set_link_up(eth_dev);
1134         /*
1135          * Even though the interrupt handler is not installed yet,
1136          * interrupts will still trigger on the asyn_fd from
1137          * Verbs context returned by ibv_open_device().
1138          */
1139         mlx5_link_update(eth_dev, 0);
1140         /* Store device configuration on private structure. */
1141         priv->config = config;
1142         /* Create drop queue. */
1143         err = mlx5_flow_create_drop_queue(eth_dev);
1144         if (err) {
1145                 DRV_LOG(ERR, "port %u drop queue allocation failed: %s",
1146                         eth_dev->data->port_id, strerror(rte_errno));
1147                 err = rte_errno;
1148                 goto error;
1149         }
1150         /* Supported Verbs flow priority number detection. */
1151         if (verb_priorities == 0)
1152                 verb_priorities = mlx5_get_max_verbs_prio(eth_dev);
1153         if (verb_priorities < MLX5_VERBS_FLOW_PRIO_8) {
1154                 DRV_LOG(ERR, "port %u wrong Verbs flow priorities: %u",
1155                         eth_dev->data->port_id, verb_priorities);
1156                 err = ENOTSUP;
1157                 goto error;
1158         }
1159         priv->config.max_verbs_prio = verb_priorities;
1160         /*
1161          * Once the device is added to the list of memory event
1162          * callback, its global MR cache table cannot be expanded
1163          * on the fly because of deadlock. If it overflows, lookup
1164          * should be done by searching MR list linearly, which is slow.
1165          */
1166         err = mlx5_mr_btree_init(&priv->mr.cache,
1167                                  MLX5_MR_BTREE_CACHE_N * 2,
1168                                  eth_dev->device->numa_node);
1169         if (err) {
1170                 err = rte_errno;
1171                 goto error;
1172         }
1173         /* Add device to memory callback list. */
1174         rte_rwlock_write_lock(&mlx5_shared_data->mem_event_rwlock);
1175         LIST_INSERT_HEAD(&mlx5_shared_data->mem_event_cb_list,
1176                          priv, mem_event_cb);
1177         rte_rwlock_write_unlock(&mlx5_shared_data->mem_event_rwlock);
1178         return eth_dev;
1179 error:
1180         if (priv) {
1181                 if (priv->nl_socket_route >= 0)
1182                         close(priv->nl_socket_route);
1183                 if (priv->nl_socket_rdma >= 0)
1184                         close(priv->nl_socket_rdma);
1185                 if (own_domain_id)
1186                         claim_zero(rte_eth_switch_domain_free(priv->domain_id));
1187                 rte_free(priv);
1188         }
1189         if (pd)
1190                 claim_zero(mlx5_glue->dealloc_pd(pd));
1191         if (eth_dev)
1192                 rte_eth_dev_release_port(eth_dev);
1193         if (ctx)
1194                 claim_zero(mlx5_glue->close_device(ctx));
1195         assert(err > 0);
1196         rte_errno = err;
1197         return NULL;
1198 }
1199
1200 /** Data associated with devices to spawn. */
1201 struct mlx5_dev_spawn_data {
1202         unsigned int ifindex; /**< Network interface index. */
1203         struct mlx5_switch_info info; /**< Switch information. */
1204         struct ibv_device *ibv_dev; /**< Associated IB device. */
1205         struct rte_eth_dev *eth_dev; /**< Associated Ethernet device. */
1206 };
1207
1208 /**
1209  * Comparison callback to sort device data.
1210  *
1211  * This is meant to be used with qsort().
1212  *
1213  * @param a[in]
1214  *   Pointer to pointer to first data object.
1215  * @param b[in]
1216  *   Pointer to pointer to second data object.
1217  *
1218  * @return
1219  *   0 if both objects are equal, less than 0 if the first argument is less
1220  *   than the second, greater than 0 otherwise.
1221  */
1222 static int
1223 mlx5_dev_spawn_data_cmp(const void *a, const void *b)
1224 {
1225         const struct mlx5_switch_info *si_a =
1226                 &((const struct mlx5_dev_spawn_data *)a)->info;
1227         const struct mlx5_switch_info *si_b =
1228                 &((const struct mlx5_dev_spawn_data *)b)->info;
1229         int ret;
1230
1231         /* Master device first. */
1232         ret = si_b->master - si_a->master;
1233         if (ret)
1234                 return ret;
1235         /* Then representor devices. */
1236         ret = si_b->representor - si_a->representor;
1237         if (ret)
1238                 return ret;
1239         /* Unidentified devices come last in no specific order. */
1240         if (!si_a->representor)
1241                 return 0;
1242         /* Order representors by name. */
1243         return si_a->port_name - si_b->port_name;
1244 }
1245
1246 /**
1247  * DPDK callback to register a PCI device.
1248  *
1249  * This function spawns Ethernet devices out of a given PCI device.
1250  *
1251  * @param[in] pci_drv
1252  *   PCI driver structure (mlx5_driver).
1253  * @param[in] pci_dev
1254  *   PCI device information.
1255  *
1256  * @return
1257  *   0 on success, a negative errno value otherwise and rte_errno is set.
1258  */
1259 static int
1260 mlx5_pci_probe(struct rte_pci_driver *pci_drv __rte_unused,
1261                struct rte_pci_device *pci_dev)
1262 {
1263         struct ibv_device **ibv_list;
1264         unsigned int n = 0;
1265         int vf;
1266         int ret;
1267
1268         assert(pci_drv == &mlx5_driver);
1269         errno = 0;
1270         ibv_list = mlx5_glue->get_device_list(&ret);
1271         if (!ibv_list) {
1272                 rte_errno = errno ? errno : ENOSYS;
1273                 DRV_LOG(ERR, "cannot list devices, is ib_uverbs loaded?");
1274                 return -rte_errno;
1275         }
1276
1277         struct ibv_device *ibv_match[ret + 1];
1278
1279         while (ret-- > 0) {
1280                 struct rte_pci_addr pci_addr;
1281
1282                 DRV_LOG(DEBUG, "checking device \"%s\"", ibv_list[ret]->name);
1283                 if (mlx5_ibv_device_to_pci_addr(ibv_list[ret], &pci_addr))
1284                         continue;
1285                 if (pci_dev->addr.domain != pci_addr.domain ||
1286                     pci_dev->addr.bus != pci_addr.bus ||
1287                     pci_dev->addr.devid != pci_addr.devid ||
1288                     pci_dev->addr.function != pci_addr.function)
1289                         continue;
1290                 DRV_LOG(INFO, "PCI information matches for device \"%s\"",
1291                         ibv_list[ret]->name);
1292                 ibv_match[n++] = ibv_list[ret];
1293         }
1294         ibv_match[n] = NULL;
1295
1296         struct mlx5_dev_spawn_data list[n];
1297         int nl_route = n ? mlx5_nl_init(0, NETLINK_ROUTE) : -1;
1298         int nl_rdma = n ? mlx5_nl_init(0, NETLINK_RDMA) : -1;
1299         unsigned int i;
1300         unsigned int u;
1301
1302         /*
1303          * The existence of several matching entries (n > 1) means port
1304          * representors have been instantiated. No existing Verbs call nor
1305          * /sys entries can tell them apart, this can only be done through
1306          * Netlink calls assuming kernel drivers are recent enough to
1307          * support them.
1308          *
1309          * In the event of identification failure through Netlink, either:
1310          *
1311          * 1. No device matches (n == 0), complain and bail out.
1312          * 2. A single IB device matches (n == 1) and is not a representor,
1313          *    assume no switch support.
1314          * 3. Otherwise no safe assumptions can be made; complain louder and
1315          *    bail out.
1316          */
1317         for (i = 0; i != n; ++i) {
1318                 list[i].ibv_dev = ibv_match[i];
1319                 list[i].eth_dev = NULL;
1320                 if (nl_rdma < 0)
1321                         list[i].ifindex = 0;
1322                 else
1323                         list[i].ifindex = mlx5_nl_ifindex
1324                                 (nl_rdma, list[i].ibv_dev->name);
1325                 if (nl_route < 0 ||
1326                     !list[i].ifindex ||
1327                     mlx5_nl_switch_info(nl_route, list[i].ifindex,
1328                                         &list[i].info)) {
1329                         list[i].ifindex = 0;
1330                         memset(&list[i].info, 0, sizeof(list[i].info));
1331                         continue;
1332                 }
1333         }
1334         if (nl_rdma >= 0)
1335                 close(nl_rdma);
1336         if (nl_route >= 0)
1337                 close(nl_route);
1338         /* Count unidentified devices. */
1339         for (u = 0, i = 0; i != n; ++i)
1340                 if (!list[i].info.master && !list[i].info.representor)
1341                         ++u;
1342         if (u) {
1343                 if (n == 1 && u == 1) {
1344                         /* Case #2. */
1345                         DRV_LOG(INFO, "no switch support detected");
1346                 } else {
1347                         /* Case #3. */
1348                         DRV_LOG(ERR,
1349                                 "unable to tell which of the matching devices"
1350                                 " is the master (lack of kernel support?)");
1351                         n = 0;
1352                 }
1353         }
1354         /*
1355          * Sort list to probe devices in natural order for users convenience
1356          * (i.e. master first, then representors from lowest to highest ID).
1357          */
1358         if (n)
1359                 qsort(list, n, sizeof(*list), mlx5_dev_spawn_data_cmp);
1360         switch (pci_dev->id.device_id) {
1361         case PCI_DEVICE_ID_MELLANOX_CONNECTX4VF:
1362         case PCI_DEVICE_ID_MELLANOX_CONNECTX4LXVF:
1363         case PCI_DEVICE_ID_MELLANOX_CONNECTX5VF:
1364         case PCI_DEVICE_ID_MELLANOX_CONNECTX5EXVF:
1365                 vf = 1;
1366                 break;
1367         default:
1368                 vf = 0;
1369         }
1370         for (i = 0; i != n; ++i) {
1371                 uint32_t restore;
1372
1373                 list[i].eth_dev = mlx5_dev_spawn
1374                         (&pci_dev->device, list[i].ibv_dev, vf, &list[i].info);
1375                 if (!list[i].eth_dev) {
1376                         if (rte_errno != EBUSY)
1377                                 break;
1378                         /* Device is disabled, ignore it. */
1379                         continue;
1380                 }
1381                 restore = list[i].eth_dev->data->dev_flags;
1382                 rte_eth_copy_pci_info(list[i].eth_dev, pci_dev);
1383                 /* Restore non-PCI flags cleared by the above call. */
1384                 list[i].eth_dev->data->dev_flags |= restore;
1385                 rte_eth_dev_probing_finish(list[i].eth_dev);
1386         }
1387         mlx5_glue->free_device_list(ibv_list);
1388         if (!n) {
1389                 DRV_LOG(WARNING,
1390                         "no Verbs device matches PCI device " PCI_PRI_FMT ","
1391                         " are kernel drivers loaded?",
1392                         pci_dev->addr.domain, pci_dev->addr.bus,
1393                         pci_dev->addr.devid, pci_dev->addr.function);
1394                 rte_errno = ENOENT;
1395                 ret = -rte_errno;
1396         } else if (i != n) {
1397                 DRV_LOG(ERR,
1398                         "probe of PCI device " PCI_PRI_FMT " aborted after"
1399                         " encountering an error: %s",
1400                         pci_dev->addr.domain, pci_dev->addr.bus,
1401                         pci_dev->addr.devid, pci_dev->addr.function,
1402                         strerror(rte_errno));
1403                 ret = -rte_errno;
1404                 /* Roll back. */
1405                 while (i--) {
1406                         if (!list[i].eth_dev)
1407                                 continue;
1408                         mlx5_dev_close(list[i].eth_dev);
1409                         if (rte_eal_process_type() == RTE_PROC_PRIMARY)
1410                                 rte_free(list[i].eth_dev->data->dev_private);
1411                         claim_zero(rte_eth_dev_release_port(list[i].eth_dev));
1412                 }
1413                 /* Restore original error. */
1414                 rte_errno = -ret;
1415         } else {
1416                 ret = 0;
1417         }
1418         return ret;
1419 }
1420
1421 static const struct rte_pci_id mlx5_pci_id_map[] = {
1422         {
1423                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
1424                                PCI_DEVICE_ID_MELLANOX_CONNECTX4)
1425         },
1426         {
1427                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
1428                                PCI_DEVICE_ID_MELLANOX_CONNECTX4VF)
1429         },
1430         {
1431                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
1432                                PCI_DEVICE_ID_MELLANOX_CONNECTX4LX)
1433         },
1434         {
1435                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
1436                                PCI_DEVICE_ID_MELLANOX_CONNECTX4LXVF)
1437         },
1438         {
1439                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
1440                                PCI_DEVICE_ID_MELLANOX_CONNECTX5)
1441         },
1442         {
1443                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
1444                                PCI_DEVICE_ID_MELLANOX_CONNECTX5VF)
1445         },
1446         {
1447                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
1448                                PCI_DEVICE_ID_MELLANOX_CONNECTX5EX)
1449         },
1450         {
1451                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
1452                                PCI_DEVICE_ID_MELLANOX_CONNECTX5EXVF)
1453         },
1454         {
1455                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
1456                                PCI_DEVICE_ID_MELLANOX_CONNECTX5BF)
1457         },
1458         {
1459                 .vendor_id = 0
1460         }
1461 };
1462
1463 static struct rte_pci_driver mlx5_driver = {
1464         .driver = {
1465                 .name = MLX5_DRIVER_NAME
1466         },
1467         .id_table = mlx5_pci_id_map,
1468         .probe = mlx5_pci_probe,
1469         .drv_flags = RTE_PCI_DRV_INTR_LSC | RTE_PCI_DRV_INTR_RMV,
1470 };
1471
1472 #ifdef RTE_LIBRTE_MLX5_DLOPEN_DEPS
1473
1474 /**
1475  * Suffix RTE_EAL_PMD_PATH with "-glue".
1476  *
1477  * This function performs a sanity check on RTE_EAL_PMD_PATH before
1478  * suffixing its last component.
1479  *
1480  * @param buf[out]
1481  *   Output buffer, should be large enough otherwise NULL is returned.
1482  * @param size
1483  *   Size of @p out.
1484  *
1485  * @return
1486  *   Pointer to @p buf or @p NULL in case suffix cannot be appended.
1487  */
1488 static char *
1489 mlx5_glue_path(char *buf, size_t size)
1490 {
1491         static const char *const bad[] = { "/", ".", "..", NULL };
1492         const char *path = RTE_EAL_PMD_PATH;
1493         size_t len = strlen(path);
1494         size_t off;
1495         int i;
1496
1497         while (len && path[len - 1] == '/')
1498                 --len;
1499         for (off = len; off && path[off - 1] != '/'; --off)
1500                 ;
1501         for (i = 0; bad[i]; ++i)
1502                 if (!strncmp(path + off, bad[i], (int)(len - off)))
1503                         goto error;
1504         i = snprintf(buf, size, "%.*s-glue", (int)len, path);
1505         if (i == -1 || (size_t)i >= size)
1506                 goto error;
1507         return buf;
1508 error:
1509         DRV_LOG(ERR,
1510                 "unable to append \"-glue\" to last component of"
1511                 " RTE_EAL_PMD_PATH (\"" RTE_EAL_PMD_PATH "\"),"
1512                 " please re-configure DPDK");
1513         return NULL;
1514 }
1515
1516 /**
1517  * Initialization routine for run-time dependency on rdma-core.
1518  */
1519 static int
1520 mlx5_glue_init(void)
1521 {
1522         char glue_path[sizeof(RTE_EAL_PMD_PATH) - 1 + sizeof("-glue")];
1523         const char *path[] = {
1524                 /*
1525                  * A basic security check is necessary before trusting
1526                  * MLX5_GLUE_PATH, which may override RTE_EAL_PMD_PATH.
1527                  */
1528                 (geteuid() == getuid() && getegid() == getgid() ?
1529                  getenv("MLX5_GLUE_PATH") : NULL),
1530                 /*
1531                  * When RTE_EAL_PMD_PATH is set, use its glue-suffixed
1532                  * variant, otherwise let dlopen() look up libraries on its
1533                  * own.
1534                  */
1535                 (*RTE_EAL_PMD_PATH ?
1536                  mlx5_glue_path(glue_path, sizeof(glue_path)) : ""),
1537         };
1538         unsigned int i = 0;
1539         void *handle = NULL;
1540         void **sym;
1541         const char *dlmsg;
1542
1543         while (!handle && i != RTE_DIM(path)) {
1544                 const char *end;
1545                 size_t len;
1546                 int ret;
1547
1548                 if (!path[i]) {
1549                         ++i;
1550                         continue;
1551                 }
1552                 end = strpbrk(path[i], ":;");
1553                 if (!end)
1554                         end = path[i] + strlen(path[i]);
1555                 len = end - path[i];
1556                 ret = 0;
1557                 do {
1558                         char name[ret + 1];
1559
1560                         ret = snprintf(name, sizeof(name), "%.*s%s" MLX5_GLUE,
1561                                        (int)len, path[i],
1562                                        (!len || *(end - 1) == '/') ? "" : "/");
1563                         if (ret == -1)
1564                                 break;
1565                         if (sizeof(name) != (size_t)ret + 1)
1566                                 continue;
1567                         DRV_LOG(DEBUG, "looking for rdma-core glue as \"%s\"",
1568                                 name);
1569                         handle = dlopen(name, RTLD_LAZY);
1570                         break;
1571                 } while (1);
1572                 path[i] = end + 1;
1573                 if (!*end)
1574                         ++i;
1575         }
1576         if (!handle) {
1577                 rte_errno = EINVAL;
1578                 dlmsg = dlerror();
1579                 if (dlmsg)
1580                         DRV_LOG(WARNING, "cannot load glue library: %s", dlmsg);
1581                 goto glue_error;
1582         }
1583         sym = dlsym(handle, "mlx5_glue");
1584         if (!sym || !*sym) {
1585                 rte_errno = EINVAL;
1586                 dlmsg = dlerror();
1587                 if (dlmsg)
1588                         DRV_LOG(ERR, "cannot resolve glue symbol: %s", dlmsg);
1589                 goto glue_error;
1590         }
1591         mlx5_glue = *sym;
1592         return 0;
1593 glue_error:
1594         if (handle)
1595                 dlclose(handle);
1596         DRV_LOG(WARNING,
1597                 "cannot initialize PMD due to missing run-time dependency on"
1598                 " rdma-core libraries (libibverbs, libmlx5)");
1599         return -rte_errno;
1600 }
1601
1602 #endif
1603
1604 /**
1605  * Driver initialization routine.
1606  */
1607 RTE_INIT(rte_mlx5_pmd_init)
1608 {
1609         /* Initialize driver log type. */
1610         mlx5_logtype = rte_log_register("pmd.net.mlx5");
1611         if (mlx5_logtype >= 0)
1612                 rte_log_set_level(mlx5_logtype, RTE_LOG_NOTICE);
1613
1614         /* Build the static tables for Verbs conversion. */
1615         mlx5_set_ptype_table();
1616         mlx5_set_cksum_table();
1617         mlx5_set_swp_types_table();
1618         /*
1619          * RDMAV_HUGEPAGES_SAFE tells ibv_fork_init() we intend to use
1620          * huge pages. Calling ibv_fork_init() during init allows
1621          * applications to use fork() safely for purposes other than
1622          * using this PMD, which is not supported in forked processes.
1623          */
1624         setenv("RDMAV_HUGEPAGES_SAFE", "1", 1);
1625         /* Match the size of Rx completion entry to the size of a cacheline. */
1626         if (RTE_CACHE_LINE_SIZE == 128)
1627                 setenv("MLX5_CQE_SIZE", "128", 0);
1628         /*
1629          * MLX5_DEVICE_FATAL_CLEANUP tells ibv_destroy functions to
1630          * cleanup all the Verbs resources even when the device was removed.
1631          */
1632         setenv("MLX5_DEVICE_FATAL_CLEANUP", "1", 1);
1633 #ifdef RTE_LIBRTE_MLX5_DLOPEN_DEPS
1634         if (mlx5_glue_init())
1635                 return;
1636         assert(mlx5_glue);
1637 #endif
1638 #ifndef NDEBUG
1639         /* Glue structure must not contain any NULL pointers. */
1640         {
1641                 unsigned int i;
1642
1643                 for (i = 0; i != sizeof(*mlx5_glue) / sizeof(void *); ++i)
1644                         assert(((const void *const *)mlx5_glue)[i]);
1645         }
1646 #endif
1647         if (strcmp(mlx5_glue->version, MLX5_GLUE_VERSION)) {
1648                 DRV_LOG(ERR,
1649                         "rdma-core glue \"%s\" mismatch: \"%s\" is required",
1650                         mlx5_glue->version, MLX5_GLUE_VERSION);
1651                 return;
1652         }
1653         mlx5_glue->fork_init();
1654         rte_pci_register(&mlx5_driver);
1655 }
1656
1657 RTE_PMD_EXPORT_NAME(net_mlx5, __COUNTER__);
1658 RTE_PMD_REGISTER_PCI_TABLE(net_mlx5, mlx5_pci_id_map);
1659 RTE_PMD_REGISTER_KMOD_DEP(net_mlx5, "* ib_uverbs & mlx5_core & mlx5_ib");