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