c15a44de86d955cf1d7217632322da44d78ce3d8
[dpdk.git] / drivers / net / mlx5 / linux / mlx5_os.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright 2015 6WIND S.A.
3  * Copyright 2020 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 <linux/rtnetlink.h>
14 #include <linux/sockios.h>
15 #include <linux/ethtool.h>
16 #include <fcntl.h>
17
18 #include <rte_malloc.h>
19 #include <ethdev_driver.h>
20 #include <ethdev_pci.h>
21 #include <rte_pci.h>
22 #include <rte_bus_pci.h>
23 #include <rte_bus_auxiliary.h>
24 #include <rte_common.h>
25 #include <rte_kvargs.h>
26 #include <rte_rwlock.h>
27 #include <rte_spinlock.h>
28 #include <rte_string_fns.h>
29 #include <rte_alarm.h>
30 #include <rte_eal_paging.h>
31
32 #include <mlx5_glue.h>
33 #include <mlx5_devx_cmds.h>
34 #include <mlx5_common.h>
35 #include <mlx5_common_mp.h>
36 #include <mlx5_common_mr.h>
37 #include <mlx5_malloc.h>
38
39 #include "mlx5_defs.h"
40 #include "mlx5.h"
41 #include "mlx5_common_os.h"
42 #include "mlx5_utils.h"
43 #include "mlx5_rxtx.h"
44 #include "mlx5_rx.h"
45 #include "mlx5_tx.h"
46 #include "mlx5_autoconf.h"
47 #include "mlx5_mr.h"
48 #include "mlx5_flow.h"
49 #include "rte_pmd_mlx5.h"
50 #include "mlx5_verbs.h"
51 #include "mlx5_nl.h"
52 #include "mlx5_devx.h"
53
54 #ifndef HAVE_IBV_MLX5_MOD_MPW
55 #define MLX5DV_CONTEXT_FLAGS_MPW_ALLOWED (1 << 2)
56 #define MLX5DV_CONTEXT_FLAGS_ENHANCED_MPW (1 << 3)
57 #endif
58
59 #ifndef HAVE_IBV_MLX5_MOD_CQE_128B_COMP
60 #define MLX5DV_CONTEXT_FLAGS_CQE_128B_COMP (1 << 4)
61 #endif
62
63 static const char *MZ_MLX5_PMD_SHARED_DATA = "mlx5_pmd_shared_data";
64
65 /* Spinlock for mlx5_shared_data allocation. */
66 static rte_spinlock_t mlx5_shared_data_lock = RTE_SPINLOCK_INITIALIZER;
67
68 /* Process local data for secondary processes. */
69 static struct mlx5_local_data mlx5_local_data;
70
71 /* rte flow indexed pool configuration. */
72 static struct mlx5_indexed_pool_config icfg[] = {
73         {
74                 .size = sizeof(struct rte_flow),
75                 .trunk_size = 64,
76                 .need_lock = 1,
77                 .release_mem_en = 0,
78                 .malloc = mlx5_malloc,
79                 .free = mlx5_free,
80                 .per_core_cache = 0,
81                 .type = "ctl_flow_ipool",
82         },
83         {
84                 .size = sizeof(struct rte_flow),
85                 .trunk_size = 64,
86                 .grow_trunk = 3,
87                 .grow_shift = 2,
88                 .need_lock = 1,
89                 .release_mem_en = 0,
90                 .malloc = mlx5_malloc,
91                 .free = mlx5_free,
92                 .per_core_cache = 1 << 14,
93                 .type = "rte_flow_ipool",
94         },
95         {
96                 .size = sizeof(struct rte_flow),
97                 .trunk_size = 64,
98                 .grow_trunk = 3,
99                 .grow_shift = 2,
100                 .need_lock = 1,
101                 .release_mem_en = 0,
102                 .malloc = mlx5_malloc,
103                 .free = mlx5_free,
104                 .per_core_cache = 0,
105                 .type = "mcp_flow_ipool",
106         },
107 };
108
109 /**
110  * Set the completion channel file descriptor interrupt as non-blocking.
111  *
112  * @param[in] rxq_obj
113  *   Pointer to RQ channel object, which includes the channel fd
114  *
115  * @param[out] fd
116  *   The file descriptor (representing the intetrrupt) used in this channel.
117  *
118  * @return
119  *   0 on successfully setting the fd to non-blocking, non-zero otherwise.
120  */
121 int
122 mlx5_os_set_nonblock_channel_fd(int fd)
123 {
124         int flags;
125
126         flags = fcntl(fd, F_GETFL);
127         return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
128 }
129
130 /**
131  * Get mlx5 device attributes. The glue function query_device_ex() is called
132  * with out parameter of type 'struct ibv_device_attr_ex *'. Then fill in mlx5
133  * device attributes from the glue out parameter.
134  *
135  * @param dev
136  *   Pointer to ibv context.
137  *
138  * @param device_attr
139  *   Pointer to mlx5 device attributes.
140  *
141  * @return
142  *   0 on success, non zero error number otherwise
143  */
144 int
145 mlx5_os_get_dev_attr(void *ctx, struct mlx5_dev_attr *device_attr)
146 {
147         int err;
148         struct ibv_device_attr_ex attr_ex;
149         memset(device_attr, 0, sizeof(*device_attr));
150         err = mlx5_glue->query_device_ex(ctx, NULL, &attr_ex);
151         if (err)
152                 return err;
153
154         device_attr->device_cap_flags_ex = attr_ex.device_cap_flags_ex;
155         device_attr->max_qp_wr = attr_ex.orig_attr.max_qp_wr;
156         device_attr->max_sge = attr_ex.orig_attr.max_sge;
157         device_attr->max_cq = attr_ex.orig_attr.max_cq;
158         device_attr->max_cqe = attr_ex.orig_attr.max_cqe;
159         device_attr->max_mr = attr_ex.orig_attr.max_mr;
160         device_attr->max_pd = attr_ex.orig_attr.max_pd;
161         device_attr->max_qp = attr_ex.orig_attr.max_qp;
162         device_attr->max_srq = attr_ex.orig_attr.max_srq;
163         device_attr->max_srq_wr = attr_ex.orig_attr.max_srq_wr;
164         device_attr->raw_packet_caps = attr_ex.raw_packet_caps;
165         device_attr->max_rwq_indirection_table_size =
166                 attr_ex.rss_caps.max_rwq_indirection_table_size;
167         device_attr->max_tso = attr_ex.tso_caps.max_tso;
168         device_attr->tso_supported_qpts = attr_ex.tso_caps.supported_qpts;
169
170         struct mlx5dv_context dv_attr = { .comp_mask = 0 };
171         err = mlx5_glue->dv_query_device(ctx, &dv_attr);
172         if (err)
173                 return err;
174
175         device_attr->flags = dv_attr.flags;
176         device_attr->comp_mask = dv_attr.comp_mask;
177 #ifdef HAVE_IBV_MLX5_MOD_SWP
178         device_attr->sw_parsing_offloads =
179                 dv_attr.sw_parsing_caps.sw_parsing_offloads;
180 #endif
181         device_attr->min_single_stride_log_num_of_bytes =
182                 dv_attr.striding_rq_caps.min_single_stride_log_num_of_bytes;
183         device_attr->max_single_stride_log_num_of_bytes =
184                 dv_attr.striding_rq_caps.max_single_stride_log_num_of_bytes;
185         device_attr->min_single_wqe_log_num_of_strides =
186                 dv_attr.striding_rq_caps.min_single_wqe_log_num_of_strides;
187         device_attr->max_single_wqe_log_num_of_strides =
188                 dv_attr.striding_rq_caps.max_single_wqe_log_num_of_strides;
189         device_attr->stride_supported_qpts =
190                 dv_attr.striding_rq_caps.supported_qpts;
191 #ifdef HAVE_IBV_DEVICE_TUNNEL_SUPPORT
192         device_attr->tunnel_offloads_caps = dv_attr.tunnel_offloads_caps;
193 #endif
194         strlcpy(device_attr->fw_ver, attr_ex.orig_attr.fw_ver,
195                 sizeof(device_attr->fw_ver));
196
197         return err;
198 }
199
200 /**
201  * Verbs callback to allocate a memory. This function should allocate the space
202  * according to the size provided residing inside a huge page.
203  * Please note that all allocation must respect the alignment from libmlx5
204  * (i.e. currently rte_mem_page_size()).
205  *
206  * @param[in] size
207  *   The size in bytes of the memory to allocate.
208  * @param[in] data
209  *   A pointer to the callback data.
210  *
211  * @return
212  *   Allocated buffer, NULL otherwise and rte_errno is set.
213  */
214 static void *
215 mlx5_alloc_verbs_buf(size_t size, void *data)
216 {
217         struct mlx5_dev_ctx_shared *sh = data;
218         void *ret;
219         size_t alignment = rte_mem_page_size();
220         if (alignment == (size_t)-1) {
221                 DRV_LOG(ERR, "Failed to get mem page size");
222                 rte_errno = ENOMEM;
223                 return NULL;
224         }
225
226         MLX5_ASSERT(data != NULL);
227         ret = mlx5_malloc(0, size, alignment, sh->numa_node);
228         if (!ret && size)
229                 rte_errno = ENOMEM;
230         return ret;
231 }
232
233 /**
234  * Detect misc5 support or not
235  *
236  * @param[in] priv
237  *   Device private data pointer
238  */
239 #ifdef HAVE_MLX5DV_DR
240 static void
241 __mlx5_discovery_misc5_cap(struct mlx5_priv *priv)
242 {
243 #ifdef HAVE_IBV_FLOW_DV_SUPPORT
244         /* Dummy VxLAN matcher to detect rdma-core misc5 cap
245          * Case: IPv4--->UDP--->VxLAN--->vni
246          */
247         void *tbl;
248         struct mlx5_flow_dv_match_params matcher_mask;
249         void *match_m;
250         void *matcher;
251         void *headers_m;
252         void *misc5_m;
253         uint32_t *tunnel_header_m;
254         struct mlx5dv_flow_matcher_attr dv_attr;
255
256         memset(&matcher_mask, 0, sizeof(matcher_mask));
257         matcher_mask.size = sizeof(matcher_mask.buf);
258         match_m = matcher_mask.buf;
259         headers_m = MLX5_ADDR_OF(fte_match_param, match_m, outer_headers);
260         misc5_m = MLX5_ADDR_OF(fte_match_param,
261                                match_m, misc_parameters_5);
262         tunnel_header_m = (uint32_t *)
263                                 MLX5_ADDR_OF(fte_match_set_misc5,
264                                 misc5_m, tunnel_header_1);
265         MLX5_SET(fte_match_set_lyr_2_4, headers_m, ip_protocol, 0xff);
266         MLX5_SET(fte_match_set_lyr_2_4, headers_m, ip_version, 4);
267         MLX5_SET(fte_match_set_lyr_2_4, headers_m, udp_dport, 0xffff);
268         *tunnel_header_m = 0xffffff;
269
270         tbl = mlx5_glue->dr_create_flow_tbl(priv->sh->rx_domain, 1);
271         if (!tbl) {
272                 DRV_LOG(INFO, "No SW steering support");
273                 return;
274         }
275         dv_attr.type = IBV_FLOW_ATTR_NORMAL,
276         dv_attr.match_mask = (void *)&matcher_mask,
277         dv_attr.match_criteria_enable =
278                         (1 << MLX5_MATCH_CRITERIA_ENABLE_OUTER_BIT) |
279                         (1 << MLX5_MATCH_CRITERIA_ENABLE_MISC5_BIT);
280         dv_attr.priority = 3;
281 #ifdef HAVE_MLX5DV_DR_ESWITCH
282         void *misc2_m;
283         if (priv->config.dv_esw_en) {
284                 /* FDB enabled reg_c_0 */
285                 dv_attr.match_criteria_enable |=
286                                 (1 << MLX5_MATCH_CRITERIA_ENABLE_MISC2_BIT);
287                 misc2_m = MLX5_ADDR_OF(fte_match_param,
288                                        match_m, misc_parameters_2);
289                 MLX5_SET(fte_match_set_misc2, misc2_m,
290                          metadata_reg_c_0, 0xffff);
291         }
292 #endif
293         matcher = mlx5_glue->dv_create_flow_matcher(priv->sh->ctx,
294                                                     &dv_attr, tbl);
295         if (matcher) {
296                 priv->sh->misc5_cap = 1;
297                 mlx5_glue->dv_destroy_flow_matcher(matcher);
298         }
299         mlx5_glue->dr_destroy_flow_tbl(tbl);
300 #else
301         RTE_SET_USED(priv);
302 #endif
303 }
304 #endif
305
306 /**
307  * Verbs callback to free a memory.
308  *
309  * @param[in] ptr
310  *   A pointer to the memory to free.
311  * @param[in] data
312  *   A pointer to the callback data.
313  */
314 static void
315 mlx5_free_verbs_buf(void *ptr, void *data __rte_unused)
316 {
317         MLX5_ASSERT(data != NULL);
318         mlx5_free(ptr);
319 }
320
321 /**
322  * Initialize DR related data within private structure.
323  * Routine checks the reference counter and does actual
324  * resources creation/initialization only if counter is zero.
325  *
326  * @param[in] priv
327  *   Pointer to the private device data structure.
328  *
329  * @return
330  *   Zero on success, positive error code otherwise.
331  */
332 static int
333 mlx5_alloc_shared_dr(struct mlx5_priv *priv)
334 {
335         struct mlx5_dev_ctx_shared *sh = priv->sh;
336         char s[MLX5_NAME_SIZE] __rte_unused;
337         int err;
338
339         MLX5_ASSERT(sh && sh->refcnt);
340         if (sh->refcnt > 1)
341                 return 0;
342         err = mlx5_alloc_table_hash_list(priv);
343         if (err)
344                 goto error;
345         /* The resources below are only valid with DV support. */
346 #ifdef HAVE_IBV_FLOW_DV_SUPPORT
347         /* Init port id action list. */
348         snprintf(s, sizeof(s), "%s_port_id_action_list", sh->ibdev_name);
349         sh->port_id_action_list = mlx5_list_create(s, sh, true,
350                                                    flow_dv_port_id_create_cb,
351                                                    flow_dv_port_id_match_cb,
352                                                    flow_dv_port_id_remove_cb,
353                                                    flow_dv_port_id_clone_cb,
354                                                  flow_dv_port_id_clone_free_cb);
355         if (!sh->port_id_action_list)
356                 goto error;
357         /* Init push vlan action list. */
358         snprintf(s, sizeof(s), "%s_push_vlan_action_list", sh->ibdev_name);
359         sh->push_vlan_action_list = mlx5_list_create(s, sh, true,
360                                                     flow_dv_push_vlan_create_cb,
361                                                     flow_dv_push_vlan_match_cb,
362                                                     flow_dv_push_vlan_remove_cb,
363                                                     flow_dv_push_vlan_clone_cb,
364                                                flow_dv_push_vlan_clone_free_cb);
365         if (!sh->push_vlan_action_list)
366                 goto error;
367         /* Init sample action list. */
368         snprintf(s, sizeof(s), "%s_sample_action_list", sh->ibdev_name);
369         sh->sample_action_list = mlx5_list_create(s, sh, true,
370                                                   flow_dv_sample_create_cb,
371                                                   flow_dv_sample_match_cb,
372                                                   flow_dv_sample_remove_cb,
373                                                   flow_dv_sample_clone_cb,
374                                                   flow_dv_sample_clone_free_cb);
375         if (!sh->sample_action_list)
376                 goto error;
377         /* Init dest array action list. */
378         snprintf(s, sizeof(s), "%s_dest_array_list", sh->ibdev_name);
379         sh->dest_array_list = mlx5_list_create(s, sh, true,
380                                                flow_dv_dest_array_create_cb,
381                                                flow_dv_dest_array_match_cb,
382                                                flow_dv_dest_array_remove_cb,
383                                                flow_dv_dest_array_clone_cb,
384                                               flow_dv_dest_array_clone_free_cb);
385         if (!sh->dest_array_list)
386                 goto error;
387 #endif
388 #ifdef HAVE_MLX5DV_DR
389         void *domain;
390
391         /* Reference counter is zero, we should initialize structures. */
392         domain = mlx5_glue->dr_create_domain(sh->ctx,
393                                              MLX5DV_DR_DOMAIN_TYPE_NIC_RX);
394         if (!domain) {
395                 DRV_LOG(ERR, "ingress mlx5dv_dr_create_domain failed");
396                 err = errno;
397                 goto error;
398         }
399         sh->rx_domain = domain;
400         domain = mlx5_glue->dr_create_domain(sh->ctx,
401                                              MLX5DV_DR_DOMAIN_TYPE_NIC_TX);
402         if (!domain) {
403                 DRV_LOG(ERR, "egress mlx5dv_dr_create_domain failed");
404                 err = errno;
405                 goto error;
406         }
407         sh->tx_domain = domain;
408 #ifdef HAVE_MLX5DV_DR_ESWITCH
409         if (priv->config.dv_esw_en) {
410                 domain  = mlx5_glue->dr_create_domain
411                         (sh->ctx, MLX5DV_DR_DOMAIN_TYPE_FDB);
412                 if (!domain) {
413                         DRV_LOG(ERR, "FDB mlx5dv_dr_create_domain failed");
414                         err = errno;
415                         goto error;
416                 }
417                 sh->fdb_domain = domain;
418         }
419         /*
420          * The drop action is just some dummy placeholder in rdma-core. It
421          * does not belong to domains and has no any attributes, and, can be
422          * shared by the entire device.
423          */
424         sh->dr_drop_action = mlx5_glue->dr_create_flow_action_drop();
425         if (!sh->dr_drop_action) {
426                 DRV_LOG(ERR, "FDB mlx5dv_dr_create_flow_action_drop");
427                 err = errno;
428                 goto error;
429         }
430 #endif
431         if (!sh->tunnel_hub && priv->config.dv_miss_info)
432                 err = mlx5_alloc_tunnel_hub(sh);
433         if (err) {
434                 DRV_LOG(ERR, "mlx5_alloc_tunnel_hub failed err=%d", err);
435                 goto error;
436         }
437         if (priv->config.reclaim_mode == MLX5_RCM_AGGR) {
438                 mlx5_glue->dr_reclaim_domain_memory(sh->rx_domain, 1);
439                 mlx5_glue->dr_reclaim_domain_memory(sh->tx_domain, 1);
440                 if (sh->fdb_domain)
441                         mlx5_glue->dr_reclaim_domain_memory(sh->fdb_domain, 1);
442         }
443         sh->pop_vlan_action = mlx5_glue->dr_create_flow_action_pop_vlan();
444         if (!priv->config.allow_duplicate_pattern) {
445 #ifndef HAVE_MLX5_DR_ALLOW_DUPLICATE
446                 DRV_LOG(WARNING, "Disallow duplicate pattern is not supported - maybe old rdma-core version?");
447 #endif
448                 mlx5_glue->dr_allow_duplicate_rules(sh->rx_domain, 0);
449                 mlx5_glue->dr_allow_duplicate_rules(sh->tx_domain, 0);
450                 if (sh->fdb_domain)
451                         mlx5_glue->dr_allow_duplicate_rules(sh->fdb_domain, 0);
452         }
453
454         __mlx5_discovery_misc5_cap(priv);
455 #endif /* HAVE_MLX5DV_DR */
456         sh->default_miss_action =
457                         mlx5_glue->dr_create_flow_action_default_miss();
458         if (!sh->default_miss_action)
459                 DRV_LOG(WARNING, "Default miss action is not supported.");
460         return 0;
461 error:
462         /* Rollback the created objects. */
463         if (sh->rx_domain) {
464                 mlx5_glue->dr_destroy_domain(sh->rx_domain);
465                 sh->rx_domain = NULL;
466         }
467         if (sh->tx_domain) {
468                 mlx5_glue->dr_destroy_domain(sh->tx_domain);
469                 sh->tx_domain = NULL;
470         }
471         if (sh->fdb_domain) {
472                 mlx5_glue->dr_destroy_domain(sh->fdb_domain);
473                 sh->fdb_domain = NULL;
474         }
475         if (sh->dr_drop_action) {
476                 mlx5_glue->destroy_flow_action(sh->dr_drop_action);
477                 sh->dr_drop_action = NULL;
478         }
479         if (sh->pop_vlan_action) {
480                 mlx5_glue->destroy_flow_action(sh->pop_vlan_action);
481                 sh->pop_vlan_action = NULL;
482         }
483         if (sh->encaps_decaps) {
484                 mlx5_hlist_destroy(sh->encaps_decaps);
485                 sh->encaps_decaps = NULL;
486         }
487         if (sh->modify_cmds) {
488                 mlx5_hlist_destroy(sh->modify_cmds);
489                 sh->modify_cmds = NULL;
490         }
491         if (sh->tag_table) {
492                 /* tags should be destroyed with flow before. */
493                 mlx5_hlist_destroy(sh->tag_table);
494                 sh->tag_table = NULL;
495         }
496         if (sh->tunnel_hub) {
497                 mlx5_release_tunnel_hub(sh, priv->dev_port);
498                 sh->tunnel_hub = NULL;
499         }
500         mlx5_free_table_hash_list(priv);
501         if (sh->port_id_action_list) {
502                 mlx5_list_destroy(sh->port_id_action_list);
503                 sh->port_id_action_list = NULL;
504         }
505         if (sh->push_vlan_action_list) {
506                 mlx5_list_destroy(sh->push_vlan_action_list);
507                 sh->push_vlan_action_list = NULL;
508         }
509         if (sh->sample_action_list) {
510                 mlx5_list_destroy(sh->sample_action_list);
511                 sh->sample_action_list = NULL;
512         }
513         if (sh->dest_array_list) {
514                 mlx5_list_destroy(sh->dest_array_list);
515                 sh->dest_array_list = NULL;
516         }
517         return err;
518 }
519
520 /**
521  * Destroy DR related data within private structure.
522  *
523  * @param[in] priv
524  *   Pointer to the private device data structure.
525  */
526 void
527 mlx5_os_free_shared_dr(struct mlx5_priv *priv)
528 {
529         struct mlx5_dev_ctx_shared *sh = priv->sh;
530
531         MLX5_ASSERT(sh && sh->refcnt);
532         if (sh->refcnt > 1)
533                 return;
534 #ifdef HAVE_MLX5DV_DR
535         if (sh->rx_domain) {
536                 mlx5_glue->dr_destroy_domain(sh->rx_domain);
537                 sh->rx_domain = NULL;
538         }
539         if (sh->tx_domain) {
540                 mlx5_glue->dr_destroy_domain(sh->tx_domain);
541                 sh->tx_domain = NULL;
542         }
543 #ifdef HAVE_MLX5DV_DR_ESWITCH
544         if (sh->fdb_domain) {
545                 mlx5_glue->dr_destroy_domain(sh->fdb_domain);
546                 sh->fdb_domain = NULL;
547         }
548         if (sh->dr_drop_action) {
549                 mlx5_glue->destroy_flow_action(sh->dr_drop_action);
550                 sh->dr_drop_action = NULL;
551         }
552 #endif
553         if (sh->pop_vlan_action) {
554                 mlx5_glue->destroy_flow_action(sh->pop_vlan_action);
555                 sh->pop_vlan_action = NULL;
556         }
557 #endif /* HAVE_MLX5DV_DR */
558         if (sh->default_miss_action)
559                 mlx5_glue->destroy_flow_action
560                                 (sh->default_miss_action);
561         if (sh->encaps_decaps) {
562                 mlx5_hlist_destroy(sh->encaps_decaps);
563                 sh->encaps_decaps = NULL;
564         }
565         if (sh->modify_cmds) {
566                 mlx5_hlist_destroy(sh->modify_cmds);
567                 sh->modify_cmds = NULL;
568         }
569         if (sh->tag_table) {
570                 /* tags should be destroyed with flow before. */
571                 mlx5_hlist_destroy(sh->tag_table);
572                 sh->tag_table = NULL;
573         }
574         if (sh->tunnel_hub) {
575                 mlx5_release_tunnel_hub(sh, priv->dev_port);
576                 sh->tunnel_hub = NULL;
577         }
578         mlx5_free_table_hash_list(priv);
579         if (sh->port_id_action_list) {
580                 mlx5_list_destroy(sh->port_id_action_list);
581                 sh->port_id_action_list = NULL;
582         }
583         if (sh->push_vlan_action_list) {
584                 mlx5_list_destroy(sh->push_vlan_action_list);
585                 sh->push_vlan_action_list = NULL;
586         }
587         if (sh->sample_action_list) {
588                 mlx5_list_destroy(sh->sample_action_list);
589                 sh->sample_action_list = NULL;
590         }
591         if (sh->dest_array_list) {
592                 mlx5_list_destroy(sh->dest_array_list);
593                 sh->dest_array_list = NULL;
594         }
595 }
596
597 /**
598  * Initialize shared data between primary and secondary process.
599  *
600  * A memzone is reserved by primary process and secondary processes attach to
601  * the memzone.
602  *
603  * @return
604  *   0 on success, a negative errno value otherwise and rte_errno is set.
605  */
606 static int
607 mlx5_init_shared_data(void)
608 {
609         const struct rte_memzone *mz;
610         int ret = 0;
611
612         rte_spinlock_lock(&mlx5_shared_data_lock);
613         if (mlx5_shared_data == NULL) {
614                 if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
615                         /* Allocate shared memory. */
616                         mz = rte_memzone_reserve(MZ_MLX5_PMD_SHARED_DATA,
617                                                  sizeof(*mlx5_shared_data),
618                                                  SOCKET_ID_ANY, 0);
619                         if (mz == NULL) {
620                                 DRV_LOG(ERR,
621                                         "Cannot allocate mlx5 shared data");
622                                 ret = -rte_errno;
623                                 goto error;
624                         }
625                         mlx5_shared_data = mz->addr;
626                         memset(mlx5_shared_data, 0, sizeof(*mlx5_shared_data));
627                         rte_spinlock_init(&mlx5_shared_data->lock);
628                 } else {
629                         /* Lookup allocated shared memory. */
630                         mz = rte_memzone_lookup(MZ_MLX5_PMD_SHARED_DATA);
631                         if (mz == NULL) {
632                                 DRV_LOG(ERR,
633                                         "Cannot attach mlx5 shared data");
634                                 ret = -rte_errno;
635                                 goto error;
636                         }
637                         mlx5_shared_data = mz->addr;
638                         memset(&mlx5_local_data, 0, sizeof(mlx5_local_data));
639                 }
640         }
641 error:
642         rte_spinlock_unlock(&mlx5_shared_data_lock);
643         return ret;
644 }
645
646 /**
647  * PMD global initialization.
648  *
649  * Independent from individual device, this function initializes global
650  * per-PMD data structures distinguishing primary and secondary processes.
651  * Hence, each initialization is called once per a process.
652  *
653  * @return
654  *   0 on success, a negative errno value otherwise and rte_errno is set.
655  */
656 static int
657 mlx5_init_once(void)
658 {
659         struct mlx5_shared_data *sd;
660         struct mlx5_local_data *ld = &mlx5_local_data;
661         int ret = 0;
662
663         if (mlx5_init_shared_data())
664                 return -rte_errno;
665         sd = mlx5_shared_data;
666         MLX5_ASSERT(sd);
667         rte_spinlock_lock(&sd->lock);
668         switch (rte_eal_process_type()) {
669         case RTE_PROC_PRIMARY:
670                 if (sd->init_done)
671                         break;
672                 LIST_INIT(&sd->mem_event_cb_list);
673                 rte_rwlock_init(&sd->mem_event_rwlock);
674                 rte_mem_event_callback_register("MLX5_MEM_EVENT_CB",
675                                                 mlx5_mr_mem_event_cb, NULL);
676                 ret = mlx5_mp_init_primary(MLX5_MP_NAME,
677                                            mlx5_mp_os_primary_handle);
678                 if (ret)
679                         goto out;
680                 sd->init_done = true;
681                 break;
682         case RTE_PROC_SECONDARY:
683                 if (ld->init_done)
684                         break;
685                 ret = mlx5_mp_init_secondary(MLX5_MP_NAME,
686                                              mlx5_mp_os_secondary_handle);
687                 if (ret)
688                         goto out;
689                 ++sd->secondary_cnt;
690                 ld->init_done = true;
691                 break;
692         default:
693                 break;
694         }
695 out:
696         rte_spinlock_unlock(&sd->lock);
697         return ret;
698 }
699
700 /**
701  * Create the Tx queue DevX/Verbs object.
702  *
703  * @param dev
704  *   Pointer to Ethernet device.
705  * @param idx
706  *   Queue index in DPDK Tx queue array.
707  *
708  * @return
709  *   0 on success, a negative errno value otherwise and rte_errno is set.
710  */
711 static int
712 mlx5_os_txq_obj_new(struct rte_eth_dev *dev, uint16_t idx)
713 {
714         struct mlx5_priv *priv = dev->data->dev_private;
715         struct mlx5_txq_data *txq_data = (*priv->txqs)[idx];
716         struct mlx5_txq_ctrl *txq_ctrl =
717                         container_of(txq_data, struct mlx5_txq_ctrl, txq);
718
719         if (txq_ctrl->type == MLX5_TXQ_TYPE_HAIRPIN)
720                 return mlx5_txq_devx_obj_new(dev, idx);
721 #ifdef HAVE_MLX5DV_DEVX_UAR_OFFSET
722         if (!priv->config.dv_esw_en)
723                 return mlx5_txq_devx_obj_new(dev, idx);
724 #endif
725         return mlx5_txq_ibv_obj_new(dev, idx);
726 }
727
728 /**
729  * Release an Tx DevX/verbs queue object.
730  *
731  * @param txq_obj
732  *   DevX/Verbs Tx queue object.
733  */
734 static void
735 mlx5_os_txq_obj_release(struct mlx5_txq_obj *txq_obj)
736 {
737         if (txq_obj->txq_ctrl->type == MLX5_TXQ_TYPE_HAIRPIN) {
738                 mlx5_txq_devx_obj_release(txq_obj);
739                 return;
740         }
741 #ifdef HAVE_MLX5DV_DEVX_UAR_OFFSET
742         if (!txq_obj->txq_ctrl->priv->config.dv_esw_en) {
743                 mlx5_txq_devx_obj_release(txq_obj);
744                 return;
745         }
746 #endif
747         mlx5_txq_ibv_obj_release(txq_obj);
748 }
749
750 /**
751  * DV flow counter mode detect and config.
752  *
753  * @param dev
754  *   Pointer to rte_eth_dev structure.
755  *
756  */
757 static void
758 mlx5_flow_counter_mode_config(struct rte_eth_dev *dev __rte_unused)
759 {
760 #ifdef HAVE_IBV_FLOW_DV_SUPPORT
761         struct mlx5_priv *priv = dev->data->dev_private;
762         struct mlx5_dev_ctx_shared *sh = priv->sh;
763         bool fallback;
764
765 #ifndef HAVE_IBV_DEVX_ASYNC
766         fallback = true;
767 #else
768         fallback = false;
769         if (!priv->config.devx || !priv->config.dv_flow_en ||
770             !priv->config.hca_attr.flow_counters_dump ||
771             !(priv->config.hca_attr.flow_counter_bulk_alloc_bitmap & 0x4) ||
772             (mlx5_flow_dv_discover_counter_offset_support(dev) == -ENOTSUP))
773                 fallback = true;
774 #endif
775         if (fallback)
776                 DRV_LOG(INFO, "Use fall-back DV counter management. Flow "
777                         "counter dump:%d, bulk_alloc_bitmap:0x%hhx.",
778                         priv->config.hca_attr.flow_counters_dump,
779                         priv->config.hca_attr.flow_counter_bulk_alloc_bitmap);
780         /* Initialize fallback mode only on the port initializes sh. */
781         if (sh->refcnt == 1)
782                 sh->cmng.counter_fallback = fallback;
783         else if (fallback != sh->cmng.counter_fallback)
784                 DRV_LOG(WARNING, "Port %d in sh has different fallback mode "
785                         "with others:%d.", PORT_ID(priv), fallback);
786 #endif
787 }
788
789 static void
790 mlx5_queue_counter_id_prepare(struct rte_eth_dev *dev)
791 {
792         struct mlx5_priv *priv = dev->data->dev_private;
793         void *ctx = priv->sh->ctx;
794
795         priv->q_counters = mlx5_devx_cmd_queue_counter_alloc(ctx);
796         if (!priv->q_counters) {
797                 struct ibv_cq *cq = mlx5_glue->create_cq(ctx, 1, NULL, NULL, 0);
798                 struct ibv_wq *wq;
799
800                 DRV_LOG(DEBUG, "Port %d queue counter object cannot be created "
801                         "by DevX - fall-back to use the kernel driver global "
802                         "queue counter.", dev->data->port_id);
803                 /* Create WQ by kernel and query its queue counter ID. */
804                 if (cq) {
805                         wq = mlx5_glue->create_wq(ctx,
806                                                   &(struct ibv_wq_init_attr){
807                                                     .wq_type = IBV_WQT_RQ,
808                                                     .max_wr = 1,
809                                                     .max_sge = 1,
810                                                     .pd = priv->sh->pd,
811                                                     .cq = cq,
812                                                 });
813                         if (wq) {
814                                 /* Counter is assigned only on RDY state. */
815                                 int ret = mlx5_glue->modify_wq(wq,
816                                                  &(struct ibv_wq_attr){
817                                                  .attr_mask = IBV_WQ_ATTR_STATE,
818                                                  .wq_state = IBV_WQS_RDY,
819                                                 });
820
821                                 if (ret == 0)
822                                         mlx5_devx_cmd_wq_query(wq,
823                                                          &priv->counter_set_id);
824                                 claim_zero(mlx5_glue->destroy_wq(wq));
825                         }
826                         claim_zero(mlx5_glue->destroy_cq(cq));
827                 }
828         } else {
829                 priv->counter_set_id = priv->q_counters->id;
830         }
831         if (priv->counter_set_id == 0)
832                 DRV_LOG(INFO, "Part of the port %d statistics will not be "
833                         "available.", dev->data->port_id);
834 }
835
836 /**
837  * Check if representor spawn info match devargs.
838  *
839  * @param spawn
840  *   Verbs device parameters (name, port, switch_info) to spawn.
841  * @param eth_da
842  *   Device devargs to probe.
843  *
844  * @return
845  *   Match result.
846  */
847 static bool
848 mlx5_representor_match(struct mlx5_dev_spawn_data *spawn,
849                        struct rte_eth_devargs *eth_da)
850 {
851         struct mlx5_switch_info *switch_info = &spawn->info;
852         unsigned int p, f;
853         uint16_t id;
854         uint16_t repr_id = mlx5_representor_id_encode(switch_info,
855                                                       eth_da->type);
856
857         switch (eth_da->type) {
858         case RTE_ETH_REPRESENTOR_SF:
859                 if (!(spawn->info.port_name == -1 &&
860                       switch_info->name_type ==
861                                 MLX5_PHYS_PORT_NAME_TYPE_PFHPF) &&
862                     switch_info->name_type != MLX5_PHYS_PORT_NAME_TYPE_PFSF) {
863                         rte_errno = EBUSY;
864                         return false;
865                 }
866                 break;
867         case RTE_ETH_REPRESENTOR_VF:
868                 /* Allows HPF representor index -1 as exception. */
869                 if (!(spawn->info.port_name == -1 &&
870                       switch_info->name_type ==
871                                 MLX5_PHYS_PORT_NAME_TYPE_PFHPF) &&
872                     switch_info->name_type != MLX5_PHYS_PORT_NAME_TYPE_PFVF) {
873                         rte_errno = EBUSY;
874                         return false;
875                 }
876                 break;
877         case RTE_ETH_REPRESENTOR_NONE:
878                 rte_errno = EBUSY;
879                 return false;
880         default:
881                 rte_errno = ENOTSUP;
882                 DRV_LOG(ERR, "unsupported representor type");
883                 return false;
884         }
885         /* Check representor ID: */
886         for (p = 0; p < eth_da->nb_ports; ++p) {
887                 if (spawn->pf_bond < 0) {
888                         /* For non-LAG mode, allow and ignore pf. */
889                         switch_info->pf_num = eth_da->ports[p];
890                         repr_id = mlx5_representor_id_encode(switch_info,
891                                                              eth_da->type);
892                 }
893                 for (f = 0; f < eth_da->nb_representor_ports; ++f) {
894                         id = MLX5_REPRESENTOR_ID
895                                 (eth_da->ports[p], eth_da->type,
896                                  eth_da->representor_ports[f]);
897                         if (repr_id == id)
898                                 return true;
899                 }
900         }
901         rte_errno = EBUSY;
902         return false;
903 }
904
905
906 /**
907  * Spawn an Ethernet device from Verbs information.
908  *
909  * @param dpdk_dev
910  *   Backing DPDK device.
911  * @param spawn
912  *   Verbs device parameters (name, port, switch_info) to spawn.
913  * @param config
914  *   Device configuration parameters.
915  * @param config
916  *   Device arguments.
917  *
918  * @return
919  *   A valid Ethernet device object on success, NULL otherwise and rte_errno
920  *   is set. The following errors are defined:
921  *
922  *   EBUSY: device is not supposed to be spawned.
923  *   EEXIST: device is already spawned
924  */
925 static struct rte_eth_dev *
926 mlx5_dev_spawn(struct rte_device *dpdk_dev,
927                struct mlx5_dev_spawn_data *spawn,
928                struct mlx5_dev_config *config,
929                struct rte_eth_devargs *eth_da)
930 {
931         const struct mlx5_switch_info *switch_info = &spawn->info;
932         struct mlx5_dev_ctx_shared *sh = NULL;
933         struct ibv_port_attr port_attr;
934         struct mlx5dv_context dv_attr = { .comp_mask = 0 };
935         struct rte_eth_dev *eth_dev = NULL;
936         struct mlx5_priv *priv = NULL;
937         int err = 0;
938         unsigned int hw_padding = 0;
939         unsigned int mps;
940         unsigned int tunnel_en = 0;
941         unsigned int mpls_en = 0;
942         unsigned int swp = 0;
943         unsigned int mprq = 0;
944         unsigned int mprq_min_stride_size_n = 0;
945         unsigned int mprq_max_stride_size_n = 0;
946         unsigned int mprq_min_stride_num_n = 0;
947         unsigned int mprq_max_stride_num_n = 0;
948         struct rte_ether_addr mac;
949         char name[RTE_ETH_NAME_MAX_LEN];
950         int own_domain_id = 0;
951         uint16_t port_id;
952         struct mlx5_port_info vport_info = { .query_flags = 0 };
953         int i;
954
955         /* Determine if this port representor is supposed to be spawned. */
956         if (switch_info->representor && dpdk_dev->devargs &&
957             !mlx5_representor_match(spawn, eth_da))
958                 return NULL;
959         /* Build device name. */
960         if (spawn->pf_bond < 0) {
961                 /* Single device. */
962                 if (!switch_info->representor)
963                         strlcpy(name, dpdk_dev->name, sizeof(name));
964                 else
965                         err = snprintf(name, sizeof(name), "%s_representor_%s%u",
966                                  dpdk_dev->name,
967                                  switch_info->name_type ==
968                                  MLX5_PHYS_PORT_NAME_TYPE_PFSF ? "sf" : "vf",
969                                  switch_info->port_name);
970         } else {
971                 /* Bonding device. */
972                 if (!switch_info->representor) {
973                         err = snprintf(name, sizeof(name), "%s_%s",
974                                  dpdk_dev->name,
975                                  mlx5_os_get_dev_device_name(spawn->phys_dev));
976                 } else {
977                         err = snprintf(name, sizeof(name), "%s_%s_representor_c%dpf%d%s%u",
978                                 dpdk_dev->name,
979                                 mlx5_os_get_dev_device_name(spawn->phys_dev),
980                                 switch_info->ctrl_num,
981                                 switch_info->pf_num,
982                                 switch_info->name_type ==
983                                 MLX5_PHYS_PORT_NAME_TYPE_PFSF ? "sf" : "vf",
984                                 switch_info->port_name);
985                 }
986         }
987         if (err >= (int)sizeof(name))
988                 DRV_LOG(WARNING, "device name overflow %s", name);
989         /* check if the device is already spawned */
990         if (rte_eth_dev_get_port_by_name(name, &port_id) == 0) {
991                 rte_errno = EEXIST;
992                 return NULL;
993         }
994         DRV_LOG(DEBUG, "naming Ethernet device \"%s\"", name);
995         if (rte_eal_process_type() == RTE_PROC_SECONDARY) {
996                 struct mlx5_mp_id mp_id;
997
998                 eth_dev = rte_eth_dev_attach_secondary(name);
999                 if (eth_dev == NULL) {
1000                         DRV_LOG(ERR, "can not attach rte ethdev");
1001                         rte_errno = ENOMEM;
1002                         return NULL;
1003                 }
1004                 eth_dev->device = dpdk_dev;
1005                 eth_dev->dev_ops = &mlx5_dev_sec_ops;
1006                 eth_dev->rx_descriptor_status = mlx5_rx_descriptor_status;
1007                 eth_dev->tx_descriptor_status = mlx5_tx_descriptor_status;
1008                 err = mlx5_proc_priv_init(eth_dev);
1009                 if (err)
1010                         return NULL;
1011                 mp_id.port_id = eth_dev->data->port_id;
1012                 strlcpy(mp_id.name, MLX5_MP_NAME, RTE_MP_MAX_NAME_LEN);
1013                 /* Receive command fd from primary process */
1014                 err = mlx5_mp_req_verbs_cmd_fd(&mp_id);
1015                 if (err < 0)
1016                         goto err_secondary;
1017                 /* Remap UAR for Tx queues. */
1018                 err = mlx5_tx_uar_init_secondary(eth_dev, err);
1019                 if (err)
1020                         goto err_secondary;
1021                 /*
1022                  * Ethdev pointer is still required as input since
1023                  * the primary device is not accessible from the
1024                  * secondary process.
1025                  */
1026                 eth_dev->rx_pkt_burst = mlx5_select_rx_function(eth_dev);
1027                 eth_dev->tx_pkt_burst = mlx5_select_tx_function(eth_dev);
1028                 return eth_dev;
1029 err_secondary:
1030                 mlx5_dev_close(eth_dev);
1031                 return NULL;
1032         }
1033         /*
1034          * Some parameters ("tx_db_nc" in particularly) are needed in
1035          * advance to create dv/verbs device context. We proceed the
1036          * devargs here to get ones, and later proceed devargs again
1037          * to override some hardware settings.
1038          */
1039         err = mlx5_args(config, dpdk_dev->devargs);
1040         if (err) {
1041                 err = rte_errno;
1042                 DRV_LOG(ERR, "failed to process device arguments: %s",
1043                         strerror(rte_errno));
1044                 goto error;
1045         }
1046         if (config->dv_miss_info) {
1047                 if (switch_info->master || switch_info->representor)
1048                         config->dv_xmeta_en = MLX5_XMETA_MODE_META16;
1049         }
1050         mlx5_malloc_mem_select(config->sys_mem_en);
1051         sh = mlx5_alloc_shared_dev_ctx(spawn, config);
1052         if (!sh)
1053                 return NULL;
1054         config->devx = sh->devx;
1055 #ifdef HAVE_MLX5DV_DR_ACTION_DEST_DEVX_TIR
1056         config->dest_tir = 1;
1057 #endif
1058 #ifdef HAVE_IBV_MLX5_MOD_SWP
1059         dv_attr.comp_mask |= MLX5DV_CONTEXT_MASK_SWP;
1060 #endif
1061         /*
1062          * Multi-packet send is supported by ConnectX-4 Lx PF as well
1063          * as all ConnectX-5 devices.
1064          */
1065 #ifdef HAVE_IBV_DEVICE_TUNNEL_SUPPORT
1066         dv_attr.comp_mask |= MLX5DV_CONTEXT_MASK_TUNNEL_OFFLOADS;
1067 #endif
1068 #ifdef HAVE_IBV_DEVICE_STRIDING_RQ_SUPPORT
1069         dv_attr.comp_mask |= MLX5DV_CONTEXT_MASK_STRIDING_RQ;
1070 #endif
1071         mlx5_glue->dv_query_device(sh->ctx, &dv_attr);
1072         if (dv_attr.flags & MLX5DV_CONTEXT_FLAGS_MPW_ALLOWED) {
1073                 if (dv_attr.flags & MLX5DV_CONTEXT_FLAGS_ENHANCED_MPW) {
1074                         DRV_LOG(DEBUG, "enhanced MPW is supported");
1075                         mps = MLX5_MPW_ENHANCED;
1076                 } else {
1077                         DRV_LOG(DEBUG, "MPW is supported");
1078                         mps = MLX5_MPW;
1079                 }
1080         } else {
1081                 DRV_LOG(DEBUG, "MPW isn't supported");
1082                 mps = MLX5_MPW_DISABLED;
1083         }
1084 #ifdef HAVE_IBV_MLX5_MOD_SWP
1085         if (dv_attr.comp_mask & MLX5DV_CONTEXT_MASK_SWP)
1086                 swp = dv_attr.sw_parsing_caps.sw_parsing_offloads;
1087         DRV_LOG(DEBUG, "SWP support: %u", swp);
1088 #endif
1089         config->swp = !!swp;
1090 #ifdef HAVE_IBV_DEVICE_STRIDING_RQ_SUPPORT
1091         if (dv_attr.comp_mask & MLX5DV_CONTEXT_MASK_STRIDING_RQ) {
1092                 struct mlx5dv_striding_rq_caps mprq_caps =
1093                         dv_attr.striding_rq_caps;
1094
1095                 DRV_LOG(DEBUG, "\tmin_single_stride_log_num_of_bytes: %d",
1096                         mprq_caps.min_single_stride_log_num_of_bytes);
1097                 DRV_LOG(DEBUG, "\tmax_single_stride_log_num_of_bytes: %d",
1098                         mprq_caps.max_single_stride_log_num_of_bytes);
1099                 DRV_LOG(DEBUG, "\tmin_single_wqe_log_num_of_strides: %d",
1100                         mprq_caps.min_single_wqe_log_num_of_strides);
1101                 DRV_LOG(DEBUG, "\tmax_single_wqe_log_num_of_strides: %d",
1102                         mprq_caps.max_single_wqe_log_num_of_strides);
1103                 DRV_LOG(DEBUG, "\tsupported_qpts: %d",
1104                         mprq_caps.supported_qpts);
1105                 DRV_LOG(DEBUG, "device supports Multi-Packet RQ");
1106                 mprq = 1;
1107                 mprq_min_stride_size_n =
1108                         mprq_caps.min_single_stride_log_num_of_bytes;
1109                 mprq_max_stride_size_n =
1110                         mprq_caps.max_single_stride_log_num_of_bytes;
1111                 mprq_min_stride_num_n =
1112                         mprq_caps.min_single_wqe_log_num_of_strides;
1113                 mprq_max_stride_num_n =
1114                         mprq_caps.max_single_wqe_log_num_of_strides;
1115         }
1116 #endif
1117         /* Rx CQE compression is enabled by default. */
1118         config->cqe_comp = 1;
1119 #ifdef HAVE_IBV_DEVICE_TUNNEL_SUPPORT
1120         if (dv_attr.comp_mask & MLX5DV_CONTEXT_MASK_TUNNEL_OFFLOADS) {
1121                 tunnel_en = ((dv_attr.tunnel_offloads_caps &
1122                               MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_VXLAN) &&
1123                              (dv_attr.tunnel_offloads_caps &
1124                               MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_GRE) &&
1125                              (dv_attr.tunnel_offloads_caps &
1126                               MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_GENEVE));
1127         }
1128         DRV_LOG(DEBUG, "tunnel offloading is %ssupported",
1129                 tunnel_en ? "" : "not ");
1130 #else
1131         DRV_LOG(WARNING,
1132                 "tunnel offloading disabled due to old OFED/rdma-core version");
1133 #endif
1134         config->tunnel_en = tunnel_en;
1135 #ifdef HAVE_IBV_DEVICE_MPLS_SUPPORT
1136         mpls_en = ((dv_attr.tunnel_offloads_caps &
1137                     MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_CW_MPLS_OVER_GRE) &&
1138                    (dv_attr.tunnel_offloads_caps &
1139                     MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_CW_MPLS_OVER_UDP));
1140         DRV_LOG(DEBUG, "MPLS over GRE/UDP tunnel offloading is %ssupported",
1141                 mpls_en ? "" : "not ");
1142 #else
1143         DRV_LOG(WARNING, "MPLS over GRE/UDP tunnel offloading disabled due to"
1144                 " old OFED/rdma-core version or firmware configuration");
1145 #endif
1146         config->mpls_en = mpls_en;
1147         /* Check port status. */
1148         err = mlx5_glue->query_port(sh->ctx, spawn->phys_port, &port_attr);
1149         if (err) {
1150                 DRV_LOG(ERR, "port query failed: %s", strerror(err));
1151                 goto error;
1152         }
1153         if (port_attr.link_layer != IBV_LINK_LAYER_ETHERNET) {
1154                 DRV_LOG(ERR, "port is not configured in Ethernet mode");
1155                 err = EINVAL;
1156                 goto error;
1157         }
1158         if (port_attr.state != IBV_PORT_ACTIVE)
1159                 DRV_LOG(DEBUG, "port is not active: \"%s\" (%d)",
1160                         mlx5_glue->port_state_str(port_attr.state),
1161                         port_attr.state);
1162         /* Allocate private eth device data. */
1163         priv = mlx5_malloc(MLX5_MEM_ZERO | MLX5_MEM_RTE,
1164                            sizeof(*priv),
1165                            RTE_CACHE_LINE_SIZE, SOCKET_ID_ANY);
1166         if (priv == NULL) {
1167                 DRV_LOG(ERR, "priv allocation failure");
1168                 err = ENOMEM;
1169                 goto error;
1170         }
1171         priv->sh = sh;
1172         priv->dev_port = spawn->phys_port;
1173         priv->pci_dev = spawn->pci_dev;
1174         priv->mtu = RTE_ETHER_MTU;
1175         /* Some internal functions rely on Netlink sockets, open them now. */
1176         priv->nl_socket_rdma = mlx5_nl_init(NETLINK_RDMA);
1177         priv->nl_socket_route = mlx5_nl_init(NETLINK_ROUTE);
1178         priv->representor = !!switch_info->representor;
1179         priv->master = !!switch_info->master;
1180         priv->domain_id = RTE_ETH_DEV_SWITCH_DOMAIN_ID_INVALID;
1181         priv->vport_meta_tag = 0;
1182         priv->vport_meta_mask = 0;
1183         priv->pf_bond = spawn->pf_bond;
1184
1185         DRV_LOG(DEBUG,
1186                 "dev_port=%u bus=%s pci=%s master=%d representor=%d pf_bond=%d\n",
1187                 priv->dev_port, dpdk_dev->bus->name,
1188                 priv->pci_dev ? priv->pci_dev->name : "NONE",
1189                 priv->master, priv->representor, priv->pf_bond);
1190
1191         /*
1192          * If we have E-Switch we should determine the vport attributes.
1193          * E-Switch may use either source vport field or reg_c[0] metadata
1194          * register to match on vport index. The engaged part of metadata
1195          * register is defined by mask.
1196          */
1197         if (switch_info->representor || switch_info->master) {
1198                 err = mlx5_glue->devx_port_query(sh->ctx,
1199                                                  spawn->phys_port,
1200                                                  &vport_info);
1201                 if (err) {
1202                         DRV_LOG(WARNING,
1203                                 "can't query devx port %d on device %s",
1204                                 spawn->phys_port,
1205                                 mlx5_os_get_dev_device_name(spawn->phys_dev));
1206                         vport_info.query_flags = 0;
1207                 }
1208         }
1209         if (vport_info.query_flags & MLX5_PORT_QUERY_REG_C0) {
1210                 priv->vport_meta_tag = vport_info.vport_meta_tag;
1211                 priv->vport_meta_mask = vport_info.vport_meta_mask;
1212                 if (!priv->vport_meta_mask) {
1213                         DRV_LOG(ERR, "vport zero mask for port %d"
1214                                      " on bonding device %s",
1215                                      spawn->phys_port,
1216                                      mlx5_os_get_dev_device_name
1217                                                         (spawn->phys_dev));
1218                         err = ENOTSUP;
1219                         goto error;
1220                 }
1221                 if (priv->vport_meta_tag & ~priv->vport_meta_mask) {
1222                         DRV_LOG(ERR, "invalid vport tag for port %d"
1223                                      " on bonding device %s",
1224                                      spawn->phys_port,
1225                                      mlx5_os_get_dev_device_name
1226                                                         (spawn->phys_dev));
1227                         err = ENOTSUP;
1228                         goto error;
1229                 }
1230         }
1231         if (vport_info.query_flags & MLX5_PORT_QUERY_VPORT) {
1232                 priv->vport_id = vport_info.vport_id;
1233         } else if (spawn->pf_bond >= 0 &&
1234                    (switch_info->representor || switch_info->master)) {
1235                 DRV_LOG(ERR, "can't deduce vport index for port %d"
1236                              " on bonding device %s",
1237                              spawn->phys_port,
1238                              mlx5_os_get_dev_device_name(spawn->phys_dev));
1239                 err = ENOTSUP;
1240                 goto error;
1241         } else {
1242                 /*
1243                  * Suppose vport index in compatible way. Kernel/rdma_core
1244                  * support single E-Switch per PF configurations only and
1245                  * vport_id field contains the vport index for associated VF,
1246                  * which is deduced from representor port name.
1247                  * For example, let's have the IB device port 10, it has
1248                  * attached network device eth0, which has port name attribute
1249                  * pf0vf2, we can deduce the VF number as 2, and set vport index
1250                  * as 3 (2+1). This assigning schema should be changed if the
1251                  * multiple E-Switch instances per PF configurations or/and PCI
1252                  * subfunctions are added.
1253                  */
1254                 priv->vport_id = switch_info->representor ?
1255                                  switch_info->port_name + 1 : -1;
1256         }
1257         priv->representor_id = mlx5_representor_id_encode(switch_info,
1258                                                           eth_da->type);
1259         /*
1260          * Look for sibling devices in order to reuse their switch domain
1261          * if any, otherwise allocate one.
1262          */
1263         MLX5_ETH_FOREACH_DEV(port_id, dpdk_dev) {
1264                 const struct mlx5_priv *opriv =
1265                         rte_eth_devices[port_id].data->dev_private;
1266
1267                 if (!opriv ||
1268                     opriv->sh != priv->sh ||
1269                         opriv->domain_id ==
1270                         RTE_ETH_DEV_SWITCH_DOMAIN_ID_INVALID)
1271                         continue;
1272                 priv->domain_id = opriv->domain_id;
1273                 DRV_LOG(DEBUG, "dev_port-%u inherit domain_id=%u\n",
1274                         priv->dev_port, priv->domain_id);
1275                 break;
1276         }
1277         if (priv->domain_id == RTE_ETH_DEV_SWITCH_DOMAIN_ID_INVALID) {
1278                 err = rte_eth_switch_domain_alloc(&priv->domain_id);
1279                 if (err) {
1280                         err = rte_errno;
1281                         DRV_LOG(ERR, "unable to allocate switch domain: %s",
1282                                 strerror(rte_errno));
1283                         goto error;
1284                 }
1285                 own_domain_id = 1;
1286                 DRV_LOG(DEBUG, "dev_port-%u new domain_id=%u\n",
1287                         priv->dev_port, priv->domain_id);
1288         }
1289         /* Override some values set by hardware configuration. */
1290         mlx5_args(config, dpdk_dev->devargs);
1291         err = mlx5_dev_check_sibling_config(priv, config);
1292         if (err)
1293                 goto error;
1294         config->hw_csum = !!(sh->device_attr.device_cap_flags_ex &
1295                             IBV_DEVICE_RAW_IP_CSUM);
1296         DRV_LOG(DEBUG, "checksum offloading is %ssupported",
1297                 (config->hw_csum ? "" : "not "));
1298 #if !defined(HAVE_IBV_DEVICE_COUNTERS_SET_V42) && \
1299         !defined(HAVE_IBV_DEVICE_COUNTERS_SET_V45)
1300         DRV_LOG(DEBUG, "counters are not supported");
1301 #endif
1302 #if !defined(HAVE_IBV_FLOW_DV_SUPPORT) || !defined(HAVE_MLX5DV_DR)
1303         if (config->dv_flow_en) {
1304                 DRV_LOG(WARNING, "DV flow is not supported");
1305                 config->dv_flow_en = 0;
1306         }
1307 #endif
1308         if (spawn->max_port > UINT8_MAX) {
1309                 /* Verbs can't support ports larger than 255 by design. */
1310                 DRV_LOG(ERR, "can't support IB ports > UINT8_MAX");
1311                 err = EINVAL;
1312                 goto error;
1313         }
1314         config->ind_table_max_size =
1315                 sh->device_attr.max_rwq_indirection_table_size;
1316         /*
1317          * Remove this check once DPDK supports larger/variable
1318          * indirection tables.
1319          */
1320         if (config->ind_table_max_size > (unsigned int)ETH_RSS_RETA_SIZE_512)
1321                 config->ind_table_max_size = ETH_RSS_RETA_SIZE_512;
1322         DRV_LOG(DEBUG, "maximum Rx indirection table size is %u",
1323                 config->ind_table_max_size);
1324         config->hw_vlan_strip = !!(sh->device_attr.raw_packet_caps &
1325                                   IBV_RAW_PACKET_CAP_CVLAN_STRIPPING);
1326         DRV_LOG(DEBUG, "VLAN stripping is %ssupported",
1327                 (config->hw_vlan_strip ? "" : "not "));
1328         config->hw_fcs_strip = !!(sh->device_attr.raw_packet_caps &
1329                                  IBV_RAW_PACKET_CAP_SCATTER_FCS);
1330 #if defined(HAVE_IBV_WQ_FLAG_RX_END_PADDING)
1331         hw_padding = !!sh->device_attr.rx_pad_end_addr_align;
1332 #elif defined(HAVE_IBV_WQ_FLAGS_PCI_WRITE_END_PADDING)
1333         hw_padding = !!(sh->device_attr.device_cap_flags_ex &
1334                         IBV_DEVICE_PCI_WRITE_END_PADDING);
1335 #endif
1336         if (config->hw_padding && !hw_padding) {
1337                 DRV_LOG(DEBUG, "Rx end alignment padding isn't supported");
1338                 config->hw_padding = 0;
1339         } else if (config->hw_padding) {
1340                 DRV_LOG(DEBUG, "Rx end alignment padding is enabled");
1341         }
1342         config->tso = (sh->device_attr.max_tso > 0 &&
1343                       (sh->device_attr.tso_supported_qpts &
1344                        (1 << IBV_QPT_RAW_PACKET)));
1345         if (config->tso)
1346                 config->tso_max_payload_sz = sh->device_attr.max_tso;
1347         /*
1348          * MPW is disabled by default, while the Enhanced MPW is enabled
1349          * by default.
1350          */
1351         if (config->mps == MLX5_ARG_UNSET)
1352                 config->mps = (mps == MLX5_MPW_ENHANCED) ? MLX5_MPW_ENHANCED :
1353                                                           MLX5_MPW_DISABLED;
1354         else
1355                 config->mps = config->mps ? mps : MLX5_MPW_DISABLED;
1356         DRV_LOG(INFO, "%sMPS is %s",
1357                 config->mps == MLX5_MPW_ENHANCED ? "enhanced " :
1358                 config->mps == MLX5_MPW ? "legacy " : "",
1359                 config->mps != MLX5_MPW_DISABLED ? "enabled" : "disabled");
1360         if (config->devx) {
1361                 err = mlx5_devx_cmd_query_hca_attr(sh->ctx, &config->hca_attr);
1362                 if (err) {
1363                         err = -err;
1364                         goto error;
1365                 }
1366                 /* Check relax ordering support. */
1367                 if (!haswell_broadwell_cpu) {
1368                         sh->cmng.relaxed_ordering_write =
1369                                 config->hca_attr.relaxed_ordering_write;
1370                         sh->cmng.relaxed_ordering_read =
1371                                 config->hca_attr.relaxed_ordering_read;
1372                 } else {
1373                         sh->cmng.relaxed_ordering_read = 0;
1374                         sh->cmng.relaxed_ordering_write = 0;
1375                 }
1376                 sh->rq_ts_format = config->hca_attr.rq_ts_format;
1377                 sh->sq_ts_format = config->hca_attr.sq_ts_format;
1378                 sh->steering_format_version =
1379                         config->hca_attr.steering_format_version;
1380                 sh->qp_ts_format = config->hca_attr.qp_ts_format;
1381                 /* Check for LRO support. */
1382                 if (config->dest_tir && config->hca_attr.lro_cap &&
1383                     config->dv_flow_en) {
1384                         /* TBD check tunnel lro caps. */
1385                         config->lro.supported = config->hca_attr.lro_cap;
1386                         DRV_LOG(DEBUG, "Device supports LRO");
1387                         /*
1388                          * If LRO timeout is not configured by application,
1389                          * use the minimal supported value.
1390                          */
1391                         if (!config->lro.timeout)
1392                                 config->lro.timeout =
1393                                 config->hca_attr.lro_timer_supported_periods[0];
1394                         DRV_LOG(DEBUG, "LRO session timeout set to %d usec",
1395                                 config->lro.timeout);
1396                         DRV_LOG(DEBUG, "LRO minimal size of TCP segment "
1397                                 "required for coalescing is %d bytes",
1398                                 config->hca_attr.lro_min_mss_size);
1399                 }
1400 #if defined(HAVE_MLX5DV_DR) && \
1401         (defined(HAVE_MLX5_DR_CREATE_ACTION_FLOW_METER) || \
1402          defined(HAVE_MLX5_DR_CREATE_ACTION_ASO))
1403                 if (config->hca_attr.qos.sup &&
1404                     config->hca_attr.qos.flow_meter_old &&
1405                     config->dv_flow_en) {
1406                         uint8_t reg_c_mask =
1407                                 config->hca_attr.qos.flow_meter_reg_c_ids;
1408                         /*
1409                          * Meter needs two REG_C's for color match and pre-sfx
1410                          * flow match. Here get the REG_C for color match.
1411                          * REG_C_0 and REG_C_1 is reserved for metadata feature.
1412                          */
1413                         reg_c_mask &= 0xfc;
1414                         if (__builtin_popcount(reg_c_mask) < 1) {
1415                                 priv->mtr_en = 0;
1416                                 DRV_LOG(WARNING, "No available register for"
1417                                         " meter.");
1418                         } else {
1419                                 /*
1420                                  * The meter color register is used by the
1421                                  * flow-hit feature as well.
1422                                  * The flow-hit feature must use REG_C_3
1423                                  * Prefer REG_C_3 if it is available.
1424                                  */
1425                                 if (reg_c_mask & (1 << (REG_C_3 - REG_C_0)))
1426                                         priv->mtr_color_reg = REG_C_3;
1427                                 else
1428                                         priv->mtr_color_reg = ffs(reg_c_mask)
1429                                                               - 1 + REG_C_0;
1430                                 priv->mtr_en = 1;
1431                                 priv->mtr_reg_share =
1432                                       config->hca_attr.qos.flow_meter;
1433                                 DRV_LOG(DEBUG, "The REG_C meter uses is %d",
1434                                         priv->mtr_color_reg);
1435                         }
1436                 }
1437                 if (config->hca_attr.qos.sup &&
1438                         config->hca_attr.qos.flow_meter_aso_sup) {
1439                         uint32_t log_obj_size =
1440                                 rte_log2_u32(MLX5_ASO_MTRS_PER_POOL >> 1);
1441                         if (log_obj_size >=
1442                         config->hca_attr.qos.log_meter_aso_granularity &&
1443                         log_obj_size <=
1444                         config->hca_attr.qos.log_meter_aso_max_alloc)
1445                                 sh->meter_aso_en = 1;
1446                 }
1447                 if (priv->mtr_en) {
1448                         err = mlx5_aso_flow_mtrs_mng_init(priv->sh);
1449                         if (err) {
1450                                 err = -err;
1451                                 goto error;
1452                         }
1453                 }
1454                 if (config->hca_attr.flow.tunnel_header_0_1)
1455                         sh->tunnel_header_0_1 = 1;
1456 #endif
1457 #ifdef HAVE_MLX5_DR_CREATE_ACTION_ASO
1458                 if (config->hca_attr.flow_hit_aso &&
1459                     priv->mtr_color_reg == REG_C_3) {
1460                         sh->flow_hit_aso_en = 1;
1461                         err = mlx5_flow_aso_age_mng_init(sh);
1462                         if (err) {
1463                                 err = -err;
1464                                 goto error;
1465                         }
1466                         DRV_LOG(DEBUG, "Flow Hit ASO is supported.");
1467                 }
1468 #endif /* HAVE_MLX5_DR_CREATE_ACTION_ASO */
1469 #if defined(HAVE_MLX5_DR_CREATE_ACTION_ASO) && \
1470         defined(HAVE_MLX5_DR_ACTION_ASO_CT)
1471                 if (config->hca_attr.ct_offload &&
1472                     priv->mtr_color_reg == REG_C_3) {
1473                         err = mlx5_flow_aso_ct_mng_init(sh);
1474                         if (err) {
1475                                 err = -err;
1476                                 goto error;
1477                         }
1478                         DRV_LOG(DEBUG, "CT ASO is supported.");
1479                         sh->ct_aso_en = 1;
1480                 }
1481 #endif /* HAVE_MLX5_DR_CREATE_ACTION_ASO && HAVE_MLX5_DR_ACTION_ASO_CT */
1482 #if defined(HAVE_MLX5DV_DR) && defined(HAVE_MLX5_DR_CREATE_ACTION_FLOW_SAMPLE)
1483                 if (config->hca_attr.log_max_ft_sampler_num > 0  &&
1484                     config->dv_flow_en) {
1485                         priv->sampler_en = 1;
1486                         DRV_LOG(DEBUG, "Sampler enabled!");
1487                 } else {
1488                         priv->sampler_en = 0;
1489                         if (!config->hca_attr.log_max_ft_sampler_num)
1490                                 DRV_LOG(WARNING,
1491                                         "No available register for sampler.");
1492                         else
1493                                 DRV_LOG(DEBUG, "DV flow is not supported!");
1494                 }
1495 #endif
1496         }
1497         if (config->cqe_comp && RTE_CACHE_LINE_SIZE == 128 &&
1498             !(dv_attr.flags & MLX5DV_CONTEXT_FLAGS_CQE_128B_COMP)) {
1499                 DRV_LOG(WARNING, "Rx CQE 128B compression is not supported");
1500                 config->cqe_comp = 0;
1501         }
1502         if (config->cqe_comp_fmt == MLX5_CQE_RESP_FORMAT_FTAG_STRIDX &&
1503             (!config->devx || !config->hca_attr.mini_cqe_resp_flow_tag)) {
1504                 DRV_LOG(WARNING, "Flow Tag CQE compression"
1505                                  " format isn't supported.");
1506                 config->cqe_comp = 0;
1507         }
1508         if (config->cqe_comp_fmt == MLX5_CQE_RESP_FORMAT_L34H_STRIDX &&
1509             (!config->devx || !config->hca_attr.mini_cqe_resp_l3_l4_tag)) {
1510                 DRV_LOG(WARNING, "L3/L4 Header CQE compression"
1511                                  " format isn't supported.");
1512                 config->cqe_comp = 0;
1513         }
1514         DRV_LOG(DEBUG, "Rx CQE compression is %ssupported",
1515                         config->cqe_comp ? "" : "not ");
1516         if (config->tx_pp) {
1517                 DRV_LOG(DEBUG, "Timestamp counter frequency %u kHz",
1518                         config->hca_attr.dev_freq_khz);
1519                 DRV_LOG(DEBUG, "Packet pacing is %ssupported",
1520                         config->hca_attr.qos.packet_pacing ? "" : "not ");
1521                 DRV_LOG(DEBUG, "Cross channel ops are %ssupported",
1522                         config->hca_attr.cross_channel ? "" : "not ");
1523                 DRV_LOG(DEBUG, "WQE index ignore is %ssupported",
1524                         config->hca_attr.wqe_index_ignore ? "" : "not ");
1525                 DRV_LOG(DEBUG, "Non-wire SQ feature is %ssupported",
1526                         config->hca_attr.non_wire_sq ? "" : "not ");
1527                 DRV_LOG(DEBUG, "Static WQE SQ feature is %ssupported (%d)",
1528                         config->hca_attr.log_max_static_sq_wq ? "" : "not ",
1529                         config->hca_attr.log_max_static_sq_wq);
1530                 DRV_LOG(DEBUG, "WQE rate PP mode is %ssupported",
1531                         config->hca_attr.qos.wqe_rate_pp ? "" : "not ");
1532                 if (!config->devx) {
1533                         DRV_LOG(ERR, "DevX is required for packet pacing");
1534                         err = ENODEV;
1535                         goto error;
1536                 }
1537                 if (!config->hca_attr.qos.packet_pacing) {
1538                         DRV_LOG(ERR, "Packet pacing is not supported");
1539                         err = ENODEV;
1540                         goto error;
1541                 }
1542                 if (!config->hca_attr.cross_channel) {
1543                         DRV_LOG(ERR, "Cross channel operations are"
1544                                      " required for packet pacing");
1545                         err = ENODEV;
1546                         goto error;
1547                 }
1548                 if (!config->hca_attr.wqe_index_ignore) {
1549                         DRV_LOG(ERR, "WQE index ignore feature is"
1550                                      " required for packet pacing");
1551                         err = ENODEV;
1552                         goto error;
1553                 }
1554                 if (!config->hca_attr.non_wire_sq) {
1555                         DRV_LOG(ERR, "Non-wire SQ feature is"
1556                                      " required for packet pacing");
1557                         err = ENODEV;
1558                         goto error;
1559                 }
1560                 if (!config->hca_attr.log_max_static_sq_wq) {
1561                         DRV_LOG(ERR, "Static WQE SQ feature is"
1562                                      " required for packet pacing");
1563                         err = ENODEV;
1564                         goto error;
1565                 }
1566                 if (!config->hca_attr.qos.wqe_rate_pp) {
1567                         DRV_LOG(ERR, "WQE rate mode is required"
1568                                      " for packet pacing");
1569                         err = ENODEV;
1570                         goto error;
1571                 }
1572 #ifndef HAVE_MLX5DV_DEVX_UAR_OFFSET
1573                 DRV_LOG(ERR, "DevX does not provide UAR offset,"
1574                              " can't create queues for packet pacing");
1575                 err = ENODEV;
1576                 goto error;
1577 #endif
1578         }
1579         if (config->devx) {
1580                 uint32_t reg[MLX5_ST_SZ_DW(register_mtutc)];
1581
1582                 err = config->hca_attr.access_register_user ?
1583                         mlx5_devx_cmd_register_read
1584                                 (sh->ctx, MLX5_REGISTER_ID_MTUTC, 0,
1585                                 reg, MLX5_ST_SZ_DW(register_mtutc)) : ENOTSUP;
1586                 if (!err) {
1587                         uint32_t ts_mode;
1588
1589                         /* MTUTC register is read successfully. */
1590                         ts_mode = MLX5_GET(register_mtutc, reg,
1591                                            time_stamp_mode);
1592                         if (ts_mode == MLX5_MTUTC_TIMESTAMP_MODE_REAL_TIME)
1593                                 config->rt_timestamp = 1;
1594                 } else {
1595                         /* Kernel does not support register reading. */
1596                         if (config->hca_attr.dev_freq_khz ==
1597                                                  (NS_PER_S / MS_PER_S))
1598                                 config->rt_timestamp = 1;
1599                 }
1600         }
1601         /*
1602          * If HW has bug working with tunnel packet decapsulation and
1603          * scatter FCS, and decapsulation is needed, clear the hw_fcs_strip
1604          * bit. Then DEV_RX_OFFLOAD_KEEP_CRC bit will not be set anymore.
1605          */
1606         if (config->hca_attr.scatter_fcs_w_decap_disable && config->decap_en)
1607                 config->hw_fcs_strip = 0;
1608         DRV_LOG(DEBUG, "FCS stripping configuration is %ssupported",
1609                 (config->hw_fcs_strip ? "" : "not "));
1610         if (config->mprq.enabled && mprq) {
1611                 if (config->mprq.stride_num_n &&
1612                     (config->mprq.stride_num_n > mprq_max_stride_num_n ||
1613                      config->mprq.stride_num_n < mprq_min_stride_num_n)) {
1614                         config->mprq.stride_num_n =
1615                                 RTE_MIN(RTE_MAX(MLX5_MPRQ_STRIDE_NUM_N,
1616                                                 mprq_min_stride_num_n),
1617                                         mprq_max_stride_num_n);
1618                         DRV_LOG(WARNING,
1619                                 "the number of strides"
1620                                 " for Multi-Packet RQ is out of range,"
1621                                 " setting default value (%u)",
1622                                 1 << config->mprq.stride_num_n);
1623                 }
1624                 if (config->mprq.stride_size_n &&
1625                     (config->mprq.stride_size_n > mprq_max_stride_size_n ||
1626                      config->mprq.stride_size_n < mprq_min_stride_size_n)) {
1627                         config->mprq.stride_size_n =
1628                                 RTE_MIN(RTE_MAX(MLX5_MPRQ_STRIDE_SIZE_N,
1629                                                 mprq_min_stride_size_n),
1630                                         mprq_max_stride_size_n);
1631                         DRV_LOG(WARNING,
1632                                 "the size of a stride"
1633                                 " for Multi-Packet RQ is out of range,"
1634                                 " setting default value (%u)",
1635                                 1 << config->mprq.stride_size_n);
1636                 }
1637                 config->mprq.min_stride_size_n = mprq_min_stride_size_n;
1638                 config->mprq.max_stride_size_n = mprq_max_stride_size_n;
1639         } else if (config->mprq.enabled && !mprq) {
1640                 DRV_LOG(WARNING, "Multi-Packet RQ isn't supported");
1641                 config->mprq.enabled = 0;
1642         }
1643         if (config->max_dump_files_num == 0)
1644                 config->max_dump_files_num = 128;
1645         eth_dev = rte_eth_dev_allocate(name);
1646         if (eth_dev == NULL) {
1647                 DRV_LOG(ERR, "can not allocate rte ethdev");
1648                 err = ENOMEM;
1649                 goto error;
1650         }
1651         if (priv->representor) {
1652                 eth_dev->data->dev_flags |= RTE_ETH_DEV_REPRESENTOR;
1653                 eth_dev->data->representor_id = priv->representor_id;
1654         }
1655         priv->mp_id.port_id = eth_dev->data->port_id;
1656         strlcpy(priv->mp_id.name, MLX5_MP_NAME, RTE_MP_MAX_NAME_LEN);
1657         /*
1658          * Store associated network device interface index. This index
1659          * is permanent throughout the lifetime of device. So, we may store
1660          * the ifindex here and use the cached value further.
1661          */
1662         MLX5_ASSERT(spawn->ifindex);
1663         priv->if_index = spawn->ifindex;
1664         eth_dev->data->dev_private = priv;
1665         priv->dev_data = eth_dev->data;
1666         eth_dev->data->mac_addrs = priv->mac;
1667         eth_dev->device = dpdk_dev;
1668         eth_dev->data->dev_flags |= RTE_ETH_DEV_AUTOFILL_QUEUE_XSTATS;
1669         /* Configure the first MAC address by default. */
1670         if (mlx5_get_mac(eth_dev, &mac.addr_bytes)) {
1671                 DRV_LOG(ERR,
1672                         "port %u cannot get MAC address, is mlx5_en"
1673                         " loaded? (errno: %s)",
1674                         eth_dev->data->port_id, strerror(rte_errno));
1675                 err = ENODEV;
1676                 goto error;
1677         }
1678         DRV_LOG(INFO,
1679                 "port %u MAC address is %02x:%02x:%02x:%02x:%02x:%02x",
1680                 eth_dev->data->port_id,
1681                 mac.addr_bytes[0], mac.addr_bytes[1],
1682                 mac.addr_bytes[2], mac.addr_bytes[3],
1683                 mac.addr_bytes[4], mac.addr_bytes[5]);
1684 #ifdef RTE_LIBRTE_MLX5_DEBUG
1685         {
1686                 char ifname[MLX5_NAMESIZE];
1687
1688                 if (mlx5_get_ifname(eth_dev, &ifname) == 0)
1689                         DRV_LOG(DEBUG, "port %u ifname is \"%s\"",
1690                                 eth_dev->data->port_id, ifname);
1691                 else
1692                         DRV_LOG(DEBUG, "port %u ifname is unknown",
1693                                 eth_dev->data->port_id);
1694         }
1695 #endif
1696         /* Get actual MTU if possible. */
1697         err = mlx5_get_mtu(eth_dev, &priv->mtu);
1698         if (err) {
1699                 err = rte_errno;
1700                 goto error;
1701         }
1702         DRV_LOG(DEBUG, "port %u MTU is %u", eth_dev->data->port_id,
1703                 priv->mtu);
1704         /* Initialize burst functions to prevent crashes before link-up. */
1705         eth_dev->rx_pkt_burst = removed_rx_burst;
1706         eth_dev->tx_pkt_burst = removed_tx_burst;
1707         eth_dev->dev_ops = &mlx5_dev_ops;
1708         eth_dev->rx_descriptor_status = mlx5_rx_descriptor_status;
1709         eth_dev->tx_descriptor_status = mlx5_tx_descriptor_status;
1710         eth_dev->rx_queue_count = mlx5_rx_queue_count;
1711         /* Register MAC address. */
1712         claim_zero(mlx5_mac_addr_add(eth_dev, &mac, 0, 0));
1713         if (config->vf && config->vf_nl_en)
1714                 mlx5_nl_mac_addr_sync(priv->nl_socket_route,
1715                                       mlx5_ifindex(eth_dev),
1716                                       eth_dev->data->mac_addrs,
1717                                       MLX5_MAX_MAC_ADDRESSES);
1718         priv->ctrl_flows = 0;
1719         rte_spinlock_init(&priv->flow_list_lock);
1720         TAILQ_INIT(&priv->flow_meters);
1721         priv->mtr_profile_tbl = mlx5_l3t_create(MLX5_L3T_TYPE_PTR);
1722         if (!priv->mtr_profile_tbl)
1723                 goto error;
1724         /* Hint libmlx5 to use PMD allocator for data plane resources */
1725         mlx5_glue->dv_set_context_attr(sh->ctx,
1726                         MLX5DV_CTX_ATTR_BUF_ALLOCATORS,
1727                         (void *)((uintptr_t)&(struct mlx5dv_ctx_allocators){
1728                                 .alloc = &mlx5_alloc_verbs_buf,
1729                                 .free = &mlx5_free_verbs_buf,
1730                                 .data = sh,
1731                         }));
1732         /* Bring Ethernet device up. */
1733         DRV_LOG(DEBUG, "port %u forcing Ethernet interface up",
1734                 eth_dev->data->port_id);
1735         mlx5_set_link_up(eth_dev);
1736         /*
1737          * Even though the interrupt handler is not installed yet,
1738          * interrupts will still trigger on the async_fd from
1739          * Verbs context returned by ibv_open_device().
1740          */
1741         mlx5_link_update(eth_dev, 0);
1742 #ifdef HAVE_MLX5DV_DR_ESWITCH
1743         if (!(config->hca_attr.eswitch_manager && config->dv_flow_en &&
1744               (switch_info->representor || switch_info->master)))
1745                 config->dv_esw_en = 0;
1746 #else
1747         config->dv_esw_en = 0;
1748 #endif
1749         /* Detect minimal data bytes to inline. */
1750         mlx5_set_min_inline(spawn, config);
1751         /* Store device configuration on private structure. */
1752         priv->config = *config;
1753         for (i = 0; i < MLX5_FLOW_TYPE_MAXI; i++) {
1754                 icfg[i].release_mem_en = !!config->reclaim_mode;
1755                 if (config->reclaim_mode)
1756                         icfg[i].per_core_cache = 0;
1757                 priv->flows[i] = mlx5_ipool_create(&icfg[i]);
1758                 if (!priv->flows[i])
1759                         goto error;
1760         }
1761         /* Create context for virtual machine VLAN workaround. */
1762         priv->vmwa_context = mlx5_vlan_vmwa_init(eth_dev, spawn->ifindex);
1763         if (config->dv_flow_en) {
1764                 err = mlx5_alloc_shared_dr(priv);
1765                 if (err)
1766                         goto error;
1767         }
1768         if (config->devx && config->dv_flow_en && config->dest_tir) {
1769                 priv->obj_ops = devx_obj_ops;
1770                 priv->obj_ops.drop_action_create =
1771                                                 ibv_obj_ops.drop_action_create;
1772                 priv->obj_ops.drop_action_destroy =
1773                                                 ibv_obj_ops.drop_action_destroy;
1774 #ifndef HAVE_MLX5DV_DEVX_UAR_OFFSET
1775                 priv->obj_ops.txq_obj_modify = ibv_obj_ops.txq_obj_modify;
1776 #else
1777                 if (config->dv_esw_en)
1778                         priv->obj_ops.txq_obj_modify =
1779                                                 ibv_obj_ops.txq_obj_modify;
1780 #endif
1781                 /* Use specific wrappers for Tx object. */
1782                 priv->obj_ops.txq_obj_new = mlx5_os_txq_obj_new;
1783                 priv->obj_ops.txq_obj_release = mlx5_os_txq_obj_release;
1784                 mlx5_queue_counter_id_prepare(eth_dev);
1785                 priv->obj_ops.lb_dummy_queue_create =
1786                                         mlx5_rxq_ibv_obj_dummy_lb_create;
1787                 priv->obj_ops.lb_dummy_queue_release =
1788                                         mlx5_rxq_ibv_obj_dummy_lb_release;
1789         } else {
1790                 priv->obj_ops = ibv_obj_ops;
1791         }
1792         if (config->tx_pp &&
1793             (priv->config.dv_esw_en ||
1794              priv->obj_ops.txq_obj_new != mlx5_os_txq_obj_new)) {
1795                 /*
1796                  * HAVE_MLX5DV_DEVX_UAR_OFFSET is required to support
1797                  * packet pacing and already checked above.
1798                  * Hence, we should only make sure the SQs will be created
1799                  * with DevX, not with Verbs.
1800                  * Verbs allocates the SQ UAR on its own and it can't be shared
1801                  * with Clock Queue UAR as required for Tx scheduling.
1802                  */
1803                 DRV_LOG(ERR, "Verbs SQs, UAR can't be shared as required for packet pacing");
1804                 err = ENODEV;
1805                 goto error;
1806         }
1807         priv->drop_queue.hrxq = mlx5_drop_action_create(eth_dev);
1808         if (!priv->drop_queue.hrxq)
1809                 goto error;
1810         /* Supported Verbs flow priority number detection. */
1811         err = mlx5_flow_discover_priorities(eth_dev);
1812         if (err < 0) {
1813                 err = -err;
1814                 goto error;
1815         }
1816         priv->config.flow_prio = err;
1817         if (!priv->config.dv_esw_en &&
1818             priv->config.dv_xmeta_en != MLX5_XMETA_MODE_LEGACY) {
1819                 DRV_LOG(WARNING, "metadata mode %u is not supported "
1820                                  "(no E-Switch)", priv->config.dv_xmeta_en);
1821                 priv->config.dv_xmeta_en = MLX5_XMETA_MODE_LEGACY;
1822         }
1823         mlx5_set_metadata_mask(eth_dev);
1824         if (priv->config.dv_xmeta_en != MLX5_XMETA_MODE_LEGACY &&
1825             !priv->sh->dv_regc0_mask) {
1826                 DRV_LOG(ERR, "metadata mode %u is not supported "
1827                              "(no metadata reg_c[0] is available)",
1828                              priv->config.dv_xmeta_en);
1829                         err = ENOTSUP;
1830                         goto error;
1831         }
1832         priv->hrxqs = mlx5_list_create("hrxq", eth_dev, true,
1833                                        mlx5_hrxq_create_cb,
1834                                        mlx5_hrxq_match_cb,
1835                                        mlx5_hrxq_remove_cb,
1836                                        mlx5_hrxq_clone_cb,
1837                                        mlx5_hrxq_clone_free_cb);
1838         if (!priv->hrxqs)
1839                 goto error;
1840         rte_rwlock_init(&priv->ind_tbls_lock);
1841         /* Query availability of metadata reg_c's. */
1842         err = mlx5_flow_discover_mreg_c(eth_dev);
1843         if (err < 0) {
1844                 err = -err;
1845                 goto error;
1846         }
1847         if (!mlx5_flow_ext_mreg_supported(eth_dev)) {
1848                 DRV_LOG(DEBUG,
1849                         "port %u extensive metadata register is not supported",
1850                         eth_dev->data->port_id);
1851                 if (priv->config.dv_xmeta_en != MLX5_XMETA_MODE_LEGACY) {
1852                         DRV_LOG(ERR, "metadata mode %u is not supported "
1853                                      "(no metadata registers available)",
1854                                      priv->config.dv_xmeta_en);
1855                         err = ENOTSUP;
1856                         goto error;
1857                 }
1858         }
1859         if (priv->config.dv_flow_en &&
1860             priv->config.dv_xmeta_en != MLX5_XMETA_MODE_LEGACY &&
1861             mlx5_flow_ext_mreg_supported(eth_dev) &&
1862             priv->sh->dv_regc0_mask) {
1863                 priv->mreg_cp_tbl = mlx5_hlist_create(MLX5_FLOW_MREG_HNAME,
1864                                                       MLX5_FLOW_MREG_HTABLE_SZ,
1865                                                       false, true, eth_dev,
1866                                                       flow_dv_mreg_create_cb,
1867                                                       flow_dv_mreg_match_cb,
1868                                                       flow_dv_mreg_remove_cb,
1869                                                       flow_dv_mreg_clone_cb,
1870                                                     flow_dv_mreg_clone_free_cb);
1871                 if (!priv->mreg_cp_tbl) {
1872                         err = ENOMEM;
1873                         goto error;
1874                 }
1875         }
1876         rte_spinlock_init(&priv->shared_act_sl);
1877         mlx5_flow_counter_mode_config(eth_dev);
1878         if (priv->config.dv_flow_en)
1879                 eth_dev->data->dev_flags |= RTE_ETH_DEV_FLOW_OPS_THREAD_SAFE;
1880         return eth_dev;
1881 error:
1882         if (priv) {
1883                 if (priv->mreg_cp_tbl)
1884                         mlx5_hlist_destroy(priv->mreg_cp_tbl);
1885                 if (priv->sh)
1886                         mlx5_os_free_shared_dr(priv);
1887                 if (priv->nl_socket_route >= 0)
1888                         close(priv->nl_socket_route);
1889                 if (priv->nl_socket_rdma >= 0)
1890                         close(priv->nl_socket_rdma);
1891                 if (priv->vmwa_context)
1892                         mlx5_vlan_vmwa_exit(priv->vmwa_context);
1893                 if (eth_dev && priv->drop_queue.hrxq)
1894                         mlx5_drop_action_destroy(eth_dev);
1895                 if (priv->mtr_profile_tbl)
1896                         mlx5_l3t_destroy(priv->mtr_profile_tbl);
1897                 if (own_domain_id)
1898                         claim_zero(rte_eth_switch_domain_free(priv->domain_id));
1899                 if (priv->hrxqs)
1900                         mlx5_list_destroy(priv->hrxqs);
1901                 mlx5_free(priv);
1902                 if (eth_dev != NULL)
1903                         eth_dev->data->dev_private = NULL;
1904         }
1905         if (eth_dev != NULL) {
1906                 /* mac_addrs must not be freed alone because part of
1907                  * dev_private
1908                  **/
1909                 eth_dev->data->mac_addrs = NULL;
1910                 rte_eth_dev_release_port(eth_dev);
1911         }
1912         if (sh)
1913                 mlx5_free_shared_dev_ctx(sh);
1914         MLX5_ASSERT(err > 0);
1915         rte_errno = err;
1916         return NULL;
1917 }
1918
1919 /**
1920  * Comparison callback to sort device data.
1921  *
1922  * This is meant to be used with qsort().
1923  *
1924  * @param a[in]
1925  *   Pointer to pointer to first data object.
1926  * @param b[in]
1927  *   Pointer to pointer to second data object.
1928  *
1929  * @return
1930  *   0 if both objects are equal, less than 0 if the first argument is less
1931  *   than the second, greater than 0 otherwise.
1932  */
1933 static int
1934 mlx5_dev_spawn_data_cmp(const void *a, const void *b)
1935 {
1936         const struct mlx5_switch_info *si_a =
1937                 &((const struct mlx5_dev_spawn_data *)a)->info;
1938         const struct mlx5_switch_info *si_b =
1939                 &((const struct mlx5_dev_spawn_data *)b)->info;
1940         int ret;
1941
1942         /* Master device first. */
1943         ret = si_b->master - si_a->master;
1944         if (ret)
1945                 return ret;
1946         /* Then representor devices. */
1947         ret = si_b->representor - si_a->representor;
1948         if (ret)
1949                 return ret;
1950         /* Unidentified devices come last in no specific order. */
1951         if (!si_a->representor)
1952                 return 0;
1953         /* Order representors by name. */
1954         return si_a->port_name - si_b->port_name;
1955 }
1956
1957 /**
1958  * Match PCI information for possible slaves of bonding device.
1959  *
1960  * @param[in] ibv_dev
1961  *   Pointer to Infiniband device structure.
1962  * @param[in] pci_dev
1963  *   Pointer to primary PCI address structure to match.
1964  * @param[in] nl_rdma
1965  *   Netlink RDMA group socket handle.
1966  * @param[in] owner
1967  *   Rerepsentor owner PF index.
1968  * @param[out] bond_info
1969  *   Pointer to bonding information.
1970  *
1971  * @return
1972  *   negative value if no bonding device found, otherwise
1973  *   positive index of slave PF in bonding.
1974  */
1975 static int
1976 mlx5_device_bond_pci_match(const struct ibv_device *ibv_dev,
1977                            const struct rte_pci_addr *pci_dev,
1978                            int nl_rdma, uint16_t owner,
1979                            struct mlx5_bond_info *bond_info)
1980 {
1981         char ifname[IF_NAMESIZE + 1];
1982         unsigned int ifindex;
1983         unsigned int np, i;
1984         FILE *bond_file = NULL, *file;
1985         int pf = -1;
1986         int ret;
1987
1988         /*
1989          * Try to get master device name. If something goes
1990          * wrong suppose the lack of kernel support and no
1991          * bonding devices.
1992          */
1993         memset(bond_info, 0, sizeof(*bond_info));
1994         if (nl_rdma < 0)
1995                 return -1;
1996         if (!strstr(ibv_dev->name, "bond"))
1997                 return -1;
1998         np = mlx5_nl_portnum(nl_rdma, ibv_dev->name);
1999         if (!np)
2000                 return -1;
2001         /*
2002          * The Master device might not be on the predefined
2003          * port (not on port index 1, it is not garanted),
2004          * we have to scan all Infiniband device port and
2005          * find master.
2006          */
2007         for (i = 1; i <= np; ++i) {
2008                 /* Check whether Infiniband port is populated. */
2009                 ifindex = mlx5_nl_ifindex(nl_rdma, ibv_dev->name, i);
2010                 if (!ifindex)
2011                         continue;
2012                 if (!if_indextoname(ifindex, ifname))
2013                         continue;
2014                 /* Try to read bonding slave names from sysfs. */
2015                 MKSTR(slaves,
2016                       "/sys/class/net/%s/master/bonding/slaves", ifname);
2017                 bond_file = fopen(slaves, "r");
2018                 if (bond_file)
2019                         break;
2020         }
2021         if (!bond_file)
2022                 return -1;
2023         /* Use safe format to check maximal buffer length. */
2024         MLX5_ASSERT(atol(RTE_STR(IF_NAMESIZE)) == IF_NAMESIZE);
2025         while (fscanf(bond_file, "%" RTE_STR(IF_NAMESIZE) "s", ifname) == 1) {
2026                 char tmp_str[IF_NAMESIZE + 32];
2027                 struct rte_pci_addr pci_addr;
2028                 struct mlx5_switch_info info;
2029
2030                 /* Process slave interface names in the loop. */
2031                 snprintf(tmp_str, sizeof(tmp_str),
2032                          "/sys/class/net/%s", ifname);
2033                 if (mlx5_get_pci_addr(tmp_str, &pci_addr)) {
2034                         DRV_LOG(WARNING, "can not get PCI address"
2035                                          " for netdev \"%s\"", ifname);
2036                         continue;
2037                 }
2038                 /* Slave interface PCI address match found. */
2039                 snprintf(tmp_str, sizeof(tmp_str),
2040                          "/sys/class/net/%s/phys_port_name", ifname);
2041                 file = fopen(tmp_str, "rb");
2042                 if (!file)
2043                         break;
2044                 info.name_type = MLX5_PHYS_PORT_NAME_TYPE_NOTSET;
2045                 if (fscanf(file, "%32s", tmp_str) == 1)
2046                         mlx5_translate_port_name(tmp_str, &info);
2047                 fclose(file);
2048                 /* Only process PF ports. */
2049                 if (info.name_type != MLX5_PHYS_PORT_NAME_TYPE_LEGACY &&
2050                     info.name_type != MLX5_PHYS_PORT_NAME_TYPE_UPLINK)
2051                         continue;
2052                 /* Check max bonding member. */
2053                 if (info.port_name >= MLX5_BOND_MAX_PORTS) {
2054                         DRV_LOG(WARNING, "bonding index out of range, "
2055                                 "please increase MLX5_BOND_MAX_PORTS: %s",
2056                                 tmp_str);
2057                         break;
2058                 }
2059                 /* Match PCI address, allows BDF0+pfx or BDFx+pfx. */
2060                 if (pci_dev->domain == pci_addr.domain &&
2061                     pci_dev->bus == pci_addr.bus &&
2062                     pci_dev->devid == pci_addr.devid &&
2063                     ((pci_dev->function == 0 &&
2064                       pci_dev->function + owner == pci_addr.function) ||
2065                      (pci_dev->function == owner &&
2066                       pci_addr.function == owner)))
2067                         pf = info.port_name;
2068                 /* Get ifindex. */
2069                 snprintf(tmp_str, sizeof(tmp_str),
2070                          "/sys/class/net/%s/ifindex", ifname);
2071                 file = fopen(tmp_str, "rb");
2072                 if (!file)
2073                         break;
2074                 ret = fscanf(file, "%u", &ifindex);
2075                 fclose(file);
2076                 if (ret != 1)
2077                         break;
2078                 /* Save bonding info. */
2079                 strncpy(bond_info->ports[info.port_name].ifname, ifname,
2080                         sizeof(bond_info->ports[0].ifname));
2081                 bond_info->ports[info.port_name].pci_addr = pci_addr;
2082                 bond_info->ports[info.port_name].ifindex = ifindex;
2083                 bond_info->n_port++;
2084         }
2085         if (pf >= 0) {
2086                 /* Get bond interface info */
2087                 ret = mlx5_sysfs_bond_info(ifindex, &bond_info->ifindex,
2088                                            bond_info->ifname);
2089                 if (ret)
2090                         DRV_LOG(ERR, "unable to get bond info: %s",
2091                                 strerror(rte_errno));
2092                 else
2093                         DRV_LOG(INFO, "PF device %u, bond device %u(%s)",
2094                                 ifindex, bond_info->ifindex, bond_info->ifname);
2095         }
2096         return pf;
2097 }
2098
2099 static void
2100 mlx5_os_config_default(struct mlx5_dev_config *config)
2101 {
2102         memset(config, 0, sizeof(*config));
2103         config->mps = MLX5_ARG_UNSET;
2104         config->dbnc = MLX5_ARG_UNSET;
2105         config->rx_vec_en = 1;
2106         config->txq_inline_max = MLX5_ARG_UNSET;
2107         config->txq_inline_min = MLX5_ARG_UNSET;
2108         config->txq_inline_mpw = MLX5_ARG_UNSET;
2109         config->txqs_inline = MLX5_ARG_UNSET;
2110         config->vf_nl_en = 1;
2111         config->mr_ext_memseg_en = 1;
2112         config->mprq.max_memcpy_len = MLX5_MPRQ_MEMCPY_DEFAULT_LEN;
2113         config->mprq.min_rxqs_num = MLX5_MPRQ_MIN_RXQS;
2114         config->dv_esw_en = 1;
2115         config->dv_flow_en = 1;
2116         config->decap_en = 1;
2117         config->log_hp_size = MLX5_ARG_UNSET;
2118 }
2119
2120 /**
2121  * Register a PCI device within bonding.
2122  *
2123  * This function spawns Ethernet devices out of a given PCI device and
2124  * bonding owner PF index.
2125  *
2126  * @param[in] pci_dev
2127  *   PCI device information.
2128  * @param[in] req_eth_da
2129  *   Requested ethdev device argument.
2130  * @param[in] owner_id
2131  *   Requested owner PF port ID within bonding device, default to 0.
2132  *
2133  * @return
2134  *   0 on success, a negative errno value otherwise and rte_errno is set.
2135  */
2136 static int
2137 mlx5_os_pci_probe_pf(struct rte_pci_device *pci_dev,
2138                      struct rte_eth_devargs *req_eth_da,
2139                      uint16_t owner_id)
2140 {
2141         struct ibv_device **ibv_list;
2142         /*
2143          * Number of found IB Devices matching with requested PCI BDF.
2144          * nd != 1 means there are multiple IB devices over the same
2145          * PCI device and we have representors and master.
2146          */
2147         unsigned int nd = 0;
2148         /*
2149          * Number of found IB device Ports. nd = 1 and np = 1..n means
2150          * we have the single multiport IB device, and there may be
2151          * representors attached to some of found ports.
2152          */
2153         unsigned int np = 0;
2154         /*
2155          * Number of DPDK ethernet devices to Spawn - either over
2156          * multiple IB devices or multiple ports of single IB device.
2157          * Actually this is the number of iterations to spawn.
2158          */
2159         unsigned int ns = 0;
2160         /*
2161          * Bonding device
2162          *   < 0 - no bonding device (single one)
2163          *  >= 0 - bonding device (value is slave PF index)
2164          */
2165         int bd = -1;
2166         struct mlx5_dev_spawn_data *list = NULL;
2167         struct mlx5_dev_config dev_config;
2168         unsigned int dev_config_vf;
2169         struct rte_eth_devargs eth_da = *req_eth_da;
2170         struct rte_pci_addr owner_pci = pci_dev->addr; /* Owner PF. */
2171         struct mlx5_bond_info bond_info;
2172         int ret = -1;
2173
2174         errno = 0;
2175         ibv_list = mlx5_glue->get_device_list(&ret);
2176         if (!ibv_list) {
2177                 rte_errno = errno ? errno : ENOSYS;
2178                 DRV_LOG(ERR, "cannot list devices, is ib_uverbs loaded?");
2179                 return -rte_errno;
2180         }
2181         /*
2182          * First scan the list of all Infiniband devices to find
2183          * matching ones, gathering into the list.
2184          */
2185         struct ibv_device *ibv_match[ret + 1];
2186         int nl_route = mlx5_nl_init(NETLINK_ROUTE);
2187         int nl_rdma = mlx5_nl_init(NETLINK_RDMA);
2188         unsigned int i;
2189
2190         while (ret-- > 0) {
2191                 struct rte_pci_addr pci_addr;
2192
2193                 DRV_LOG(DEBUG, "checking device \"%s\"", ibv_list[ret]->name);
2194                 bd = mlx5_device_bond_pci_match
2195                                 (ibv_list[ret], &owner_pci, nl_rdma, owner_id,
2196                                  &bond_info);
2197                 if (bd >= 0) {
2198                         /*
2199                          * Bonding device detected. Only one match is allowed,
2200                          * the bonding is supported over multi-port IB device,
2201                          * there should be no matches on representor PCI
2202                          * functions or non VF LAG bonding devices with
2203                          * specified address.
2204                          */
2205                         if (nd) {
2206                                 DRV_LOG(ERR,
2207                                         "multiple PCI match on bonding device"
2208                                         "\"%s\" found", ibv_list[ret]->name);
2209                                 rte_errno = ENOENT;
2210                                 ret = -rte_errno;
2211                                 goto exit;
2212                         }
2213                         /* Amend owner pci address if owner PF ID specified. */
2214                         if (eth_da.nb_representor_ports)
2215                                 owner_pci.function += owner_id;
2216                         DRV_LOG(INFO, "PCI information matches for"
2217                                       " slave %d bonding device \"%s\"",
2218                                       bd, ibv_list[ret]->name);
2219                         ibv_match[nd++] = ibv_list[ret];
2220                         break;
2221                 } else {
2222                         /* Bonding device not found. */
2223                         if (mlx5_get_pci_addr(ibv_list[ret]->ibdev_path,
2224                                               &pci_addr))
2225                                 continue;
2226                         if (owner_pci.domain != pci_addr.domain ||
2227                             owner_pci.bus != pci_addr.bus ||
2228                             owner_pci.devid != pci_addr.devid ||
2229                             owner_pci.function != pci_addr.function)
2230                                 continue;
2231                         DRV_LOG(INFO, "PCI information matches for device \"%s\"",
2232                                 ibv_list[ret]->name);
2233                         ibv_match[nd++] = ibv_list[ret];
2234                 }
2235         }
2236         ibv_match[nd] = NULL;
2237         if (!nd) {
2238                 /* No device matches, just complain and bail out. */
2239                 DRV_LOG(WARNING,
2240                         "no Verbs device matches PCI device " PCI_PRI_FMT ","
2241                         " are kernel drivers loaded?",
2242                         owner_pci.domain, owner_pci.bus,
2243                         owner_pci.devid, owner_pci.function);
2244                 rte_errno = ENOENT;
2245                 ret = -rte_errno;
2246                 goto exit;
2247         }
2248         if (nd == 1) {
2249                 /*
2250                  * Found single matching device may have multiple ports.
2251                  * Each port may be representor, we have to check the port
2252                  * number and check the representors existence.
2253                  */
2254                 if (nl_rdma >= 0)
2255                         np = mlx5_nl_portnum(nl_rdma, ibv_match[0]->name);
2256                 if (!np)
2257                         DRV_LOG(WARNING, "can not get IB device \"%s\""
2258                                          " ports number", ibv_match[0]->name);
2259                 if (bd >= 0 && !np) {
2260                         DRV_LOG(ERR, "can not get ports"
2261                                      " for bonding device");
2262                         rte_errno = ENOENT;
2263                         ret = -rte_errno;
2264                         goto exit;
2265                 }
2266         }
2267         /*
2268          * Now we can determine the maximal
2269          * amount of devices to be spawned.
2270          */
2271         list = mlx5_malloc(MLX5_MEM_ZERO,
2272                            sizeof(struct mlx5_dev_spawn_data) *
2273                            (np ? np : nd),
2274                            RTE_CACHE_LINE_SIZE, SOCKET_ID_ANY);
2275         if (!list) {
2276                 DRV_LOG(ERR, "spawn data array allocation failure");
2277                 rte_errno = ENOMEM;
2278                 ret = -rte_errno;
2279                 goto exit;
2280         }
2281         if (bd >= 0 || np > 1) {
2282                 /*
2283                  * Single IB device with multiple ports found,
2284                  * it may be E-Switch master device and representors.
2285                  * We have to perform identification through the ports.
2286                  */
2287                 MLX5_ASSERT(nl_rdma >= 0);
2288                 MLX5_ASSERT(ns == 0);
2289                 MLX5_ASSERT(nd == 1);
2290                 MLX5_ASSERT(np);
2291                 for (i = 1; i <= np; ++i) {
2292                         list[ns].bond_info = &bond_info;
2293                         list[ns].max_port = np;
2294                         list[ns].phys_port = i;
2295                         list[ns].phys_dev = ibv_match[0];
2296                         list[ns].eth_dev = NULL;
2297                         list[ns].pci_dev = pci_dev;
2298                         list[ns].pf_bond = bd;
2299                         list[ns].ifindex = mlx5_nl_ifindex
2300                                 (nl_rdma,
2301                                 mlx5_os_get_dev_device_name
2302                                                 (list[ns].phys_dev), i);
2303                         if (!list[ns].ifindex) {
2304                                 /*
2305                                  * No network interface index found for the
2306                                  * specified port, it means there is no
2307                                  * representor on this port. It's OK,
2308                                  * there can be disabled ports, for example
2309                                  * if sriov_numvfs < sriov_totalvfs.
2310                                  */
2311                                 continue;
2312                         }
2313                         ret = -1;
2314                         if (nl_route >= 0)
2315                                 ret = mlx5_nl_switch_info
2316                                                (nl_route,
2317                                                 list[ns].ifindex,
2318                                                 &list[ns].info);
2319                         if (ret || (!list[ns].info.representor &&
2320                                     !list[ns].info.master)) {
2321                                 /*
2322                                  * We failed to recognize representors with
2323                                  * Netlink, let's try to perform the task
2324                                  * with sysfs.
2325                                  */
2326                                 ret =  mlx5_sysfs_switch_info
2327                                                 (list[ns].ifindex,
2328                                                  &list[ns].info);
2329                         }
2330                         if (!ret && bd >= 0) {
2331                                 switch (list[ns].info.name_type) {
2332                                 case MLX5_PHYS_PORT_NAME_TYPE_UPLINK:
2333                                         if (np == 1) {
2334                                                 /*
2335                                                  * Force standalone bonding
2336                                                  * device for ROCE LAG
2337                                                  * confgiurations.
2338                                                  */
2339                                                 list[ns].info.master = 0;
2340                                                 list[ns].info.representor = 0;
2341                                         }
2342                                         if (list[ns].info.port_name == bd)
2343                                                 ns++;
2344                                         break;
2345                                 case MLX5_PHYS_PORT_NAME_TYPE_PFHPF:
2346                                         /* Fallthrough */
2347                                 case MLX5_PHYS_PORT_NAME_TYPE_PFVF:
2348                                         /* Fallthrough */
2349                                 case MLX5_PHYS_PORT_NAME_TYPE_PFSF:
2350                                         if (list[ns].info.pf_num == bd)
2351                                                 ns++;
2352                                         break;
2353                                 default:
2354                                         break;
2355                                 }
2356                                 continue;
2357                         }
2358                         if (!ret && (list[ns].info.representor ^
2359                                      list[ns].info.master))
2360                                 ns++;
2361                 }
2362                 if (!ns) {
2363                         DRV_LOG(ERR,
2364                                 "unable to recognize master/representors"
2365                                 " on the IB device with multiple ports");
2366                         rte_errno = ENOENT;
2367                         ret = -rte_errno;
2368                         goto exit;
2369                 }
2370         } else {
2371                 /*
2372                  * The existence of several matching entries (nd > 1) means
2373                  * port representors have been instantiated. No existing Verbs
2374                  * call nor sysfs entries can tell them apart, this can only
2375                  * be done through Netlink calls assuming kernel drivers are
2376                  * recent enough to support them.
2377                  *
2378                  * In the event of identification failure through Netlink,
2379                  * try again through sysfs, then:
2380                  *
2381                  * 1. A single IB device matches (nd == 1) with single
2382                  *    port (np=0/1) and is not a representor, assume
2383                  *    no switch support.
2384                  *
2385                  * 2. Otherwise no safe assumptions can be made;
2386                  *    complain louder and bail out.
2387                  */
2388                 for (i = 0; i != nd; ++i) {
2389                         memset(&list[ns].info, 0, sizeof(list[ns].info));
2390                         list[ns].bond_info = NULL;
2391                         list[ns].max_port = 1;
2392                         list[ns].phys_port = 1;
2393                         list[ns].phys_dev = ibv_match[i];
2394                         list[ns].eth_dev = NULL;
2395                         list[ns].pci_dev = pci_dev;
2396                         list[ns].pf_bond = -1;
2397                         list[ns].ifindex = 0;
2398                         if (nl_rdma >= 0)
2399                                 list[ns].ifindex = mlx5_nl_ifindex
2400                                 (nl_rdma,
2401                                 mlx5_os_get_dev_device_name
2402                                                 (list[ns].phys_dev), 1);
2403                         if (!list[ns].ifindex) {
2404                                 char ifname[IF_NAMESIZE];
2405
2406                                 /*
2407                                  * Netlink failed, it may happen with old
2408                                  * ib_core kernel driver (before 4.16).
2409                                  * We can assume there is old driver because
2410                                  * here we are processing single ports IB
2411                                  * devices. Let's try sysfs to retrieve
2412                                  * the ifindex. The method works for
2413                                  * master device only.
2414                                  */
2415                                 if (nd > 1) {
2416                                         /*
2417                                          * Multiple devices found, assume
2418                                          * representors, can not distinguish
2419                                          * master/representor and retrieve
2420                                          * ifindex via sysfs.
2421                                          */
2422                                         continue;
2423                                 }
2424                                 ret = mlx5_get_ifname_sysfs
2425                                         (ibv_match[i]->ibdev_path, ifname);
2426                                 if (!ret)
2427                                         list[ns].ifindex =
2428                                                 if_nametoindex(ifname);
2429                                 if (!list[ns].ifindex) {
2430                                         /*
2431                                          * No network interface index found
2432                                          * for the specified device, it means
2433                                          * there it is neither representor
2434                                          * nor master.
2435                                          */
2436                                         continue;
2437                                 }
2438                         }
2439                         ret = -1;
2440                         if (nl_route >= 0)
2441                                 ret = mlx5_nl_switch_info
2442                                                (nl_route,
2443                                                 list[ns].ifindex,
2444                                                 &list[ns].info);
2445                         if (ret || (!list[ns].info.representor &&
2446                                     !list[ns].info.master)) {
2447                                 /*
2448                                  * We failed to recognize representors with
2449                                  * Netlink, let's try to perform the task
2450                                  * with sysfs.
2451                                  */
2452                                 ret =  mlx5_sysfs_switch_info
2453                                                 (list[ns].ifindex,
2454                                                  &list[ns].info);
2455                         }
2456                         if (!ret && (list[ns].info.representor ^
2457                                      list[ns].info.master)) {
2458                                 ns++;
2459                         } else if ((nd == 1) &&
2460                                    !list[ns].info.representor &&
2461                                    !list[ns].info.master) {
2462                                 /*
2463                                  * Single IB device with
2464                                  * one physical port and
2465                                  * attached network device.
2466                                  * May be SRIOV is not enabled
2467                                  * or there is no representors.
2468                                  */
2469                                 DRV_LOG(INFO, "no E-Switch support detected");
2470                                 ns++;
2471                                 break;
2472                         }
2473                 }
2474                 if (!ns) {
2475                         DRV_LOG(ERR,
2476                                 "unable to recognize master/representors"
2477                                 " on the multiple IB devices");
2478                         rte_errno = ENOENT;
2479                         ret = -rte_errno;
2480                         goto exit;
2481                 }
2482                 /*
2483                  * New kernels may add the switch_id attribute for the case
2484                  * there is no E-Switch and we wrongly recognized the
2485                  * only device as master. Override this if there is the
2486                  * single device with single port and new device name
2487                  * format present.
2488                  */
2489                 if (nd == 1 &&
2490                     list[0].info.name_type == MLX5_PHYS_PORT_NAME_TYPE_UPLINK) {
2491                         list[0].info.master = 0;
2492                         list[0].info.representor = 0;
2493                 }
2494         }
2495         MLX5_ASSERT(ns);
2496         /*
2497          * Sort list to probe devices in natural order for users convenience
2498          * (i.e. master first, then representors from lowest to highest ID).
2499          */
2500         qsort(list, ns, sizeof(*list), mlx5_dev_spawn_data_cmp);
2501         /* Device specific configuration. */
2502         switch (pci_dev->id.device_id) {
2503         case PCI_DEVICE_ID_MELLANOX_CONNECTX4VF:
2504         case PCI_DEVICE_ID_MELLANOX_CONNECTX4LXVF:
2505         case PCI_DEVICE_ID_MELLANOX_CONNECTX5VF:
2506         case PCI_DEVICE_ID_MELLANOX_CONNECTX5EXVF:
2507         case PCI_DEVICE_ID_MELLANOX_CONNECTX5BFVF:
2508         case PCI_DEVICE_ID_MELLANOX_CONNECTX6VF:
2509         case PCI_DEVICE_ID_MELLANOX_CONNECTXVF:
2510                 dev_config_vf = 1;
2511                 break;
2512         default:
2513                 dev_config_vf = 0;
2514                 break;
2515         }
2516         if (eth_da.type != RTE_ETH_REPRESENTOR_NONE) {
2517                 /* Set devargs default values. */
2518                 if (eth_da.nb_mh_controllers == 0) {
2519                         eth_da.nb_mh_controllers = 1;
2520                         eth_da.mh_controllers[0] = 0;
2521                 }
2522                 if (eth_da.nb_ports == 0 && ns > 0) {
2523                         if (list[0].pf_bond >= 0 && list[0].info.representor)
2524                                 DRV_LOG(WARNING, "Representor on Bonding device should use pf#vf# syntax: %s",
2525                                         pci_dev->device.devargs->args);
2526                         eth_da.nb_ports = 1;
2527                         eth_da.ports[0] = list[0].info.pf_num;
2528                 }
2529                 if (eth_da.nb_representor_ports == 0) {
2530                         eth_da.nb_representor_ports = 1;
2531                         eth_da.representor_ports[0] = 0;
2532                 }
2533         }
2534         for (i = 0; i != ns; ++i) {
2535                 uint32_t restore;
2536
2537                 /* Default configuration. */
2538                 mlx5_os_config_default(&dev_config);
2539                 dev_config.vf = dev_config_vf;
2540                 dev_config.allow_duplicate_pattern = 1;
2541                 list[i].numa_node = pci_dev->device.numa_node;
2542                 list[i].eth_dev = mlx5_dev_spawn(&pci_dev->device,
2543                                                  &list[i],
2544                                                  &dev_config,
2545                                                  &eth_da);
2546                 if (!list[i].eth_dev) {
2547                         if (rte_errno != EBUSY && rte_errno != EEXIST)
2548                                 break;
2549                         /* Device is disabled or already spawned. Ignore it. */
2550                         continue;
2551                 }
2552                 restore = list[i].eth_dev->data->dev_flags;
2553                 rte_eth_copy_pci_info(list[i].eth_dev, pci_dev);
2554                 /**
2555                  * Each representor has a dedicated interrupts vector.
2556                  * rte_eth_copy_pci_info() assigns PF interrupts handle to
2557                  * representor eth_dev object because representor and PF
2558                  * share the same PCI address.
2559                  * Override representor device with a dedicated
2560                  * interrupts handle here.
2561                  * Representor interrupts handle is released in mlx5_dev_stop().
2562                  */
2563                 if (list[i].info.representor) {
2564                         struct rte_intr_handle *intr_handle;
2565                         intr_handle = mlx5_malloc(MLX5_MEM_SYS | MLX5_MEM_ZERO,
2566                                                   sizeof(*intr_handle), 0,
2567                                                   SOCKET_ID_ANY);
2568                         if (!intr_handle) {
2569                                 DRV_LOG(ERR,
2570                                         "port %u failed to allocate memory for interrupt handler "
2571                                         "Rx interrupts will not be supported",
2572                                         i);
2573                                 rte_errno = ENOMEM;
2574                                 ret = -rte_errno;
2575                                 goto exit;
2576                         }
2577                         list[i].eth_dev->intr_handle = intr_handle;
2578                 }
2579                 /* Restore non-PCI flags cleared by the above call. */
2580                 list[i].eth_dev->data->dev_flags |= restore;
2581                 rte_eth_dev_probing_finish(list[i].eth_dev);
2582         }
2583         if (i != ns) {
2584                 DRV_LOG(ERR,
2585                         "probe of PCI device " PCI_PRI_FMT " aborted after"
2586                         " encountering an error: %s",
2587                         owner_pci.domain, owner_pci.bus,
2588                         owner_pci.devid, owner_pci.function,
2589                         strerror(rte_errno));
2590                 ret = -rte_errno;
2591                 /* Roll back. */
2592                 while (i--) {
2593                         if (!list[i].eth_dev)
2594                                 continue;
2595                         mlx5_dev_close(list[i].eth_dev);
2596                         /* mac_addrs must not be freed because in dev_private */
2597                         list[i].eth_dev->data->mac_addrs = NULL;
2598                         claim_zero(rte_eth_dev_release_port(list[i].eth_dev));
2599                 }
2600                 /* Restore original error. */
2601                 rte_errno = -ret;
2602         } else {
2603                 ret = 0;
2604         }
2605 exit:
2606         /*
2607          * Do the routine cleanup:
2608          * - close opened Netlink sockets
2609          * - free allocated spawn data array
2610          * - free the Infiniband device list
2611          */
2612         if (nl_rdma >= 0)
2613                 close(nl_rdma);
2614         if (nl_route >= 0)
2615                 close(nl_route);
2616         if (list)
2617                 mlx5_free(list);
2618         MLX5_ASSERT(ibv_list);
2619         mlx5_glue->free_device_list(ibv_list);
2620         return ret;
2621 }
2622
2623 static int
2624 mlx5_os_parse_eth_devargs(struct rte_device *dev,
2625                           struct rte_eth_devargs *eth_da)
2626 {
2627         int ret = 0;
2628
2629         if (dev->devargs == NULL)
2630                 return 0;
2631         memset(eth_da, 0, sizeof(*eth_da));
2632         /* Parse representor information first from class argument. */
2633         if (dev->devargs->cls_str)
2634                 ret = rte_eth_devargs_parse(dev->devargs->cls_str, eth_da);
2635         if (ret != 0) {
2636                 DRV_LOG(ERR, "failed to parse device arguments: %s",
2637                         dev->devargs->cls_str);
2638                 return -rte_errno;
2639         }
2640         if (eth_da->type == RTE_ETH_REPRESENTOR_NONE) {
2641                 /* Parse legacy device argument */
2642                 ret = rte_eth_devargs_parse(dev->devargs->args, eth_da);
2643                 if (ret) {
2644                         DRV_LOG(ERR, "failed to parse device arguments: %s",
2645                                 dev->devargs->args);
2646                         return -rte_errno;
2647                 }
2648         }
2649         return 0;
2650 }
2651
2652 /**
2653  * Callback to register a PCI device.
2654  *
2655  * This function spawns Ethernet devices out of a given PCI device.
2656  *
2657  * @param[in] pci_dev
2658  *   PCI device information.
2659  *
2660  * @return
2661  *   0 on success, a negative errno value otherwise and rte_errno is set.
2662  */
2663 static int
2664 mlx5_os_pci_probe(struct rte_pci_device *pci_dev)
2665 {
2666         struct rte_eth_devargs eth_da = { .nb_ports = 0 };
2667         int ret = 0;
2668         uint16_t p;
2669
2670         ret = mlx5_os_parse_eth_devargs(&pci_dev->device, &eth_da);
2671         if (ret != 0)
2672                 return ret;
2673
2674         if (eth_da.nb_ports > 0) {
2675                 /* Iterate all port if devargs pf is range: "pf[0-1]vf[...]". */
2676                 for (p = 0; p < eth_da.nb_ports; p++)
2677                         ret = mlx5_os_pci_probe_pf(pci_dev, &eth_da,
2678                                                    eth_da.ports[p]);
2679         } else {
2680                 ret = mlx5_os_pci_probe_pf(pci_dev, &eth_da, 0);
2681         }
2682         return ret;
2683 }
2684
2685 /* Probe a single SF device on auxiliary bus, no representor support. */
2686 static int
2687 mlx5_os_auxiliary_probe(struct rte_device *dev)
2688 {
2689         struct rte_eth_devargs eth_da = { .nb_ports = 0 };
2690         struct mlx5_dev_config config;
2691         struct mlx5_dev_spawn_data spawn = { .pf_bond = -1 };
2692         struct rte_auxiliary_device *adev = RTE_DEV_TO_AUXILIARY(dev);
2693         struct rte_eth_dev *eth_dev;
2694         int ret = 0;
2695
2696         /* Parse ethdev devargs. */
2697         ret = mlx5_os_parse_eth_devargs(dev, &eth_da);
2698         if (ret != 0)
2699                 return ret;
2700         /* Set default config data. */
2701         mlx5_os_config_default(&config);
2702         config.sf = 1;
2703         /* Init spawn data. */
2704         spawn.max_port = 1;
2705         spawn.phys_port = 1;
2706         spawn.phys_dev = mlx5_os_get_ibv_dev(dev);
2707         if (spawn.phys_dev == NULL)
2708                 return -rte_errno;
2709         ret = mlx5_auxiliary_get_ifindex(dev->name);
2710         if (ret < 0) {
2711                 DRV_LOG(ERR, "failed to get ethdev ifindex: %s", dev->name);
2712                 return ret;
2713         }
2714         spawn.ifindex = ret;
2715         spawn.numa_node = dev->numa_node;
2716         /* Spawn device. */
2717         eth_dev = mlx5_dev_spawn(dev, &spawn, &config, &eth_da);
2718         if (eth_dev == NULL)
2719                 return -rte_errno;
2720         /* Post create. */
2721         eth_dev->intr_handle = &adev->intr_handle;
2722         if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
2723                 eth_dev->data->dev_flags |= RTE_ETH_DEV_INTR_LSC;
2724                 eth_dev->data->dev_flags |= RTE_ETH_DEV_INTR_RMV;
2725                 eth_dev->data->numa_node = dev->numa_node;
2726         }
2727         rte_eth_dev_probing_finish(eth_dev);
2728         return 0;
2729 }
2730
2731 /**
2732  * Net class driver callback to probe a device.
2733  *
2734  * This function probe PCI bus device(s) or a single SF on auxiliary bus.
2735  *
2736  * @param[in] dev
2737  *   Pointer to the generic device.
2738  *
2739  * @return
2740  *   0 on success, the function cannot fail.
2741  */
2742 int
2743 mlx5_os_net_probe(struct rte_device *dev)
2744 {
2745         int ret;
2746
2747         if (rte_eal_process_type() == RTE_PROC_PRIMARY)
2748                 mlx5_pmd_socket_init();
2749         ret = mlx5_init_once();
2750         if (ret) {
2751                 DRV_LOG(ERR, "unable to init PMD global data: %s",
2752                         strerror(rte_errno));
2753                 return -rte_errno;
2754         }
2755         if (mlx5_dev_is_pci(dev))
2756                 return mlx5_os_pci_probe(RTE_DEV_TO_PCI(dev));
2757         else
2758                 return mlx5_os_auxiliary_probe(dev);
2759 }
2760
2761 static int
2762 mlx5_config_doorbell_mapping_env(const struct mlx5_dev_config *config)
2763 {
2764         char *env;
2765         int value;
2766
2767         MLX5_ASSERT(rte_eal_process_type() == RTE_PROC_PRIMARY);
2768         /* Get environment variable to store. */
2769         env = getenv(MLX5_SHUT_UP_BF);
2770         value = env ? !!strcmp(env, "0") : MLX5_ARG_UNSET;
2771         if (config->dbnc == MLX5_ARG_UNSET)
2772                 setenv(MLX5_SHUT_UP_BF, MLX5_SHUT_UP_BF_DEFAULT, 1);
2773         else
2774                 setenv(MLX5_SHUT_UP_BF,
2775                        config->dbnc == MLX5_TXDB_NCACHED ? "1" : "0", 1);
2776         return value;
2777 }
2778
2779 static void
2780 mlx5_restore_doorbell_mapping_env(int value)
2781 {
2782         MLX5_ASSERT(rte_eal_process_type() == RTE_PROC_PRIMARY);
2783         /* Restore the original environment variable state. */
2784         if (value == MLX5_ARG_UNSET)
2785                 unsetenv(MLX5_SHUT_UP_BF);
2786         else
2787                 setenv(MLX5_SHUT_UP_BF, value ? "1" : "0", 1);
2788 }
2789
2790 /**
2791  * Extract pdn of PD object using DV API.
2792  *
2793  * @param[in] pd
2794  *   Pointer to the verbs PD object.
2795  * @param[out] pdn
2796  *   Pointer to the PD object number variable.
2797  *
2798  * @return
2799  *   0 on success, error value otherwise.
2800  */
2801 int
2802 mlx5_os_get_pdn(void *pd, uint32_t *pdn)
2803 {
2804 #ifdef HAVE_IBV_FLOW_DV_SUPPORT
2805         struct mlx5dv_obj obj;
2806         struct mlx5dv_pd pd_info;
2807         int ret = 0;
2808
2809         obj.pd.in = pd;
2810         obj.pd.out = &pd_info;
2811         ret = mlx5_glue->dv_init_obj(&obj, MLX5DV_OBJ_PD);
2812         if (ret) {
2813                 DRV_LOG(DEBUG, "Fail to get PD object info");
2814                 return ret;
2815         }
2816         *pdn = pd_info.pdn;
2817         return 0;
2818 #else
2819         (void)pd;
2820         (void)pdn;
2821         return -ENOTSUP;
2822 #endif /* HAVE_IBV_FLOW_DV_SUPPORT */
2823 }
2824
2825 /**
2826  * Function API to open IB device.
2827  *
2828  * This function calls the Linux glue APIs to open a device.
2829  *
2830  * @param[in] spawn
2831  *   Pointer to the IB device attributes (name, port, etc).
2832  * @param[out] config
2833  *   Pointer to device configuration structure.
2834  * @param[out] sh
2835  *   Pointer to shared context structure.
2836  *
2837  * @return
2838  *   0 on success, a positive error value otherwise.
2839  */
2840 int
2841 mlx5_os_open_device(const struct mlx5_dev_spawn_data *spawn,
2842                      const struct mlx5_dev_config *config,
2843                      struct mlx5_dev_ctx_shared *sh)
2844 {
2845         int dbmap_env;
2846         int err = 0;
2847
2848         pthread_mutex_init(&sh->txpp.mutex, NULL);
2849         /*
2850          * Configure environment variable "MLX5_BF_SHUT_UP"
2851          * before the device creation. The rdma_core library
2852          * checks the variable at device creation and
2853          * stores the result internally.
2854          */
2855         dbmap_env = mlx5_config_doorbell_mapping_env(config);
2856         /* Try to open IB device with DV first, then usual Verbs. */
2857         errno = 0;
2858         sh->ctx = mlx5_glue->dv_open_device(spawn->phys_dev);
2859         if (sh->ctx) {
2860                 sh->devx = 1;
2861                 DRV_LOG(DEBUG, "DevX is supported");
2862                 /* The device is created, no need for environment. */
2863                 mlx5_restore_doorbell_mapping_env(dbmap_env);
2864         } else {
2865                 /* The environment variable is still configured. */
2866                 sh->ctx = mlx5_glue->open_device(spawn->phys_dev);
2867                 err = errno ? errno : ENODEV;
2868                 /*
2869                  * The environment variable is not needed anymore,
2870                  * all device creation attempts are completed.
2871                  */
2872                 mlx5_restore_doorbell_mapping_env(dbmap_env);
2873                 if (!sh->ctx)
2874                         return err;
2875                 DRV_LOG(DEBUG, "DevX is NOT supported");
2876                 err = 0;
2877         }
2878         if (!err && sh->ctx) {
2879                 /* Hint libmlx5 to use PMD allocator for data plane resources */
2880                 mlx5_glue->dv_set_context_attr(sh->ctx,
2881                         MLX5DV_CTX_ATTR_BUF_ALLOCATORS,
2882                         (void *)((uintptr_t)&(struct mlx5dv_ctx_allocators){
2883                                 .alloc = &mlx5_alloc_verbs_buf,
2884                                 .free = &mlx5_free_verbs_buf,
2885                                 .data = sh,
2886                         }));
2887         }
2888         return err;
2889 }
2890
2891 /**
2892  * Install shared asynchronous device events handler.
2893  * This function is implemented to support event sharing
2894  * between multiple ports of single IB device.
2895  *
2896  * @param sh
2897  *   Pointer to mlx5_dev_ctx_shared object.
2898  */
2899 void
2900 mlx5_os_dev_shared_handler_install(struct mlx5_dev_ctx_shared *sh)
2901 {
2902         int ret;
2903         int flags;
2904
2905         sh->intr_handle.fd = -1;
2906         flags = fcntl(((struct ibv_context *)sh->ctx)->async_fd, F_GETFL);
2907         ret = fcntl(((struct ibv_context *)sh->ctx)->async_fd,
2908                     F_SETFL, flags | O_NONBLOCK);
2909         if (ret) {
2910                 DRV_LOG(INFO, "failed to change file descriptor async event"
2911                         " queue");
2912         } else {
2913                 sh->intr_handle.fd = ((struct ibv_context *)sh->ctx)->async_fd;
2914                 sh->intr_handle.type = RTE_INTR_HANDLE_EXT;
2915                 if (rte_intr_callback_register(&sh->intr_handle,
2916                                         mlx5_dev_interrupt_handler, sh)) {
2917                         DRV_LOG(INFO, "Fail to install the shared interrupt.");
2918                         sh->intr_handle.fd = -1;
2919                 }
2920         }
2921         if (sh->devx) {
2922 #ifdef HAVE_IBV_DEVX_ASYNC
2923                 sh->intr_handle_devx.fd = -1;
2924                 sh->devx_comp =
2925                         (void *)mlx5_glue->devx_create_cmd_comp(sh->ctx);
2926                 struct mlx5dv_devx_cmd_comp *devx_comp = sh->devx_comp;
2927                 if (!devx_comp) {
2928                         DRV_LOG(INFO, "failed to allocate devx_comp.");
2929                         return;
2930                 }
2931                 flags = fcntl(devx_comp->fd, F_GETFL);
2932                 ret = fcntl(devx_comp->fd, F_SETFL, flags | O_NONBLOCK);
2933                 if (ret) {
2934                         DRV_LOG(INFO, "failed to change file descriptor"
2935                                 " devx comp");
2936                         return;
2937                 }
2938                 sh->intr_handle_devx.fd = devx_comp->fd;
2939                 sh->intr_handle_devx.type = RTE_INTR_HANDLE_EXT;
2940                 if (rte_intr_callback_register(&sh->intr_handle_devx,
2941                                         mlx5_dev_interrupt_handler_devx, sh)) {
2942                         DRV_LOG(INFO, "Fail to install the devx shared"
2943                                 " interrupt.");
2944                         sh->intr_handle_devx.fd = -1;
2945                 }
2946 #endif /* HAVE_IBV_DEVX_ASYNC */
2947         }
2948 }
2949
2950 /**
2951  * Uninstall shared asynchronous device events handler.
2952  * This function is implemented to support event sharing
2953  * between multiple ports of single IB device.
2954  *
2955  * @param dev
2956  *   Pointer to mlx5_dev_ctx_shared object.
2957  */
2958 void
2959 mlx5_os_dev_shared_handler_uninstall(struct mlx5_dev_ctx_shared *sh)
2960 {
2961         if (sh->intr_handle.fd >= 0)
2962                 mlx5_intr_callback_unregister(&sh->intr_handle,
2963                                               mlx5_dev_interrupt_handler, sh);
2964 #ifdef HAVE_IBV_DEVX_ASYNC
2965         if (sh->intr_handle_devx.fd >= 0)
2966                 rte_intr_callback_unregister(&sh->intr_handle_devx,
2967                                   mlx5_dev_interrupt_handler_devx, sh);
2968         if (sh->devx_comp)
2969                 mlx5_glue->devx_destroy_cmd_comp(sh->devx_comp);
2970 #endif
2971 }
2972
2973 /**
2974  * Read statistics by a named counter.
2975  *
2976  * @param[in] priv
2977  *   Pointer to the private device data structure.
2978  * @param[in] ctr_name
2979  *   Pointer to the name of the statistic counter to read
2980  * @param[out] stat
2981  *   Pointer to read statistic value.
2982  * @return
2983  *   0 on success and stat is valud, 1 if failed to read the value
2984  *   rte_errno is set.
2985  *
2986  */
2987 int
2988 mlx5_os_read_dev_stat(struct mlx5_priv *priv, const char *ctr_name,
2989                       uint64_t *stat)
2990 {
2991         int fd;
2992
2993         if (priv->sh) {
2994                 if (priv->q_counters != NULL &&
2995                     strcmp(ctr_name, "out_of_buffer") == 0)
2996                         return mlx5_devx_cmd_queue_counter_query
2997                                         (priv->q_counters, 0, (uint32_t *)stat);
2998                 MKSTR(path, "%s/ports/%d/hw_counters/%s",
2999                       priv->sh->ibdev_path,
3000                       priv->dev_port,
3001                       ctr_name);
3002                 fd = open(path, O_RDONLY);
3003                 /*
3004                  * in switchdev the file location is not per port
3005                  * but rather in <ibdev_path>/hw_counters/<file_name>.
3006                  */
3007                 if (fd == -1) {
3008                         MKSTR(path1, "%s/hw_counters/%s",
3009                               priv->sh->ibdev_path,
3010                               ctr_name);
3011                         fd = open(path1, O_RDONLY);
3012                 }
3013                 if (fd != -1) {
3014                         char buf[21] = {'\0'};
3015                         ssize_t n = read(fd, buf, sizeof(buf));
3016
3017                         close(fd);
3018                         if (n != -1) {
3019                                 *stat = strtoull(buf, NULL, 10);
3020                                 return 0;
3021                         }
3022                 }
3023         }
3024         *stat = 0;
3025         return 1;
3026 }
3027
3028 /**
3029  * Set the reg_mr and dereg_mr call backs
3030  *
3031  * @param reg_mr_cb[out]
3032  *   Pointer to reg_mr func
3033  * @param dereg_mr_cb[out]
3034  *   Pointer to dereg_mr func
3035  *
3036  */
3037 void
3038 mlx5_os_set_reg_mr_cb(mlx5_reg_mr_t *reg_mr_cb,
3039                       mlx5_dereg_mr_t *dereg_mr_cb)
3040 {
3041         *reg_mr_cb = mlx5_mr_verbs_ops.reg_mr;
3042         *dereg_mr_cb = mlx5_mr_verbs_ops.dereg_mr;
3043 }
3044
3045 /**
3046  * Remove a MAC address from device
3047  *
3048  * @param dev
3049  *   Pointer to Ethernet device structure.
3050  * @param index
3051  *   MAC address index.
3052  */
3053 void
3054 mlx5_os_mac_addr_remove(struct rte_eth_dev *dev, uint32_t index)
3055 {
3056         struct mlx5_priv *priv = dev->data->dev_private;
3057         const int vf = priv->config.vf;
3058
3059         if (vf)
3060                 mlx5_nl_mac_addr_remove(priv->nl_socket_route,
3061                                         mlx5_ifindex(dev), priv->mac_own,
3062                                         &dev->data->mac_addrs[index], index);
3063 }
3064
3065 /**
3066  * Adds a MAC address to the device
3067  *
3068  * @param dev
3069  *   Pointer to Ethernet device structure.
3070  * @param mac_addr
3071  *   MAC address to register.
3072  * @param index
3073  *   MAC address index.
3074  *
3075  * @return
3076  *   0 on success, a negative errno value otherwise
3077  */
3078 int
3079 mlx5_os_mac_addr_add(struct rte_eth_dev *dev, struct rte_ether_addr *mac,
3080                      uint32_t index)
3081 {
3082         struct mlx5_priv *priv = dev->data->dev_private;
3083         const int vf = priv->config.vf;
3084         int ret = 0;
3085
3086         if (vf)
3087                 ret = mlx5_nl_mac_addr_add(priv->nl_socket_route,
3088                                            mlx5_ifindex(dev), priv->mac_own,
3089                                            mac, index);
3090         return ret;
3091 }
3092
3093 /**
3094  * Modify a VF MAC address
3095  *
3096  * @param priv
3097  *   Pointer to device private data.
3098  * @param mac_addr
3099  *   MAC address to modify into.
3100  * @param iface_idx
3101  *   Net device interface index
3102  * @param vf_index
3103  *   VF index
3104  *
3105  * @return
3106  *   0 on success, a negative errno value otherwise
3107  */
3108 int
3109 mlx5_os_vf_mac_addr_modify(struct mlx5_priv *priv,
3110                            unsigned int iface_idx,
3111                            struct rte_ether_addr *mac_addr,
3112                            int vf_index)
3113 {
3114         return mlx5_nl_vf_mac_addr_modify
3115                 (priv->nl_socket_route, iface_idx, mac_addr, vf_index);
3116 }
3117
3118 /**
3119  * Set device promiscuous mode
3120  *
3121  * @param dev
3122  *   Pointer to Ethernet device structure.
3123  * @param enable
3124  *   0 - promiscuous is disabled, otherwise - enabled
3125  *
3126  * @return
3127  *   0 on success, a negative error value otherwise
3128  */
3129 int
3130 mlx5_os_set_promisc(struct rte_eth_dev *dev, int enable)
3131 {
3132         struct mlx5_priv *priv = dev->data->dev_private;
3133
3134         return mlx5_nl_promisc(priv->nl_socket_route,
3135                                mlx5_ifindex(dev), !!enable);
3136 }
3137
3138 /**
3139  * Set device promiscuous mode
3140  *
3141  * @param dev
3142  *   Pointer to Ethernet device structure.
3143  * @param enable
3144  *   0 - all multicase is disabled, otherwise - enabled
3145  *
3146  * @return
3147  *   0 on success, a negative error value otherwise
3148  */
3149 int
3150 mlx5_os_set_allmulti(struct rte_eth_dev *dev, int enable)
3151 {
3152         struct mlx5_priv *priv = dev->data->dev_private;
3153
3154         return mlx5_nl_allmulti(priv->nl_socket_route,
3155                                 mlx5_ifindex(dev), !!enable);
3156 }
3157
3158 /**
3159  * Flush device MAC addresses
3160  *
3161  * @param dev
3162  *   Pointer to Ethernet device structure.
3163  *
3164  */
3165 void
3166 mlx5_os_mac_addr_flush(struct rte_eth_dev *dev)
3167 {
3168         struct mlx5_priv *priv = dev->data->dev_private;
3169
3170         mlx5_nl_mac_addr_flush(priv->nl_socket_route, mlx5_ifindex(dev),
3171                                dev->data->mac_addrs,
3172                                MLX5_MAX_MAC_ADDRESSES, priv->mac_own);
3173 }