net/mlx5: convert jump resource to indexed
[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 <stdint.h>
10 #include <stdlib.h>
11 #include <errno.h>
12 #include <net/if.h>
13 #include <sys/mman.h>
14 #include <linux/rtnetlink.h>
15
16 /* Verbs header. */
17 /* ISO C doesn't support unnamed structs/unions, disabling -pedantic. */
18 #ifdef PEDANTIC
19 #pragma GCC diagnostic ignored "-Wpedantic"
20 #endif
21 #include <infiniband/verbs.h>
22 #ifdef PEDANTIC
23 #pragma GCC diagnostic error "-Wpedantic"
24 #endif
25
26 #include <rte_malloc.h>
27 #include <rte_ethdev_driver.h>
28 #include <rte_ethdev_pci.h>
29 #include <rte_pci.h>
30 #include <rte_bus_pci.h>
31 #include <rte_common.h>
32 #include <rte_kvargs.h>
33 #include <rte_rwlock.h>
34 #include <rte_spinlock.h>
35 #include <rte_string_fns.h>
36 #include <rte_alarm.h>
37
38 #include <mlx5_glue.h>
39 #include <mlx5_devx_cmds.h>
40 #include <mlx5_common.h>
41 #include <mlx5_common_mp.h>
42
43 #include "mlx5_defs.h"
44 #include "mlx5.h"
45 #include "mlx5_utils.h"
46 #include "mlx5_rxtx.h"
47 #include "mlx5_autoconf.h"
48 #include "mlx5_mr.h"
49 #include "mlx5_flow.h"
50 #include "rte_pmd_mlx5.h"
51
52 /* Device parameter to enable RX completion queue compression. */
53 #define MLX5_RXQ_CQE_COMP_EN "rxq_cqe_comp_en"
54
55 /* Device parameter to enable RX completion entry padding to 128B. */
56 #define MLX5_RXQ_CQE_PAD_EN "rxq_cqe_pad_en"
57
58 /* Device parameter to enable padding Rx packet to cacheline size. */
59 #define MLX5_RXQ_PKT_PAD_EN "rxq_pkt_pad_en"
60
61 /* Device parameter to enable Multi-Packet Rx queue. */
62 #define MLX5_RX_MPRQ_EN "mprq_en"
63
64 /* Device parameter to configure log 2 of the number of strides for MPRQ. */
65 #define MLX5_RX_MPRQ_LOG_STRIDE_NUM "mprq_log_stride_num"
66
67 /* Device parameter to configure log 2 of the stride size for MPRQ. */
68 #define MLX5_RX_MPRQ_LOG_STRIDE_SIZE "mprq_log_stride_size"
69
70 /* Device parameter to limit the size of memcpy'd packet for MPRQ. */
71 #define MLX5_RX_MPRQ_MAX_MEMCPY_LEN "mprq_max_memcpy_len"
72
73 /* Device parameter to set the minimum number of Rx queues to enable MPRQ. */
74 #define MLX5_RXQS_MIN_MPRQ "rxqs_min_mprq"
75
76 /* Device parameter to configure inline send. Deprecated, ignored.*/
77 #define MLX5_TXQ_INLINE "txq_inline"
78
79 /* Device parameter to limit packet size to inline with ordinary SEND. */
80 #define MLX5_TXQ_INLINE_MAX "txq_inline_max"
81
82 /* Device parameter to configure minimal data size to inline. */
83 #define MLX5_TXQ_INLINE_MIN "txq_inline_min"
84
85 /* Device parameter to limit packet size to inline with Enhanced MPW. */
86 #define MLX5_TXQ_INLINE_MPW "txq_inline_mpw"
87
88 /*
89  * Device parameter to configure the number of TX queues threshold for
90  * enabling inline send.
91  */
92 #define MLX5_TXQS_MIN_INLINE "txqs_min_inline"
93
94 /*
95  * Device parameter to configure the number of TX queues threshold for
96  * enabling vectorized Tx, deprecated, ignored (no vectorized Tx routines).
97  */
98 #define MLX5_TXQS_MAX_VEC "txqs_max_vec"
99
100 /* Device parameter to enable multi-packet send WQEs. */
101 #define MLX5_TXQ_MPW_EN "txq_mpw_en"
102
103 /*
104  * Device parameter to force doorbell register mapping
105  * to non-cahed region eliminating the extra write memory barrier.
106  */
107 #define MLX5_TX_DB_NC "tx_db_nc"
108
109 /*
110  * Device parameter to include 2 dsegs in the title WQEBB.
111  * Deprecated, ignored.
112  */
113 #define MLX5_TXQ_MPW_HDR_DSEG_EN "txq_mpw_hdr_dseg_en"
114
115 /*
116  * Device parameter to limit the size of inlining packet.
117  * Deprecated, ignored.
118  */
119 #define MLX5_TXQ_MAX_INLINE_LEN "txq_max_inline_len"
120
121 /*
122  * Device parameter to enable hardware Tx vector.
123  * Deprecated, ignored (no vectorized Tx routines anymore).
124  */
125 #define MLX5_TX_VEC_EN "tx_vec_en"
126
127 /* Device parameter to enable hardware Rx vector. */
128 #define MLX5_RX_VEC_EN "rx_vec_en"
129
130 /* Allow L3 VXLAN flow creation. */
131 #define MLX5_L3_VXLAN_EN "l3_vxlan_en"
132
133 /* Activate DV E-Switch flow steering. */
134 #define MLX5_DV_ESW_EN "dv_esw_en"
135
136 /* Activate DV flow steering. */
137 #define MLX5_DV_FLOW_EN "dv_flow_en"
138
139 /* Enable extensive flow metadata support. */
140 #define MLX5_DV_XMETA_EN "dv_xmeta_en"
141
142 /* Activate Netlink support in VF mode. */
143 #define MLX5_VF_NL_EN "vf_nl_en"
144
145 /* Enable extending memsegs when creating a MR. */
146 #define MLX5_MR_EXT_MEMSEG_EN "mr_ext_memseg_en"
147
148 /* Select port representors to instantiate. */
149 #define MLX5_REPRESENTOR "representor"
150
151 /* Device parameter to configure the maximum number of dump files per queue. */
152 #define MLX5_MAX_DUMP_FILES_NUM "max_dump_files_num"
153
154 /* Configure timeout of LRO session (in microseconds). */
155 #define MLX5_LRO_TIMEOUT_USEC "lro_timeout_usec"
156
157 /*
158  * Device parameter to configure the total data buffer size for a single
159  * hairpin queue (logarithm value).
160  */
161 #define MLX5_HP_BUF_SIZE "hp_buf_log_sz"
162
163 #ifndef HAVE_IBV_MLX5_MOD_MPW
164 #define MLX5DV_CONTEXT_FLAGS_MPW_ALLOWED (1 << 2)
165 #define MLX5DV_CONTEXT_FLAGS_ENHANCED_MPW (1 << 3)
166 #endif
167
168 #ifndef HAVE_IBV_MLX5_MOD_CQE_128B_COMP
169 #define MLX5DV_CONTEXT_FLAGS_CQE_128B_COMP (1 << 4)
170 #endif
171
172 static const char *MZ_MLX5_PMD_SHARED_DATA = "mlx5_pmd_shared_data";
173
174 /* Shared memory between primary and secondary processes. */
175 struct mlx5_shared_data *mlx5_shared_data;
176
177 /* Spinlock for mlx5_shared_data allocation. */
178 static rte_spinlock_t mlx5_shared_data_lock = RTE_SPINLOCK_INITIALIZER;
179
180 /* Process local data for secondary processes. */
181 static struct mlx5_local_data mlx5_local_data;
182
183 /** Driver-specific log messages type. */
184 int mlx5_logtype;
185
186 /** Data associated with devices to spawn. */
187 struct mlx5_dev_spawn_data {
188         uint32_t ifindex; /**< Network interface index. */
189         uint32_t max_port; /**< IB device maximal port index. */
190         uint32_t ibv_port; /**< IB device physical port index. */
191         int pf_bond; /**< bonding device PF index. < 0 - no bonding */
192         struct mlx5_switch_info info; /**< Switch information. */
193         struct ibv_device *ibv_dev; /**< Associated IB device. */
194         struct rte_eth_dev *eth_dev; /**< Associated Ethernet device. */
195         struct rte_pci_device *pci_dev; /**< Backend PCI device. */
196 };
197
198 static LIST_HEAD(, mlx5_ibv_shared) mlx5_ibv_list = LIST_HEAD_INITIALIZER();
199 static pthread_mutex_t mlx5_ibv_list_mutex = PTHREAD_MUTEX_INITIALIZER;
200
201 static struct mlx5_indexed_pool_config mlx5_ipool_cfg[] = {
202         {
203                 .size = sizeof(struct mlx5_flow_dv_encap_decap_resource),
204                 .trunk_size = 64,
205                 .grow_trunk = 3,
206                 .grow_shift = 2,
207                 .need_lock = 0,
208                 .release_mem_en = 1,
209                 .malloc = rte_malloc_socket,
210                 .free = rte_free,
211                 .type = "mlx5_encap_decap_ipool",
212         },
213         {
214                 .size = sizeof(struct mlx5_flow_dv_push_vlan_action_resource),
215                 .trunk_size = 64,
216                 .grow_trunk = 3,
217                 .grow_shift = 2,
218                 .need_lock = 0,
219                 .release_mem_en = 1,
220                 .malloc = rte_malloc_socket,
221                 .free = rte_free,
222                 .type = "mlx5_push_vlan_ipool",
223         },
224         {
225                 .size = sizeof(struct mlx5_flow_dv_tag_resource),
226                 .trunk_size = 64,
227                 .grow_trunk = 3,
228                 .grow_shift = 2,
229                 .need_lock = 0,
230                 .release_mem_en = 1,
231                 .malloc = rte_malloc_socket,
232                 .free = rte_free,
233                 .type = "mlx5_tag_ipool",
234         },
235         {
236                 .size = sizeof(struct mlx5_flow_dv_port_id_action_resource),
237                 .trunk_size = 64,
238                 .grow_trunk = 3,
239                 .grow_shift = 2,
240                 .need_lock = 0,
241                 .release_mem_en = 1,
242                 .malloc = rte_malloc_socket,
243                 .free = rte_free,
244                 .type = "mlx5_port_id_ipool",
245         },
246         {
247                 .size = sizeof(struct mlx5_flow_tbl_data_entry),
248                 .trunk_size = 64,
249                 .grow_trunk = 3,
250                 .grow_shift = 2,
251                 .need_lock = 0,
252                 .release_mem_en = 1,
253                 .malloc = rte_malloc_socket,
254                 .free = rte_free,
255                 .type = "mlx5_jump_ipool",
256         },
257 };
258
259
260 #define MLX5_FLOW_MIN_ID_POOL_SIZE 512
261 #define MLX5_ID_GENERATION_ARRAY_FACTOR 16
262
263 #define MLX5_FLOW_TABLE_HLIST_ARRAY_SIZE 4096
264 #define MLX5_TAGS_HLIST_ARRAY_SIZE 8192
265
266 /**
267  * Allocate ID pool structure.
268  *
269  * @param[in] max_id
270  *   The maximum id can be allocated from the pool.
271  *
272  * @return
273  *   Pointer to pool object, NULL value otherwise.
274  */
275 struct mlx5_flow_id_pool *
276 mlx5_flow_id_pool_alloc(uint32_t max_id)
277 {
278         struct mlx5_flow_id_pool *pool;
279         void *mem;
280
281         pool = rte_zmalloc("id pool allocation", sizeof(*pool),
282                            RTE_CACHE_LINE_SIZE);
283         if (!pool) {
284                 DRV_LOG(ERR, "can't allocate id pool");
285                 rte_errno  = ENOMEM;
286                 return NULL;
287         }
288         mem = rte_zmalloc("", MLX5_FLOW_MIN_ID_POOL_SIZE * sizeof(uint32_t),
289                           RTE_CACHE_LINE_SIZE);
290         if (!mem) {
291                 DRV_LOG(ERR, "can't allocate mem for id pool");
292                 rte_errno  = ENOMEM;
293                 goto error;
294         }
295         pool->free_arr = mem;
296         pool->curr = pool->free_arr;
297         pool->last = pool->free_arr + MLX5_FLOW_MIN_ID_POOL_SIZE;
298         pool->base_index = 0;
299         pool->max_id = max_id;
300         return pool;
301 error:
302         rte_free(pool);
303         return NULL;
304 }
305
306 /**
307  * Release ID pool structure.
308  *
309  * @param[in] pool
310  *   Pointer to flow id pool object to free.
311  */
312 void
313 mlx5_flow_id_pool_release(struct mlx5_flow_id_pool *pool)
314 {
315         rte_free(pool->free_arr);
316         rte_free(pool);
317 }
318
319 /**
320  * Generate ID.
321  *
322  * @param[in] pool
323  *   Pointer to flow id pool.
324  * @param[out] id
325  *   The generated ID.
326  *
327  * @return
328  *   0 on success, error value otherwise.
329  */
330 uint32_t
331 mlx5_flow_id_get(struct mlx5_flow_id_pool *pool, uint32_t *id)
332 {
333         if (pool->curr == pool->free_arr) {
334                 if (pool->base_index == pool->max_id) {
335                         rte_errno  = ENOMEM;
336                         DRV_LOG(ERR, "no free id");
337                         return -rte_errno;
338                 }
339                 *id = ++pool->base_index;
340                 return 0;
341         }
342         *id = *(--pool->curr);
343         return 0;
344 }
345
346 /**
347  * Release ID.
348  *
349  * @param[in] pool
350  *   Pointer to flow id pool.
351  * @param[out] id
352  *   The generated ID.
353  *
354  * @return
355  *   0 on success, error value otherwise.
356  */
357 uint32_t
358 mlx5_flow_id_release(struct mlx5_flow_id_pool *pool, uint32_t id)
359 {
360         uint32_t size;
361         uint32_t size2;
362         void *mem;
363
364         if (pool->curr == pool->last) {
365                 size = pool->curr - pool->free_arr;
366                 size2 = size * MLX5_ID_GENERATION_ARRAY_FACTOR;
367                 MLX5_ASSERT(size2 > size);
368                 mem = rte_malloc("", size2 * sizeof(uint32_t), 0);
369                 if (!mem) {
370                         DRV_LOG(ERR, "can't allocate mem for id pool");
371                         rte_errno  = ENOMEM;
372                         return -rte_errno;
373                 }
374                 memcpy(mem, pool->free_arr, size * sizeof(uint32_t));
375                 rte_free(pool->free_arr);
376                 pool->free_arr = mem;
377                 pool->curr = pool->free_arr + size;
378                 pool->last = pool->free_arr + size2;
379         }
380         *pool->curr = id;
381         pool->curr++;
382         return 0;
383 }
384
385 /**
386  * Initialize the counters management structure.
387  *
388  * @param[in] sh
389  *   Pointer to mlx5_ibv_shared object to free
390  */
391 static void
392 mlx5_flow_counters_mng_init(struct mlx5_ibv_shared *sh)
393 {
394         uint8_t i;
395
396         TAILQ_INIT(&sh->cmng.flow_counters);
397         for (i = 0; i < RTE_DIM(sh->cmng.ccont); ++i)
398                 TAILQ_INIT(&sh->cmng.ccont[i].pool_list);
399 }
400
401 /**
402  * Destroy all the resources allocated for a counter memory management.
403  *
404  * @param[in] mng
405  *   Pointer to the memory management structure.
406  */
407 static void
408 mlx5_flow_destroy_counter_stat_mem_mng(struct mlx5_counter_stats_mem_mng *mng)
409 {
410         uint8_t *mem = (uint8_t *)(uintptr_t)mng->raws[0].data;
411
412         LIST_REMOVE(mng, next);
413         claim_zero(mlx5_devx_cmd_destroy(mng->dm));
414         claim_zero(mlx5_glue->devx_umem_dereg(mng->umem));
415         rte_free(mem);
416 }
417
418 /**
419  * Close and release all the resources of the counters management.
420  *
421  * @param[in] sh
422  *   Pointer to mlx5_ibv_shared object to free.
423  */
424 static void
425 mlx5_flow_counters_mng_close(struct mlx5_ibv_shared *sh)
426 {
427         struct mlx5_counter_stats_mem_mng *mng;
428         uint8_t i;
429         int j;
430         int retries = 1024;
431
432         rte_errno = 0;
433         while (--retries) {
434                 rte_eal_alarm_cancel(mlx5_flow_query_alarm, sh);
435                 if (rte_errno != EINPROGRESS)
436                         break;
437                 rte_pause();
438         }
439         for (i = 0; i < RTE_DIM(sh->cmng.ccont); ++i) {
440                 struct mlx5_flow_counter_pool *pool;
441                 uint32_t batch = !!(i % 2);
442
443                 if (!sh->cmng.ccont[i].pools)
444                         continue;
445                 pool = TAILQ_FIRST(&sh->cmng.ccont[i].pool_list);
446                 while (pool) {
447                         if (batch) {
448                                 if (pool->min_dcs)
449                                         claim_zero
450                                         (mlx5_devx_cmd_destroy(pool->min_dcs));
451                         }
452                         for (j = 0; j < MLX5_COUNTERS_PER_POOL; ++j) {
453                                 if (pool->counters_raw[j].action)
454                                         claim_zero
455                                         (mlx5_glue->destroy_flow_action
456                                                (pool->counters_raw[j].action));
457                                 if (!batch && MLX5_GET_POOL_CNT_EXT
458                                     (pool, j)->dcs)
459                                         claim_zero(mlx5_devx_cmd_destroy
460                                                   (MLX5_GET_POOL_CNT_EXT
461                                                   (pool, j)->dcs));
462                         }
463                         TAILQ_REMOVE(&sh->cmng.ccont[i].pool_list, pool,
464                                      next);
465                         rte_free(pool);
466                         pool = TAILQ_FIRST(&sh->cmng.ccont[i].pool_list);
467                 }
468                 rte_free(sh->cmng.ccont[i].pools);
469         }
470         mng = LIST_FIRST(&sh->cmng.mem_mngs);
471         while (mng) {
472                 mlx5_flow_destroy_counter_stat_mem_mng(mng);
473                 mng = LIST_FIRST(&sh->cmng.mem_mngs);
474         }
475         memset(&sh->cmng, 0, sizeof(sh->cmng));
476 }
477
478 /**
479  * Initialize the flow resources' indexed mempool.
480  *
481  * @param[in] sh
482  *   Pointer to mlx5_ibv_shared object.
483  */
484 static void
485 mlx5_flow_ipool_create(struct mlx5_ibv_shared *sh)
486 {
487         uint8_t i;
488
489         for (i = 0; i < MLX5_IPOOL_MAX; ++i)
490                 sh->ipool[i] = mlx5_ipool_create(&mlx5_ipool_cfg[i]);
491 }
492
493 /**
494  * Release the flow resources' indexed mempool.
495  *
496  * @param[in] sh
497  *   Pointer to mlx5_ibv_shared object.
498  */
499 static void
500 mlx5_flow_ipool_destroy(struct mlx5_ibv_shared *sh)
501 {
502         uint8_t i;
503
504         for (i = 0; i < MLX5_IPOOL_MAX; ++i)
505                 mlx5_ipool_destroy(sh->ipool[i]);
506 }
507
508 /**
509  * Extract pdn of PD object using DV API.
510  *
511  * @param[in] pd
512  *   Pointer to the verbs PD object.
513  * @param[out] pdn
514  *   Pointer to the PD object number variable.
515  *
516  * @return
517  *   0 on success, error value otherwise.
518  */
519 #ifdef HAVE_IBV_FLOW_DV_SUPPORT
520 static int
521 mlx5_get_pdn(struct ibv_pd *pd __rte_unused, uint32_t *pdn __rte_unused)
522 {
523         struct mlx5dv_obj obj;
524         struct mlx5dv_pd pd_info;
525         int ret = 0;
526
527         obj.pd.in = pd;
528         obj.pd.out = &pd_info;
529         ret = mlx5_glue->dv_init_obj(&obj, MLX5DV_OBJ_PD);
530         if (ret) {
531                 DRV_LOG(DEBUG, "Fail to get PD object info");
532                 return ret;
533         }
534         *pdn = pd_info.pdn;
535         return 0;
536 }
537 #endif /* HAVE_IBV_FLOW_DV_SUPPORT */
538
539 static int
540 mlx5_config_doorbell_mapping_env(const struct mlx5_dev_config *config)
541 {
542         char *env;
543         int value;
544
545         MLX5_ASSERT(rte_eal_process_type() == RTE_PROC_PRIMARY);
546         /* Get environment variable to store. */
547         env = getenv(MLX5_SHUT_UP_BF);
548         value = env ? !!strcmp(env, "0") : MLX5_ARG_UNSET;
549         if (config->dbnc == MLX5_ARG_UNSET)
550                 setenv(MLX5_SHUT_UP_BF, MLX5_SHUT_UP_BF_DEFAULT, 1);
551         else
552                 setenv(MLX5_SHUT_UP_BF,
553                        config->dbnc == MLX5_TXDB_NCACHED ? "1" : "0", 1);
554         return value;
555 }
556
557 static void
558 mlx5_restore_doorbell_mapping_env(int value)
559 {
560         MLX5_ASSERT(rte_eal_process_type() == RTE_PROC_PRIMARY);
561         /* Restore the original environment variable state. */
562         if (value == MLX5_ARG_UNSET)
563                 unsetenv(MLX5_SHUT_UP_BF);
564         else
565                 setenv(MLX5_SHUT_UP_BF, value ? "1" : "0", 1);
566 }
567
568 /**
569  * Allocate shared IB device context. If there is multiport device the
570  * master and representors will share this context, if there is single
571  * port dedicated IB device, the context will be used by only given
572  * port due to unification.
573  *
574  * Routine first searches the context for the specified IB device name,
575  * if found the shared context assumed and reference counter is incremented.
576  * If no context found the new one is created and initialized with specified
577  * IB device context and parameters.
578  *
579  * @param[in] spawn
580  *   Pointer to the IB device attributes (name, port, etc).
581  * @param[in] config
582  *   Pointer to device configuration structure.
583  *
584  * @return
585  *   Pointer to mlx5_ibv_shared object on success,
586  *   otherwise NULL and rte_errno is set.
587  */
588 static struct mlx5_ibv_shared *
589 mlx5_alloc_shared_ibctx(const struct mlx5_dev_spawn_data *spawn,
590                         const struct mlx5_dev_config *config)
591 {
592         struct mlx5_ibv_shared *sh;
593         int dbmap_env;
594         int err = 0;
595         uint32_t i;
596 #ifdef HAVE_IBV_FLOW_DV_SUPPORT
597         struct mlx5_devx_tis_attr tis_attr = { 0 };
598 #endif
599
600         MLX5_ASSERT(spawn);
601         /* Secondary process should not create the shared context. */
602         MLX5_ASSERT(rte_eal_process_type() == RTE_PROC_PRIMARY);
603         pthread_mutex_lock(&mlx5_ibv_list_mutex);
604         /* Search for IB context by device name. */
605         LIST_FOREACH(sh, &mlx5_ibv_list, next) {
606                 if (!strcmp(sh->ibdev_name, spawn->ibv_dev->name)) {
607                         sh->refcnt++;
608                         goto exit;
609                 }
610         }
611         /* No device found, we have to create new shared context. */
612         MLX5_ASSERT(spawn->max_port);
613         sh = rte_zmalloc("ethdev shared ib context",
614                          sizeof(struct mlx5_ibv_shared) +
615                          spawn->max_port *
616                          sizeof(struct mlx5_ibv_shared_port),
617                          RTE_CACHE_LINE_SIZE);
618         if (!sh) {
619                 DRV_LOG(ERR, "shared context allocation failure");
620                 rte_errno  = ENOMEM;
621                 goto exit;
622         }
623         /*
624          * Configure environment variable "MLX5_BF_SHUT_UP"
625          * before the device creation. The rdma_core library
626          * checks the variable at device creation and
627          * stores the result internally.
628          */
629         dbmap_env = mlx5_config_doorbell_mapping_env(config);
630         /* Try to open IB device with DV first, then usual Verbs. */
631         errno = 0;
632         sh->ctx = mlx5_glue->dv_open_device(spawn->ibv_dev);
633         if (sh->ctx) {
634                 sh->devx = 1;
635                 DRV_LOG(DEBUG, "DevX is supported");
636                 /* The device is created, no need for environment. */
637                 mlx5_restore_doorbell_mapping_env(dbmap_env);
638         } else {
639                 /* The environment variable is still configured. */
640                 sh->ctx = mlx5_glue->open_device(spawn->ibv_dev);
641                 err = errno ? errno : ENODEV;
642                 /*
643                  * The environment variable is not needed anymore,
644                  * all device creation attempts are completed.
645                  */
646                 mlx5_restore_doorbell_mapping_env(dbmap_env);
647                 if (!sh->ctx)
648                         goto error;
649                 DRV_LOG(DEBUG, "DevX is NOT supported");
650         }
651         err = mlx5_glue->query_device_ex(sh->ctx, NULL, &sh->device_attr);
652         if (err) {
653                 DRV_LOG(DEBUG, "ibv_query_device_ex() failed");
654                 goto error;
655         }
656         sh->refcnt = 1;
657         sh->max_port = spawn->max_port;
658         strncpy(sh->ibdev_name, sh->ctx->device->name,
659                 sizeof(sh->ibdev_name));
660         strncpy(sh->ibdev_path, sh->ctx->device->ibdev_path,
661                 sizeof(sh->ibdev_path));
662         pthread_mutex_init(&sh->intr_mutex, NULL);
663         /*
664          * Setting port_id to max unallowed value means
665          * there is no interrupt subhandler installed for
666          * the given port index i.
667          */
668         for (i = 0; i < sh->max_port; i++) {
669                 sh->port[i].ih_port_id = RTE_MAX_ETHPORTS;
670                 sh->port[i].devx_ih_port_id = RTE_MAX_ETHPORTS;
671         }
672         sh->pd = mlx5_glue->alloc_pd(sh->ctx);
673         if (sh->pd == NULL) {
674                 DRV_LOG(ERR, "PD allocation failure");
675                 err = ENOMEM;
676                 goto error;
677         }
678 #ifdef HAVE_IBV_FLOW_DV_SUPPORT
679         if (sh->devx) {
680                 err = mlx5_get_pdn(sh->pd, &sh->pdn);
681                 if (err) {
682                         DRV_LOG(ERR, "Fail to extract pdn from PD");
683                         goto error;
684                 }
685                 sh->td = mlx5_devx_cmd_create_td(sh->ctx);
686                 if (!sh->td) {
687                         DRV_LOG(ERR, "TD allocation failure");
688                         err = ENOMEM;
689                         goto error;
690                 }
691                 tis_attr.transport_domain = sh->td->id;
692                 sh->tis = mlx5_devx_cmd_create_tis(sh->ctx, &tis_attr);
693                 if (!sh->tis) {
694                         DRV_LOG(ERR, "TIS allocation failure");
695                         err = ENOMEM;
696                         goto error;
697                 }
698         }
699         sh->flow_id_pool = mlx5_flow_id_pool_alloc(UINT32_MAX);
700         if (!sh->flow_id_pool) {
701                 DRV_LOG(ERR, "can't create flow id pool");
702                 err = ENOMEM;
703                 goto error;
704         }
705 #endif /* HAVE_IBV_FLOW_DV_SUPPORT */
706         /*
707          * Once the device is added to the list of memory event
708          * callback, its global MR cache table cannot be expanded
709          * on the fly because of deadlock. If it overflows, lookup
710          * should be done by searching MR list linearly, which is slow.
711          *
712          * At this point the device is not added to the memory
713          * event list yet, context is just being created.
714          */
715         err = mlx5_mr_btree_init(&sh->share_cache.cache,
716                                  MLX5_MR_BTREE_CACHE_N * 2,
717                                  spawn->pci_dev->device.numa_node);
718         if (err) {
719                 err = rte_errno;
720                 goto error;
721         }
722         mlx5_flow_counters_mng_init(sh);
723         mlx5_flow_ipool_create(sh);
724         /* Add device to memory callback list. */
725         rte_rwlock_write_lock(&mlx5_shared_data->mem_event_rwlock);
726         LIST_INSERT_HEAD(&mlx5_shared_data->mem_event_cb_list,
727                          sh, mem_event_cb);
728         rte_rwlock_write_unlock(&mlx5_shared_data->mem_event_rwlock);
729         /* Add context to the global device list. */
730         LIST_INSERT_HEAD(&mlx5_ibv_list, sh, next);
731 exit:
732         pthread_mutex_unlock(&mlx5_ibv_list_mutex);
733         return sh;
734 error:
735         pthread_mutex_unlock(&mlx5_ibv_list_mutex);
736         MLX5_ASSERT(sh);
737         if (sh->tis)
738                 claim_zero(mlx5_devx_cmd_destroy(sh->tis));
739         if (sh->td)
740                 claim_zero(mlx5_devx_cmd_destroy(sh->td));
741         if (sh->pd)
742                 claim_zero(mlx5_glue->dealloc_pd(sh->pd));
743         if (sh->ctx)
744                 claim_zero(mlx5_glue->close_device(sh->ctx));
745         if (sh->flow_id_pool)
746                 mlx5_flow_id_pool_release(sh->flow_id_pool);
747         rte_free(sh);
748         MLX5_ASSERT(err > 0);
749         rte_errno = err;
750         return NULL;
751 }
752
753 /**
754  * Free shared IB device context. Decrement counter and if zero free
755  * all allocated resources and close handles.
756  *
757  * @param[in] sh
758  *   Pointer to mlx5_ibv_shared object to free
759  */
760 static void
761 mlx5_free_shared_ibctx(struct mlx5_ibv_shared *sh)
762 {
763         pthread_mutex_lock(&mlx5_ibv_list_mutex);
764 #ifdef RTE_LIBRTE_MLX5_DEBUG
765         /* Check the object presence in the list. */
766         struct mlx5_ibv_shared *lctx;
767
768         LIST_FOREACH(lctx, &mlx5_ibv_list, next)
769                 if (lctx == sh)
770                         break;
771         MLX5_ASSERT(lctx);
772         if (lctx != sh) {
773                 DRV_LOG(ERR, "Freeing non-existing shared IB context");
774                 goto exit;
775         }
776 #endif
777         MLX5_ASSERT(sh);
778         MLX5_ASSERT(sh->refcnt);
779         /* Secondary process should not free the shared context. */
780         MLX5_ASSERT(rte_eal_process_type() == RTE_PROC_PRIMARY);
781         if (--sh->refcnt)
782                 goto exit;
783         /* Remove from memory callback device list. */
784         rte_rwlock_write_lock(&mlx5_shared_data->mem_event_rwlock);
785         LIST_REMOVE(sh, mem_event_cb);
786         rte_rwlock_write_unlock(&mlx5_shared_data->mem_event_rwlock);
787         /* Release created Memory Regions. */
788         mlx5_mr_release_cache(&sh->share_cache);
789         /* Remove context from the global device list. */
790         LIST_REMOVE(sh, next);
791         /*
792          *  Ensure there is no async event handler installed.
793          *  Only primary process handles async device events.
794          **/
795         mlx5_flow_counters_mng_close(sh);
796         mlx5_flow_ipool_destroy(sh);
797         MLX5_ASSERT(!sh->intr_cnt);
798         if (sh->intr_cnt)
799                 mlx5_intr_callback_unregister
800                         (&sh->intr_handle, mlx5_dev_interrupt_handler, sh);
801 #ifdef HAVE_MLX5_DEVX_ASYNC_SUPPORT
802         if (sh->devx_intr_cnt) {
803                 if (sh->intr_handle_devx.fd)
804                         rte_intr_callback_unregister(&sh->intr_handle_devx,
805                                           mlx5_dev_interrupt_handler_devx, sh);
806                 if (sh->devx_comp)
807                         mlx5dv_devx_destroy_cmd_comp(sh->devx_comp);
808         }
809 #endif
810         pthread_mutex_destroy(&sh->intr_mutex);
811         if (sh->pd)
812                 claim_zero(mlx5_glue->dealloc_pd(sh->pd));
813         if (sh->tis)
814                 claim_zero(mlx5_devx_cmd_destroy(sh->tis));
815         if (sh->td)
816                 claim_zero(mlx5_devx_cmd_destroy(sh->td));
817         if (sh->ctx)
818                 claim_zero(mlx5_glue->close_device(sh->ctx));
819         if (sh->flow_id_pool)
820                 mlx5_flow_id_pool_release(sh->flow_id_pool);
821         rte_free(sh);
822 exit:
823         pthread_mutex_unlock(&mlx5_ibv_list_mutex);
824 }
825
826 /**
827  * Destroy table hash list and all the root entries per domain.
828  *
829  * @param[in] priv
830  *   Pointer to the private device data structure.
831  */
832 static void
833 mlx5_free_table_hash_list(struct mlx5_priv *priv)
834 {
835         struct mlx5_ibv_shared *sh = priv->sh;
836         struct mlx5_flow_tbl_data_entry *tbl_data;
837         union mlx5_flow_tbl_key table_key = {
838                 {
839                         .table_id = 0,
840                         .reserved = 0,
841                         .domain = 0,
842                         .direction = 0,
843                 }
844         };
845         struct mlx5_hlist_entry *pos;
846
847         if (!sh->flow_tbls)
848                 return;
849         pos = mlx5_hlist_lookup(sh->flow_tbls, table_key.v64);
850         if (pos) {
851                 tbl_data = container_of(pos, struct mlx5_flow_tbl_data_entry,
852                                         entry);
853                 MLX5_ASSERT(tbl_data);
854                 mlx5_hlist_remove(sh->flow_tbls, pos);
855                 rte_free(tbl_data);
856         }
857         table_key.direction = 1;
858         pos = mlx5_hlist_lookup(sh->flow_tbls, table_key.v64);
859         if (pos) {
860                 tbl_data = container_of(pos, struct mlx5_flow_tbl_data_entry,
861                                         entry);
862                 MLX5_ASSERT(tbl_data);
863                 mlx5_hlist_remove(sh->flow_tbls, pos);
864                 rte_free(tbl_data);
865         }
866         table_key.direction = 0;
867         table_key.domain = 1;
868         pos = mlx5_hlist_lookup(sh->flow_tbls, table_key.v64);
869         if (pos) {
870                 tbl_data = container_of(pos, struct mlx5_flow_tbl_data_entry,
871                                         entry);
872                 MLX5_ASSERT(tbl_data);
873                 mlx5_hlist_remove(sh->flow_tbls, pos);
874                 rte_free(tbl_data);
875         }
876         mlx5_hlist_destroy(sh->flow_tbls, NULL, NULL);
877 }
878
879 /**
880  * Initialize flow table hash list and create the root tables entry
881  * for each domain.
882  *
883  * @param[in] priv
884  *   Pointer to the private device data structure.
885  *
886  * @return
887  *   Zero on success, positive error code otherwise.
888  */
889 static int
890 mlx5_alloc_table_hash_list(struct mlx5_priv *priv)
891 {
892         struct mlx5_ibv_shared *sh = priv->sh;
893         char s[MLX5_HLIST_NAMESIZE];
894         int err = 0;
895
896         MLX5_ASSERT(sh);
897         snprintf(s, sizeof(s), "%s_flow_table", priv->sh->ibdev_name);
898         sh->flow_tbls = mlx5_hlist_create(s, MLX5_FLOW_TABLE_HLIST_ARRAY_SIZE);
899         if (!sh->flow_tbls) {
900                 DRV_LOG(ERR, "flow tables with hash creation failed.\n");
901                 err = ENOMEM;
902                 return err;
903         }
904 #ifndef HAVE_MLX5DV_DR
905         /*
906          * In case we have not DR support, the zero tables should be created
907          * because DV expect to see them even if they cannot be created by
908          * RDMA-CORE.
909          */
910         union mlx5_flow_tbl_key table_key = {
911                 {
912                         .table_id = 0,
913                         .reserved = 0,
914                         .domain = 0,
915                         .direction = 0,
916                 }
917         };
918         struct mlx5_flow_tbl_data_entry *tbl_data = rte_zmalloc(NULL,
919                                                           sizeof(*tbl_data), 0);
920
921         if (!tbl_data) {
922                 err = ENOMEM;
923                 goto error;
924         }
925         tbl_data->entry.key = table_key.v64;
926         err = mlx5_hlist_insert(sh->flow_tbls, &tbl_data->entry);
927         if (err)
928                 goto error;
929         rte_atomic32_init(&tbl_data->tbl.refcnt);
930         rte_atomic32_inc(&tbl_data->tbl.refcnt);
931         table_key.direction = 1;
932         tbl_data = rte_zmalloc(NULL, sizeof(*tbl_data), 0);
933         if (!tbl_data) {
934                 err = ENOMEM;
935                 goto error;
936         }
937         tbl_data->entry.key = table_key.v64;
938         err = mlx5_hlist_insert(sh->flow_tbls, &tbl_data->entry);
939         if (err)
940                 goto error;
941         rte_atomic32_init(&tbl_data->tbl.refcnt);
942         rte_atomic32_inc(&tbl_data->tbl.refcnt);
943         table_key.direction = 0;
944         table_key.domain = 1;
945         tbl_data = rte_zmalloc(NULL, sizeof(*tbl_data), 0);
946         if (!tbl_data) {
947                 err = ENOMEM;
948                 goto error;
949         }
950         tbl_data->entry.key = table_key.v64;
951         err = mlx5_hlist_insert(sh->flow_tbls, &tbl_data->entry);
952         if (err)
953                 goto error;
954         rte_atomic32_init(&tbl_data->tbl.refcnt);
955         rte_atomic32_inc(&tbl_data->tbl.refcnt);
956         return err;
957 error:
958         mlx5_free_table_hash_list(priv);
959 #endif /* HAVE_MLX5DV_DR */
960         return err;
961 }
962
963 /**
964  * Initialize DR related data within private structure.
965  * Routine checks the reference counter and does actual
966  * resources creation/initialization only if counter is zero.
967  *
968  * @param[in] priv
969  *   Pointer to the private device data structure.
970  *
971  * @return
972  *   Zero on success, positive error code otherwise.
973  */
974 static int
975 mlx5_alloc_shared_dr(struct mlx5_priv *priv)
976 {
977         struct mlx5_ibv_shared *sh = priv->sh;
978         char s[MLX5_HLIST_NAMESIZE];
979         int err = 0;
980
981         if (!sh->flow_tbls)
982                 err = mlx5_alloc_table_hash_list(priv);
983         else
984                 DRV_LOG(DEBUG, "sh->flow_tbls[%p] already created, reuse\n",
985                         (void *)sh->flow_tbls);
986         if (err)
987                 return err;
988         /* Create tags hash list table. */
989         snprintf(s, sizeof(s), "%s_tags", sh->ibdev_name);
990         sh->tag_table = mlx5_hlist_create(s, MLX5_TAGS_HLIST_ARRAY_SIZE);
991         if (!sh->tag_table) {
992                 DRV_LOG(ERR, "tags with hash creation failed.\n");
993                 err = ENOMEM;
994                 goto error;
995         }
996 #ifdef HAVE_MLX5DV_DR
997         void *domain;
998
999         if (sh->dv_refcnt) {
1000                 /* Shared DV/DR structures is already initialized. */
1001                 sh->dv_refcnt++;
1002                 priv->dr_shared = 1;
1003                 return 0;
1004         }
1005         /* Reference counter is zero, we should initialize structures. */
1006         domain = mlx5_glue->dr_create_domain(sh->ctx,
1007                                              MLX5DV_DR_DOMAIN_TYPE_NIC_RX);
1008         if (!domain) {
1009                 DRV_LOG(ERR, "ingress mlx5dv_dr_create_domain failed");
1010                 err = errno;
1011                 goto error;
1012         }
1013         sh->rx_domain = domain;
1014         domain = mlx5_glue->dr_create_domain(sh->ctx,
1015                                              MLX5DV_DR_DOMAIN_TYPE_NIC_TX);
1016         if (!domain) {
1017                 DRV_LOG(ERR, "egress mlx5dv_dr_create_domain failed");
1018                 err = errno;
1019                 goto error;
1020         }
1021         pthread_mutex_init(&sh->dv_mutex, NULL);
1022         sh->tx_domain = domain;
1023 #ifdef HAVE_MLX5DV_DR_ESWITCH
1024         if (priv->config.dv_esw_en) {
1025                 domain  = mlx5_glue->dr_create_domain
1026                         (sh->ctx, MLX5DV_DR_DOMAIN_TYPE_FDB);
1027                 if (!domain) {
1028                         DRV_LOG(ERR, "FDB mlx5dv_dr_create_domain failed");
1029                         err = errno;
1030                         goto error;
1031                 }
1032                 sh->fdb_domain = domain;
1033                 sh->esw_drop_action = mlx5_glue->dr_create_flow_action_drop();
1034         }
1035 #endif
1036         sh->pop_vlan_action = mlx5_glue->dr_create_flow_action_pop_vlan();
1037 #endif /* HAVE_MLX5DV_DR */
1038         sh->dv_refcnt++;
1039         priv->dr_shared = 1;
1040         return 0;
1041 error:
1042         /* Rollback the created objects. */
1043         if (sh->rx_domain) {
1044                 mlx5_glue->dr_destroy_domain(sh->rx_domain);
1045                 sh->rx_domain = NULL;
1046         }
1047         if (sh->tx_domain) {
1048                 mlx5_glue->dr_destroy_domain(sh->tx_domain);
1049                 sh->tx_domain = NULL;
1050         }
1051         if (sh->fdb_domain) {
1052                 mlx5_glue->dr_destroy_domain(sh->fdb_domain);
1053                 sh->fdb_domain = NULL;
1054         }
1055         if (sh->esw_drop_action) {
1056                 mlx5_glue->destroy_flow_action(sh->esw_drop_action);
1057                 sh->esw_drop_action = NULL;
1058         }
1059         if (sh->pop_vlan_action) {
1060                 mlx5_glue->destroy_flow_action(sh->pop_vlan_action);
1061                 sh->pop_vlan_action = NULL;
1062         }
1063         if (sh->tag_table) {
1064                 /* tags should be destroyed with flow before. */
1065                 mlx5_hlist_destroy(sh->tag_table, NULL, NULL);
1066                 sh->tag_table = NULL;
1067         }
1068         mlx5_free_table_hash_list(priv);
1069         return err;
1070 }
1071
1072 /**
1073  * Destroy DR related data within private structure.
1074  *
1075  * @param[in] priv
1076  *   Pointer to the private device data structure.
1077  */
1078 static void
1079 mlx5_free_shared_dr(struct mlx5_priv *priv)
1080 {
1081         struct mlx5_ibv_shared *sh;
1082
1083         if (!priv->dr_shared)
1084                 return;
1085         priv->dr_shared = 0;
1086         sh = priv->sh;
1087         MLX5_ASSERT(sh);
1088 #ifdef HAVE_MLX5DV_DR
1089         MLX5_ASSERT(sh->dv_refcnt);
1090         if (sh->dv_refcnt && --sh->dv_refcnt)
1091                 return;
1092         if (sh->rx_domain) {
1093                 mlx5_glue->dr_destroy_domain(sh->rx_domain);
1094                 sh->rx_domain = NULL;
1095         }
1096         if (sh->tx_domain) {
1097                 mlx5_glue->dr_destroy_domain(sh->tx_domain);
1098                 sh->tx_domain = NULL;
1099         }
1100 #ifdef HAVE_MLX5DV_DR_ESWITCH
1101         if (sh->fdb_domain) {
1102                 mlx5_glue->dr_destroy_domain(sh->fdb_domain);
1103                 sh->fdb_domain = NULL;
1104         }
1105         if (sh->esw_drop_action) {
1106                 mlx5_glue->destroy_flow_action(sh->esw_drop_action);
1107                 sh->esw_drop_action = NULL;
1108         }
1109 #endif
1110         if (sh->pop_vlan_action) {
1111                 mlx5_glue->destroy_flow_action(sh->pop_vlan_action);
1112                 sh->pop_vlan_action = NULL;
1113         }
1114         pthread_mutex_destroy(&sh->dv_mutex);
1115 #endif /* HAVE_MLX5DV_DR */
1116         if (sh->tag_table) {
1117                 /* tags should be destroyed with flow before. */
1118                 mlx5_hlist_destroy(sh->tag_table, NULL, NULL);
1119                 sh->tag_table = NULL;
1120         }
1121         mlx5_free_table_hash_list(priv);
1122 }
1123
1124 /**
1125  * Initialize shared data between primary and secondary process.
1126  *
1127  * A memzone is reserved by primary process and secondary processes attach to
1128  * the memzone.
1129  *
1130  * @return
1131  *   0 on success, a negative errno value otherwise and rte_errno is set.
1132  */
1133 static int
1134 mlx5_init_shared_data(void)
1135 {
1136         const struct rte_memzone *mz;
1137         int ret = 0;
1138
1139         rte_spinlock_lock(&mlx5_shared_data_lock);
1140         if (mlx5_shared_data == NULL) {
1141                 if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
1142                         /* Allocate shared memory. */
1143                         mz = rte_memzone_reserve(MZ_MLX5_PMD_SHARED_DATA,
1144                                                  sizeof(*mlx5_shared_data),
1145                                                  SOCKET_ID_ANY, 0);
1146                         if (mz == NULL) {
1147                                 DRV_LOG(ERR,
1148                                         "Cannot allocate mlx5 shared data");
1149                                 ret = -rte_errno;
1150                                 goto error;
1151                         }
1152                         mlx5_shared_data = mz->addr;
1153                         memset(mlx5_shared_data, 0, sizeof(*mlx5_shared_data));
1154                         rte_spinlock_init(&mlx5_shared_data->lock);
1155                 } else {
1156                         /* Lookup allocated shared memory. */
1157                         mz = rte_memzone_lookup(MZ_MLX5_PMD_SHARED_DATA);
1158                         if (mz == NULL) {
1159                                 DRV_LOG(ERR,
1160                                         "Cannot attach mlx5 shared data");
1161                                 ret = -rte_errno;
1162                                 goto error;
1163                         }
1164                         mlx5_shared_data = mz->addr;
1165                         memset(&mlx5_local_data, 0, sizeof(mlx5_local_data));
1166                 }
1167         }
1168 error:
1169         rte_spinlock_unlock(&mlx5_shared_data_lock);
1170         return ret;
1171 }
1172
1173 /**
1174  * Retrieve integer value from environment variable.
1175  *
1176  * @param[in] name
1177  *   Environment variable name.
1178  *
1179  * @return
1180  *   Integer value, 0 if the variable is not set.
1181  */
1182 int
1183 mlx5_getenv_int(const char *name)
1184 {
1185         const char *val = getenv(name);
1186
1187         if (val == NULL)
1188                 return 0;
1189         return atoi(val);
1190 }
1191
1192 /**
1193  * Verbs callback to allocate a memory. This function should allocate the space
1194  * according to the size provided residing inside a huge page.
1195  * Please note that all allocation must respect the alignment from libmlx5
1196  * (i.e. currently sysconf(_SC_PAGESIZE)).
1197  *
1198  * @param[in] size
1199  *   The size in bytes of the memory to allocate.
1200  * @param[in] data
1201  *   A pointer to the callback data.
1202  *
1203  * @return
1204  *   Allocated buffer, NULL otherwise and rte_errno is set.
1205  */
1206 static void *
1207 mlx5_alloc_verbs_buf(size_t size, void *data)
1208 {
1209         struct mlx5_priv *priv = data;
1210         void *ret;
1211         size_t alignment = sysconf(_SC_PAGESIZE);
1212         unsigned int socket = SOCKET_ID_ANY;
1213
1214         if (priv->verbs_alloc_ctx.type == MLX5_VERBS_ALLOC_TYPE_TX_QUEUE) {
1215                 const struct mlx5_txq_ctrl *ctrl = priv->verbs_alloc_ctx.obj;
1216
1217                 socket = ctrl->socket;
1218         } else if (priv->verbs_alloc_ctx.type ==
1219                    MLX5_VERBS_ALLOC_TYPE_RX_QUEUE) {
1220                 const struct mlx5_rxq_ctrl *ctrl = priv->verbs_alloc_ctx.obj;
1221
1222                 socket = ctrl->socket;
1223         }
1224         MLX5_ASSERT(data != NULL);
1225         ret = rte_malloc_socket(__func__, size, alignment, socket);
1226         if (!ret && size)
1227                 rte_errno = ENOMEM;
1228         return ret;
1229 }
1230
1231 /**
1232  * Verbs callback to free a memory.
1233  *
1234  * @param[in] ptr
1235  *   A pointer to the memory to free.
1236  * @param[in] data
1237  *   A pointer to the callback data.
1238  */
1239 static void
1240 mlx5_free_verbs_buf(void *ptr, void *data __rte_unused)
1241 {
1242         MLX5_ASSERT(data != NULL);
1243         rte_free(ptr);
1244 }
1245
1246 /**
1247  * DPDK callback to add udp tunnel port
1248  *
1249  * @param[in] dev
1250  *   A pointer to eth_dev
1251  * @param[in] udp_tunnel
1252  *   A pointer to udp tunnel
1253  *
1254  * @return
1255  *   0 on valid udp ports and tunnels, -ENOTSUP otherwise.
1256  */
1257 int
1258 mlx5_udp_tunnel_port_add(struct rte_eth_dev *dev __rte_unused,
1259                          struct rte_eth_udp_tunnel *udp_tunnel)
1260 {
1261         MLX5_ASSERT(udp_tunnel != NULL);
1262         if (udp_tunnel->prot_type == RTE_TUNNEL_TYPE_VXLAN &&
1263             udp_tunnel->udp_port == 4789)
1264                 return 0;
1265         if (udp_tunnel->prot_type == RTE_TUNNEL_TYPE_VXLAN_GPE &&
1266             udp_tunnel->udp_port == 4790)
1267                 return 0;
1268         return -ENOTSUP;
1269 }
1270
1271 /**
1272  * Initialize process private data structure.
1273  *
1274  * @param dev
1275  *   Pointer to Ethernet device structure.
1276  *
1277  * @return
1278  *   0 on success, a negative errno value otherwise and rte_errno is set.
1279  */
1280 int
1281 mlx5_proc_priv_init(struct rte_eth_dev *dev)
1282 {
1283         struct mlx5_priv *priv = dev->data->dev_private;
1284         struct mlx5_proc_priv *ppriv;
1285         size_t ppriv_size;
1286
1287         /*
1288          * UAR register table follows the process private structure. BlueFlame
1289          * registers for Tx queues are stored in the table.
1290          */
1291         ppriv_size =
1292                 sizeof(struct mlx5_proc_priv) + priv->txqs_n * sizeof(void *);
1293         ppriv = rte_malloc_socket("mlx5_proc_priv", ppriv_size,
1294                                   RTE_CACHE_LINE_SIZE, dev->device->numa_node);
1295         if (!ppriv) {
1296                 rte_errno = ENOMEM;
1297                 return -rte_errno;
1298         }
1299         ppriv->uar_table_sz = ppriv_size;
1300         dev->process_private = ppriv;
1301         return 0;
1302 }
1303
1304 /**
1305  * Un-initialize process private data structure.
1306  *
1307  * @param dev
1308  *   Pointer to Ethernet device structure.
1309  */
1310 static void
1311 mlx5_proc_priv_uninit(struct rte_eth_dev *dev)
1312 {
1313         if (!dev->process_private)
1314                 return;
1315         rte_free(dev->process_private);
1316         dev->process_private = NULL;
1317 }
1318
1319 /**
1320  * DPDK callback to close the device.
1321  *
1322  * Destroy all queues and objects, free memory.
1323  *
1324  * @param dev
1325  *   Pointer to Ethernet device structure.
1326  */
1327 static void
1328 mlx5_dev_close(struct rte_eth_dev *dev)
1329 {
1330         struct mlx5_priv *priv = dev->data->dev_private;
1331         unsigned int i;
1332         int ret;
1333
1334         DRV_LOG(DEBUG, "port %u closing device \"%s\"",
1335                 dev->data->port_id,
1336                 ((priv->sh->ctx != NULL) ? priv->sh->ctx->device->name : ""));
1337         /* In case mlx5_dev_stop() has not been called. */
1338         mlx5_dev_interrupt_handler_uninstall(dev);
1339         mlx5_dev_interrupt_handler_devx_uninstall(dev);
1340         /*
1341          * If default mreg copy action is removed at the stop stage,
1342          * the search will return none and nothing will be done anymore.
1343          */
1344         mlx5_flow_stop_default(dev);
1345         mlx5_traffic_disable(dev);
1346         /*
1347          * If all the flows are already flushed in the device stop stage,
1348          * then this will return directly without any action.
1349          */
1350         mlx5_flow_list_flush(dev, &priv->flows, true);
1351         mlx5_flow_meter_flush(dev, NULL);
1352         /* Free the intermediate buffers for flow creation. */
1353         mlx5_flow_free_intermediate(dev);
1354         /* Prevent crashes when queues are still in use. */
1355         dev->rx_pkt_burst = removed_rx_burst;
1356         dev->tx_pkt_burst = removed_tx_burst;
1357         rte_wmb();
1358         /* Disable datapath on secondary process. */
1359         mlx5_mp_req_stop_rxtx(dev);
1360         if (priv->rxqs != NULL) {
1361                 /* XXX race condition if mlx5_rx_burst() is still running. */
1362                 usleep(1000);
1363                 for (i = 0; (i != priv->rxqs_n); ++i)
1364                         mlx5_rxq_release(dev, i);
1365                 priv->rxqs_n = 0;
1366                 priv->rxqs = NULL;
1367         }
1368         if (priv->txqs != NULL) {
1369                 /* XXX race condition if mlx5_tx_burst() is still running. */
1370                 usleep(1000);
1371                 for (i = 0; (i != priv->txqs_n); ++i)
1372                         mlx5_txq_release(dev, i);
1373                 priv->txqs_n = 0;
1374                 priv->txqs = NULL;
1375         }
1376         mlx5_proc_priv_uninit(dev);
1377         if (priv->mreg_cp_tbl)
1378                 mlx5_hlist_destroy(priv->mreg_cp_tbl, NULL, NULL);
1379         mlx5_mprq_free_mp(dev);
1380         mlx5_free_shared_dr(priv);
1381         if (priv->rss_conf.rss_key != NULL)
1382                 rte_free(priv->rss_conf.rss_key);
1383         if (priv->reta_idx != NULL)
1384                 rte_free(priv->reta_idx);
1385         if (priv->config.vf)
1386                 mlx5_nl_mac_addr_flush(priv->nl_socket_route, mlx5_ifindex(dev),
1387                                        dev->data->mac_addrs,
1388                                        MLX5_MAX_MAC_ADDRESSES, priv->mac_own);
1389         if (priv->nl_socket_route >= 0)
1390                 close(priv->nl_socket_route);
1391         if (priv->nl_socket_rdma >= 0)
1392                 close(priv->nl_socket_rdma);
1393         if (priv->vmwa_context)
1394                 mlx5_vlan_vmwa_exit(priv->vmwa_context);
1395         if (priv->sh) {
1396                 /*
1397                  * Free the shared context in last turn, because the cleanup
1398                  * routines above may use some shared fields, like
1399                  * mlx5_nl_mac_addr_flush() uses ibdev_path for retrieveing
1400                  * ifindex if Netlink fails.
1401                  */
1402                 mlx5_free_shared_ibctx(priv->sh);
1403                 priv->sh = NULL;
1404         }
1405         ret = mlx5_hrxq_verify(dev);
1406         if (ret)
1407                 DRV_LOG(WARNING, "port %u some hash Rx queue still remain",
1408                         dev->data->port_id);
1409         ret = mlx5_ind_table_obj_verify(dev);
1410         if (ret)
1411                 DRV_LOG(WARNING, "port %u some indirection table still remain",
1412                         dev->data->port_id);
1413         ret = mlx5_rxq_obj_verify(dev);
1414         if (ret)
1415                 DRV_LOG(WARNING, "port %u some Rx queue objects still remain",
1416                         dev->data->port_id);
1417         ret = mlx5_rxq_verify(dev);
1418         if (ret)
1419                 DRV_LOG(WARNING, "port %u some Rx queues still remain",
1420                         dev->data->port_id);
1421         ret = mlx5_txq_obj_verify(dev);
1422         if (ret)
1423                 DRV_LOG(WARNING, "port %u some Verbs Tx queue still remain",
1424                         dev->data->port_id);
1425         ret = mlx5_txq_verify(dev);
1426         if (ret)
1427                 DRV_LOG(WARNING, "port %u some Tx queues still remain",
1428                         dev->data->port_id);
1429         ret = mlx5_flow_verify(dev);
1430         if (ret)
1431                 DRV_LOG(WARNING, "port %u some flows still remain",
1432                         dev->data->port_id);
1433         if (priv->domain_id != RTE_ETH_DEV_SWITCH_DOMAIN_ID_INVALID) {
1434                 unsigned int c = 0;
1435                 uint16_t port_id;
1436
1437                 MLX5_ETH_FOREACH_DEV(port_id, priv->pci_dev) {
1438                         struct mlx5_priv *opriv =
1439                                 rte_eth_devices[port_id].data->dev_private;
1440
1441                         if (!opriv ||
1442                             opriv->domain_id != priv->domain_id ||
1443                             &rte_eth_devices[port_id] == dev)
1444                                 continue;
1445                         ++c;
1446                         break;
1447                 }
1448                 if (!c)
1449                         claim_zero(rte_eth_switch_domain_free(priv->domain_id));
1450         }
1451         memset(priv, 0, sizeof(*priv));
1452         priv->domain_id = RTE_ETH_DEV_SWITCH_DOMAIN_ID_INVALID;
1453         /*
1454          * Reset mac_addrs to NULL such that it is not freed as part of
1455          * rte_eth_dev_release_port(). mac_addrs is part of dev_private so
1456          * it is freed when dev_private is freed.
1457          */
1458         dev->data->mac_addrs = NULL;
1459 }
1460
1461 const struct eth_dev_ops mlx5_dev_ops = {
1462         .dev_configure = mlx5_dev_configure,
1463         .dev_start = mlx5_dev_start,
1464         .dev_stop = mlx5_dev_stop,
1465         .dev_set_link_down = mlx5_set_link_down,
1466         .dev_set_link_up = mlx5_set_link_up,
1467         .dev_close = mlx5_dev_close,
1468         .promiscuous_enable = mlx5_promiscuous_enable,
1469         .promiscuous_disable = mlx5_promiscuous_disable,
1470         .allmulticast_enable = mlx5_allmulticast_enable,
1471         .allmulticast_disable = mlx5_allmulticast_disable,
1472         .link_update = mlx5_link_update,
1473         .stats_get = mlx5_stats_get,
1474         .stats_reset = mlx5_stats_reset,
1475         .xstats_get = mlx5_xstats_get,
1476         .xstats_reset = mlx5_xstats_reset,
1477         .xstats_get_names = mlx5_xstats_get_names,
1478         .fw_version_get = mlx5_fw_version_get,
1479         .dev_infos_get = mlx5_dev_infos_get,
1480         .read_clock = mlx5_read_clock,
1481         .dev_supported_ptypes_get = mlx5_dev_supported_ptypes_get,
1482         .vlan_filter_set = mlx5_vlan_filter_set,
1483         .rx_queue_setup = mlx5_rx_queue_setup,
1484         .rx_hairpin_queue_setup = mlx5_rx_hairpin_queue_setup,
1485         .tx_queue_setup = mlx5_tx_queue_setup,
1486         .tx_hairpin_queue_setup = mlx5_tx_hairpin_queue_setup,
1487         .rx_queue_release = mlx5_rx_queue_release,
1488         .tx_queue_release = mlx5_tx_queue_release,
1489         .flow_ctrl_get = mlx5_dev_get_flow_ctrl,
1490         .flow_ctrl_set = mlx5_dev_set_flow_ctrl,
1491         .mac_addr_remove = mlx5_mac_addr_remove,
1492         .mac_addr_add = mlx5_mac_addr_add,
1493         .mac_addr_set = mlx5_mac_addr_set,
1494         .set_mc_addr_list = mlx5_set_mc_addr_list,
1495         .mtu_set = mlx5_dev_set_mtu,
1496         .vlan_strip_queue_set = mlx5_vlan_strip_queue_set,
1497         .vlan_offload_set = mlx5_vlan_offload_set,
1498         .reta_update = mlx5_dev_rss_reta_update,
1499         .reta_query = mlx5_dev_rss_reta_query,
1500         .rss_hash_update = mlx5_rss_hash_update,
1501         .rss_hash_conf_get = mlx5_rss_hash_conf_get,
1502         .filter_ctrl = mlx5_dev_filter_ctrl,
1503         .rx_descriptor_status = mlx5_rx_descriptor_status,
1504         .tx_descriptor_status = mlx5_tx_descriptor_status,
1505         .rxq_info_get = mlx5_rxq_info_get,
1506         .txq_info_get = mlx5_txq_info_get,
1507         .rx_burst_mode_get = mlx5_rx_burst_mode_get,
1508         .tx_burst_mode_get = mlx5_tx_burst_mode_get,
1509         .rx_queue_count = mlx5_rx_queue_count,
1510         .rx_queue_intr_enable = mlx5_rx_intr_enable,
1511         .rx_queue_intr_disable = mlx5_rx_intr_disable,
1512         .is_removed = mlx5_is_removed,
1513         .udp_tunnel_port_add  = mlx5_udp_tunnel_port_add,
1514         .get_module_info = mlx5_get_module_info,
1515         .get_module_eeprom = mlx5_get_module_eeprom,
1516         .hairpin_cap_get = mlx5_hairpin_cap_get,
1517         .mtr_ops_get = mlx5_flow_meter_ops_get,
1518 };
1519
1520 /* Available operations from secondary process. */
1521 static const struct eth_dev_ops mlx5_dev_sec_ops = {
1522         .stats_get = mlx5_stats_get,
1523         .stats_reset = mlx5_stats_reset,
1524         .xstats_get = mlx5_xstats_get,
1525         .xstats_reset = mlx5_xstats_reset,
1526         .xstats_get_names = mlx5_xstats_get_names,
1527         .fw_version_get = mlx5_fw_version_get,
1528         .dev_infos_get = mlx5_dev_infos_get,
1529         .rx_descriptor_status = mlx5_rx_descriptor_status,
1530         .tx_descriptor_status = mlx5_tx_descriptor_status,
1531         .rxq_info_get = mlx5_rxq_info_get,
1532         .txq_info_get = mlx5_txq_info_get,
1533         .rx_burst_mode_get = mlx5_rx_burst_mode_get,
1534         .tx_burst_mode_get = mlx5_tx_burst_mode_get,
1535         .get_module_info = mlx5_get_module_info,
1536         .get_module_eeprom = mlx5_get_module_eeprom,
1537 };
1538
1539 /* Available operations in flow isolated mode. */
1540 const struct eth_dev_ops mlx5_dev_ops_isolate = {
1541         .dev_configure = mlx5_dev_configure,
1542         .dev_start = mlx5_dev_start,
1543         .dev_stop = mlx5_dev_stop,
1544         .dev_set_link_down = mlx5_set_link_down,
1545         .dev_set_link_up = mlx5_set_link_up,
1546         .dev_close = mlx5_dev_close,
1547         .promiscuous_enable = mlx5_promiscuous_enable,
1548         .promiscuous_disable = mlx5_promiscuous_disable,
1549         .allmulticast_enable = mlx5_allmulticast_enable,
1550         .allmulticast_disable = mlx5_allmulticast_disable,
1551         .link_update = mlx5_link_update,
1552         .stats_get = mlx5_stats_get,
1553         .stats_reset = mlx5_stats_reset,
1554         .xstats_get = mlx5_xstats_get,
1555         .xstats_reset = mlx5_xstats_reset,
1556         .xstats_get_names = mlx5_xstats_get_names,
1557         .fw_version_get = mlx5_fw_version_get,
1558         .dev_infos_get = mlx5_dev_infos_get,
1559         .dev_supported_ptypes_get = mlx5_dev_supported_ptypes_get,
1560         .vlan_filter_set = mlx5_vlan_filter_set,
1561         .rx_queue_setup = mlx5_rx_queue_setup,
1562         .rx_hairpin_queue_setup = mlx5_rx_hairpin_queue_setup,
1563         .tx_queue_setup = mlx5_tx_queue_setup,
1564         .tx_hairpin_queue_setup = mlx5_tx_hairpin_queue_setup,
1565         .rx_queue_release = mlx5_rx_queue_release,
1566         .tx_queue_release = mlx5_tx_queue_release,
1567         .flow_ctrl_get = mlx5_dev_get_flow_ctrl,
1568         .flow_ctrl_set = mlx5_dev_set_flow_ctrl,
1569         .mac_addr_remove = mlx5_mac_addr_remove,
1570         .mac_addr_add = mlx5_mac_addr_add,
1571         .mac_addr_set = mlx5_mac_addr_set,
1572         .set_mc_addr_list = mlx5_set_mc_addr_list,
1573         .mtu_set = mlx5_dev_set_mtu,
1574         .vlan_strip_queue_set = mlx5_vlan_strip_queue_set,
1575         .vlan_offload_set = mlx5_vlan_offload_set,
1576         .filter_ctrl = mlx5_dev_filter_ctrl,
1577         .rx_descriptor_status = mlx5_rx_descriptor_status,
1578         .tx_descriptor_status = mlx5_tx_descriptor_status,
1579         .rxq_info_get = mlx5_rxq_info_get,
1580         .txq_info_get = mlx5_txq_info_get,
1581         .rx_burst_mode_get = mlx5_rx_burst_mode_get,
1582         .tx_burst_mode_get = mlx5_tx_burst_mode_get,
1583         .rx_queue_intr_enable = mlx5_rx_intr_enable,
1584         .rx_queue_intr_disable = mlx5_rx_intr_disable,
1585         .is_removed = mlx5_is_removed,
1586         .get_module_info = mlx5_get_module_info,
1587         .get_module_eeprom = mlx5_get_module_eeprom,
1588         .hairpin_cap_get = mlx5_hairpin_cap_get,
1589         .mtr_ops_get = mlx5_flow_meter_ops_get,
1590 };
1591
1592 /**
1593  * Verify and store value for device argument.
1594  *
1595  * @param[in] key
1596  *   Key argument to verify.
1597  * @param[in] val
1598  *   Value associated with key.
1599  * @param opaque
1600  *   User data.
1601  *
1602  * @return
1603  *   0 on success, a negative errno value otherwise and rte_errno is set.
1604  */
1605 static int
1606 mlx5_args_check(const char *key, const char *val, void *opaque)
1607 {
1608         struct mlx5_dev_config *config = opaque;
1609         unsigned long tmp;
1610
1611         /* No-op, port representors are processed in mlx5_dev_spawn(). */
1612         if (!strcmp(MLX5_REPRESENTOR, key))
1613                 return 0;
1614         errno = 0;
1615         tmp = strtoul(val, NULL, 0);
1616         if (errno) {
1617                 rte_errno = errno;
1618                 DRV_LOG(WARNING, "%s: \"%s\" is not a valid integer", key, val);
1619                 return -rte_errno;
1620         }
1621         if (strcmp(MLX5_RXQ_CQE_COMP_EN, key) == 0) {
1622                 config->cqe_comp = !!tmp;
1623         } else if (strcmp(MLX5_RXQ_CQE_PAD_EN, key) == 0) {
1624                 config->cqe_pad = !!tmp;
1625         } else if (strcmp(MLX5_RXQ_PKT_PAD_EN, key) == 0) {
1626                 config->hw_padding = !!tmp;
1627         } else if (strcmp(MLX5_RX_MPRQ_EN, key) == 0) {
1628                 config->mprq.enabled = !!tmp;
1629         } else if (strcmp(MLX5_RX_MPRQ_LOG_STRIDE_NUM, key) == 0) {
1630                 config->mprq.stride_num_n = tmp;
1631         } else if (strcmp(MLX5_RX_MPRQ_LOG_STRIDE_SIZE, key) == 0) {
1632                 config->mprq.stride_size_n = tmp;
1633         } else if (strcmp(MLX5_RX_MPRQ_MAX_MEMCPY_LEN, key) == 0) {
1634                 config->mprq.max_memcpy_len = tmp;
1635         } else if (strcmp(MLX5_RXQS_MIN_MPRQ, key) == 0) {
1636                 config->mprq.min_rxqs_num = tmp;
1637         } else if (strcmp(MLX5_TXQ_INLINE, key) == 0) {
1638                 DRV_LOG(WARNING, "%s: deprecated parameter,"
1639                                  " converted to txq_inline_max", key);
1640                 config->txq_inline_max = tmp;
1641         } else if (strcmp(MLX5_TXQ_INLINE_MAX, key) == 0) {
1642                 config->txq_inline_max = tmp;
1643         } else if (strcmp(MLX5_TXQ_INLINE_MIN, key) == 0) {
1644                 config->txq_inline_min = tmp;
1645         } else if (strcmp(MLX5_TXQ_INLINE_MPW, key) == 0) {
1646                 config->txq_inline_mpw = tmp;
1647         } else if (strcmp(MLX5_TXQS_MIN_INLINE, key) == 0) {
1648                 config->txqs_inline = tmp;
1649         } else if (strcmp(MLX5_TXQS_MAX_VEC, key) == 0) {
1650                 DRV_LOG(WARNING, "%s: deprecated parameter, ignored", key);
1651         } else if (strcmp(MLX5_TXQ_MPW_EN, key) == 0) {
1652                 config->mps = !!tmp;
1653         } else if (strcmp(MLX5_TX_DB_NC, key) == 0) {
1654                 if (tmp != MLX5_TXDB_CACHED &&
1655                     tmp != MLX5_TXDB_NCACHED &&
1656                     tmp != MLX5_TXDB_HEURISTIC) {
1657                         DRV_LOG(ERR, "invalid Tx doorbell "
1658                                      "mapping parameter");
1659                         rte_errno = EINVAL;
1660                         return -rte_errno;
1661                 }
1662                 config->dbnc = tmp;
1663         } else if (strcmp(MLX5_TXQ_MPW_HDR_DSEG_EN, key) == 0) {
1664                 DRV_LOG(WARNING, "%s: deprecated parameter, ignored", key);
1665         } else if (strcmp(MLX5_TXQ_MAX_INLINE_LEN, key) == 0) {
1666                 DRV_LOG(WARNING, "%s: deprecated parameter,"
1667                                  " converted to txq_inline_mpw", key);
1668                 config->txq_inline_mpw = tmp;
1669         } else if (strcmp(MLX5_TX_VEC_EN, key) == 0) {
1670                 DRV_LOG(WARNING, "%s: deprecated parameter, ignored", key);
1671         } else if (strcmp(MLX5_RX_VEC_EN, key) == 0) {
1672                 config->rx_vec_en = !!tmp;
1673         } else if (strcmp(MLX5_L3_VXLAN_EN, key) == 0) {
1674                 config->l3_vxlan_en = !!tmp;
1675         } else if (strcmp(MLX5_VF_NL_EN, key) == 0) {
1676                 config->vf_nl_en = !!tmp;
1677         } else if (strcmp(MLX5_DV_ESW_EN, key) == 0) {
1678                 config->dv_esw_en = !!tmp;
1679         } else if (strcmp(MLX5_DV_FLOW_EN, key) == 0) {
1680                 config->dv_flow_en = !!tmp;
1681         } else if (strcmp(MLX5_DV_XMETA_EN, key) == 0) {
1682                 if (tmp != MLX5_XMETA_MODE_LEGACY &&
1683                     tmp != MLX5_XMETA_MODE_META16 &&
1684                     tmp != MLX5_XMETA_MODE_META32) {
1685                         DRV_LOG(ERR, "invalid extensive "
1686                                      "metadata parameter");
1687                         rte_errno = EINVAL;
1688                         return -rte_errno;
1689                 }
1690                 config->dv_xmeta_en = tmp;
1691         } else if (strcmp(MLX5_MR_EXT_MEMSEG_EN, key) == 0) {
1692                 config->mr_ext_memseg_en = !!tmp;
1693         } else if (strcmp(MLX5_MAX_DUMP_FILES_NUM, key) == 0) {
1694                 config->max_dump_files_num = tmp;
1695         } else if (strcmp(MLX5_LRO_TIMEOUT_USEC, key) == 0) {
1696                 config->lro.timeout = tmp;
1697         } else if (strcmp(MLX5_CLASS_ARG_NAME, key) == 0) {
1698                 DRV_LOG(DEBUG, "class argument is %s.", val);
1699         } else if (strcmp(MLX5_HP_BUF_SIZE, key) == 0) {
1700                 config->log_hp_size = tmp;
1701         } else {
1702                 DRV_LOG(WARNING, "%s: unknown parameter", key);
1703                 rte_errno = EINVAL;
1704                 return -rte_errno;
1705         }
1706         return 0;
1707 }
1708
1709 /**
1710  * Parse device parameters.
1711  *
1712  * @param config
1713  *   Pointer to device configuration structure.
1714  * @param devargs
1715  *   Device arguments structure.
1716  *
1717  * @return
1718  *   0 on success, a negative errno value otherwise and rte_errno is set.
1719  */
1720 static int
1721 mlx5_args(struct mlx5_dev_config *config, struct rte_devargs *devargs)
1722 {
1723         const char **params = (const char *[]){
1724                 MLX5_RXQ_CQE_COMP_EN,
1725                 MLX5_RXQ_CQE_PAD_EN,
1726                 MLX5_RXQ_PKT_PAD_EN,
1727                 MLX5_RX_MPRQ_EN,
1728                 MLX5_RX_MPRQ_LOG_STRIDE_NUM,
1729                 MLX5_RX_MPRQ_LOG_STRIDE_SIZE,
1730                 MLX5_RX_MPRQ_MAX_MEMCPY_LEN,
1731                 MLX5_RXQS_MIN_MPRQ,
1732                 MLX5_TXQ_INLINE,
1733                 MLX5_TXQ_INLINE_MIN,
1734                 MLX5_TXQ_INLINE_MAX,
1735                 MLX5_TXQ_INLINE_MPW,
1736                 MLX5_TXQS_MIN_INLINE,
1737                 MLX5_TXQS_MAX_VEC,
1738                 MLX5_TXQ_MPW_EN,
1739                 MLX5_TXQ_MPW_HDR_DSEG_EN,
1740                 MLX5_TXQ_MAX_INLINE_LEN,
1741                 MLX5_TX_DB_NC,
1742                 MLX5_TX_VEC_EN,
1743                 MLX5_RX_VEC_EN,
1744                 MLX5_L3_VXLAN_EN,
1745                 MLX5_VF_NL_EN,
1746                 MLX5_DV_ESW_EN,
1747                 MLX5_DV_FLOW_EN,
1748                 MLX5_DV_XMETA_EN,
1749                 MLX5_MR_EXT_MEMSEG_EN,
1750                 MLX5_REPRESENTOR,
1751                 MLX5_MAX_DUMP_FILES_NUM,
1752                 MLX5_LRO_TIMEOUT_USEC,
1753                 MLX5_CLASS_ARG_NAME,
1754                 MLX5_HP_BUF_SIZE,
1755                 NULL,
1756         };
1757         struct rte_kvargs *kvlist;
1758         int ret = 0;
1759         int i;
1760
1761         if (devargs == NULL)
1762                 return 0;
1763         /* Following UGLY cast is done to pass checkpatch. */
1764         kvlist = rte_kvargs_parse(devargs->args, params);
1765         if (kvlist == NULL) {
1766                 rte_errno = EINVAL;
1767                 return -rte_errno;
1768         }
1769         /* Process parameters. */
1770         for (i = 0; (params[i] != NULL); ++i) {
1771                 if (rte_kvargs_count(kvlist, params[i])) {
1772                         ret = rte_kvargs_process(kvlist, params[i],
1773                                                  mlx5_args_check, config);
1774                         if (ret) {
1775                                 rte_errno = EINVAL;
1776                                 rte_kvargs_free(kvlist);
1777                                 return -rte_errno;
1778                         }
1779                 }
1780         }
1781         rte_kvargs_free(kvlist);
1782         return 0;
1783 }
1784
1785 static struct rte_pci_driver mlx5_driver;
1786
1787 /**
1788  * PMD global initialization.
1789  *
1790  * Independent from individual device, this function initializes global
1791  * per-PMD data structures distinguishing primary and secondary processes.
1792  * Hence, each initialization is called once per a process.
1793  *
1794  * @return
1795  *   0 on success, a negative errno value otherwise and rte_errno is set.
1796  */
1797 static int
1798 mlx5_init_once(void)
1799 {
1800         struct mlx5_shared_data *sd;
1801         struct mlx5_local_data *ld = &mlx5_local_data;
1802         int ret = 0;
1803
1804         if (mlx5_init_shared_data())
1805                 return -rte_errno;
1806         sd = mlx5_shared_data;
1807         MLX5_ASSERT(sd);
1808         rte_spinlock_lock(&sd->lock);
1809         switch (rte_eal_process_type()) {
1810         case RTE_PROC_PRIMARY:
1811                 if (sd->init_done)
1812                         break;
1813                 LIST_INIT(&sd->mem_event_cb_list);
1814                 rte_rwlock_init(&sd->mem_event_rwlock);
1815                 rte_mem_event_callback_register("MLX5_MEM_EVENT_CB",
1816                                                 mlx5_mr_mem_event_cb, NULL);
1817                 ret = mlx5_mp_init_primary(MLX5_MP_NAME,
1818                                            mlx5_mp_primary_handle);
1819                 if (ret)
1820                         goto out;
1821                 sd->init_done = true;
1822                 break;
1823         case RTE_PROC_SECONDARY:
1824                 if (ld->init_done)
1825                         break;
1826                 ret = mlx5_mp_init_secondary(MLX5_MP_NAME,
1827                                              mlx5_mp_secondary_handle);
1828                 if (ret)
1829                         goto out;
1830                 ++sd->secondary_cnt;
1831                 ld->init_done = true;
1832                 break;
1833         default:
1834                 break;
1835         }
1836 out:
1837         rte_spinlock_unlock(&sd->lock);
1838         return ret;
1839 }
1840
1841 /**
1842  * Configures the minimal amount of data to inline into WQE
1843  * while sending packets.
1844  *
1845  * - the txq_inline_min has the maximal priority, if this
1846  *   key is specified in devargs
1847  * - if DevX is enabled the inline mode is queried from the
1848  *   device (HCA attributes and NIC vport context if needed).
1849  * - otherwise L2 mode (18 bytes) is assumed for ConnectX-4/4 Lx
1850  *   and none (0 bytes) for other NICs
1851  *
1852  * @param spawn
1853  *   Verbs device parameters (name, port, switch_info) to spawn.
1854  * @param config
1855  *   Device configuration parameters.
1856  */
1857 static void
1858 mlx5_set_min_inline(struct mlx5_dev_spawn_data *spawn,
1859                     struct mlx5_dev_config *config)
1860 {
1861         if (config->txq_inline_min != MLX5_ARG_UNSET) {
1862                 /* Application defines size of inlined data explicitly. */
1863                 switch (spawn->pci_dev->id.device_id) {
1864                 case PCI_DEVICE_ID_MELLANOX_CONNECTX4:
1865                 case PCI_DEVICE_ID_MELLANOX_CONNECTX4VF:
1866                         if (config->txq_inline_min <
1867                                        (int)MLX5_INLINE_HSIZE_L2) {
1868                                 DRV_LOG(DEBUG,
1869                                         "txq_inline_mix aligned to minimal"
1870                                         " ConnectX-4 required value %d",
1871                                         (int)MLX5_INLINE_HSIZE_L2);
1872                                 config->txq_inline_min = MLX5_INLINE_HSIZE_L2;
1873                         }
1874                         break;
1875                 }
1876                 goto exit;
1877         }
1878         if (config->hca_attr.eth_net_offloads) {
1879                 /* We have DevX enabled, inline mode queried successfully. */
1880                 switch (config->hca_attr.wqe_inline_mode) {
1881                 case MLX5_CAP_INLINE_MODE_L2:
1882                         /* outer L2 header must be inlined. */
1883                         config->txq_inline_min = MLX5_INLINE_HSIZE_L2;
1884                         goto exit;
1885                 case MLX5_CAP_INLINE_MODE_NOT_REQUIRED:
1886                         /* No inline data are required by NIC. */
1887                         config->txq_inline_min = MLX5_INLINE_HSIZE_NONE;
1888                         config->hw_vlan_insert =
1889                                 config->hca_attr.wqe_vlan_insert;
1890                         DRV_LOG(DEBUG, "Tx VLAN insertion is supported");
1891                         goto exit;
1892                 case MLX5_CAP_INLINE_MODE_VPORT_CONTEXT:
1893                         /* inline mode is defined by NIC vport context. */
1894                         if (!config->hca_attr.eth_virt)
1895                                 break;
1896                         switch (config->hca_attr.vport_inline_mode) {
1897                         case MLX5_INLINE_MODE_NONE:
1898                                 config->txq_inline_min =
1899                                         MLX5_INLINE_HSIZE_NONE;
1900                                 goto exit;
1901                         case MLX5_INLINE_MODE_L2:
1902                                 config->txq_inline_min =
1903                                         MLX5_INLINE_HSIZE_L2;
1904                                 goto exit;
1905                         case MLX5_INLINE_MODE_IP:
1906                                 config->txq_inline_min =
1907                                         MLX5_INLINE_HSIZE_L3;
1908                                 goto exit;
1909                         case MLX5_INLINE_MODE_TCP_UDP:
1910                                 config->txq_inline_min =
1911                                         MLX5_INLINE_HSIZE_L4;
1912                                 goto exit;
1913                         case MLX5_INLINE_MODE_INNER_L2:
1914                                 config->txq_inline_min =
1915                                         MLX5_INLINE_HSIZE_INNER_L2;
1916                                 goto exit;
1917                         case MLX5_INLINE_MODE_INNER_IP:
1918                                 config->txq_inline_min =
1919                                         MLX5_INLINE_HSIZE_INNER_L3;
1920                                 goto exit;
1921                         case MLX5_INLINE_MODE_INNER_TCP_UDP:
1922                                 config->txq_inline_min =
1923                                         MLX5_INLINE_HSIZE_INNER_L4;
1924                                 goto exit;
1925                         }
1926                 }
1927         }
1928         /*
1929          * We get here if we are unable to deduce
1930          * inline data size with DevX. Try PCI ID
1931          * to determine old NICs.
1932          */
1933         switch (spawn->pci_dev->id.device_id) {
1934         case PCI_DEVICE_ID_MELLANOX_CONNECTX4:
1935         case PCI_DEVICE_ID_MELLANOX_CONNECTX4VF:
1936         case PCI_DEVICE_ID_MELLANOX_CONNECTX4LX:
1937         case PCI_DEVICE_ID_MELLANOX_CONNECTX4LXVF:
1938                 config->txq_inline_min = MLX5_INLINE_HSIZE_L2;
1939                 config->hw_vlan_insert = 0;
1940                 break;
1941         case PCI_DEVICE_ID_MELLANOX_CONNECTX5:
1942         case PCI_DEVICE_ID_MELLANOX_CONNECTX5VF:
1943         case PCI_DEVICE_ID_MELLANOX_CONNECTX5EX:
1944         case PCI_DEVICE_ID_MELLANOX_CONNECTX5EXVF:
1945                 /*
1946                  * These NICs support VLAN insertion from WQE and
1947                  * report the wqe_vlan_insert flag. But there is the bug
1948                  * and PFC control may be broken, so disable feature.
1949                  */
1950                 config->hw_vlan_insert = 0;
1951                 config->txq_inline_min = MLX5_INLINE_HSIZE_NONE;
1952                 break;
1953         default:
1954                 config->txq_inline_min = MLX5_INLINE_HSIZE_NONE;
1955                 break;
1956         }
1957 exit:
1958         DRV_LOG(DEBUG, "min tx inline configured: %d", config->txq_inline_min);
1959 }
1960
1961 /**
1962  * Configures the metadata mask fields in the shared context.
1963  *
1964  * @param [in] dev
1965  *   Pointer to Ethernet device.
1966  */
1967 static void
1968 mlx5_set_metadata_mask(struct rte_eth_dev *dev)
1969 {
1970         struct mlx5_priv *priv = dev->data->dev_private;
1971         struct mlx5_ibv_shared *sh = priv->sh;
1972         uint32_t meta, mark, reg_c0;
1973
1974         reg_c0 = ~priv->vport_meta_mask;
1975         switch (priv->config.dv_xmeta_en) {
1976         case MLX5_XMETA_MODE_LEGACY:
1977                 meta = UINT32_MAX;
1978                 mark = MLX5_FLOW_MARK_MASK;
1979                 break;
1980         case MLX5_XMETA_MODE_META16:
1981                 meta = reg_c0 >> rte_bsf32(reg_c0);
1982                 mark = MLX5_FLOW_MARK_MASK;
1983                 break;
1984         case MLX5_XMETA_MODE_META32:
1985                 meta = UINT32_MAX;
1986                 mark = (reg_c0 >> rte_bsf32(reg_c0)) & MLX5_FLOW_MARK_MASK;
1987                 break;
1988         default:
1989                 meta = 0;
1990                 mark = 0;
1991                 MLX5_ASSERT(false);
1992                 break;
1993         }
1994         if (sh->dv_mark_mask && sh->dv_mark_mask != mark)
1995                 DRV_LOG(WARNING, "metadata MARK mask mismatche %08X:%08X",
1996                                  sh->dv_mark_mask, mark);
1997         else
1998                 sh->dv_mark_mask = mark;
1999         if (sh->dv_meta_mask && sh->dv_meta_mask != meta)
2000                 DRV_LOG(WARNING, "metadata META mask mismatche %08X:%08X",
2001                                  sh->dv_meta_mask, meta);
2002         else
2003                 sh->dv_meta_mask = meta;
2004         if (sh->dv_regc0_mask && sh->dv_regc0_mask != reg_c0)
2005                 DRV_LOG(WARNING, "metadata reg_c0 mask mismatche %08X:%08X",
2006                                  sh->dv_meta_mask, reg_c0);
2007         else
2008                 sh->dv_regc0_mask = reg_c0;
2009         DRV_LOG(DEBUG, "metadata mode %u", priv->config.dv_xmeta_en);
2010         DRV_LOG(DEBUG, "metadata MARK mask %08X", sh->dv_mark_mask);
2011         DRV_LOG(DEBUG, "metadata META mask %08X", sh->dv_meta_mask);
2012         DRV_LOG(DEBUG, "metadata reg_c0 mask %08X", sh->dv_regc0_mask);
2013 }
2014
2015 /**
2016  * Allocate page of door-bells and register it using DevX API.
2017  *
2018  * @param [in] dev
2019  *   Pointer to Ethernet device.
2020  *
2021  * @return
2022  *   Pointer to new page on success, NULL otherwise.
2023  */
2024 static struct mlx5_devx_dbr_page *
2025 mlx5_alloc_dbr_page(struct rte_eth_dev *dev)
2026 {
2027         struct mlx5_priv *priv = dev->data->dev_private;
2028         struct mlx5_devx_dbr_page *page;
2029
2030         /* Allocate space for door-bell page and management data. */
2031         page = rte_calloc_socket(__func__, 1, sizeof(struct mlx5_devx_dbr_page),
2032                                  RTE_CACHE_LINE_SIZE, dev->device->numa_node);
2033         if (!page) {
2034                 DRV_LOG(ERR, "port %u cannot allocate dbr page",
2035                         dev->data->port_id);
2036                 return NULL;
2037         }
2038         /* Register allocated memory. */
2039         page->umem = mlx5_glue->devx_umem_reg(priv->sh->ctx, page->dbrs,
2040                                               MLX5_DBR_PAGE_SIZE, 0);
2041         if (!page->umem) {
2042                 DRV_LOG(ERR, "port %u cannot umem reg dbr page",
2043                         dev->data->port_id);
2044                 rte_free(page);
2045                 return NULL;
2046         }
2047         return page;
2048 }
2049
2050 /**
2051  * Find the next available door-bell, allocate new page if needed.
2052  *
2053  * @param [in] dev
2054  *   Pointer to Ethernet device.
2055  * @param [out] dbr_page
2056  *   Door-bell page containing the page data.
2057  *
2058  * @return
2059  *   Door-bell address offset on success, a negative error value otherwise.
2060  */
2061 int64_t
2062 mlx5_get_dbr(struct rte_eth_dev *dev, struct mlx5_devx_dbr_page **dbr_page)
2063 {
2064         struct mlx5_priv *priv = dev->data->dev_private;
2065         struct mlx5_devx_dbr_page *page = NULL;
2066         uint32_t i, j;
2067
2068         LIST_FOREACH(page, &priv->dbrpgs, next)
2069                 if (page->dbr_count < MLX5_DBR_PER_PAGE)
2070                         break;
2071         if (!page) { /* No page with free door-bell exists. */
2072                 page = mlx5_alloc_dbr_page(dev);
2073                 if (!page) /* Failed to allocate new page. */
2074                         return (-1);
2075                 LIST_INSERT_HEAD(&priv->dbrpgs, page, next);
2076         }
2077         /* Loop to find bitmap part with clear bit. */
2078         for (i = 0;
2079              i < MLX5_DBR_BITMAP_SIZE && page->dbr_bitmap[i] == UINT64_MAX;
2080              i++)
2081                 ; /* Empty. */
2082         /* Find the first clear bit. */
2083         j = rte_bsf64(~page->dbr_bitmap[i]);
2084         MLX5_ASSERT(i < (MLX5_DBR_PER_PAGE / 64));
2085         page->dbr_bitmap[i] |= (1 << j);
2086         page->dbr_count++;
2087         *dbr_page = page;
2088         return (((i * 64) + j) * sizeof(uint64_t));
2089 }
2090
2091 /**
2092  * Release a door-bell record.
2093  *
2094  * @param [in] dev
2095  *   Pointer to Ethernet device.
2096  * @param [in] umem_id
2097  *   UMEM ID of page containing the door-bell record to release.
2098  * @param [in] offset
2099  *   Offset of door-bell record in page.
2100  *
2101  * @return
2102  *   0 on success, a negative error value otherwise.
2103  */
2104 int32_t
2105 mlx5_release_dbr(struct rte_eth_dev *dev, uint32_t umem_id, uint64_t offset)
2106 {
2107         struct mlx5_priv *priv = dev->data->dev_private;
2108         struct mlx5_devx_dbr_page *page = NULL;
2109         int ret = 0;
2110
2111         LIST_FOREACH(page, &priv->dbrpgs, next)
2112                 /* Find the page this address belongs to. */
2113                 if (page->umem->umem_id == umem_id)
2114                         break;
2115         if (!page)
2116                 return -EINVAL;
2117         page->dbr_count--;
2118         if (!page->dbr_count) {
2119                 /* Page not used, free it and remove from list. */
2120                 LIST_REMOVE(page, next);
2121                 if (page->umem)
2122                         ret = -mlx5_glue->devx_umem_dereg(page->umem);
2123                 rte_free(page);
2124         } else {
2125                 /* Mark in bitmap that this door-bell is not in use. */
2126                 offset /= MLX5_DBR_SIZE;
2127                 int i = offset / 64;
2128                 int j = offset % 64;
2129
2130                 page->dbr_bitmap[i] &= ~(1 << j);
2131         }
2132         return ret;
2133 }
2134
2135 int
2136 rte_pmd_mlx5_get_dyn_flag_names(char *names[], unsigned int n)
2137 {
2138         static const char *const dynf_names[] = {
2139                 RTE_PMD_MLX5_FINE_GRANULARITY_INLINE,
2140                 RTE_MBUF_DYNFLAG_METADATA_NAME
2141         };
2142         unsigned int i;
2143
2144         if (n < RTE_DIM(dynf_names))
2145                 return -ENOMEM;
2146         for (i = 0; i < RTE_DIM(dynf_names); i++) {
2147                 if (names[i] == NULL)
2148                         return -EINVAL;
2149                 strcpy(names[i], dynf_names[i]);
2150         }
2151         return RTE_DIM(dynf_names);
2152 }
2153
2154 /**
2155  * Check sibling device configurations.
2156  *
2157  * Sibling devices sharing the Infiniband device context
2158  * should have compatible configurations. This regards
2159  * representors and bonding slaves.
2160  *
2161  * @param priv
2162  *   Private device descriptor.
2163  * @param config
2164  *   Configuration of the device is going to be created.
2165  *
2166  * @return
2167  *   0 on success, EINVAL otherwise
2168  */
2169 static int
2170 mlx5_dev_check_sibling_config(struct mlx5_priv *priv,
2171                               struct mlx5_dev_config *config)
2172 {
2173         struct mlx5_ibv_shared *sh = priv->sh;
2174         struct mlx5_dev_config *sh_conf = NULL;
2175         uint16_t port_id;
2176
2177         MLX5_ASSERT(sh);
2178         /* Nothing to compare for the single/first device. */
2179         if (sh->refcnt == 1)
2180                 return 0;
2181         /* Find the device with shared context. */
2182         MLX5_ETH_FOREACH_DEV(port_id, priv->pci_dev) {
2183                 struct mlx5_priv *opriv =
2184                         rte_eth_devices[port_id].data->dev_private;
2185
2186                 if (opriv && opriv != priv && opriv->sh == sh) {
2187                         sh_conf = &opriv->config;
2188                         break;
2189                 }
2190         }
2191         if (!sh_conf)
2192                 return 0;
2193         if (sh_conf->dv_flow_en ^ config->dv_flow_en) {
2194                 DRV_LOG(ERR, "\"dv_flow_en\" configuration mismatch"
2195                              " for shared %s context", sh->ibdev_name);
2196                 rte_errno = EINVAL;
2197                 return rte_errno;
2198         }
2199         if (sh_conf->dv_xmeta_en ^ config->dv_xmeta_en) {
2200                 DRV_LOG(ERR, "\"dv_xmeta_en\" configuration mismatch"
2201                              " for shared %s context", sh->ibdev_name);
2202                 rte_errno = EINVAL;
2203                 return rte_errno;
2204         }
2205         return 0;
2206 }
2207 /**
2208  * Spawn an Ethernet device from Verbs information.
2209  *
2210  * @param dpdk_dev
2211  *   Backing DPDK device.
2212  * @param spawn
2213  *   Verbs device parameters (name, port, switch_info) to spawn.
2214  * @param config
2215  *   Device configuration parameters.
2216  *
2217  * @return
2218  *   A valid Ethernet device object on success, NULL otherwise and rte_errno
2219  *   is set. The following errors are defined:
2220  *
2221  *   EBUSY: device is not supposed to be spawned.
2222  *   EEXIST: device is already spawned
2223  */
2224 static struct rte_eth_dev *
2225 mlx5_dev_spawn(struct rte_device *dpdk_dev,
2226                struct mlx5_dev_spawn_data *spawn,
2227                struct mlx5_dev_config config)
2228 {
2229         const struct mlx5_switch_info *switch_info = &spawn->info;
2230         struct mlx5_ibv_shared *sh = NULL;
2231         struct ibv_port_attr port_attr;
2232         struct mlx5dv_context dv_attr = { .comp_mask = 0 };
2233         struct rte_eth_dev *eth_dev = NULL;
2234         struct mlx5_priv *priv = NULL;
2235         int err = 0;
2236         unsigned int hw_padding = 0;
2237         unsigned int mps;
2238         unsigned int cqe_comp;
2239         unsigned int cqe_pad = 0;
2240         unsigned int tunnel_en = 0;
2241         unsigned int mpls_en = 0;
2242         unsigned int swp = 0;
2243         unsigned int mprq = 0;
2244         unsigned int mprq_min_stride_size_n = 0;
2245         unsigned int mprq_max_stride_size_n = 0;
2246         unsigned int mprq_min_stride_num_n = 0;
2247         unsigned int mprq_max_stride_num_n = 0;
2248         struct rte_ether_addr mac;
2249         char name[RTE_ETH_NAME_MAX_LEN];
2250         int own_domain_id = 0;
2251         uint16_t port_id;
2252         unsigned int i;
2253 #ifdef HAVE_MLX5DV_DR_DEVX_PORT
2254         struct mlx5dv_devx_port devx_port = { .comp_mask = 0 };
2255 #endif
2256
2257         /* Determine if this port representor is supposed to be spawned. */
2258         if (switch_info->representor && dpdk_dev->devargs) {
2259                 struct rte_eth_devargs eth_da;
2260
2261                 err = rte_eth_devargs_parse(dpdk_dev->devargs->args, &eth_da);
2262                 if (err) {
2263                         rte_errno = -err;
2264                         DRV_LOG(ERR, "failed to process device arguments: %s",
2265                                 strerror(rte_errno));
2266                         return NULL;
2267                 }
2268                 for (i = 0; i < eth_da.nb_representor_ports; ++i)
2269                         if (eth_da.representor_ports[i] ==
2270                             (uint16_t)switch_info->port_name)
2271                                 break;
2272                 if (i == eth_da.nb_representor_ports) {
2273                         rte_errno = EBUSY;
2274                         return NULL;
2275                 }
2276         }
2277         /* Build device name. */
2278         if (spawn->pf_bond <  0) {
2279                 /* Single device. */
2280                 if (!switch_info->representor)
2281                         strlcpy(name, dpdk_dev->name, sizeof(name));
2282                 else
2283                         snprintf(name, sizeof(name), "%s_representor_%u",
2284                                  dpdk_dev->name, switch_info->port_name);
2285         } else {
2286                 /* Bonding device. */
2287                 if (!switch_info->representor)
2288                         snprintf(name, sizeof(name), "%s_%s",
2289                                  dpdk_dev->name, spawn->ibv_dev->name);
2290                 else
2291                         snprintf(name, sizeof(name), "%s_%s_representor_%u",
2292                                  dpdk_dev->name, spawn->ibv_dev->name,
2293                                  switch_info->port_name);
2294         }
2295         /* check if the device is already spawned */
2296         if (rte_eth_dev_get_port_by_name(name, &port_id) == 0) {
2297                 rte_errno = EEXIST;
2298                 return NULL;
2299         }
2300         DRV_LOG(DEBUG, "naming Ethernet device \"%s\"", name);
2301         if (rte_eal_process_type() == RTE_PROC_SECONDARY) {
2302                 struct mlx5_mp_id mp_id;
2303
2304                 eth_dev = rte_eth_dev_attach_secondary(name);
2305                 if (eth_dev == NULL) {
2306                         DRV_LOG(ERR, "can not attach rte ethdev");
2307                         rte_errno = ENOMEM;
2308                         return NULL;
2309                 }
2310                 eth_dev->device = dpdk_dev;
2311                 eth_dev->dev_ops = &mlx5_dev_sec_ops;
2312                 err = mlx5_proc_priv_init(eth_dev);
2313                 if (err)
2314                         return NULL;
2315                 mp_id.port_id = eth_dev->data->port_id;
2316                 strlcpy(mp_id.name, MLX5_MP_NAME, RTE_MP_MAX_NAME_LEN);
2317                 /* Receive command fd from primary process */
2318                 err = mlx5_mp_req_verbs_cmd_fd(&mp_id);
2319                 if (err < 0)
2320                         return NULL;
2321                 /* Remap UAR for Tx queues. */
2322                 err = mlx5_tx_uar_init_secondary(eth_dev, err);
2323                 if (err)
2324                         return NULL;
2325                 /*
2326                  * Ethdev pointer is still required as input since
2327                  * the primary device is not accessible from the
2328                  * secondary process.
2329                  */
2330                 eth_dev->rx_pkt_burst = mlx5_select_rx_function(eth_dev);
2331                 eth_dev->tx_pkt_burst = mlx5_select_tx_function(eth_dev);
2332                 return eth_dev;
2333         }
2334         /*
2335          * Some parameters ("tx_db_nc" in particularly) are needed in
2336          * advance to create dv/verbs device context. We proceed the
2337          * devargs here to get ones, and later proceed devargs again
2338          * to override some hardware settings.
2339          */
2340         err = mlx5_args(&config, dpdk_dev->devargs);
2341         if (err) {
2342                 err = rte_errno;
2343                 DRV_LOG(ERR, "failed to process device arguments: %s",
2344                         strerror(rte_errno));
2345                 goto error;
2346         }
2347         sh = mlx5_alloc_shared_ibctx(spawn, &config);
2348         if (!sh)
2349                 return NULL;
2350         config.devx = sh->devx;
2351 #ifdef HAVE_MLX5DV_DR_ACTION_DEST_DEVX_TIR
2352         config.dest_tir = 1;
2353 #endif
2354 #ifdef HAVE_IBV_MLX5_MOD_SWP
2355         dv_attr.comp_mask |= MLX5DV_CONTEXT_MASK_SWP;
2356 #endif
2357         /*
2358          * Multi-packet send is supported by ConnectX-4 Lx PF as well
2359          * as all ConnectX-5 devices.
2360          */
2361 #ifdef HAVE_IBV_DEVICE_TUNNEL_SUPPORT
2362         dv_attr.comp_mask |= MLX5DV_CONTEXT_MASK_TUNNEL_OFFLOADS;
2363 #endif
2364 #ifdef HAVE_IBV_DEVICE_STRIDING_RQ_SUPPORT
2365         dv_attr.comp_mask |= MLX5DV_CONTEXT_MASK_STRIDING_RQ;
2366 #endif
2367         mlx5_glue->dv_query_device(sh->ctx, &dv_attr);
2368         if (dv_attr.flags & MLX5DV_CONTEXT_FLAGS_MPW_ALLOWED) {
2369                 if (dv_attr.flags & MLX5DV_CONTEXT_FLAGS_ENHANCED_MPW) {
2370                         DRV_LOG(DEBUG, "enhanced MPW is supported");
2371                         mps = MLX5_MPW_ENHANCED;
2372                 } else {
2373                         DRV_LOG(DEBUG, "MPW is supported");
2374                         mps = MLX5_MPW;
2375                 }
2376         } else {
2377                 DRV_LOG(DEBUG, "MPW isn't supported");
2378                 mps = MLX5_MPW_DISABLED;
2379         }
2380 #ifdef HAVE_IBV_MLX5_MOD_SWP
2381         if (dv_attr.comp_mask & MLX5DV_CONTEXT_MASK_SWP)
2382                 swp = dv_attr.sw_parsing_caps.sw_parsing_offloads;
2383         DRV_LOG(DEBUG, "SWP support: %u", swp);
2384 #endif
2385         config.swp = !!swp;
2386 #ifdef HAVE_IBV_DEVICE_STRIDING_RQ_SUPPORT
2387         if (dv_attr.comp_mask & MLX5DV_CONTEXT_MASK_STRIDING_RQ) {
2388                 struct mlx5dv_striding_rq_caps mprq_caps =
2389                         dv_attr.striding_rq_caps;
2390
2391                 DRV_LOG(DEBUG, "\tmin_single_stride_log_num_of_bytes: %d",
2392                         mprq_caps.min_single_stride_log_num_of_bytes);
2393                 DRV_LOG(DEBUG, "\tmax_single_stride_log_num_of_bytes: %d",
2394                         mprq_caps.max_single_stride_log_num_of_bytes);
2395                 DRV_LOG(DEBUG, "\tmin_single_wqe_log_num_of_strides: %d",
2396                         mprq_caps.min_single_wqe_log_num_of_strides);
2397                 DRV_LOG(DEBUG, "\tmax_single_wqe_log_num_of_strides: %d",
2398                         mprq_caps.max_single_wqe_log_num_of_strides);
2399                 DRV_LOG(DEBUG, "\tsupported_qpts: %d",
2400                         mprq_caps.supported_qpts);
2401                 DRV_LOG(DEBUG, "device supports Multi-Packet RQ");
2402                 mprq = 1;
2403                 mprq_min_stride_size_n =
2404                         mprq_caps.min_single_stride_log_num_of_bytes;
2405                 mprq_max_stride_size_n =
2406                         mprq_caps.max_single_stride_log_num_of_bytes;
2407                 mprq_min_stride_num_n =
2408                         mprq_caps.min_single_wqe_log_num_of_strides;
2409                 mprq_max_stride_num_n =
2410                         mprq_caps.max_single_wqe_log_num_of_strides;
2411         }
2412 #endif
2413         if (RTE_CACHE_LINE_SIZE == 128 &&
2414             !(dv_attr.flags & MLX5DV_CONTEXT_FLAGS_CQE_128B_COMP))
2415                 cqe_comp = 0;
2416         else
2417                 cqe_comp = 1;
2418         config.cqe_comp = cqe_comp;
2419 #ifdef HAVE_IBV_MLX5_MOD_CQE_128B_PAD
2420         /* Whether device supports 128B Rx CQE padding. */
2421         cqe_pad = RTE_CACHE_LINE_SIZE == 128 &&
2422                   (dv_attr.flags & MLX5DV_CONTEXT_FLAGS_CQE_128B_PAD);
2423 #endif
2424 #ifdef HAVE_IBV_DEVICE_TUNNEL_SUPPORT
2425         if (dv_attr.comp_mask & MLX5DV_CONTEXT_MASK_TUNNEL_OFFLOADS) {
2426                 tunnel_en = ((dv_attr.tunnel_offloads_caps &
2427                               MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_VXLAN) &&
2428                              (dv_attr.tunnel_offloads_caps &
2429                               MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_GRE) &&
2430                              (dv_attr.tunnel_offloads_caps &
2431                               MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_GENEVE));
2432         }
2433         DRV_LOG(DEBUG, "tunnel offloading is %ssupported",
2434                 tunnel_en ? "" : "not ");
2435 #else
2436         DRV_LOG(WARNING,
2437                 "tunnel offloading disabled due to old OFED/rdma-core version");
2438 #endif
2439         config.tunnel_en = tunnel_en;
2440 #ifdef HAVE_IBV_DEVICE_MPLS_SUPPORT
2441         mpls_en = ((dv_attr.tunnel_offloads_caps &
2442                     MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_CW_MPLS_OVER_GRE) &&
2443                    (dv_attr.tunnel_offloads_caps &
2444                     MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_CW_MPLS_OVER_UDP));
2445         DRV_LOG(DEBUG, "MPLS over GRE/UDP tunnel offloading is %ssupported",
2446                 mpls_en ? "" : "not ");
2447 #else
2448         DRV_LOG(WARNING, "MPLS over GRE/UDP tunnel offloading disabled due to"
2449                 " old OFED/rdma-core version or firmware configuration");
2450 #endif
2451         config.mpls_en = mpls_en;
2452         /* Check port status. */
2453         err = mlx5_glue->query_port(sh->ctx, spawn->ibv_port, &port_attr);
2454         if (err) {
2455                 DRV_LOG(ERR, "port query failed: %s", strerror(err));
2456                 goto error;
2457         }
2458         if (port_attr.link_layer != IBV_LINK_LAYER_ETHERNET) {
2459                 DRV_LOG(ERR, "port is not configured in Ethernet mode");
2460                 err = EINVAL;
2461                 goto error;
2462         }
2463         if (port_attr.state != IBV_PORT_ACTIVE)
2464                 DRV_LOG(DEBUG, "port is not active: \"%s\" (%d)",
2465                         mlx5_glue->port_state_str(port_attr.state),
2466                         port_attr.state);
2467         /* Allocate private eth device data. */
2468         priv = rte_zmalloc("ethdev private structure",
2469                            sizeof(*priv),
2470                            RTE_CACHE_LINE_SIZE);
2471         if (priv == NULL) {
2472                 DRV_LOG(ERR, "priv allocation failure");
2473                 err = ENOMEM;
2474                 goto error;
2475         }
2476         priv->sh = sh;
2477         priv->ibv_port = spawn->ibv_port;
2478         priv->pci_dev = spawn->pci_dev;
2479         priv->mtu = RTE_ETHER_MTU;
2480         priv->mp_id.port_id = port_id;
2481         strlcpy(priv->mp_id.name, MLX5_MP_NAME, RTE_MP_MAX_NAME_LEN);
2482 #ifndef RTE_ARCH_64
2483         /* Initialize UAR access locks for 32bit implementations. */
2484         rte_spinlock_init(&priv->uar_lock_cq);
2485         for (i = 0; i < MLX5_UAR_PAGE_NUM_MAX; i++)
2486                 rte_spinlock_init(&priv->uar_lock[i]);
2487 #endif
2488         /* Some internal functions rely on Netlink sockets, open them now. */
2489         priv->nl_socket_rdma = mlx5_nl_init(NETLINK_RDMA);
2490         priv->nl_socket_route = mlx5_nl_init(NETLINK_ROUTE);
2491         priv->representor = !!switch_info->representor;
2492         priv->master = !!switch_info->master;
2493         priv->domain_id = RTE_ETH_DEV_SWITCH_DOMAIN_ID_INVALID;
2494         priv->vport_meta_tag = 0;
2495         priv->vport_meta_mask = 0;
2496         priv->pf_bond = spawn->pf_bond;
2497 #ifdef HAVE_MLX5DV_DR_DEVX_PORT
2498         /*
2499          * The DevX port query API is implemented. E-Switch may use
2500          * either vport or reg_c[0] metadata register to match on
2501          * vport index. The engaged part of metadata register is
2502          * defined by mask.
2503          */
2504         if (switch_info->representor || switch_info->master) {
2505                 devx_port.comp_mask = MLX5DV_DEVX_PORT_VPORT |
2506                                       MLX5DV_DEVX_PORT_MATCH_REG_C_0;
2507                 err = mlx5_glue->devx_port_query(sh->ctx, spawn->ibv_port,
2508                                                  &devx_port);
2509                 if (err) {
2510                         DRV_LOG(WARNING,
2511                                 "can't query devx port %d on device %s",
2512                                 spawn->ibv_port, spawn->ibv_dev->name);
2513                         devx_port.comp_mask = 0;
2514                 }
2515         }
2516         if (devx_port.comp_mask & MLX5DV_DEVX_PORT_MATCH_REG_C_0) {
2517                 priv->vport_meta_tag = devx_port.reg_c_0.value;
2518                 priv->vport_meta_mask = devx_port.reg_c_0.mask;
2519                 if (!priv->vport_meta_mask) {
2520                         DRV_LOG(ERR, "vport zero mask for port %d"
2521                                      " on bonding device %s",
2522                                      spawn->ibv_port, spawn->ibv_dev->name);
2523                         err = ENOTSUP;
2524                         goto error;
2525                 }
2526                 if (priv->vport_meta_tag & ~priv->vport_meta_mask) {
2527                         DRV_LOG(ERR, "invalid vport tag for port %d"
2528                                      " on bonding device %s",
2529                                      spawn->ibv_port, spawn->ibv_dev->name);
2530                         err = ENOTSUP;
2531                         goto error;
2532                 }
2533         }
2534         if (devx_port.comp_mask & MLX5DV_DEVX_PORT_VPORT) {
2535                 priv->vport_id = devx_port.vport_num;
2536         } else if (spawn->pf_bond >= 0) {
2537                 DRV_LOG(ERR, "can't deduce vport index for port %d"
2538                              " on bonding device %s",
2539                              spawn->ibv_port, spawn->ibv_dev->name);
2540                 err = ENOTSUP;
2541                 goto error;
2542         } else {
2543                 /* Suppose vport index in compatible way. */
2544                 priv->vport_id = switch_info->representor ?
2545                                  switch_info->port_name + 1 : -1;
2546         }
2547 #else
2548         /*
2549          * Kernel/rdma_core support single E-Switch per PF configurations
2550          * only and vport_id field contains the vport index for
2551          * associated VF, which is deduced from representor port name.
2552          * For example, let's have the IB device port 10, it has
2553          * attached network device eth0, which has port name attribute
2554          * pf0vf2, we can deduce the VF number as 2, and set vport index
2555          * as 3 (2+1). This assigning schema should be changed if the
2556          * multiple E-Switch instances per PF configurations or/and PCI
2557          * subfunctions are added.
2558          */
2559         priv->vport_id = switch_info->representor ?
2560                          switch_info->port_name + 1 : -1;
2561 #endif
2562         /* representor_id field keeps the unmodified VF index. */
2563         priv->representor_id = switch_info->representor ?
2564                                switch_info->port_name : -1;
2565         /*
2566          * Look for sibling devices in order to reuse their switch domain
2567          * if any, otherwise allocate one.
2568          */
2569         MLX5_ETH_FOREACH_DEV(port_id, priv->pci_dev) {
2570                 const struct mlx5_priv *opriv =
2571                         rte_eth_devices[port_id].data->dev_private;
2572
2573                 if (!opriv ||
2574                     opriv->sh != priv->sh ||
2575                         opriv->domain_id ==
2576                         RTE_ETH_DEV_SWITCH_DOMAIN_ID_INVALID)
2577                         continue;
2578                 priv->domain_id = opriv->domain_id;
2579                 break;
2580         }
2581         if (priv->domain_id == RTE_ETH_DEV_SWITCH_DOMAIN_ID_INVALID) {
2582                 err = rte_eth_switch_domain_alloc(&priv->domain_id);
2583                 if (err) {
2584                         err = rte_errno;
2585                         DRV_LOG(ERR, "unable to allocate switch domain: %s",
2586                                 strerror(rte_errno));
2587                         goto error;
2588                 }
2589                 own_domain_id = 1;
2590         }
2591         /* Override some values set by hardware configuration. */
2592         mlx5_args(&config, dpdk_dev->devargs);
2593         err = mlx5_dev_check_sibling_config(priv, &config);
2594         if (err)
2595                 goto error;
2596         config.hw_csum = !!(sh->device_attr.device_cap_flags_ex &
2597                             IBV_DEVICE_RAW_IP_CSUM);
2598         DRV_LOG(DEBUG, "checksum offloading is %ssupported",
2599                 (config.hw_csum ? "" : "not "));
2600 #if !defined(HAVE_IBV_DEVICE_COUNTERS_SET_V42) && \
2601         !defined(HAVE_IBV_DEVICE_COUNTERS_SET_V45)
2602         DRV_LOG(DEBUG, "counters are not supported");
2603 #endif
2604 #if !defined(HAVE_IBV_FLOW_DV_SUPPORT) || !defined(HAVE_MLX5DV_DR)
2605         if (config.dv_flow_en) {
2606                 DRV_LOG(WARNING, "DV flow is not supported");
2607                 config.dv_flow_en = 0;
2608         }
2609 #endif
2610         config.ind_table_max_size =
2611                 sh->device_attr.rss_caps.max_rwq_indirection_table_size;
2612         /*
2613          * Remove this check once DPDK supports larger/variable
2614          * indirection tables.
2615          */
2616         if (config.ind_table_max_size > (unsigned int)ETH_RSS_RETA_SIZE_512)
2617                 config.ind_table_max_size = ETH_RSS_RETA_SIZE_512;
2618         DRV_LOG(DEBUG, "maximum Rx indirection table size is %u",
2619                 config.ind_table_max_size);
2620         config.hw_vlan_strip = !!(sh->device_attr.raw_packet_caps &
2621                                   IBV_RAW_PACKET_CAP_CVLAN_STRIPPING);
2622         DRV_LOG(DEBUG, "VLAN stripping is %ssupported",
2623                 (config.hw_vlan_strip ? "" : "not "));
2624         config.hw_fcs_strip = !!(sh->device_attr.raw_packet_caps &
2625                                  IBV_RAW_PACKET_CAP_SCATTER_FCS);
2626         DRV_LOG(DEBUG, "FCS stripping configuration is %ssupported",
2627                 (config.hw_fcs_strip ? "" : "not "));
2628 #if defined(HAVE_IBV_WQ_FLAG_RX_END_PADDING)
2629         hw_padding = !!sh->device_attr.rx_pad_end_addr_align;
2630 #elif defined(HAVE_IBV_WQ_FLAGS_PCI_WRITE_END_PADDING)
2631         hw_padding = !!(sh->device_attr.device_cap_flags_ex &
2632                         IBV_DEVICE_PCI_WRITE_END_PADDING);
2633 #endif
2634         if (config.hw_padding && !hw_padding) {
2635                 DRV_LOG(DEBUG, "Rx end alignment padding isn't supported");
2636                 config.hw_padding = 0;
2637         } else if (config.hw_padding) {
2638                 DRV_LOG(DEBUG, "Rx end alignment padding is enabled");
2639         }
2640         config.tso = (sh->device_attr.tso_caps.max_tso > 0 &&
2641                       (sh->device_attr.tso_caps.supported_qpts &
2642                        (1 << IBV_QPT_RAW_PACKET)));
2643         if (config.tso)
2644                 config.tso_max_payload_sz = sh->device_attr.tso_caps.max_tso;
2645         /*
2646          * MPW is disabled by default, while the Enhanced MPW is enabled
2647          * by default.
2648          */
2649         if (config.mps == MLX5_ARG_UNSET)
2650                 config.mps = (mps == MLX5_MPW_ENHANCED) ? MLX5_MPW_ENHANCED :
2651                                                           MLX5_MPW_DISABLED;
2652         else
2653                 config.mps = config.mps ? mps : MLX5_MPW_DISABLED;
2654         DRV_LOG(INFO, "%sMPS is %s",
2655                 config.mps == MLX5_MPW_ENHANCED ? "enhanced " :
2656                 config.mps == MLX5_MPW ? "legacy " : "",
2657                 config.mps != MLX5_MPW_DISABLED ? "enabled" : "disabled");
2658         if (config.cqe_comp && !cqe_comp) {
2659                 DRV_LOG(WARNING, "Rx CQE compression isn't supported");
2660                 config.cqe_comp = 0;
2661         }
2662         if (config.cqe_pad && !cqe_pad) {
2663                 DRV_LOG(WARNING, "Rx CQE padding isn't supported");
2664                 config.cqe_pad = 0;
2665         } else if (config.cqe_pad) {
2666                 DRV_LOG(INFO, "Rx CQE padding is enabled");
2667         }
2668         if (config.devx) {
2669                 priv->counter_fallback = 0;
2670                 err = mlx5_devx_cmd_query_hca_attr(sh->ctx, &config.hca_attr);
2671                 if (err) {
2672                         err = -err;
2673                         goto error;
2674                 }
2675                 if (!config.hca_attr.flow_counters_dump)
2676                         priv->counter_fallback = 1;
2677 #ifndef HAVE_IBV_DEVX_ASYNC
2678                 priv->counter_fallback = 1;
2679 #endif
2680                 if (priv->counter_fallback)
2681                         DRV_LOG(INFO, "Use fall-back DV counter management");
2682                 /* Check for LRO support. */
2683                 if (config.dest_tir && config.hca_attr.lro_cap &&
2684                     config.dv_flow_en) {
2685                         /* TBD check tunnel lro caps. */
2686                         config.lro.supported = config.hca_attr.lro_cap;
2687                         DRV_LOG(DEBUG, "Device supports LRO");
2688                         /*
2689                          * If LRO timeout is not configured by application,
2690                          * use the minimal supported value.
2691                          */
2692                         if (!config.lro.timeout)
2693                                 config.lro.timeout =
2694                                 config.hca_attr.lro_timer_supported_periods[0];
2695                         DRV_LOG(DEBUG, "LRO session timeout set to %d usec",
2696                                 config.lro.timeout);
2697                 }
2698 #if defined(HAVE_MLX5DV_DR) && defined(HAVE_MLX5_DR_CREATE_ACTION_FLOW_METER)
2699                 if (config.hca_attr.qos.sup && config.hca_attr.qos.srtcm_sup &&
2700                     config.dv_flow_en) {
2701                         uint8_t reg_c_mask =
2702                                 config.hca_attr.qos.flow_meter_reg_c_ids;
2703                         /*
2704                          * Meter needs two REG_C's for color match and pre-sfx
2705                          * flow match. Here get the REG_C for color match.
2706                          * REG_C_0 and REG_C_1 is reserved for metadata feature.
2707                          */
2708                         reg_c_mask &= 0xfc;
2709                         if (__builtin_popcount(reg_c_mask) < 1) {
2710                                 priv->mtr_en = 0;
2711                                 DRV_LOG(WARNING, "No available register for"
2712                                         " meter.");
2713                         } else {
2714                                 priv->mtr_color_reg = ffs(reg_c_mask) - 1 +
2715                                                       REG_C_0;
2716                                 priv->mtr_en = 1;
2717                                 priv->mtr_reg_share =
2718                                       config.hca_attr.qos.flow_meter_reg_share;
2719                                 DRV_LOG(DEBUG, "The REG_C meter uses is %d",
2720                                         priv->mtr_color_reg);
2721                         }
2722                 }
2723 #endif
2724         }
2725         if (config.mprq.enabled && mprq) {
2726                 if (config.mprq.stride_num_n &&
2727                     (config.mprq.stride_num_n > mprq_max_stride_num_n ||
2728                      config.mprq.stride_num_n < mprq_min_stride_num_n)) {
2729                         config.mprq.stride_num_n =
2730                                 RTE_MIN(RTE_MAX(MLX5_MPRQ_STRIDE_NUM_N,
2731                                                 mprq_min_stride_num_n),
2732                                         mprq_max_stride_num_n);
2733                         DRV_LOG(WARNING,
2734                                 "the number of strides"
2735                                 " for Multi-Packet RQ is out of range,"
2736                                 " setting default value (%u)",
2737                                 1 << config.mprq.stride_num_n);
2738                 }
2739                 if (config.mprq.stride_size_n &&
2740                     (config.mprq.stride_size_n > mprq_max_stride_size_n ||
2741                      config.mprq.stride_size_n < mprq_min_stride_size_n)) {
2742                         config.mprq.stride_size_n =
2743                                 RTE_MIN(RTE_MAX(MLX5_MPRQ_STRIDE_SIZE_N,
2744                                                 mprq_min_stride_size_n),
2745                                         mprq_max_stride_size_n);
2746                         DRV_LOG(WARNING,
2747                                 "the size of a stride"
2748                                 " for Multi-Packet RQ is out of range,"
2749                                 " setting default value (%u)",
2750                                 1 << config.mprq.stride_size_n);
2751                 }
2752                 config.mprq.min_stride_size_n = mprq_min_stride_size_n;
2753                 config.mprq.max_stride_size_n = mprq_max_stride_size_n;
2754         } else if (config.mprq.enabled && !mprq) {
2755                 DRV_LOG(WARNING, "Multi-Packet RQ isn't supported");
2756                 config.mprq.enabled = 0;
2757         }
2758         if (config.max_dump_files_num == 0)
2759                 config.max_dump_files_num = 128;
2760         eth_dev = rte_eth_dev_allocate(name);
2761         if (eth_dev == NULL) {
2762                 DRV_LOG(ERR, "can not allocate rte ethdev");
2763                 err = ENOMEM;
2764                 goto error;
2765         }
2766         /* Flag to call rte_eth_dev_release_port() in rte_eth_dev_close(). */
2767         eth_dev->data->dev_flags |= RTE_ETH_DEV_CLOSE_REMOVE;
2768         if (priv->representor) {
2769                 eth_dev->data->dev_flags |= RTE_ETH_DEV_REPRESENTOR;
2770                 eth_dev->data->representor_id = priv->representor_id;
2771         }
2772         /*
2773          * Store associated network device interface index. This index
2774          * is permanent throughout the lifetime of device. So, we may store
2775          * the ifindex here and use the cached value further.
2776          */
2777         MLX5_ASSERT(spawn->ifindex);
2778         priv->if_index = spawn->ifindex;
2779         eth_dev->data->dev_private = priv;
2780         priv->dev_data = eth_dev->data;
2781         eth_dev->data->mac_addrs = priv->mac;
2782         eth_dev->device = dpdk_dev;
2783         /* Configure the first MAC address by default. */
2784         if (mlx5_get_mac(eth_dev, &mac.addr_bytes)) {
2785                 DRV_LOG(ERR,
2786                         "port %u cannot get MAC address, is mlx5_en"
2787                         " loaded? (errno: %s)",
2788                         eth_dev->data->port_id, strerror(rte_errno));
2789                 err = ENODEV;
2790                 goto error;
2791         }
2792         DRV_LOG(INFO,
2793                 "port %u MAC address is %02x:%02x:%02x:%02x:%02x:%02x",
2794                 eth_dev->data->port_id,
2795                 mac.addr_bytes[0], mac.addr_bytes[1],
2796                 mac.addr_bytes[2], mac.addr_bytes[3],
2797                 mac.addr_bytes[4], mac.addr_bytes[5]);
2798 #ifdef RTE_LIBRTE_MLX5_DEBUG
2799         {
2800                 char ifname[IF_NAMESIZE];
2801
2802                 if (mlx5_get_ifname(eth_dev, &ifname) == 0)
2803                         DRV_LOG(DEBUG, "port %u ifname is \"%s\"",
2804                                 eth_dev->data->port_id, ifname);
2805                 else
2806                         DRV_LOG(DEBUG, "port %u ifname is unknown",
2807                                 eth_dev->data->port_id);
2808         }
2809 #endif
2810         /* Get actual MTU if possible. */
2811         err = mlx5_get_mtu(eth_dev, &priv->mtu);
2812         if (err) {
2813                 err = rte_errno;
2814                 goto error;
2815         }
2816         DRV_LOG(DEBUG, "port %u MTU is %u", eth_dev->data->port_id,
2817                 priv->mtu);
2818         /* Initialize burst functions to prevent crashes before link-up. */
2819         eth_dev->rx_pkt_burst = removed_rx_burst;
2820         eth_dev->tx_pkt_burst = removed_tx_burst;
2821         eth_dev->dev_ops = &mlx5_dev_ops;
2822         /* Register MAC address. */
2823         claim_zero(mlx5_mac_addr_add(eth_dev, &mac, 0, 0));
2824         if (config.vf && config.vf_nl_en)
2825                 mlx5_nl_mac_addr_sync(priv->nl_socket_route,
2826                                       mlx5_ifindex(eth_dev),
2827                                       eth_dev->data->mac_addrs,
2828                                       MLX5_MAX_MAC_ADDRESSES);
2829         TAILQ_INIT(&priv->flows);
2830         TAILQ_INIT(&priv->ctrl_flows);
2831         TAILQ_INIT(&priv->flow_meters);
2832         TAILQ_INIT(&priv->flow_meter_profiles);
2833         /* Hint libmlx5 to use PMD allocator for data plane resources */
2834         struct mlx5dv_ctx_allocators alctr = {
2835                 .alloc = &mlx5_alloc_verbs_buf,
2836                 .free = &mlx5_free_verbs_buf,
2837                 .data = priv,
2838         };
2839         mlx5_glue->dv_set_context_attr(sh->ctx,
2840                                        MLX5DV_CTX_ATTR_BUF_ALLOCATORS,
2841                                        (void *)((uintptr_t)&alctr));
2842         /* Bring Ethernet device up. */
2843         DRV_LOG(DEBUG, "port %u forcing Ethernet interface up",
2844                 eth_dev->data->port_id);
2845         mlx5_set_link_up(eth_dev);
2846         /*
2847          * Even though the interrupt handler is not installed yet,
2848          * interrupts will still trigger on the async_fd from
2849          * Verbs context returned by ibv_open_device().
2850          */
2851         mlx5_link_update(eth_dev, 0);
2852 #ifdef HAVE_MLX5DV_DR_ESWITCH
2853         if (!(config.hca_attr.eswitch_manager && config.dv_flow_en &&
2854               (switch_info->representor || switch_info->master)))
2855                 config.dv_esw_en = 0;
2856 #else
2857         config.dv_esw_en = 0;
2858 #endif
2859         /* Detect minimal data bytes to inline. */
2860         mlx5_set_min_inline(spawn, &config);
2861         /* Store device configuration on private structure. */
2862         priv->config = config;
2863         /* Create context for virtual machine VLAN workaround. */
2864         priv->vmwa_context = mlx5_vlan_vmwa_init(eth_dev, spawn->ifindex);
2865         if (config.dv_flow_en) {
2866                 err = mlx5_alloc_shared_dr(priv);
2867                 if (err)
2868                         goto error;
2869                 /*
2870                  * RSS id is shared with meter flow id. Meter flow id can only
2871                  * use the 24 MSB of the register.
2872                  */
2873                 priv->qrss_id_pool = mlx5_flow_id_pool_alloc(UINT32_MAX >>
2874                                      MLX5_MTR_COLOR_BITS);
2875                 if (!priv->qrss_id_pool) {
2876                         DRV_LOG(ERR, "can't create flow id pool");
2877                         err = ENOMEM;
2878                         goto error;
2879                 }
2880         }
2881         /* Supported Verbs flow priority number detection. */
2882         err = mlx5_flow_discover_priorities(eth_dev);
2883         if (err < 0) {
2884                 err = -err;
2885                 goto error;
2886         }
2887         priv->config.flow_prio = err;
2888         if (!priv->config.dv_esw_en &&
2889             priv->config.dv_xmeta_en != MLX5_XMETA_MODE_LEGACY) {
2890                 DRV_LOG(WARNING, "metadata mode %u is not supported "
2891                                  "(no E-Switch)", priv->config.dv_xmeta_en);
2892                 priv->config.dv_xmeta_en = MLX5_XMETA_MODE_LEGACY;
2893         }
2894         mlx5_set_metadata_mask(eth_dev);
2895         if (priv->config.dv_xmeta_en != MLX5_XMETA_MODE_LEGACY &&
2896             !priv->sh->dv_regc0_mask) {
2897                 DRV_LOG(ERR, "metadata mode %u is not supported "
2898                              "(no metadata reg_c[0] is available)",
2899                              priv->config.dv_xmeta_en);
2900                         err = ENOTSUP;
2901                         goto error;
2902         }
2903         /*
2904          * Allocate the buffer for flow creating, just once.
2905          * The allocation must be done before any flow creating.
2906          */
2907         mlx5_flow_alloc_intermediate(eth_dev);
2908         /* Query availibility of metadata reg_c's. */
2909         err = mlx5_flow_discover_mreg_c(eth_dev);
2910         if (err < 0) {
2911                 err = -err;
2912                 goto error;
2913         }
2914         if (!mlx5_flow_ext_mreg_supported(eth_dev)) {
2915                 DRV_LOG(DEBUG,
2916                         "port %u extensive metadata register is not supported",
2917                         eth_dev->data->port_id);
2918                 if (priv->config.dv_xmeta_en != MLX5_XMETA_MODE_LEGACY) {
2919                         DRV_LOG(ERR, "metadata mode %u is not supported "
2920                                      "(no metadata registers available)",
2921                                      priv->config.dv_xmeta_en);
2922                         err = ENOTSUP;
2923                         goto error;
2924                 }
2925         }
2926         if (priv->config.dv_flow_en &&
2927             priv->config.dv_xmeta_en != MLX5_XMETA_MODE_LEGACY &&
2928             mlx5_flow_ext_mreg_supported(eth_dev) &&
2929             priv->sh->dv_regc0_mask) {
2930                 priv->mreg_cp_tbl = mlx5_hlist_create(MLX5_FLOW_MREG_HNAME,
2931                                                       MLX5_FLOW_MREG_HTABLE_SZ);
2932                 if (!priv->mreg_cp_tbl) {
2933                         err = ENOMEM;
2934                         goto error;
2935                 }
2936         }
2937         return eth_dev;
2938 error:
2939         if (priv) {
2940                 if (priv->mreg_cp_tbl)
2941                         mlx5_hlist_destroy(priv->mreg_cp_tbl, NULL, NULL);
2942                 if (priv->sh)
2943                         mlx5_free_shared_dr(priv);
2944                 if (priv->nl_socket_route >= 0)
2945                         close(priv->nl_socket_route);
2946                 if (priv->nl_socket_rdma >= 0)
2947                         close(priv->nl_socket_rdma);
2948                 if (priv->vmwa_context)
2949                         mlx5_vlan_vmwa_exit(priv->vmwa_context);
2950                 if (priv->qrss_id_pool)
2951                         mlx5_flow_id_pool_release(priv->qrss_id_pool);
2952                 if (own_domain_id)
2953                         claim_zero(rte_eth_switch_domain_free(priv->domain_id));
2954                 rte_free(priv);
2955                 if (eth_dev != NULL)
2956                         eth_dev->data->dev_private = NULL;
2957         }
2958         if (eth_dev != NULL) {
2959                 /* mac_addrs must not be freed alone because part of dev_private */
2960                 eth_dev->data->mac_addrs = NULL;
2961                 rte_eth_dev_release_port(eth_dev);
2962         }
2963         if (sh)
2964                 mlx5_free_shared_ibctx(sh);
2965         MLX5_ASSERT(err > 0);
2966         rte_errno = err;
2967         return NULL;
2968 }
2969
2970 /**
2971  * Comparison callback to sort device data.
2972  *
2973  * This is meant to be used with qsort().
2974  *
2975  * @param a[in]
2976  *   Pointer to pointer to first data object.
2977  * @param b[in]
2978  *   Pointer to pointer to second data object.
2979  *
2980  * @return
2981  *   0 if both objects are equal, less than 0 if the first argument is less
2982  *   than the second, greater than 0 otherwise.
2983  */
2984 static int
2985 mlx5_dev_spawn_data_cmp(const void *a, const void *b)
2986 {
2987         const struct mlx5_switch_info *si_a =
2988                 &((const struct mlx5_dev_spawn_data *)a)->info;
2989         const struct mlx5_switch_info *si_b =
2990                 &((const struct mlx5_dev_spawn_data *)b)->info;
2991         int ret;
2992
2993         /* Master device first. */
2994         ret = si_b->master - si_a->master;
2995         if (ret)
2996                 return ret;
2997         /* Then representor devices. */
2998         ret = si_b->representor - si_a->representor;
2999         if (ret)
3000                 return ret;
3001         /* Unidentified devices come last in no specific order. */
3002         if (!si_a->representor)
3003                 return 0;
3004         /* Order representors by name. */
3005         return si_a->port_name - si_b->port_name;
3006 }
3007
3008 /**
3009  * Match PCI information for possible slaves of bonding device.
3010  *
3011  * @param[in] ibv_dev
3012  *   Pointer to Infiniband device structure.
3013  * @param[in] pci_dev
3014  *   Pointer to PCI device structure to match PCI address.
3015  * @param[in] nl_rdma
3016  *   Netlink RDMA group socket handle.
3017  *
3018  * @return
3019  *   negative value if no bonding device found, otherwise
3020  *   positive index of slave PF in bonding.
3021  */
3022 static int
3023 mlx5_device_bond_pci_match(const struct ibv_device *ibv_dev,
3024                            const struct rte_pci_device *pci_dev,
3025                            int nl_rdma)
3026 {
3027         char ifname[IF_NAMESIZE + 1];
3028         unsigned int ifindex;
3029         unsigned int np, i;
3030         FILE *file = NULL;
3031         int pf = -1;
3032
3033         /*
3034          * Try to get master device name. If something goes
3035          * wrong suppose the lack of kernel support and no
3036          * bonding devices.
3037          */
3038         if (nl_rdma < 0)
3039                 return -1;
3040         if (!strstr(ibv_dev->name, "bond"))
3041                 return -1;
3042         np = mlx5_nl_portnum(nl_rdma, ibv_dev->name);
3043         if (!np)
3044                 return -1;
3045         /*
3046          * The Master device might not be on the predefined
3047          * port (not on port index 1, it is not garanted),
3048          * we have to scan all Infiniband device port and
3049          * find master.
3050          */
3051         for (i = 1; i <= np; ++i) {
3052                 /* Check whether Infiniband port is populated. */
3053                 ifindex = mlx5_nl_ifindex(nl_rdma, ibv_dev->name, i);
3054                 if (!ifindex)
3055                         continue;
3056                 if (!if_indextoname(ifindex, ifname))
3057                         continue;
3058                 /* Try to read bonding slave names from sysfs. */
3059                 MKSTR(slaves,
3060                       "/sys/class/net/%s/master/bonding/slaves", ifname);
3061                 file = fopen(slaves, "r");
3062                 if (file)
3063                         break;
3064         }
3065         if (!file)
3066                 return -1;
3067         /* Use safe format to check maximal buffer length. */
3068         MLX5_ASSERT(atol(RTE_STR(IF_NAMESIZE)) == IF_NAMESIZE);
3069         while (fscanf(file, "%" RTE_STR(IF_NAMESIZE) "s", ifname) == 1) {
3070                 char tmp_str[IF_NAMESIZE + 32];
3071                 struct rte_pci_addr pci_addr;
3072                 struct mlx5_switch_info info;
3073
3074                 /* Process slave interface names in the loop. */
3075                 snprintf(tmp_str, sizeof(tmp_str),
3076                          "/sys/class/net/%s", ifname);
3077                 if (mlx5_dev_to_pci_addr(tmp_str, &pci_addr)) {
3078                         DRV_LOG(WARNING, "can not get PCI address"
3079                                          " for netdev \"%s\"", ifname);
3080                         continue;
3081                 }
3082                 if (pci_dev->addr.domain != pci_addr.domain ||
3083                     pci_dev->addr.bus != pci_addr.bus ||
3084                     pci_dev->addr.devid != pci_addr.devid ||
3085                     pci_dev->addr.function != pci_addr.function)
3086                         continue;
3087                 /* Slave interface PCI address match found. */
3088                 fclose(file);
3089                 snprintf(tmp_str, sizeof(tmp_str),
3090                          "/sys/class/net/%s/phys_port_name", ifname);
3091                 file = fopen(tmp_str, "rb");
3092                 if (!file)
3093                         break;
3094                 info.name_type = MLX5_PHYS_PORT_NAME_TYPE_NOTSET;
3095                 if (fscanf(file, "%32s", tmp_str) == 1)
3096                         mlx5_translate_port_name(tmp_str, &info);
3097                 if (info.name_type == MLX5_PHYS_PORT_NAME_TYPE_LEGACY ||
3098                     info.name_type == MLX5_PHYS_PORT_NAME_TYPE_UPLINK)
3099                         pf = info.port_name;
3100                 break;
3101         }
3102         if (file)
3103                 fclose(file);
3104         return pf;
3105 }
3106
3107 /**
3108  * DPDK callback to register a PCI device.
3109  *
3110  * This function spawns Ethernet devices out of a given PCI device.
3111  *
3112  * @param[in] pci_drv
3113  *   PCI driver structure (mlx5_driver).
3114  * @param[in] pci_dev
3115  *   PCI device information.
3116  *
3117  * @return
3118  *   0 on success, a negative errno value otherwise and rte_errno is set.
3119  */
3120 static int
3121 mlx5_pci_probe(struct rte_pci_driver *pci_drv __rte_unused,
3122                struct rte_pci_device *pci_dev)
3123 {
3124         struct ibv_device **ibv_list;
3125         /*
3126          * Number of found IB Devices matching with requested PCI BDF.
3127          * nd != 1 means there are multiple IB devices over the same
3128          * PCI device and we have representors and master.
3129          */
3130         unsigned int nd = 0;
3131         /*
3132          * Number of found IB device Ports. nd = 1 and np = 1..n means
3133          * we have the single multiport IB device, and there may be
3134          * representors attached to some of found ports.
3135          */
3136         unsigned int np = 0;
3137         /*
3138          * Number of DPDK ethernet devices to Spawn - either over
3139          * multiple IB devices or multiple ports of single IB device.
3140          * Actually this is the number of iterations to spawn.
3141          */
3142         unsigned int ns = 0;
3143         /*
3144          * Bonding device
3145          *   < 0 - no bonding device (single one)
3146          *  >= 0 - bonding device (value is slave PF index)
3147          */
3148         int bd = -1;
3149         struct mlx5_dev_spawn_data *list = NULL;
3150         struct mlx5_dev_config dev_config;
3151         int ret;
3152
3153         if (mlx5_class_get(pci_dev->device.devargs) != MLX5_CLASS_NET) {
3154                 DRV_LOG(DEBUG, "Skip probing - should be probed by other mlx5"
3155                         " driver.");
3156                 return 1;
3157         }
3158         if (rte_eal_process_type() == RTE_PROC_PRIMARY)
3159                 mlx5_pmd_socket_init();
3160         ret = mlx5_init_once();
3161         if (ret) {
3162                 DRV_LOG(ERR, "unable to init PMD global data: %s",
3163                         strerror(rte_errno));
3164                 return -rte_errno;
3165         }
3166         MLX5_ASSERT(pci_drv == &mlx5_driver);
3167         errno = 0;
3168         ibv_list = mlx5_glue->get_device_list(&ret);
3169         if (!ibv_list) {
3170                 rte_errno = errno ? errno : ENOSYS;
3171                 DRV_LOG(ERR, "cannot list devices, is ib_uverbs loaded?");
3172                 return -rte_errno;
3173         }
3174         /*
3175          * First scan the list of all Infiniband devices to find
3176          * matching ones, gathering into the list.
3177          */
3178         struct ibv_device *ibv_match[ret + 1];
3179         int nl_route = mlx5_nl_init(NETLINK_ROUTE);
3180         int nl_rdma = mlx5_nl_init(NETLINK_RDMA);
3181         unsigned int i;
3182
3183         while (ret-- > 0) {
3184                 struct rte_pci_addr pci_addr;
3185
3186                 DRV_LOG(DEBUG, "checking device \"%s\"", ibv_list[ret]->name);
3187                 bd = mlx5_device_bond_pci_match
3188                                 (ibv_list[ret], pci_dev, nl_rdma);
3189                 if (bd >= 0) {
3190                         /*
3191                          * Bonding device detected. Only one match is allowed,
3192                          * the bonding is supported over multi-port IB device,
3193                          * there should be no matches on representor PCI
3194                          * functions or non VF LAG bonding devices with
3195                          * specified address.
3196                          */
3197                         if (nd) {
3198                                 DRV_LOG(ERR,
3199                                         "multiple PCI match on bonding device"
3200                                         "\"%s\" found", ibv_list[ret]->name);
3201                                 rte_errno = ENOENT;
3202                                 ret = -rte_errno;
3203                                 goto exit;
3204                         }
3205                         DRV_LOG(INFO, "PCI information matches for"
3206                                       " slave %d bonding device \"%s\"",
3207                                       bd, ibv_list[ret]->name);
3208                         ibv_match[nd++] = ibv_list[ret];
3209                         break;
3210                 }
3211                 if (mlx5_dev_to_pci_addr
3212                         (ibv_list[ret]->ibdev_path, &pci_addr))
3213                         continue;
3214                 if (pci_dev->addr.domain != pci_addr.domain ||
3215                     pci_dev->addr.bus != pci_addr.bus ||
3216                     pci_dev->addr.devid != pci_addr.devid ||
3217                     pci_dev->addr.function != pci_addr.function)
3218                         continue;
3219                 DRV_LOG(INFO, "PCI information matches for device \"%s\"",
3220                         ibv_list[ret]->name);
3221                 ibv_match[nd++] = ibv_list[ret];
3222         }
3223         ibv_match[nd] = NULL;
3224         if (!nd) {
3225                 /* No device matches, just complain and bail out. */
3226                 DRV_LOG(WARNING,
3227                         "no Verbs device matches PCI device " PCI_PRI_FMT ","
3228                         " are kernel drivers loaded?",
3229                         pci_dev->addr.domain, pci_dev->addr.bus,
3230                         pci_dev->addr.devid, pci_dev->addr.function);
3231                 rte_errno = ENOENT;
3232                 ret = -rte_errno;
3233                 goto exit;
3234         }
3235         if (nd == 1) {
3236                 /*
3237                  * Found single matching device may have multiple ports.
3238                  * Each port may be representor, we have to check the port
3239                  * number and check the representors existence.
3240                  */
3241                 if (nl_rdma >= 0)
3242                         np = mlx5_nl_portnum(nl_rdma, ibv_match[0]->name);
3243                 if (!np)
3244                         DRV_LOG(WARNING, "can not get IB device \"%s\""
3245                                          " ports number", ibv_match[0]->name);
3246                 if (bd >= 0 && !np) {
3247                         DRV_LOG(ERR, "can not get ports"
3248                                      " for bonding device");
3249                         rte_errno = ENOENT;
3250                         ret = -rte_errno;
3251                         goto exit;
3252                 }
3253         }
3254 #ifndef HAVE_MLX5DV_DR_DEVX_PORT
3255         if (bd >= 0) {
3256                 /*
3257                  * This may happen if there is VF LAG kernel support and
3258                  * application is compiled with older rdma_core library.
3259                  */
3260                 DRV_LOG(ERR,
3261                         "No kernel/verbs support for VF LAG bonding found.");
3262                 rte_errno = ENOTSUP;
3263                 ret = -rte_errno;
3264                 goto exit;
3265         }
3266 #endif
3267         /*
3268          * Now we can determine the maximal
3269          * amount of devices to be spawned.
3270          */
3271         list = rte_zmalloc("device spawn data",
3272                          sizeof(struct mlx5_dev_spawn_data) *
3273                          (np ? np : nd),
3274                          RTE_CACHE_LINE_SIZE);
3275         if (!list) {
3276                 DRV_LOG(ERR, "spawn data array allocation failure");
3277                 rte_errno = ENOMEM;
3278                 ret = -rte_errno;
3279                 goto exit;
3280         }
3281         if (bd >= 0 || np > 1) {
3282                 /*
3283                  * Single IB device with multiple ports found,
3284                  * it may be E-Switch master device and representors.
3285                  * We have to perform identification trough the ports.
3286                  */
3287                 MLX5_ASSERT(nl_rdma >= 0);
3288                 MLX5_ASSERT(ns == 0);
3289                 MLX5_ASSERT(nd == 1);
3290                 MLX5_ASSERT(np);
3291                 for (i = 1; i <= np; ++i) {
3292                         list[ns].max_port = np;
3293                         list[ns].ibv_port = i;
3294                         list[ns].ibv_dev = ibv_match[0];
3295                         list[ns].eth_dev = NULL;
3296                         list[ns].pci_dev = pci_dev;
3297                         list[ns].pf_bond = bd;
3298                         list[ns].ifindex = mlx5_nl_ifindex
3299                                         (nl_rdma, list[ns].ibv_dev->name, i);
3300                         if (!list[ns].ifindex) {
3301                                 /*
3302                                  * No network interface index found for the
3303                                  * specified port, it means there is no
3304                                  * representor on this port. It's OK,
3305                                  * there can be disabled ports, for example
3306                                  * if sriov_numvfs < sriov_totalvfs.
3307                                  */
3308                                 continue;
3309                         }
3310                         ret = -1;
3311                         if (nl_route >= 0)
3312                                 ret = mlx5_nl_switch_info
3313                                                (nl_route,
3314                                                 list[ns].ifindex,
3315                                                 &list[ns].info);
3316                         if (ret || (!list[ns].info.representor &&
3317                                     !list[ns].info.master)) {
3318                                 /*
3319                                  * We failed to recognize representors with
3320                                  * Netlink, let's try to perform the task
3321                                  * with sysfs.
3322                                  */
3323                                 ret =  mlx5_sysfs_switch_info
3324                                                 (list[ns].ifindex,
3325                                                  &list[ns].info);
3326                         }
3327                         if (!ret && bd >= 0) {
3328                                 switch (list[ns].info.name_type) {
3329                                 case MLX5_PHYS_PORT_NAME_TYPE_UPLINK:
3330                                         if (list[ns].info.port_name == bd)
3331                                                 ns++;
3332                                         break;
3333                                 case MLX5_PHYS_PORT_NAME_TYPE_PFVF:
3334                                         if (list[ns].info.pf_num == bd)
3335                                                 ns++;
3336                                         break;
3337                                 default:
3338                                         break;
3339                                 }
3340                                 continue;
3341                         }
3342                         if (!ret && (list[ns].info.representor ^
3343                                      list[ns].info.master))
3344                                 ns++;
3345                 }
3346                 if (!ns) {
3347                         DRV_LOG(ERR,
3348                                 "unable to recognize master/representors"
3349                                 " on the IB device with multiple ports");
3350                         rte_errno = ENOENT;
3351                         ret = -rte_errno;
3352                         goto exit;
3353                 }
3354         } else {
3355                 /*
3356                  * The existence of several matching entries (nd > 1) means
3357                  * port representors have been instantiated. No existing Verbs
3358                  * call nor sysfs entries can tell them apart, this can only
3359                  * be done through Netlink calls assuming kernel drivers are
3360                  * recent enough to support them.
3361                  *
3362                  * In the event of identification failure through Netlink,
3363                  * try again through sysfs, then:
3364                  *
3365                  * 1. A single IB device matches (nd == 1) with single
3366                  *    port (np=0/1) and is not a representor, assume
3367                  *    no switch support.
3368                  *
3369                  * 2. Otherwise no safe assumptions can be made;
3370                  *    complain louder and bail out.
3371                  */
3372                 np = 1;
3373                 for (i = 0; i != nd; ++i) {
3374                         memset(&list[ns].info, 0, sizeof(list[ns].info));
3375                         list[ns].max_port = 1;
3376                         list[ns].ibv_port = 1;
3377                         list[ns].ibv_dev = ibv_match[i];
3378                         list[ns].eth_dev = NULL;
3379                         list[ns].pci_dev = pci_dev;
3380                         list[ns].pf_bond = -1;
3381                         list[ns].ifindex = 0;
3382                         if (nl_rdma >= 0)
3383                                 list[ns].ifindex = mlx5_nl_ifindex
3384                                         (nl_rdma, list[ns].ibv_dev->name, 1);
3385                         if (!list[ns].ifindex) {
3386                                 char ifname[IF_NAMESIZE];
3387
3388                                 /*
3389                                  * Netlink failed, it may happen with old
3390                                  * ib_core kernel driver (before 4.16).
3391                                  * We can assume there is old driver because
3392                                  * here we are processing single ports IB
3393                                  * devices. Let's try sysfs to retrieve
3394                                  * the ifindex. The method works for
3395                                  * master device only.
3396                                  */
3397                                 if (nd > 1) {
3398                                         /*
3399                                          * Multiple devices found, assume
3400                                          * representors, can not distinguish
3401                                          * master/representor and retrieve
3402                                          * ifindex via sysfs.
3403                                          */
3404                                         continue;
3405                                 }
3406                                 ret = mlx5_get_master_ifname
3407                                         (ibv_match[i]->ibdev_path, &ifname);
3408                                 if (!ret)
3409                                         list[ns].ifindex =
3410                                                 if_nametoindex(ifname);
3411                                 if (!list[ns].ifindex) {
3412                                         /*
3413                                          * No network interface index found
3414                                          * for the specified device, it means
3415                                          * there it is neither representor
3416                                          * nor master.
3417                                          */
3418                                         continue;
3419                                 }
3420                         }
3421                         ret = -1;
3422                         if (nl_route >= 0)
3423                                 ret = mlx5_nl_switch_info
3424                                                (nl_route,
3425                                                 list[ns].ifindex,
3426                                                 &list[ns].info);
3427                         if (ret || (!list[ns].info.representor &&
3428                                     !list[ns].info.master)) {
3429                                 /*
3430                                  * We failed to recognize representors with
3431                                  * Netlink, let's try to perform the task
3432                                  * with sysfs.
3433                                  */
3434                                 ret =  mlx5_sysfs_switch_info
3435                                                 (list[ns].ifindex,
3436                                                  &list[ns].info);
3437                         }
3438                         if (!ret && (list[ns].info.representor ^
3439                                      list[ns].info.master)) {
3440                                 ns++;
3441                         } else if ((nd == 1) &&
3442                                    !list[ns].info.representor &&
3443                                    !list[ns].info.master) {
3444                                 /*
3445                                  * Single IB device with
3446                                  * one physical port and
3447                                  * attached network device.
3448                                  * May be SRIOV is not enabled
3449                                  * or there is no representors.
3450                                  */
3451                                 DRV_LOG(INFO, "no E-Switch support detected");
3452                                 ns++;
3453                                 break;
3454                         }
3455                 }
3456                 if (!ns) {
3457                         DRV_LOG(ERR,
3458                                 "unable to recognize master/representors"
3459                                 " on the multiple IB devices");
3460                         rte_errno = ENOENT;
3461                         ret = -rte_errno;
3462                         goto exit;
3463                 }
3464         }
3465         MLX5_ASSERT(ns);
3466         /*
3467          * Sort list to probe devices in natural order for users convenience
3468          * (i.e. master first, then representors from lowest to highest ID).
3469          */
3470         qsort(list, ns, sizeof(*list), mlx5_dev_spawn_data_cmp);
3471         /* Default configuration. */
3472         dev_config = (struct mlx5_dev_config){
3473                 .hw_padding = 0,
3474                 .mps = MLX5_ARG_UNSET,
3475                 .dbnc = MLX5_ARG_UNSET,
3476                 .rx_vec_en = 1,
3477                 .txq_inline_max = MLX5_ARG_UNSET,
3478                 .txq_inline_min = MLX5_ARG_UNSET,
3479                 .txq_inline_mpw = MLX5_ARG_UNSET,
3480                 .txqs_inline = MLX5_ARG_UNSET,
3481                 .vf_nl_en = 1,
3482                 .mr_ext_memseg_en = 1,
3483                 .mprq = {
3484                         .enabled = 0, /* Disabled by default. */
3485                         .stride_num_n = 0,
3486                         .stride_size_n = 0,
3487                         .max_memcpy_len = MLX5_MPRQ_MEMCPY_DEFAULT_LEN,
3488                         .min_rxqs_num = MLX5_MPRQ_MIN_RXQS,
3489                 },
3490                 .dv_esw_en = 1,
3491                 .dv_flow_en = 1,
3492                 .log_hp_size = MLX5_ARG_UNSET,
3493         };
3494         /* Device specific configuration. */
3495         switch (pci_dev->id.device_id) {
3496         case PCI_DEVICE_ID_MELLANOX_CONNECTX4VF:
3497         case PCI_DEVICE_ID_MELLANOX_CONNECTX4LXVF:
3498         case PCI_DEVICE_ID_MELLANOX_CONNECTX5VF:
3499         case PCI_DEVICE_ID_MELLANOX_CONNECTX5EXVF:
3500         case PCI_DEVICE_ID_MELLANOX_CONNECTX5BFVF:
3501         case PCI_DEVICE_ID_MELLANOX_CONNECTX6VF:
3502         case PCI_DEVICE_ID_MELLANOX_CONNECTX6DXVF:
3503                 dev_config.vf = 1;
3504                 break;
3505         default:
3506                 break;
3507         }
3508         for (i = 0; i != ns; ++i) {
3509                 uint32_t restore;
3510
3511                 list[i].eth_dev = mlx5_dev_spawn(&pci_dev->device,
3512                                                  &list[i],
3513                                                  dev_config);
3514                 if (!list[i].eth_dev) {
3515                         if (rte_errno != EBUSY && rte_errno != EEXIST)
3516                                 break;
3517                         /* Device is disabled or already spawned. Ignore it. */
3518                         continue;
3519                 }
3520                 restore = list[i].eth_dev->data->dev_flags;
3521                 rte_eth_copy_pci_info(list[i].eth_dev, pci_dev);
3522                 /* Restore non-PCI flags cleared by the above call. */
3523                 list[i].eth_dev->data->dev_flags |= restore;
3524                 mlx5_dev_interrupt_handler_devx_install(list[i].eth_dev);
3525                 rte_eth_dev_probing_finish(list[i].eth_dev);
3526         }
3527         if (i != ns) {
3528                 DRV_LOG(ERR,
3529                         "probe of PCI device " PCI_PRI_FMT " aborted after"
3530                         " encountering an error: %s",
3531                         pci_dev->addr.domain, pci_dev->addr.bus,
3532                         pci_dev->addr.devid, pci_dev->addr.function,
3533                         strerror(rte_errno));
3534                 ret = -rte_errno;
3535                 /* Roll back. */
3536                 while (i--) {
3537                         if (!list[i].eth_dev)
3538                                 continue;
3539                         mlx5_dev_close(list[i].eth_dev);
3540                         /* mac_addrs must not be freed because in dev_private */
3541                         list[i].eth_dev->data->mac_addrs = NULL;
3542                         claim_zero(rte_eth_dev_release_port(list[i].eth_dev));
3543                 }
3544                 /* Restore original error. */
3545                 rte_errno = -ret;
3546         } else {
3547                 ret = 0;
3548         }
3549 exit:
3550         /*
3551          * Do the routine cleanup:
3552          * - close opened Netlink sockets
3553          * - free allocated spawn data array
3554          * - free the Infiniband device list
3555          */
3556         if (nl_rdma >= 0)
3557                 close(nl_rdma);
3558         if (nl_route >= 0)
3559                 close(nl_route);
3560         if (list)
3561                 rte_free(list);
3562         MLX5_ASSERT(ibv_list);
3563         mlx5_glue->free_device_list(ibv_list);
3564         return ret;
3565 }
3566
3567 /**
3568  * Look for the ethernet device belonging to mlx5 driver.
3569  *
3570  * @param[in] port_id
3571  *   port_id to start looking for device.
3572  * @param[in] pci_dev
3573  *   Pointer to the hint PCI device. When device is being probed
3574  *   the its siblings (master and preceding representors might
3575  *   not have assigned driver yet (because the mlx5_pci_probe()
3576  *   is not completed yet, for this case match on hint PCI
3577  *   device may be used to detect sibling device.
3578  *
3579  * @return
3580  *   port_id of found device, RTE_MAX_ETHPORT if not found.
3581  */
3582 uint16_t
3583 mlx5_eth_find_next(uint16_t port_id, struct rte_pci_device *pci_dev)
3584 {
3585         while (port_id < RTE_MAX_ETHPORTS) {
3586                 struct rte_eth_dev *dev = &rte_eth_devices[port_id];
3587
3588                 if (dev->state != RTE_ETH_DEV_UNUSED &&
3589                     dev->device &&
3590                     (dev->device == &pci_dev->device ||
3591                      (dev->device->driver &&
3592                      dev->device->driver->name &&
3593                      !strcmp(dev->device->driver->name, MLX5_DRIVER_NAME))))
3594                         break;
3595                 port_id++;
3596         }
3597         if (port_id >= RTE_MAX_ETHPORTS)
3598                 return RTE_MAX_ETHPORTS;
3599         return port_id;
3600 }
3601
3602 /**
3603  * DPDK callback to remove a PCI device.
3604  *
3605  * This function removes all Ethernet devices belong to a given PCI device.
3606  *
3607  * @param[in] pci_dev
3608  *   Pointer to the PCI device.
3609  *
3610  * @return
3611  *   0 on success, the function cannot fail.
3612  */
3613 static int
3614 mlx5_pci_remove(struct rte_pci_device *pci_dev)
3615 {
3616         uint16_t port_id;
3617
3618         RTE_ETH_FOREACH_DEV_OF(port_id, &pci_dev->device)
3619                 rte_eth_dev_close(port_id);
3620         return 0;
3621 }
3622
3623 static const struct rte_pci_id mlx5_pci_id_map[] = {
3624         {
3625                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
3626                                PCI_DEVICE_ID_MELLANOX_CONNECTX4)
3627         },
3628         {
3629                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
3630                                PCI_DEVICE_ID_MELLANOX_CONNECTX4VF)
3631         },
3632         {
3633                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
3634                                PCI_DEVICE_ID_MELLANOX_CONNECTX4LX)
3635         },
3636         {
3637                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
3638                                PCI_DEVICE_ID_MELLANOX_CONNECTX4LXVF)
3639         },
3640         {
3641                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
3642                                PCI_DEVICE_ID_MELLANOX_CONNECTX5)
3643         },
3644         {
3645                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
3646                                PCI_DEVICE_ID_MELLANOX_CONNECTX5VF)
3647         },
3648         {
3649                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
3650                                PCI_DEVICE_ID_MELLANOX_CONNECTX5EX)
3651         },
3652         {
3653                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
3654                                PCI_DEVICE_ID_MELLANOX_CONNECTX5EXVF)
3655         },
3656         {
3657                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
3658                                PCI_DEVICE_ID_MELLANOX_CONNECTX5BF)
3659         },
3660         {
3661                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
3662                                PCI_DEVICE_ID_MELLANOX_CONNECTX5BFVF)
3663         },
3664         {
3665                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
3666                                 PCI_DEVICE_ID_MELLANOX_CONNECTX6)
3667         },
3668         {
3669                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
3670                                 PCI_DEVICE_ID_MELLANOX_CONNECTX6VF)
3671         },
3672         {
3673                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
3674                                 PCI_DEVICE_ID_MELLANOX_CONNECTX6DX)
3675         },
3676         {
3677                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
3678                                 PCI_DEVICE_ID_MELLANOX_CONNECTX6DXVF)
3679         },
3680         {
3681                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
3682                                 PCI_DEVICE_ID_MELLANOX_CONNECTX6DXBF)
3683         },
3684         {
3685                 .vendor_id = 0
3686         }
3687 };
3688
3689 static struct rte_pci_driver mlx5_driver = {
3690         .driver = {
3691                 .name = MLX5_DRIVER_NAME
3692         },
3693         .id_table = mlx5_pci_id_map,
3694         .probe = mlx5_pci_probe,
3695         .remove = mlx5_pci_remove,
3696         .dma_map = mlx5_dma_map,
3697         .dma_unmap = mlx5_dma_unmap,
3698         .drv_flags = RTE_PCI_DRV_INTR_LSC | RTE_PCI_DRV_INTR_RMV |
3699                      RTE_PCI_DRV_PROBE_AGAIN,
3700 };
3701
3702 /**
3703  * Driver initialization routine.
3704  */
3705 RTE_INIT(rte_mlx5_pmd_init)
3706 {
3707         /* Initialize driver log type. */
3708         mlx5_logtype = rte_log_register("pmd.net.mlx5");
3709         if (mlx5_logtype >= 0)
3710                 rte_log_set_level(mlx5_logtype, RTE_LOG_NOTICE);
3711
3712         /* Build the static tables for Verbs conversion. */
3713         mlx5_set_ptype_table();
3714         mlx5_set_cksum_table();
3715         mlx5_set_swp_types_table();
3716         if (mlx5_glue)
3717                 rte_pci_register(&mlx5_driver);
3718 }
3719
3720 RTE_PMD_EXPORT_NAME(net_mlx5, __COUNTER__);
3721 RTE_PMD_REGISTER_PCI_TABLE(net_mlx5, mlx5_pci_id_map);
3722 RTE_PMD_REGISTER_KMOD_DEP(net_mlx5, "* ib_uverbs & mlx5_core & mlx5_ib");