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