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