common/mlx5: share memory related devargs
[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 /**
790  * DR flow drop action support detect.
791  *
792  * @param dev
793  *   Pointer to rte_eth_dev structure.
794  *
795  */
796 static void
797 mlx5_flow_drop_action_config(struct rte_eth_dev *dev __rte_unused)
798 {
799 #ifdef HAVE_MLX5DV_DR
800         struct mlx5_priv *priv = dev->data->dev_private;
801
802         if (!priv->config.dv_flow_en || !priv->sh->dr_drop_action)
803                 return;
804         /**
805          * DR supports drop action placeholder when it is supported;
806          * otherwise, use the queue drop action.
807          */
808         if (mlx5_flow_discover_dr_action_support(dev))
809                 priv->root_drop_action = priv->drop_queue.hrxq->action;
810         else
811                 priv->root_drop_action = priv->sh->dr_drop_action;
812 #endif
813 }
814
815 static void
816 mlx5_queue_counter_id_prepare(struct rte_eth_dev *dev)
817 {
818         struct mlx5_priv *priv = dev->data->dev_private;
819         void *ctx = priv->sh->ctx;
820
821         priv->q_counters = mlx5_devx_cmd_queue_counter_alloc(ctx);
822         if (!priv->q_counters) {
823                 struct ibv_cq *cq = mlx5_glue->create_cq(ctx, 1, NULL, NULL, 0);
824                 struct ibv_wq *wq;
825
826                 DRV_LOG(DEBUG, "Port %d queue counter object cannot be created "
827                         "by DevX - fall-back to use the kernel driver global "
828                         "queue counter.", dev->data->port_id);
829                 /* Create WQ by kernel and query its queue counter ID. */
830                 if (cq) {
831                         wq = mlx5_glue->create_wq(ctx,
832                                                   &(struct ibv_wq_init_attr){
833                                                     .wq_type = IBV_WQT_RQ,
834                                                     .max_wr = 1,
835                                                     .max_sge = 1,
836                                                     .pd = priv->sh->pd,
837                                                     .cq = cq,
838                                                 });
839                         if (wq) {
840                                 /* Counter is assigned only on RDY state. */
841                                 int ret = mlx5_glue->modify_wq(wq,
842                                                  &(struct ibv_wq_attr){
843                                                  .attr_mask = IBV_WQ_ATTR_STATE,
844                                                  .wq_state = IBV_WQS_RDY,
845                                                 });
846
847                                 if (ret == 0)
848                                         mlx5_devx_cmd_wq_query(wq,
849                                                          &priv->counter_set_id);
850                                 claim_zero(mlx5_glue->destroy_wq(wq));
851                         }
852                         claim_zero(mlx5_glue->destroy_cq(cq));
853                 }
854         } else {
855                 priv->counter_set_id = priv->q_counters->id;
856         }
857         if (priv->counter_set_id == 0)
858                 DRV_LOG(INFO, "Part of the port %d statistics will not be "
859                         "available.", dev->data->port_id);
860 }
861
862 /**
863  * Check if representor spawn info match devargs.
864  *
865  * @param spawn
866  *   Verbs device parameters (name, port, switch_info) to spawn.
867  * @param eth_da
868  *   Device devargs to probe.
869  *
870  * @return
871  *   Match result.
872  */
873 static bool
874 mlx5_representor_match(struct mlx5_dev_spawn_data *spawn,
875                        struct rte_eth_devargs *eth_da)
876 {
877         struct mlx5_switch_info *switch_info = &spawn->info;
878         unsigned int p, f;
879         uint16_t id;
880         uint16_t repr_id = mlx5_representor_id_encode(switch_info,
881                                                       eth_da->type);
882
883         switch (eth_da->type) {
884         case RTE_ETH_REPRESENTOR_SF:
885                 if (!(spawn->info.port_name == -1 &&
886                       switch_info->name_type ==
887                                 MLX5_PHYS_PORT_NAME_TYPE_PFHPF) &&
888                     switch_info->name_type != MLX5_PHYS_PORT_NAME_TYPE_PFSF) {
889                         rte_errno = EBUSY;
890                         return false;
891                 }
892                 break;
893         case RTE_ETH_REPRESENTOR_VF:
894                 /* Allows HPF representor index -1 as exception. */
895                 if (!(spawn->info.port_name == -1 &&
896                       switch_info->name_type ==
897                                 MLX5_PHYS_PORT_NAME_TYPE_PFHPF) &&
898                     switch_info->name_type != MLX5_PHYS_PORT_NAME_TYPE_PFVF) {
899                         rte_errno = EBUSY;
900                         return false;
901                 }
902                 break;
903         case RTE_ETH_REPRESENTOR_NONE:
904                 rte_errno = EBUSY;
905                 return false;
906         default:
907                 rte_errno = ENOTSUP;
908                 DRV_LOG(ERR, "unsupported representor type");
909                 return false;
910         }
911         /* Check representor ID: */
912         for (p = 0; p < eth_da->nb_ports; ++p) {
913                 if (spawn->pf_bond < 0) {
914                         /* For non-LAG mode, allow and ignore pf. */
915                         switch_info->pf_num = eth_da->ports[p];
916                         repr_id = mlx5_representor_id_encode(switch_info,
917                                                              eth_da->type);
918                 }
919                 for (f = 0; f < eth_da->nb_representor_ports; ++f) {
920                         id = MLX5_REPRESENTOR_ID
921                                 (eth_da->ports[p], eth_da->type,
922                                  eth_da->representor_ports[f]);
923                         if (repr_id == id)
924                                 return true;
925                 }
926         }
927         rte_errno = EBUSY;
928         return false;
929 }
930
931
932 /**
933  * Spawn an Ethernet device from Verbs information.
934  *
935  * @param dpdk_dev
936  *   Backing DPDK device.
937  * @param spawn
938  *   Verbs device parameters (name, port, switch_info) to spawn.
939  * @param config
940  *   Device configuration parameters.
941  * @param config
942  *   Device arguments.
943  *
944  * @return
945  *   A valid Ethernet device object on success, NULL otherwise and rte_errno
946  *   is set. The following errors are defined:
947  *
948  *   EBUSY: device is not supposed to be spawned.
949  *   EEXIST: device is already spawned
950  */
951 static struct rte_eth_dev *
952 mlx5_dev_spawn(struct rte_device *dpdk_dev,
953                struct mlx5_dev_spawn_data *spawn,
954                struct mlx5_dev_config *config,
955                struct rte_eth_devargs *eth_da)
956 {
957         const struct mlx5_switch_info *switch_info = &spawn->info;
958         struct mlx5_dev_ctx_shared *sh = NULL;
959         struct ibv_port_attr port_attr;
960         struct mlx5dv_context dv_attr = { .comp_mask = 0 };
961         struct rte_eth_dev *eth_dev = NULL;
962         struct mlx5_priv *priv = NULL;
963         int err = 0;
964         unsigned int hw_padding = 0;
965         unsigned int mps;
966         unsigned int mpls_en = 0;
967         unsigned int swp = 0;
968         unsigned int mprq = 0;
969         unsigned int mprq_min_stride_size_n = 0;
970         unsigned int mprq_max_stride_size_n = 0;
971         unsigned int mprq_min_stride_num_n = 0;
972         unsigned int mprq_max_stride_num_n = 0;
973         struct rte_ether_addr mac;
974         char name[RTE_ETH_NAME_MAX_LEN];
975         int own_domain_id = 0;
976         uint16_t port_id;
977         struct mlx5_port_info vport_info = { .query_flags = 0 };
978         int i;
979
980         /* Determine if this port representor is supposed to be spawned. */
981         if (switch_info->representor && dpdk_dev->devargs &&
982             !mlx5_representor_match(spawn, eth_da))
983                 return NULL;
984         /* Build device name. */
985         if (spawn->pf_bond < 0) {
986                 /* Single device. */
987                 if (!switch_info->representor)
988                         strlcpy(name, dpdk_dev->name, sizeof(name));
989                 else
990                         err = snprintf(name, sizeof(name), "%s_representor_%s%u",
991                                  dpdk_dev->name,
992                                  switch_info->name_type ==
993                                  MLX5_PHYS_PORT_NAME_TYPE_PFSF ? "sf" : "vf",
994                                  switch_info->port_name);
995         } else {
996                 /* Bonding device. */
997                 if (!switch_info->representor) {
998                         err = snprintf(name, sizeof(name), "%s_%s",
999                                  dpdk_dev->name,
1000                                  mlx5_os_get_dev_device_name(spawn->phys_dev));
1001                 } else {
1002                         err = snprintf(name, sizeof(name), "%s_%s_representor_c%dpf%d%s%u",
1003                                 dpdk_dev->name,
1004                                 mlx5_os_get_dev_device_name(spawn->phys_dev),
1005                                 switch_info->ctrl_num,
1006                                 switch_info->pf_num,
1007                                 switch_info->name_type ==
1008                                 MLX5_PHYS_PORT_NAME_TYPE_PFSF ? "sf" : "vf",
1009                                 switch_info->port_name);
1010                 }
1011         }
1012         if (err >= (int)sizeof(name))
1013                 DRV_LOG(WARNING, "device name overflow %s", name);
1014         /* check if the device is already spawned */
1015         if (rte_eth_dev_get_port_by_name(name, &port_id) == 0) {
1016                 rte_errno = EEXIST;
1017                 return NULL;
1018         }
1019         DRV_LOG(DEBUG, "naming Ethernet device \"%s\"", name);
1020         if (rte_eal_process_type() == RTE_PROC_SECONDARY) {
1021                 struct mlx5_mp_id mp_id;
1022
1023                 eth_dev = rte_eth_dev_attach_secondary(name);
1024                 if (eth_dev == NULL) {
1025                         DRV_LOG(ERR, "can not attach rte ethdev");
1026                         rte_errno = ENOMEM;
1027                         return NULL;
1028                 }
1029                 eth_dev->device = dpdk_dev;
1030                 eth_dev->dev_ops = &mlx5_dev_sec_ops;
1031                 eth_dev->rx_descriptor_status = mlx5_rx_descriptor_status;
1032                 eth_dev->tx_descriptor_status = mlx5_tx_descriptor_status;
1033                 err = mlx5_proc_priv_init(eth_dev);
1034                 if (err)
1035                         return NULL;
1036                 mlx5_mp_id_init(&mp_id, eth_dev->data->port_id);
1037                 /* Receive command fd from primary process */
1038                 err = mlx5_mp_req_verbs_cmd_fd(&mp_id);
1039                 if (err < 0)
1040                         goto err_secondary;
1041                 /* Remap UAR for Tx queues. */
1042                 err = mlx5_tx_uar_init_secondary(eth_dev, err);
1043                 if (err)
1044                         goto err_secondary;
1045                 /*
1046                  * Ethdev pointer is still required as input since
1047                  * the primary device is not accessible from the
1048                  * secondary process.
1049                  */
1050                 eth_dev->rx_pkt_burst = mlx5_select_rx_function(eth_dev);
1051                 eth_dev->tx_pkt_burst = mlx5_select_tx_function(eth_dev);
1052                 return eth_dev;
1053 err_secondary:
1054                 mlx5_dev_close(eth_dev);
1055                 return NULL;
1056         }
1057         /*
1058          * Some parameters ("tx_db_nc" in particularly) are needed in
1059          * advance to create dv/verbs device context. We proceed the
1060          * devargs here to get ones, and later proceed devargs again
1061          * to override some hardware settings.
1062          */
1063         err = mlx5_args(config, dpdk_dev->devargs);
1064         if (err) {
1065                 err = rte_errno;
1066                 DRV_LOG(ERR, "failed to process device arguments: %s",
1067                         strerror(rte_errno));
1068                 goto error;
1069         }
1070         if (config->dv_miss_info) {
1071                 if (switch_info->master || switch_info->representor)
1072                         config->dv_xmeta_en = MLX5_XMETA_MODE_META16;
1073         }
1074         sh = mlx5_alloc_shared_dev_ctx(spawn, config);
1075         if (!sh)
1076                 return NULL;
1077         config->devx = sh->devx;
1078 #ifdef HAVE_MLX5DV_DR_ACTION_DEST_DEVX_TIR
1079         config->dest_tir = 1;
1080 #endif
1081 #ifdef HAVE_IBV_MLX5_MOD_SWP
1082         dv_attr.comp_mask |= MLX5DV_CONTEXT_MASK_SWP;
1083 #endif
1084         /*
1085          * Multi-packet send is supported by ConnectX-4 Lx PF as well
1086          * as all ConnectX-5 devices.
1087          */
1088 #ifdef HAVE_IBV_DEVICE_TUNNEL_SUPPORT
1089         dv_attr.comp_mask |= MLX5DV_CONTEXT_MASK_TUNNEL_OFFLOADS;
1090 #endif
1091 #ifdef HAVE_IBV_DEVICE_STRIDING_RQ_SUPPORT
1092         dv_attr.comp_mask |= MLX5DV_CONTEXT_MASK_STRIDING_RQ;
1093 #endif
1094         mlx5_glue->dv_query_device(sh->ctx, &dv_attr);
1095         if (dv_attr.flags & MLX5DV_CONTEXT_FLAGS_MPW_ALLOWED) {
1096                 if (dv_attr.flags & MLX5DV_CONTEXT_FLAGS_ENHANCED_MPW) {
1097                         DRV_LOG(DEBUG, "enhanced MPW is supported");
1098                         mps = MLX5_MPW_ENHANCED;
1099                 } else {
1100                         DRV_LOG(DEBUG, "MPW is supported");
1101                         mps = MLX5_MPW;
1102                 }
1103         } else {
1104                 DRV_LOG(DEBUG, "MPW isn't supported");
1105                 mps = MLX5_MPW_DISABLED;
1106         }
1107 #ifdef HAVE_IBV_MLX5_MOD_SWP
1108         if (dv_attr.comp_mask & MLX5DV_CONTEXT_MASK_SWP)
1109                 swp = dv_attr.sw_parsing_caps.sw_parsing_offloads;
1110         DRV_LOG(DEBUG, "SWP support: %u", swp);
1111 #endif
1112         config->swp = swp & (MLX5_SW_PARSING_CAP | MLX5_SW_PARSING_CSUM_CAP |
1113                 MLX5_SW_PARSING_TSO_CAP);
1114 #ifdef HAVE_IBV_DEVICE_STRIDING_RQ_SUPPORT
1115         if (dv_attr.comp_mask & MLX5DV_CONTEXT_MASK_STRIDING_RQ) {
1116                 struct mlx5dv_striding_rq_caps mprq_caps =
1117                         dv_attr.striding_rq_caps;
1118
1119                 DRV_LOG(DEBUG, "\tmin_single_stride_log_num_of_bytes: %d",
1120                         mprq_caps.min_single_stride_log_num_of_bytes);
1121                 DRV_LOG(DEBUG, "\tmax_single_stride_log_num_of_bytes: %d",
1122                         mprq_caps.max_single_stride_log_num_of_bytes);
1123                 DRV_LOG(DEBUG, "\tmin_single_wqe_log_num_of_strides: %d",
1124                         mprq_caps.min_single_wqe_log_num_of_strides);
1125                 DRV_LOG(DEBUG, "\tmax_single_wqe_log_num_of_strides: %d",
1126                         mprq_caps.max_single_wqe_log_num_of_strides);
1127                 DRV_LOG(DEBUG, "\tsupported_qpts: %d",
1128                         mprq_caps.supported_qpts);
1129                 DRV_LOG(DEBUG, "device supports Multi-Packet RQ");
1130                 mprq = 1;
1131                 mprq_min_stride_size_n =
1132                         mprq_caps.min_single_stride_log_num_of_bytes;
1133                 mprq_max_stride_size_n =
1134                         mprq_caps.max_single_stride_log_num_of_bytes;
1135                 mprq_min_stride_num_n =
1136                         mprq_caps.min_single_wqe_log_num_of_strides;
1137                 mprq_max_stride_num_n =
1138                         mprq_caps.max_single_wqe_log_num_of_strides;
1139         }
1140 #endif
1141         /* Rx CQE compression is enabled by default. */
1142         config->cqe_comp = 1;
1143 #ifdef HAVE_IBV_DEVICE_TUNNEL_SUPPORT
1144         if (dv_attr.comp_mask & MLX5DV_CONTEXT_MASK_TUNNEL_OFFLOADS) {
1145                 config->tunnel_en = dv_attr.tunnel_offloads_caps &
1146                              (MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_VXLAN |
1147                               MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_GRE |
1148                               MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_GENEVE);
1149         }
1150         if (config->tunnel_en) {
1151                 DRV_LOG(DEBUG, "tunnel offloading is supported for %s%s%s",
1152                 config->tunnel_en &
1153                 MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_VXLAN ? "[VXLAN]" : "",
1154                 config->tunnel_en &
1155                 MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_GRE ? "[GRE]" : "",
1156                 config->tunnel_en &
1157                 MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_GENEVE ? "[GENEVE]" : ""
1158                 );
1159         } else {
1160                 DRV_LOG(DEBUG, "tunnel offloading is not supported");
1161         }
1162 #else
1163         DRV_LOG(WARNING,
1164                 "tunnel offloading disabled due to old OFED/rdma-core version");
1165 #endif
1166 #ifdef HAVE_IBV_DEVICE_MPLS_SUPPORT
1167         mpls_en = ((dv_attr.tunnel_offloads_caps &
1168                     MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_CW_MPLS_OVER_GRE) &&
1169                    (dv_attr.tunnel_offloads_caps &
1170                     MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_CW_MPLS_OVER_UDP));
1171         DRV_LOG(DEBUG, "MPLS over GRE/UDP tunnel offloading is %ssupported",
1172                 mpls_en ? "" : "not ");
1173 #else
1174         DRV_LOG(WARNING, "MPLS over GRE/UDP tunnel offloading disabled due to"
1175                 " old OFED/rdma-core version or firmware configuration");
1176 #endif
1177         config->mpls_en = mpls_en;
1178         /* Check port status. */
1179         err = mlx5_glue->query_port(sh->ctx, spawn->phys_port, &port_attr);
1180         if (err) {
1181                 DRV_LOG(ERR, "port query failed: %s", strerror(err));
1182                 goto error;
1183         }
1184         if (port_attr.link_layer != IBV_LINK_LAYER_ETHERNET) {
1185                 DRV_LOG(ERR, "port is not configured in Ethernet mode");
1186                 err = EINVAL;
1187                 goto error;
1188         }
1189         if (port_attr.state != IBV_PORT_ACTIVE)
1190                 DRV_LOG(DEBUG, "port is not active: \"%s\" (%d)",
1191                         mlx5_glue->port_state_str(port_attr.state),
1192                         port_attr.state);
1193         /* Allocate private eth device data. */
1194         priv = mlx5_malloc(MLX5_MEM_ZERO | MLX5_MEM_RTE,
1195                            sizeof(*priv),
1196                            RTE_CACHE_LINE_SIZE, SOCKET_ID_ANY);
1197         if (priv == NULL) {
1198                 DRV_LOG(ERR, "priv allocation failure");
1199                 err = ENOMEM;
1200                 goto error;
1201         }
1202         priv->sh = sh;
1203         priv->dev_port = spawn->phys_port;
1204         priv->pci_dev = spawn->pci_dev;
1205         priv->mtu = RTE_ETHER_MTU;
1206         /* Some internal functions rely on Netlink sockets, open them now. */
1207         priv->nl_socket_rdma = mlx5_nl_init(NETLINK_RDMA);
1208         priv->nl_socket_route = mlx5_nl_init(NETLINK_ROUTE);
1209         priv->representor = !!switch_info->representor;
1210         priv->master = !!switch_info->master;
1211         priv->domain_id = RTE_ETH_DEV_SWITCH_DOMAIN_ID_INVALID;
1212         priv->vport_meta_tag = 0;
1213         priv->vport_meta_mask = 0;
1214         priv->pf_bond = spawn->pf_bond;
1215
1216         DRV_LOG(DEBUG,
1217                 "dev_port=%u bus=%s pci=%s master=%d representor=%d pf_bond=%d\n",
1218                 priv->dev_port, dpdk_dev->bus->name,
1219                 priv->pci_dev ? priv->pci_dev->name : "NONE",
1220                 priv->master, priv->representor, priv->pf_bond);
1221
1222         /*
1223          * If we have E-Switch we should determine the vport attributes.
1224          * E-Switch may use either source vport field or reg_c[0] metadata
1225          * register to match on vport index. The engaged part of metadata
1226          * register is defined by mask.
1227          */
1228         if (switch_info->representor || switch_info->master) {
1229                 err = mlx5_glue->devx_port_query(sh->ctx,
1230                                                  spawn->phys_port,
1231                                                  &vport_info);
1232                 if (err) {
1233                         DRV_LOG(WARNING,
1234                                 "can't query devx port %d on device %s",
1235                                 spawn->phys_port,
1236                                 mlx5_os_get_dev_device_name(spawn->phys_dev));
1237                         vport_info.query_flags = 0;
1238                 }
1239         }
1240         if (vport_info.query_flags & MLX5_PORT_QUERY_REG_C0) {
1241                 priv->vport_meta_tag = vport_info.vport_meta_tag;
1242                 priv->vport_meta_mask = vport_info.vport_meta_mask;
1243                 if (!priv->vport_meta_mask) {
1244                         DRV_LOG(ERR, "vport zero mask for port %d"
1245                                      " on bonding device %s",
1246                                      spawn->phys_port,
1247                                      mlx5_os_get_dev_device_name
1248                                                         (spawn->phys_dev));
1249                         err = ENOTSUP;
1250                         goto error;
1251                 }
1252                 if (priv->vport_meta_tag & ~priv->vport_meta_mask) {
1253                         DRV_LOG(ERR, "invalid vport tag for port %d"
1254                                      " on bonding device %s",
1255                                      spawn->phys_port,
1256                                      mlx5_os_get_dev_device_name
1257                                                         (spawn->phys_dev));
1258                         err = ENOTSUP;
1259                         goto error;
1260                 }
1261         }
1262         if (vport_info.query_flags & MLX5_PORT_QUERY_VPORT) {
1263                 priv->vport_id = vport_info.vport_id;
1264         } else if (spawn->pf_bond >= 0 &&
1265                    (switch_info->representor || switch_info->master)) {
1266                 DRV_LOG(ERR, "can't deduce vport index for port %d"
1267                              " on bonding device %s",
1268                              spawn->phys_port,
1269                              mlx5_os_get_dev_device_name(spawn->phys_dev));
1270                 err = ENOTSUP;
1271                 goto error;
1272         } else {
1273                 /*
1274                  * Suppose vport index in compatible way. Kernel/rdma_core
1275                  * support single E-Switch per PF configurations only and
1276                  * vport_id field contains the vport index for associated VF,
1277                  * which is deduced from representor port name.
1278                  * For example, let's have the IB device port 10, it has
1279                  * attached network device eth0, which has port name attribute
1280                  * pf0vf2, we can deduce the VF number as 2, and set vport index
1281                  * as 3 (2+1). This assigning schema should be changed if the
1282                  * multiple E-Switch instances per PF configurations or/and PCI
1283                  * subfunctions are added.
1284                  */
1285                 priv->vport_id = switch_info->representor ?
1286                                  switch_info->port_name + 1 : -1;
1287         }
1288         priv->representor_id = mlx5_representor_id_encode(switch_info,
1289                                                           eth_da->type);
1290         /*
1291          * Look for sibling devices in order to reuse their switch domain
1292          * if any, otherwise allocate one.
1293          */
1294         MLX5_ETH_FOREACH_DEV(port_id, dpdk_dev) {
1295                 const struct mlx5_priv *opriv =
1296                         rte_eth_devices[port_id].data->dev_private;
1297
1298                 if (!opriv ||
1299                     opriv->sh != priv->sh ||
1300                         opriv->domain_id ==
1301                         RTE_ETH_DEV_SWITCH_DOMAIN_ID_INVALID)
1302                         continue;
1303                 priv->domain_id = opriv->domain_id;
1304                 DRV_LOG(DEBUG, "dev_port-%u inherit domain_id=%u\n",
1305                         priv->dev_port, priv->domain_id);
1306                 break;
1307         }
1308         if (priv->domain_id == RTE_ETH_DEV_SWITCH_DOMAIN_ID_INVALID) {
1309                 err = rte_eth_switch_domain_alloc(&priv->domain_id);
1310                 if (err) {
1311                         err = rte_errno;
1312                         DRV_LOG(ERR, "unable to allocate switch domain: %s",
1313                                 strerror(rte_errno));
1314                         goto error;
1315                 }
1316                 own_domain_id = 1;
1317                 DRV_LOG(DEBUG, "dev_port-%u new domain_id=%u\n",
1318                         priv->dev_port, priv->domain_id);
1319         }
1320         /* Override some values set by hardware configuration. */
1321         mlx5_args(config, dpdk_dev->devargs);
1322         err = mlx5_dev_check_sibling_config(priv, config, dpdk_dev);
1323         if (err)
1324                 goto error;
1325         config->hw_csum = !!(sh->device_attr.device_cap_flags_ex &
1326                             IBV_DEVICE_RAW_IP_CSUM);
1327         DRV_LOG(DEBUG, "checksum offloading is %ssupported",
1328                 (config->hw_csum ? "" : "not "));
1329 #if !defined(HAVE_IBV_DEVICE_COUNTERS_SET_V42) && \
1330         !defined(HAVE_IBV_DEVICE_COUNTERS_SET_V45)
1331         DRV_LOG(DEBUG, "counters are not supported");
1332 #endif
1333 #if !defined(HAVE_IBV_FLOW_DV_SUPPORT) || !defined(HAVE_MLX5DV_DR)
1334         if (config->dv_flow_en) {
1335                 DRV_LOG(WARNING, "DV flow is not supported");
1336                 config->dv_flow_en = 0;
1337         }
1338 #endif
1339         if (spawn->max_port > UINT8_MAX) {
1340                 /* Verbs can't support ports larger than 255 by design. */
1341                 DRV_LOG(ERR, "can't support IB ports > UINT8_MAX");
1342                 err = EINVAL;
1343                 goto error;
1344         }
1345         config->ind_table_max_size =
1346                 sh->device_attr.max_rwq_indirection_table_size;
1347         /*
1348          * Remove this check once DPDK supports larger/variable
1349          * indirection tables.
1350          */
1351         if (config->ind_table_max_size > (unsigned int)ETH_RSS_RETA_SIZE_512)
1352                 config->ind_table_max_size = ETH_RSS_RETA_SIZE_512;
1353         DRV_LOG(DEBUG, "maximum Rx indirection table size is %u",
1354                 config->ind_table_max_size);
1355         config->hw_vlan_strip = !!(sh->device_attr.raw_packet_caps &
1356                                   IBV_RAW_PACKET_CAP_CVLAN_STRIPPING);
1357         DRV_LOG(DEBUG, "VLAN stripping is %ssupported",
1358                 (config->hw_vlan_strip ? "" : "not "));
1359         config->hw_fcs_strip = !!(sh->device_attr.raw_packet_caps &
1360                                  IBV_RAW_PACKET_CAP_SCATTER_FCS);
1361 #if defined(HAVE_IBV_WQ_FLAG_RX_END_PADDING)
1362         hw_padding = !!sh->device_attr.rx_pad_end_addr_align;
1363 #elif defined(HAVE_IBV_WQ_FLAGS_PCI_WRITE_END_PADDING)
1364         hw_padding = !!(sh->device_attr.device_cap_flags_ex &
1365                         IBV_DEVICE_PCI_WRITE_END_PADDING);
1366 #endif
1367         if (config->hw_padding && !hw_padding) {
1368                 DRV_LOG(DEBUG, "Rx end alignment padding isn't supported");
1369                 config->hw_padding = 0;
1370         } else if (config->hw_padding) {
1371                 DRV_LOG(DEBUG, "Rx end alignment padding is enabled");
1372         }
1373         config->tso = (sh->device_attr.max_tso > 0 &&
1374                       (sh->device_attr.tso_supported_qpts &
1375                        (1 << IBV_QPT_RAW_PACKET)));
1376         if (config->tso)
1377                 config->tso_max_payload_sz = sh->device_attr.max_tso;
1378         /*
1379          * MPW is disabled by default, while the Enhanced MPW is enabled
1380          * by default.
1381          */
1382         if (config->mps == MLX5_ARG_UNSET)
1383                 config->mps = (mps == MLX5_MPW_ENHANCED) ? MLX5_MPW_ENHANCED :
1384                                                           MLX5_MPW_DISABLED;
1385         else
1386                 config->mps = config->mps ? mps : MLX5_MPW_DISABLED;
1387         DRV_LOG(INFO, "%sMPS is %s",
1388                 config->mps == MLX5_MPW_ENHANCED ? "enhanced " :
1389                 config->mps == MLX5_MPW ? "legacy " : "",
1390                 config->mps != MLX5_MPW_DISABLED ? "enabled" : "disabled");
1391         if (config->devx) {
1392                 err = mlx5_devx_cmd_query_hca_attr(sh->ctx, &config->hca_attr);
1393                 if (err) {
1394                         err = -err;
1395                         goto error;
1396                 }
1397                 /* Check relax ordering support. */
1398                 if (!haswell_broadwell_cpu) {
1399                         sh->cmng.relaxed_ordering_write =
1400                                 config->hca_attr.relaxed_ordering_write;
1401                         sh->cmng.relaxed_ordering_read =
1402                                 config->hca_attr.relaxed_ordering_read;
1403                 } else {
1404                         sh->cmng.relaxed_ordering_read = 0;
1405                         sh->cmng.relaxed_ordering_write = 0;
1406                 }
1407                 sh->rq_ts_format = config->hca_attr.rq_ts_format;
1408                 sh->sq_ts_format = config->hca_attr.sq_ts_format;
1409                 sh->steering_format_version =
1410                         config->hca_attr.steering_format_version;
1411                 sh->qp_ts_format = config->hca_attr.qp_ts_format;
1412                 /* Check for LRO support. */
1413                 if (config->dest_tir && config->hca_attr.lro_cap &&
1414                     config->dv_flow_en) {
1415                         /* TBD check tunnel lro caps. */
1416                         config->lro.supported = config->hca_attr.lro_cap;
1417                         DRV_LOG(DEBUG, "Device supports LRO");
1418                         /*
1419                          * If LRO timeout is not configured by application,
1420                          * use the minimal supported value.
1421                          */
1422                         if (!config->lro.timeout)
1423                                 config->lro.timeout =
1424                                 config->hca_attr.lro_timer_supported_periods[0];
1425                         DRV_LOG(DEBUG, "LRO session timeout set to %d usec",
1426                                 config->lro.timeout);
1427                         DRV_LOG(DEBUG, "LRO minimal size of TCP segment "
1428                                 "required for coalescing is %d bytes",
1429                                 config->hca_attr.lro_min_mss_size);
1430                 }
1431 #if defined(HAVE_MLX5DV_DR) && \
1432         (defined(HAVE_MLX5_DR_CREATE_ACTION_FLOW_METER) || \
1433          defined(HAVE_MLX5_DR_CREATE_ACTION_ASO))
1434                 if (config->hca_attr.qos.sup &&
1435                     config->hca_attr.qos.flow_meter_old &&
1436                     config->dv_flow_en) {
1437                         uint8_t reg_c_mask =
1438                                 config->hca_attr.qos.flow_meter_reg_c_ids;
1439                         /*
1440                          * Meter needs two REG_C's for color match and pre-sfx
1441                          * flow match. Here get the REG_C for color match.
1442                          * REG_C_0 and REG_C_1 is reserved for metadata feature.
1443                          */
1444                         reg_c_mask &= 0xfc;
1445                         if (__builtin_popcount(reg_c_mask) < 1) {
1446                                 priv->mtr_en = 0;
1447                                 DRV_LOG(WARNING, "No available register for"
1448                                         " meter.");
1449                         } else {
1450                                 /*
1451                                  * The meter color register is used by the
1452                                  * flow-hit feature as well.
1453                                  * The flow-hit feature must use REG_C_3
1454                                  * Prefer REG_C_3 if it is available.
1455                                  */
1456                                 if (reg_c_mask & (1 << (REG_C_3 - REG_C_0)))
1457                                         priv->mtr_color_reg = REG_C_3;
1458                                 else
1459                                         priv->mtr_color_reg = ffs(reg_c_mask)
1460                                                               - 1 + REG_C_0;
1461                                 priv->mtr_en = 1;
1462                                 priv->mtr_reg_share =
1463                                       config->hca_attr.qos.flow_meter;
1464                                 DRV_LOG(DEBUG, "The REG_C meter uses is %d",
1465                                         priv->mtr_color_reg);
1466                         }
1467                 }
1468                 if (config->hca_attr.qos.sup &&
1469                         config->hca_attr.qos.flow_meter_aso_sup) {
1470                         uint32_t log_obj_size =
1471                                 rte_log2_u32(MLX5_ASO_MTRS_PER_POOL >> 1);
1472                         if (log_obj_size >=
1473                         config->hca_attr.qos.log_meter_aso_granularity &&
1474                         log_obj_size <=
1475                         config->hca_attr.qos.log_meter_aso_max_alloc)
1476                                 sh->meter_aso_en = 1;
1477                 }
1478                 if (priv->mtr_en) {
1479                         err = mlx5_aso_flow_mtrs_mng_init(priv->sh);
1480                         if (err) {
1481                                 err = -err;
1482                                 goto error;
1483                         }
1484                 }
1485                 if (config->hca_attr.flow.tunnel_header_0_1)
1486                         sh->tunnel_header_0_1 = 1;
1487 #endif
1488 #ifdef HAVE_MLX5_DR_CREATE_ACTION_ASO
1489                 if (config->hca_attr.flow_hit_aso &&
1490                     priv->mtr_color_reg == REG_C_3) {
1491                         sh->flow_hit_aso_en = 1;
1492                         err = mlx5_flow_aso_age_mng_init(sh);
1493                         if (err) {
1494                                 err = -err;
1495                                 goto error;
1496                         }
1497                         DRV_LOG(DEBUG, "Flow Hit ASO is supported.");
1498                 }
1499 #endif /* HAVE_MLX5_DR_CREATE_ACTION_ASO */
1500 #if defined(HAVE_MLX5_DR_CREATE_ACTION_ASO) && \
1501         defined(HAVE_MLX5_DR_ACTION_ASO_CT)
1502                 if (config->hca_attr.ct_offload &&
1503                     priv->mtr_color_reg == REG_C_3) {
1504                         err = mlx5_flow_aso_ct_mng_init(sh);
1505                         if (err) {
1506                                 err = -err;
1507                                 goto error;
1508                         }
1509                         DRV_LOG(DEBUG, "CT ASO is supported.");
1510                         sh->ct_aso_en = 1;
1511                 }
1512 #endif /* HAVE_MLX5_DR_CREATE_ACTION_ASO && HAVE_MLX5_DR_ACTION_ASO_CT */
1513 #if defined(HAVE_MLX5DV_DR) && defined(HAVE_MLX5_DR_CREATE_ACTION_FLOW_SAMPLE)
1514                 if (config->hca_attr.log_max_ft_sampler_num > 0  &&
1515                     config->dv_flow_en) {
1516                         priv->sampler_en = 1;
1517                         DRV_LOG(DEBUG, "Sampler enabled!");
1518                 } else {
1519                         priv->sampler_en = 0;
1520                         if (!config->hca_attr.log_max_ft_sampler_num)
1521                                 DRV_LOG(WARNING,
1522                                         "No available register for sampler.");
1523                         else
1524                                 DRV_LOG(DEBUG, "DV flow is not supported!");
1525                 }
1526 #endif
1527         }
1528         if (config->cqe_comp && RTE_CACHE_LINE_SIZE == 128 &&
1529             !(dv_attr.flags & MLX5DV_CONTEXT_FLAGS_CQE_128B_COMP)) {
1530                 DRV_LOG(WARNING, "Rx CQE 128B compression is not supported");
1531                 config->cqe_comp = 0;
1532         }
1533         if (config->cqe_comp_fmt == MLX5_CQE_RESP_FORMAT_FTAG_STRIDX &&
1534             (!config->devx || !config->hca_attr.mini_cqe_resp_flow_tag)) {
1535                 DRV_LOG(WARNING, "Flow Tag CQE compression"
1536                                  " format isn't supported.");
1537                 config->cqe_comp = 0;
1538         }
1539         if (config->cqe_comp_fmt == MLX5_CQE_RESP_FORMAT_L34H_STRIDX &&
1540             (!config->devx || !config->hca_attr.mini_cqe_resp_l3_l4_tag)) {
1541                 DRV_LOG(WARNING, "L3/L4 Header CQE compression"
1542                                  " format isn't supported.");
1543                 config->cqe_comp = 0;
1544         }
1545         DRV_LOG(DEBUG, "Rx CQE compression is %ssupported",
1546                         config->cqe_comp ? "" : "not ");
1547         if (config->tx_pp) {
1548                 DRV_LOG(DEBUG, "Timestamp counter frequency %u kHz",
1549                         config->hca_attr.dev_freq_khz);
1550                 DRV_LOG(DEBUG, "Packet pacing is %ssupported",
1551                         config->hca_attr.qos.packet_pacing ? "" : "not ");
1552                 DRV_LOG(DEBUG, "Cross channel ops are %ssupported",
1553                         config->hca_attr.cross_channel ? "" : "not ");
1554                 DRV_LOG(DEBUG, "WQE index ignore is %ssupported",
1555                         config->hca_attr.wqe_index_ignore ? "" : "not ");
1556                 DRV_LOG(DEBUG, "Non-wire SQ feature is %ssupported",
1557                         config->hca_attr.non_wire_sq ? "" : "not ");
1558                 DRV_LOG(DEBUG, "Static WQE SQ feature is %ssupported (%d)",
1559                         config->hca_attr.log_max_static_sq_wq ? "" : "not ",
1560                         config->hca_attr.log_max_static_sq_wq);
1561                 DRV_LOG(DEBUG, "WQE rate PP mode is %ssupported",
1562                         config->hca_attr.qos.wqe_rate_pp ? "" : "not ");
1563                 if (!config->devx) {
1564                         DRV_LOG(ERR, "DevX is required for packet pacing");
1565                         err = ENODEV;
1566                         goto error;
1567                 }
1568                 if (!config->hca_attr.qos.packet_pacing) {
1569                         DRV_LOG(ERR, "Packet pacing is not supported");
1570                         err = ENODEV;
1571                         goto error;
1572                 }
1573                 if (!config->hca_attr.cross_channel) {
1574                         DRV_LOG(ERR, "Cross channel operations are"
1575                                      " required for packet pacing");
1576                         err = ENODEV;
1577                         goto error;
1578                 }
1579                 if (!config->hca_attr.wqe_index_ignore) {
1580                         DRV_LOG(ERR, "WQE index ignore feature is"
1581                                      " required for packet pacing");
1582                         err = ENODEV;
1583                         goto error;
1584                 }
1585                 if (!config->hca_attr.non_wire_sq) {
1586                         DRV_LOG(ERR, "Non-wire SQ feature is"
1587                                      " required for packet pacing");
1588                         err = ENODEV;
1589                         goto error;
1590                 }
1591                 if (!config->hca_attr.log_max_static_sq_wq) {
1592                         DRV_LOG(ERR, "Static WQE SQ feature is"
1593                                      " required for packet pacing");
1594                         err = ENODEV;
1595                         goto error;
1596                 }
1597                 if (!config->hca_attr.qos.wqe_rate_pp) {
1598                         DRV_LOG(ERR, "WQE rate mode is required"
1599                                      " for packet pacing");
1600                         err = ENODEV;
1601                         goto error;
1602                 }
1603 #ifndef HAVE_MLX5DV_DEVX_UAR_OFFSET
1604                 DRV_LOG(ERR, "DevX does not provide UAR offset,"
1605                              " can't create queues for packet pacing");
1606                 err = ENODEV;
1607                 goto error;
1608 #endif
1609         }
1610         if (config->devx) {
1611                 uint32_t reg[MLX5_ST_SZ_DW(register_mtutc)];
1612
1613                 err = config->hca_attr.access_register_user ?
1614                         mlx5_devx_cmd_register_read
1615                                 (sh->ctx, MLX5_REGISTER_ID_MTUTC, 0,
1616                                 reg, MLX5_ST_SZ_DW(register_mtutc)) : ENOTSUP;
1617                 if (!err) {
1618                         uint32_t ts_mode;
1619
1620                         /* MTUTC register is read successfully. */
1621                         ts_mode = MLX5_GET(register_mtutc, reg,
1622                                            time_stamp_mode);
1623                         if (ts_mode == MLX5_MTUTC_TIMESTAMP_MODE_REAL_TIME)
1624                                 config->rt_timestamp = 1;
1625                 } else {
1626                         /* Kernel does not support register reading. */
1627                         if (config->hca_attr.dev_freq_khz ==
1628                                                  (NS_PER_S / MS_PER_S))
1629                                 config->rt_timestamp = 1;
1630                 }
1631         }
1632         /*
1633          * If HW has bug working with tunnel packet decapsulation and
1634          * scatter FCS, and decapsulation is needed, clear the hw_fcs_strip
1635          * bit. Then DEV_RX_OFFLOAD_KEEP_CRC bit will not be set anymore.
1636          */
1637         if (config->hca_attr.scatter_fcs_w_decap_disable && config->decap_en)
1638                 config->hw_fcs_strip = 0;
1639         DRV_LOG(DEBUG, "FCS stripping configuration is %ssupported",
1640                 (config->hw_fcs_strip ? "" : "not "));
1641         if (config->mprq.enabled && mprq) {
1642                 if (config->mprq.stride_num_n &&
1643                     (config->mprq.stride_num_n > mprq_max_stride_num_n ||
1644                      config->mprq.stride_num_n < mprq_min_stride_num_n)) {
1645                         config->mprq.stride_num_n =
1646                                 RTE_MIN(RTE_MAX(MLX5_MPRQ_STRIDE_NUM_N,
1647                                                 mprq_min_stride_num_n),
1648                                         mprq_max_stride_num_n);
1649                         DRV_LOG(WARNING,
1650                                 "the number of strides"
1651                                 " for Multi-Packet RQ is out of range,"
1652                                 " setting default value (%u)",
1653                                 1 << config->mprq.stride_num_n);
1654                 }
1655                 if (config->mprq.stride_size_n &&
1656                     (config->mprq.stride_size_n > mprq_max_stride_size_n ||
1657                      config->mprq.stride_size_n < mprq_min_stride_size_n)) {
1658                         config->mprq.stride_size_n =
1659                                 RTE_MIN(RTE_MAX(MLX5_MPRQ_STRIDE_SIZE_N,
1660                                                 mprq_min_stride_size_n),
1661                                         mprq_max_stride_size_n);
1662                         DRV_LOG(WARNING,
1663                                 "the size of a stride"
1664                                 " for Multi-Packet RQ is out of range,"
1665                                 " setting default value (%u)",
1666                                 1 << config->mprq.stride_size_n);
1667                 }
1668                 config->mprq.min_stride_size_n = mprq_min_stride_size_n;
1669                 config->mprq.max_stride_size_n = mprq_max_stride_size_n;
1670         } else if (config->mprq.enabled && !mprq) {
1671                 DRV_LOG(WARNING, "Multi-Packet RQ isn't supported");
1672                 config->mprq.enabled = 0;
1673         }
1674         if (config->max_dump_files_num == 0)
1675                 config->max_dump_files_num = 128;
1676         eth_dev = rte_eth_dev_allocate(name);
1677         if (eth_dev == NULL) {
1678                 DRV_LOG(ERR, "can not allocate rte ethdev");
1679                 err = ENOMEM;
1680                 goto error;
1681         }
1682         if (priv->representor) {
1683                 eth_dev->data->dev_flags |= RTE_ETH_DEV_REPRESENTOR;
1684                 eth_dev->data->representor_id = priv->representor_id;
1685                 MLX5_ETH_FOREACH_DEV(port_id, dpdk_dev) {
1686                         struct mlx5_priv *opriv =
1687                                 rte_eth_devices[port_id].data->dev_private;
1688                         if (opriv &&
1689                             opriv->master &&
1690                             opriv->domain_id == priv->domain_id &&
1691                             opriv->sh == priv->sh) {
1692                                 eth_dev->data->backer_port_id = port_id;
1693                                 break;
1694                         }
1695                 }
1696                 if (port_id >= RTE_MAX_ETHPORTS)
1697                         eth_dev->data->backer_port_id = eth_dev->data->port_id;
1698         }
1699         priv->mp_id.port_id = eth_dev->data->port_id;
1700         strlcpy(priv->mp_id.name, MLX5_MP_NAME, RTE_MP_MAX_NAME_LEN);
1701         /*
1702          * Store associated network device interface index. This index
1703          * is permanent throughout the lifetime of device. So, we may store
1704          * the ifindex here and use the cached value further.
1705          */
1706         MLX5_ASSERT(spawn->ifindex);
1707         priv->if_index = spawn->ifindex;
1708         eth_dev->data->dev_private = priv;
1709         priv->dev_data = eth_dev->data;
1710         eth_dev->data->mac_addrs = priv->mac;
1711         eth_dev->device = dpdk_dev;
1712         eth_dev->data->dev_flags |= RTE_ETH_DEV_AUTOFILL_QUEUE_XSTATS;
1713         /* Configure the first MAC address by default. */
1714         if (mlx5_get_mac(eth_dev, &mac.addr_bytes)) {
1715                 DRV_LOG(ERR,
1716                         "port %u cannot get MAC address, is mlx5_en"
1717                         " loaded? (errno: %s)",
1718                         eth_dev->data->port_id, strerror(rte_errno));
1719                 err = ENODEV;
1720                 goto error;
1721         }
1722         DRV_LOG(INFO,
1723                 "port %u MAC address is " RTE_ETHER_ADDR_PRT_FMT,
1724                 eth_dev->data->port_id, RTE_ETHER_ADDR_BYTES(&mac));
1725 #ifdef RTE_LIBRTE_MLX5_DEBUG
1726         {
1727                 char ifname[MLX5_NAMESIZE];
1728
1729                 if (mlx5_get_ifname(eth_dev, &ifname) == 0)
1730                         DRV_LOG(DEBUG, "port %u ifname is \"%s\"",
1731                                 eth_dev->data->port_id, ifname);
1732                 else
1733                         DRV_LOG(DEBUG, "port %u ifname is unknown",
1734                                 eth_dev->data->port_id);
1735         }
1736 #endif
1737         /* Get actual MTU if possible. */
1738         err = mlx5_get_mtu(eth_dev, &priv->mtu);
1739         if (err) {
1740                 err = rte_errno;
1741                 goto error;
1742         }
1743         DRV_LOG(DEBUG, "port %u MTU is %u", eth_dev->data->port_id,
1744                 priv->mtu);
1745         /* Initialize burst functions to prevent crashes before link-up. */
1746         eth_dev->rx_pkt_burst = removed_rx_burst;
1747         eth_dev->tx_pkt_burst = removed_tx_burst;
1748         eth_dev->dev_ops = &mlx5_dev_ops;
1749         eth_dev->rx_descriptor_status = mlx5_rx_descriptor_status;
1750         eth_dev->tx_descriptor_status = mlx5_tx_descriptor_status;
1751         eth_dev->rx_queue_count = mlx5_rx_queue_count;
1752         /* Register MAC address. */
1753         claim_zero(mlx5_mac_addr_add(eth_dev, &mac, 0, 0));
1754         if (config->vf && config->vf_nl_en)
1755                 mlx5_nl_mac_addr_sync(priv->nl_socket_route,
1756                                       mlx5_ifindex(eth_dev),
1757                                       eth_dev->data->mac_addrs,
1758                                       MLX5_MAX_MAC_ADDRESSES);
1759         priv->ctrl_flows = 0;
1760         rte_spinlock_init(&priv->flow_list_lock);
1761         TAILQ_INIT(&priv->flow_meters);
1762         priv->mtr_profile_tbl = mlx5_l3t_create(MLX5_L3T_TYPE_PTR);
1763         if (!priv->mtr_profile_tbl)
1764                 goto error;
1765         /* Hint libmlx5 to use PMD allocator for data plane resources */
1766         mlx5_glue->dv_set_context_attr(sh->ctx,
1767                         MLX5DV_CTX_ATTR_BUF_ALLOCATORS,
1768                         (void *)((uintptr_t)&(struct mlx5dv_ctx_allocators){
1769                                 .alloc = &mlx5_alloc_verbs_buf,
1770                                 .free = &mlx5_free_verbs_buf,
1771                                 .data = sh,
1772                         }));
1773         /* Bring Ethernet device up. */
1774         DRV_LOG(DEBUG, "port %u forcing Ethernet interface up",
1775                 eth_dev->data->port_id);
1776         mlx5_set_link_up(eth_dev);
1777         /*
1778          * Even though the interrupt handler is not installed yet,
1779          * interrupts will still trigger on the async_fd from
1780          * Verbs context returned by ibv_open_device().
1781          */
1782         mlx5_link_update(eth_dev, 0);
1783 #ifdef HAVE_MLX5DV_DR_ESWITCH
1784         if (!(config->hca_attr.eswitch_manager && config->dv_flow_en &&
1785               (switch_info->representor || switch_info->master)))
1786                 config->dv_esw_en = 0;
1787 #else
1788         config->dv_esw_en = 0;
1789 #endif
1790         /* Detect minimal data bytes to inline. */
1791         mlx5_set_min_inline(spawn, config);
1792         /* Store device configuration on private structure. */
1793         priv->config = *config;
1794         for (i = 0; i < MLX5_FLOW_TYPE_MAXI; i++) {
1795                 icfg[i].release_mem_en = !!config->reclaim_mode;
1796                 if (config->reclaim_mode)
1797                         icfg[i].per_core_cache = 0;
1798                 priv->flows[i] = mlx5_ipool_create(&icfg[i]);
1799                 if (!priv->flows[i])
1800                         goto error;
1801         }
1802         /* Create context for virtual machine VLAN workaround. */
1803         priv->vmwa_context = mlx5_vlan_vmwa_init(eth_dev, spawn->ifindex);
1804         if (config->dv_flow_en) {
1805                 err = mlx5_alloc_shared_dr(priv);
1806                 if (err)
1807                         goto error;
1808         }
1809         if (config->devx && config->dv_flow_en && config->dest_tir) {
1810                 priv->obj_ops = devx_obj_ops;
1811                 priv->obj_ops.drop_action_create =
1812                                                 ibv_obj_ops.drop_action_create;
1813                 priv->obj_ops.drop_action_destroy =
1814                                                 ibv_obj_ops.drop_action_destroy;
1815 #ifndef HAVE_MLX5DV_DEVX_UAR_OFFSET
1816                 priv->obj_ops.txq_obj_modify = ibv_obj_ops.txq_obj_modify;
1817 #else
1818                 if (config->dv_esw_en)
1819                         priv->obj_ops.txq_obj_modify =
1820                                                 ibv_obj_ops.txq_obj_modify;
1821 #endif
1822                 /* Use specific wrappers for Tx object. */
1823                 priv->obj_ops.txq_obj_new = mlx5_os_txq_obj_new;
1824                 priv->obj_ops.txq_obj_release = mlx5_os_txq_obj_release;
1825                 mlx5_queue_counter_id_prepare(eth_dev);
1826                 priv->obj_ops.lb_dummy_queue_create =
1827                                         mlx5_rxq_ibv_obj_dummy_lb_create;
1828                 priv->obj_ops.lb_dummy_queue_release =
1829                                         mlx5_rxq_ibv_obj_dummy_lb_release;
1830         } else {
1831                 priv->obj_ops = ibv_obj_ops;
1832         }
1833         if (config->tx_pp &&
1834             (priv->config.dv_esw_en ||
1835              priv->obj_ops.txq_obj_new != mlx5_os_txq_obj_new)) {
1836                 /*
1837                  * HAVE_MLX5DV_DEVX_UAR_OFFSET is required to support
1838                  * packet pacing and already checked above.
1839                  * Hence, we should only make sure the SQs will be created
1840                  * with DevX, not with Verbs.
1841                  * Verbs allocates the SQ UAR on its own and it can't be shared
1842                  * with Clock Queue UAR as required for Tx scheduling.
1843                  */
1844                 DRV_LOG(ERR, "Verbs SQs, UAR can't be shared as required for packet pacing");
1845                 err = ENODEV;
1846                 goto error;
1847         }
1848         priv->drop_queue.hrxq = mlx5_drop_action_create(eth_dev);
1849         if (!priv->drop_queue.hrxq)
1850                 goto error;
1851         /* Supported Verbs flow priority number detection. */
1852         err = mlx5_flow_discover_priorities(eth_dev);
1853         if (err < 0) {
1854                 err = -err;
1855                 goto error;
1856         }
1857         priv->config.flow_prio = err;
1858         if (!priv->config.dv_esw_en &&
1859             priv->config.dv_xmeta_en != MLX5_XMETA_MODE_LEGACY) {
1860                 DRV_LOG(WARNING, "metadata mode %u is not supported "
1861                                  "(no E-Switch)", priv->config.dv_xmeta_en);
1862                 priv->config.dv_xmeta_en = MLX5_XMETA_MODE_LEGACY;
1863         }
1864         mlx5_set_metadata_mask(eth_dev);
1865         if (priv->config.dv_xmeta_en != MLX5_XMETA_MODE_LEGACY &&
1866             !priv->sh->dv_regc0_mask) {
1867                 DRV_LOG(ERR, "metadata mode %u is not supported "
1868                              "(no metadata reg_c[0] is available)",
1869                              priv->config.dv_xmeta_en);
1870                         err = ENOTSUP;
1871                         goto error;
1872         }
1873         priv->hrxqs = mlx5_list_create("hrxq", eth_dev, true,
1874                                        mlx5_hrxq_create_cb,
1875                                        mlx5_hrxq_match_cb,
1876                                        mlx5_hrxq_remove_cb,
1877                                        mlx5_hrxq_clone_cb,
1878                                        mlx5_hrxq_clone_free_cb);
1879         if (!priv->hrxqs)
1880                 goto error;
1881         rte_rwlock_init(&priv->ind_tbls_lock);
1882         /* Query availability of metadata reg_c's. */
1883         err = mlx5_flow_discover_mreg_c(eth_dev);
1884         if (err < 0) {
1885                 err = -err;
1886                 goto error;
1887         }
1888         if (!mlx5_flow_ext_mreg_supported(eth_dev)) {
1889                 DRV_LOG(DEBUG,
1890                         "port %u extensive metadata register is not supported",
1891                         eth_dev->data->port_id);
1892                 if (priv->config.dv_xmeta_en != MLX5_XMETA_MODE_LEGACY) {
1893                         DRV_LOG(ERR, "metadata mode %u is not supported "
1894                                      "(no metadata registers available)",
1895                                      priv->config.dv_xmeta_en);
1896                         err = ENOTSUP;
1897                         goto error;
1898                 }
1899         }
1900         if (priv->config.dv_flow_en &&
1901             priv->config.dv_xmeta_en != MLX5_XMETA_MODE_LEGACY &&
1902             mlx5_flow_ext_mreg_supported(eth_dev) &&
1903             priv->sh->dv_regc0_mask) {
1904                 priv->mreg_cp_tbl = mlx5_hlist_create(MLX5_FLOW_MREG_HNAME,
1905                                                       MLX5_FLOW_MREG_HTABLE_SZ,
1906                                                       false, true, eth_dev,
1907                                                       flow_dv_mreg_create_cb,
1908                                                       flow_dv_mreg_match_cb,
1909                                                       flow_dv_mreg_remove_cb,
1910                                                       flow_dv_mreg_clone_cb,
1911                                                     flow_dv_mreg_clone_free_cb);
1912                 if (!priv->mreg_cp_tbl) {
1913                         err = ENOMEM;
1914                         goto error;
1915                 }
1916         }
1917         rte_spinlock_init(&priv->shared_act_sl);
1918         mlx5_flow_counter_mode_config(eth_dev);
1919         mlx5_flow_drop_action_config(eth_dev);
1920         if (priv->config.dv_flow_en)
1921                 eth_dev->data->dev_flags |= RTE_ETH_DEV_FLOW_OPS_THREAD_SAFE;
1922         return eth_dev;
1923 error:
1924         if (priv) {
1925                 if (priv->mreg_cp_tbl)
1926                         mlx5_hlist_destroy(priv->mreg_cp_tbl);
1927                 if (priv->sh)
1928                         mlx5_os_free_shared_dr(priv);
1929                 if (priv->nl_socket_route >= 0)
1930                         close(priv->nl_socket_route);
1931                 if (priv->nl_socket_rdma >= 0)
1932                         close(priv->nl_socket_rdma);
1933                 if (priv->vmwa_context)
1934                         mlx5_vlan_vmwa_exit(priv->vmwa_context);
1935                 if (eth_dev && priv->drop_queue.hrxq)
1936                         mlx5_drop_action_destroy(eth_dev);
1937                 if (priv->mtr_profile_tbl)
1938                         mlx5_l3t_destroy(priv->mtr_profile_tbl);
1939                 if (own_domain_id)
1940                         claim_zero(rte_eth_switch_domain_free(priv->domain_id));
1941                 if (priv->hrxqs)
1942                         mlx5_list_destroy(priv->hrxqs);
1943                 mlx5_free(priv);
1944                 if (eth_dev != NULL)
1945                         eth_dev->data->dev_private = NULL;
1946         }
1947         if (eth_dev != NULL) {
1948                 /* mac_addrs must not be freed alone because part of
1949                  * dev_private
1950                  **/
1951                 eth_dev->data->mac_addrs = NULL;
1952                 rte_eth_dev_release_port(eth_dev);
1953         }
1954         if (sh)
1955                 mlx5_free_shared_dev_ctx(sh);
1956         MLX5_ASSERT(err > 0);
1957         rte_errno = err;
1958         return NULL;
1959 }
1960
1961 /**
1962  * Comparison callback to sort device data.
1963  *
1964  * This is meant to be used with qsort().
1965  *
1966  * @param a[in]
1967  *   Pointer to pointer to first data object.
1968  * @param b[in]
1969  *   Pointer to pointer to second data object.
1970  *
1971  * @return
1972  *   0 if both objects are equal, less than 0 if the first argument is less
1973  *   than the second, greater than 0 otherwise.
1974  */
1975 static int
1976 mlx5_dev_spawn_data_cmp(const void *a, const void *b)
1977 {
1978         const struct mlx5_switch_info *si_a =
1979                 &((const struct mlx5_dev_spawn_data *)a)->info;
1980         const struct mlx5_switch_info *si_b =
1981                 &((const struct mlx5_dev_spawn_data *)b)->info;
1982         int ret;
1983
1984         /* Master device first. */
1985         ret = si_b->master - si_a->master;
1986         if (ret)
1987                 return ret;
1988         /* Then representor devices. */
1989         ret = si_b->representor - si_a->representor;
1990         if (ret)
1991                 return ret;
1992         /* Unidentified devices come last in no specific order. */
1993         if (!si_a->representor)
1994                 return 0;
1995         /* Order representors by name. */
1996         return si_a->port_name - si_b->port_name;
1997 }
1998
1999 /**
2000  * Match PCI information for possible slaves of bonding device.
2001  *
2002  * @param[in] ibv_dev
2003  *   Pointer to Infiniband device structure.
2004  * @param[in] pci_dev
2005  *   Pointer to primary PCI address structure to match.
2006  * @param[in] nl_rdma
2007  *   Netlink RDMA group socket handle.
2008  * @param[in] owner
2009  *   Rerepsentor owner PF index.
2010  * @param[out] bond_info
2011  *   Pointer to bonding information.
2012  *
2013  * @return
2014  *   negative value if no bonding device found, otherwise
2015  *   positive index of slave PF in bonding.
2016  */
2017 static int
2018 mlx5_device_bond_pci_match(const struct ibv_device *ibv_dev,
2019                            const struct rte_pci_addr *pci_dev,
2020                            int nl_rdma, uint16_t owner,
2021                            struct mlx5_bond_info *bond_info)
2022 {
2023         char ifname[IF_NAMESIZE + 1];
2024         unsigned int ifindex;
2025         unsigned int np, i;
2026         FILE *bond_file = NULL, *file;
2027         int pf = -1;
2028         int ret;
2029
2030         /*
2031          * Try to get master device name. If something goes
2032          * wrong suppose the lack of kernel support and no
2033          * bonding devices.
2034          */
2035         memset(bond_info, 0, sizeof(*bond_info));
2036         if (nl_rdma < 0)
2037                 return -1;
2038         if (!strstr(ibv_dev->name, "bond"))
2039                 return -1;
2040         np = mlx5_nl_portnum(nl_rdma, ibv_dev->name);
2041         if (!np)
2042                 return -1;
2043         /*
2044          * The Master device might not be on the predefined
2045          * port (not on port index 1, it is not garanted),
2046          * we have to scan all Infiniband device port and
2047          * find master.
2048          */
2049         for (i = 1; i <= np; ++i) {
2050                 /* Check whether Infiniband port is populated. */
2051                 ifindex = mlx5_nl_ifindex(nl_rdma, ibv_dev->name, i);
2052                 if (!ifindex)
2053                         continue;
2054                 if (!if_indextoname(ifindex, ifname))
2055                         continue;
2056                 /* Try to read bonding slave names from sysfs. */
2057                 MKSTR(slaves,
2058                       "/sys/class/net/%s/master/bonding/slaves", ifname);
2059                 bond_file = fopen(slaves, "r");
2060                 if (bond_file)
2061                         break;
2062         }
2063         if (!bond_file)
2064                 return -1;
2065         /* Use safe format to check maximal buffer length. */
2066         MLX5_ASSERT(atol(RTE_STR(IF_NAMESIZE)) == IF_NAMESIZE);
2067         while (fscanf(bond_file, "%" RTE_STR(IF_NAMESIZE) "s", ifname) == 1) {
2068                 char tmp_str[IF_NAMESIZE + 32];
2069                 struct rte_pci_addr pci_addr;
2070                 struct mlx5_switch_info info;
2071
2072                 /* Process slave interface names in the loop. */
2073                 snprintf(tmp_str, sizeof(tmp_str),
2074                          "/sys/class/net/%s", ifname);
2075                 if (mlx5_get_pci_addr(tmp_str, &pci_addr)) {
2076                         DRV_LOG(WARNING, "can not get PCI address"
2077                                          " for netdev \"%s\"", ifname);
2078                         continue;
2079                 }
2080                 /* Slave interface PCI address match found. */
2081                 snprintf(tmp_str, sizeof(tmp_str),
2082                          "/sys/class/net/%s/phys_port_name", ifname);
2083                 file = fopen(tmp_str, "rb");
2084                 if (!file)
2085                         break;
2086                 info.name_type = MLX5_PHYS_PORT_NAME_TYPE_NOTSET;
2087                 if (fscanf(file, "%32s", tmp_str) == 1)
2088                         mlx5_translate_port_name(tmp_str, &info);
2089                 fclose(file);
2090                 /* Only process PF ports. */
2091                 if (info.name_type != MLX5_PHYS_PORT_NAME_TYPE_LEGACY &&
2092                     info.name_type != MLX5_PHYS_PORT_NAME_TYPE_UPLINK)
2093                         continue;
2094                 /* Check max bonding member. */
2095                 if (info.port_name >= MLX5_BOND_MAX_PORTS) {
2096                         DRV_LOG(WARNING, "bonding index out of range, "
2097                                 "please increase MLX5_BOND_MAX_PORTS: %s",
2098                                 tmp_str);
2099                         break;
2100                 }
2101                 /* Match PCI address, allows BDF0+pfx or BDFx+pfx. */
2102                 if (pci_dev->domain == pci_addr.domain &&
2103                     pci_dev->bus == pci_addr.bus &&
2104                     pci_dev->devid == pci_addr.devid &&
2105                     ((pci_dev->function == 0 &&
2106                       pci_dev->function + owner == pci_addr.function) ||
2107                      (pci_dev->function == owner &&
2108                       pci_addr.function == owner)))
2109                         pf = info.port_name;
2110                 /* Get ifindex. */
2111                 snprintf(tmp_str, sizeof(tmp_str),
2112                          "/sys/class/net/%s/ifindex", ifname);
2113                 file = fopen(tmp_str, "rb");
2114                 if (!file)
2115                         break;
2116                 ret = fscanf(file, "%u", &ifindex);
2117                 fclose(file);
2118                 if (ret != 1)
2119                         break;
2120                 /* Save bonding info. */
2121                 strncpy(bond_info->ports[info.port_name].ifname, ifname,
2122                         sizeof(bond_info->ports[0].ifname));
2123                 bond_info->ports[info.port_name].pci_addr = pci_addr;
2124                 bond_info->ports[info.port_name].ifindex = ifindex;
2125                 bond_info->n_port++;
2126         }
2127         if (pf >= 0) {
2128                 /* Get bond interface info */
2129                 ret = mlx5_sysfs_bond_info(ifindex, &bond_info->ifindex,
2130                                            bond_info->ifname);
2131                 if (ret)
2132                         DRV_LOG(ERR, "unable to get bond info: %s",
2133                                 strerror(rte_errno));
2134                 else
2135                         DRV_LOG(INFO, "PF device %u, bond device %u(%s)",
2136                                 ifindex, bond_info->ifindex, bond_info->ifname);
2137         }
2138         return pf;
2139 }
2140
2141 static void
2142 mlx5_os_config_default(struct mlx5_dev_config *config)
2143 {
2144         memset(config, 0, sizeof(*config));
2145         config->mps = MLX5_ARG_UNSET;
2146         config->rx_vec_en = 1;
2147         config->txq_inline_max = MLX5_ARG_UNSET;
2148         config->txq_inline_min = MLX5_ARG_UNSET;
2149         config->txq_inline_mpw = MLX5_ARG_UNSET;
2150         config->txqs_inline = MLX5_ARG_UNSET;
2151         config->vf_nl_en = 1;
2152         config->mprq.max_memcpy_len = MLX5_MPRQ_MEMCPY_DEFAULT_LEN;
2153         config->mprq.min_rxqs_num = MLX5_MPRQ_MIN_RXQS;
2154         config->dv_esw_en = 1;
2155         config->dv_flow_en = 1;
2156         config->decap_en = 1;
2157         config->log_hp_size = MLX5_ARG_UNSET;
2158         config->allow_duplicate_pattern = 1;
2159 }
2160
2161 /**
2162  * Register a PCI device within bonding.
2163  *
2164  * This function spawns Ethernet devices out of a given PCI device and
2165  * bonding owner PF index.
2166  *
2167  * @param[in] cdev
2168  *   Pointer to common mlx5 device structure.
2169  * @param[in] req_eth_da
2170  *   Requested ethdev device argument.
2171  * @param[in] owner_id
2172  *   Requested owner PF port ID within bonding device, default to 0.
2173  *
2174  * @return
2175  *   0 on success, a negative errno value otherwise and rte_errno is set.
2176  */
2177 static int
2178 mlx5_os_pci_probe_pf(struct mlx5_common_device *cdev,
2179                      struct rte_eth_devargs *req_eth_da,
2180                      uint16_t owner_id)
2181 {
2182         struct ibv_device **ibv_list;
2183         /*
2184          * Number of found IB Devices matching with requested PCI BDF.
2185          * nd != 1 means there are multiple IB devices over the same
2186          * PCI device and we have representors and master.
2187          */
2188         unsigned int nd = 0;
2189         /*
2190          * Number of found IB device Ports. nd = 1 and np = 1..n means
2191          * we have the single multiport IB device, and there may be
2192          * representors attached to some of found ports.
2193          */
2194         unsigned int np = 0;
2195         /*
2196          * Number of DPDK ethernet devices to Spawn - either over
2197          * multiple IB devices or multiple ports of single IB device.
2198          * Actually this is the number of iterations to spawn.
2199          */
2200         unsigned int ns = 0;
2201         /*
2202          * Bonding device
2203          *   < 0 - no bonding device (single one)
2204          *  >= 0 - bonding device (value is slave PF index)
2205          */
2206         int bd = -1;
2207         struct rte_pci_device *pci_dev = RTE_DEV_TO_PCI(cdev->dev);
2208         struct mlx5_dev_spawn_data *list = NULL;
2209         struct mlx5_dev_config dev_config;
2210         unsigned int dev_config_vf;
2211         struct rte_eth_devargs eth_da = *req_eth_da;
2212         struct rte_pci_addr owner_pci = pci_dev->addr; /* Owner PF. */
2213         struct mlx5_bond_info bond_info;
2214         int ret = -1;
2215
2216         errno = 0;
2217         ibv_list = mlx5_glue->get_device_list(&ret);
2218         if (!ibv_list) {
2219                 rte_errno = errno ? errno : ENOSYS;
2220                 DRV_LOG(ERR, "cannot list devices, is ib_uverbs loaded?");
2221                 return -rte_errno;
2222         }
2223         /*
2224          * First scan the list of all Infiniband devices to find
2225          * matching ones, gathering into the list.
2226          */
2227         struct ibv_device *ibv_match[ret + 1];
2228         int nl_route = mlx5_nl_init(NETLINK_ROUTE);
2229         int nl_rdma = mlx5_nl_init(NETLINK_RDMA);
2230         unsigned int i;
2231
2232         while (ret-- > 0) {
2233                 struct rte_pci_addr pci_addr;
2234
2235                 DRV_LOG(DEBUG, "checking device \"%s\"", ibv_list[ret]->name);
2236                 bd = mlx5_device_bond_pci_match
2237                                 (ibv_list[ret], &owner_pci, nl_rdma, owner_id,
2238                                  &bond_info);
2239                 if (bd >= 0) {
2240                         /*
2241                          * Bonding device detected. Only one match is allowed,
2242                          * the bonding is supported over multi-port IB device,
2243                          * there should be no matches on representor PCI
2244                          * functions or non VF LAG bonding devices with
2245                          * specified address.
2246                          */
2247                         if (nd) {
2248                                 DRV_LOG(ERR,
2249                                         "multiple PCI match on bonding device"
2250                                         "\"%s\" found", ibv_list[ret]->name);
2251                                 rte_errno = ENOENT;
2252                                 ret = -rte_errno;
2253                                 goto exit;
2254                         }
2255                         /* Amend owner pci address if owner PF ID specified. */
2256                         if (eth_da.nb_representor_ports)
2257                                 owner_pci.function += owner_id;
2258                         DRV_LOG(INFO, "PCI information matches for"
2259                                       " slave %d bonding device \"%s\"",
2260                                       bd, ibv_list[ret]->name);
2261                         ibv_match[nd++] = ibv_list[ret];
2262                         break;
2263                 } else {
2264                         /* Bonding device not found. */
2265                         if (mlx5_get_pci_addr(ibv_list[ret]->ibdev_path,
2266                                               &pci_addr))
2267                                 continue;
2268                         if (owner_pci.domain != pci_addr.domain ||
2269                             owner_pci.bus != pci_addr.bus ||
2270                             owner_pci.devid != pci_addr.devid ||
2271                             owner_pci.function != pci_addr.function)
2272                                 continue;
2273                         DRV_LOG(INFO, "PCI information matches for device \"%s\"",
2274                                 ibv_list[ret]->name);
2275                         ibv_match[nd++] = ibv_list[ret];
2276                 }
2277         }
2278         ibv_match[nd] = NULL;
2279         if (!nd) {
2280                 /* No device matches, just complain and bail out. */
2281                 DRV_LOG(WARNING,
2282                         "no Verbs device matches PCI device " PCI_PRI_FMT ","
2283                         " are kernel drivers loaded?",
2284                         owner_pci.domain, owner_pci.bus,
2285                         owner_pci.devid, owner_pci.function);
2286                 rte_errno = ENOENT;
2287                 ret = -rte_errno;
2288                 goto exit;
2289         }
2290         if (nd == 1) {
2291                 /*
2292                  * Found single matching device may have multiple ports.
2293                  * Each port may be representor, we have to check the port
2294                  * number and check the representors existence.
2295                  */
2296                 if (nl_rdma >= 0)
2297                         np = mlx5_nl_portnum(nl_rdma, ibv_match[0]->name);
2298                 if (!np)
2299                         DRV_LOG(WARNING, "can not get IB device \"%s\""
2300                                          " ports number", ibv_match[0]->name);
2301                 if (bd >= 0 && !np) {
2302                         DRV_LOG(ERR, "can not get ports"
2303                                      " for bonding device");
2304                         rte_errno = ENOENT;
2305                         ret = -rte_errno;
2306                         goto exit;
2307                 }
2308         }
2309         /*
2310          * Now we can determine the maximal
2311          * amount of devices to be spawned.
2312          */
2313         list = mlx5_malloc(MLX5_MEM_ZERO,
2314                            sizeof(struct mlx5_dev_spawn_data) *
2315                            (np ? np : nd),
2316                            RTE_CACHE_LINE_SIZE, SOCKET_ID_ANY);
2317         if (!list) {
2318                 DRV_LOG(ERR, "spawn data array allocation failure");
2319                 rte_errno = ENOMEM;
2320                 ret = -rte_errno;
2321                 goto exit;
2322         }
2323         if (bd >= 0 || np > 1) {
2324                 /*
2325                  * Single IB device with multiple ports found,
2326                  * it may be E-Switch master device and representors.
2327                  * We have to perform identification through the ports.
2328                  */
2329                 MLX5_ASSERT(nl_rdma >= 0);
2330                 MLX5_ASSERT(ns == 0);
2331                 MLX5_ASSERT(nd == 1);
2332                 MLX5_ASSERT(np);
2333                 for (i = 1; i <= np; ++i) {
2334                         list[ns].bond_info = &bond_info;
2335                         list[ns].max_port = np;
2336                         list[ns].phys_port = i;
2337                         list[ns].phys_dev = ibv_match[0];
2338                         list[ns].eth_dev = NULL;
2339                         list[ns].pci_dev = pci_dev;
2340                         list[ns].cdev = cdev;
2341                         list[ns].pf_bond = bd;
2342                         list[ns].ifindex = mlx5_nl_ifindex
2343                                 (nl_rdma,
2344                                 mlx5_os_get_dev_device_name
2345                                                 (list[ns].phys_dev), i);
2346                         if (!list[ns].ifindex) {
2347                                 /*
2348                                  * No network interface index found for the
2349                                  * specified port, it means there is no
2350                                  * representor on this port. It's OK,
2351                                  * there can be disabled ports, for example
2352                                  * if sriov_numvfs < sriov_totalvfs.
2353                                  */
2354                                 continue;
2355                         }
2356                         ret = -1;
2357                         if (nl_route >= 0)
2358                                 ret = mlx5_nl_switch_info
2359                                                (nl_route,
2360                                                 list[ns].ifindex,
2361                                                 &list[ns].info);
2362                         if (ret || (!list[ns].info.representor &&
2363                                     !list[ns].info.master)) {
2364                                 /*
2365                                  * We failed to recognize representors with
2366                                  * Netlink, let's try to perform the task
2367                                  * with sysfs.
2368                                  */
2369                                 ret =  mlx5_sysfs_switch_info
2370                                                 (list[ns].ifindex,
2371                                                  &list[ns].info);
2372                         }
2373                         if (!ret && bd >= 0) {
2374                                 switch (list[ns].info.name_type) {
2375                                 case MLX5_PHYS_PORT_NAME_TYPE_UPLINK:
2376                                         if (np == 1) {
2377                                                 /*
2378                                                  * Force standalone bonding
2379                                                  * device for ROCE LAG
2380                                                  * confgiurations.
2381                                                  */
2382                                                 list[ns].info.master = 0;
2383                                                 list[ns].info.representor = 0;
2384                                         }
2385                                         if (list[ns].info.port_name == bd)
2386                                                 ns++;
2387                                         break;
2388                                 case MLX5_PHYS_PORT_NAME_TYPE_PFHPF:
2389                                         /* Fallthrough */
2390                                 case MLX5_PHYS_PORT_NAME_TYPE_PFVF:
2391                                         /* Fallthrough */
2392                                 case MLX5_PHYS_PORT_NAME_TYPE_PFSF:
2393                                         if (list[ns].info.pf_num == bd)
2394                                                 ns++;
2395                                         break;
2396                                 default:
2397                                         break;
2398                                 }
2399                                 continue;
2400                         }
2401                         if (!ret && (list[ns].info.representor ^
2402                                      list[ns].info.master))
2403                                 ns++;
2404                 }
2405                 if (!ns) {
2406                         DRV_LOG(ERR,
2407                                 "unable to recognize master/representors"
2408                                 " on the IB device with multiple ports");
2409                         rte_errno = ENOENT;
2410                         ret = -rte_errno;
2411                         goto exit;
2412                 }
2413         } else {
2414                 /*
2415                  * The existence of several matching entries (nd > 1) means
2416                  * port representors have been instantiated. No existing Verbs
2417                  * call nor sysfs entries can tell them apart, this can only
2418                  * be done through Netlink calls assuming kernel drivers are
2419                  * recent enough to support them.
2420                  *
2421                  * In the event of identification failure through Netlink,
2422                  * try again through sysfs, then:
2423                  *
2424                  * 1. A single IB device matches (nd == 1) with single
2425                  *    port (np=0/1) and is not a representor, assume
2426                  *    no switch support.
2427                  *
2428                  * 2. Otherwise no safe assumptions can be made;
2429                  *    complain louder and bail out.
2430                  */
2431                 for (i = 0; i != nd; ++i) {
2432                         memset(&list[ns].info, 0, sizeof(list[ns].info));
2433                         list[ns].bond_info = NULL;
2434                         list[ns].max_port = 1;
2435                         list[ns].phys_port = 1;
2436                         list[ns].phys_dev = ibv_match[i];
2437                         list[ns].eth_dev = NULL;
2438                         list[ns].pci_dev = pci_dev;
2439                         list[ns].cdev = cdev;
2440                         list[ns].pf_bond = -1;
2441                         list[ns].ifindex = 0;
2442                         if (nl_rdma >= 0)
2443                                 list[ns].ifindex = mlx5_nl_ifindex
2444                                 (nl_rdma,
2445                                 mlx5_os_get_dev_device_name
2446                                                 (list[ns].phys_dev), 1);
2447                         if (!list[ns].ifindex) {
2448                                 char ifname[IF_NAMESIZE];
2449
2450                                 /*
2451                                  * Netlink failed, it may happen with old
2452                                  * ib_core kernel driver (before 4.16).
2453                                  * We can assume there is old driver because
2454                                  * here we are processing single ports IB
2455                                  * devices. Let's try sysfs to retrieve
2456                                  * the ifindex. The method works for
2457                                  * master device only.
2458                                  */
2459                                 if (nd > 1) {
2460                                         /*
2461                                          * Multiple devices found, assume
2462                                          * representors, can not distinguish
2463                                          * master/representor and retrieve
2464                                          * ifindex via sysfs.
2465                                          */
2466                                         continue;
2467                                 }
2468                                 ret = mlx5_get_ifname_sysfs
2469                                         (ibv_match[i]->ibdev_path, ifname);
2470                                 if (!ret)
2471                                         list[ns].ifindex =
2472                                                 if_nametoindex(ifname);
2473                                 if (!list[ns].ifindex) {
2474                                         /*
2475                                          * No network interface index found
2476                                          * for the specified device, it means
2477                                          * there it is neither representor
2478                                          * nor master.
2479                                          */
2480                                         continue;
2481                                 }
2482                         }
2483                         ret = -1;
2484                         if (nl_route >= 0)
2485                                 ret = mlx5_nl_switch_info
2486                                                (nl_route,
2487                                                 list[ns].ifindex,
2488                                                 &list[ns].info);
2489                         if (ret || (!list[ns].info.representor &&
2490                                     !list[ns].info.master)) {
2491                                 /*
2492                                  * We failed to recognize representors with
2493                                  * Netlink, let's try to perform the task
2494                                  * with sysfs.
2495                                  */
2496                                 ret =  mlx5_sysfs_switch_info
2497                                                 (list[ns].ifindex,
2498                                                  &list[ns].info);
2499                         }
2500                         if (!ret && (list[ns].info.representor ^
2501                                      list[ns].info.master)) {
2502                                 ns++;
2503                         } else if ((nd == 1) &&
2504                                    !list[ns].info.representor &&
2505                                    !list[ns].info.master) {
2506                                 /*
2507                                  * Single IB device with
2508                                  * one physical port and
2509                                  * attached network device.
2510                                  * May be SRIOV is not enabled
2511                                  * or there is no representors.
2512                                  */
2513                                 DRV_LOG(INFO, "no E-Switch support detected");
2514                                 ns++;
2515                                 break;
2516                         }
2517                 }
2518                 if (!ns) {
2519                         DRV_LOG(ERR,
2520                                 "unable to recognize master/representors"
2521                                 " on the multiple IB devices");
2522                         rte_errno = ENOENT;
2523                         ret = -rte_errno;
2524                         goto exit;
2525                 }
2526                 /*
2527                  * New kernels may add the switch_id attribute for the case
2528                  * there is no E-Switch and we wrongly recognized the
2529                  * only device as master. Override this if there is the
2530                  * single device with single port and new device name
2531                  * format present.
2532                  */
2533                 if (nd == 1 &&
2534                     list[0].info.name_type == MLX5_PHYS_PORT_NAME_TYPE_UPLINK) {
2535                         list[0].info.master = 0;
2536                         list[0].info.representor = 0;
2537                 }
2538         }
2539         MLX5_ASSERT(ns);
2540         /*
2541          * Sort list to probe devices in natural order for users convenience
2542          * (i.e. master first, then representors from lowest to highest ID).
2543          */
2544         qsort(list, ns, sizeof(*list), mlx5_dev_spawn_data_cmp);
2545         /* Device specific configuration. */
2546         switch (pci_dev->id.device_id) {
2547         case PCI_DEVICE_ID_MELLANOX_CONNECTX4VF:
2548         case PCI_DEVICE_ID_MELLANOX_CONNECTX4LXVF:
2549         case PCI_DEVICE_ID_MELLANOX_CONNECTX5VF:
2550         case PCI_DEVICE_ID_MELLANOX_CONNECTX5EXVF:
2551         case PCI_DEVICE_ID_MELLANOX_CONNECTX5BFVF:
2552         case PCI_DEVICE_ID_MELLANOX_CONNECTX6VF:
2553         case PCI_DEVICE_ID_MELLANOX_CONNECTXVF:
2554                 dev_config_vf = 1;
2555                 break;
2556         default:
2557                 dev_config_vf = 0;
2558                 break;
2559         }
2560         if (eth_da.type != RTE_ETH_REPRESENTOR_NONE) {
2561                 /* Set devargs default values. */
2562                 if (eth_da.nb_mh_controllers == 0) {
2563                         eth_da.nb_mh_controllers = 1;
2564                         eth_da.mh_controllers[0] = 0;
2565                 }
2566                 if (eth_da.nb_ports == 0 && ns > 0) {
2567                         if (list[0].pf_bond >= 0 && list[0].info.representor)
2568                                 DRV_LOG(WARNING, "Representor on Bonding device should use pf#vf# syntax: %s",
2569                                         pci_dev->device.devargs->args);
2570                         eth_da.nb_ports = 1;
2571                         eth_da.ports[0] = list[0].info.pf_num;
2572                 }
2573                 if (eth_da.nb_representor_ports == 0) {
2574                         eth_da.nb_representor_ports = 1;
2575                         eth_da.representor_ports[0] = 0;
2576                 }
2577         }
2578         for (i = 0; i != ns; ++i) {
2579                 uint32_t restore;
2580
2581                 /* Default configuration. */
2582                 mlx5_os_config_default(&dev_config);
2583                 dev_config.vf = dev_config_vf;
2584                 list[i].eth_dev = mlx5_dev_spawn(cdev->dev, &list[i],
2585                                                  &dev_config, &eth_da);
2586                 if (!list[i].eth_dev) {
2587                         if (rte_errno != EBUSY && rte_errno != EEXIST)
2588                                 break;
2589                         /* Device is disabled or already spawned. Ignore it. */
2590                         continue;
2591                 }
2592                 restore = list[i].eth_dev->data->dev_flags;
2593                 rte_eth_copy_pci_info(list[i].eth_dev, pci_dev);
2594                 /**
2595                  * Each representor has a dedicated interrupts vector.
2596                  * rte_eth_copy_pci_info() assigns PF interrupts handle to
2597                  * representor eth_dev object because representor and PF
2598                  * share the same PCI address.
2599                  * Override representor device with a dedicated
2600                  * interrupts handle here.
2601                  * Representor interrupts handle is released in mlx5_dev_stop().
2602                  */
2603                 if (list[i].info.representor) {
2604                         struct rte_intr_handle *intr_handle;
2605                         intr_handle = mlx5_malloc(MLX5_MEM_SYS | MLX5_MEM_ZERO,
2606                                                   sizeof(*intr_handle), 0,
2607                                                   SOCKET_ID_ANY);
2608                         if (!intr_handle) {
2609                                 DRV_LOG(ERR,
2610                                         "port %u failed to allocate memory for interrupt handler "
2611                                         "Rx interrupts will not be supported",
2612                                         i);
2613                                 rte_errno = ENOMEM;
2614                                 ret = -rte_errno;
2615                                 goto exit;
2616                         }
2617                         list[i].eth_dev->intr_handle = intr_handle;
2618                 }
2619                 /* Restore non-PCI flags cleared by the above call. */
2620                 list[i].eth_dev->data->dev_flags |= restore;
2621                 rte_eth_dev_probing_finish(list[i].eth_dev);
2622         }
2623         if (i != ns) {
2624                 DRV_LOG(ERR,
2625                         "probe of PCI device " PCI_PRI_FMT " aborted after"
2626                         " encountering an error: %s",
2627                         owner_pci.domain, owner_pci.bus,
2628                         owner_pci.devid, owner_pci.function,
2629                         strerror(rte_errno));
2630                 ret = -rte_errno;
2631                 /* Roll back. */
2632                 while (i--) {
2633                         if (!list[i].eth_dev)
2634                                 continue;
2635                         mlx5_dev_close(list[i].eth_dev);
2636                         /* mac_addrs must not be freed because in dev_private */
2637                         list[i].eth_dev->data->mac_addrs = NULL;
2638                         claim_zero(rte_eth_dev_release_port(list[i].eth_dev));
2639                 }
2640                 /* Restore original error. */
2641                 rte_errno = -ret;
2642         } else {
2643                 ret = 0;
2644         }
2645 exit:
2646         /*
2647          * Do the routine cleanup:
2648          * - close opened Netlink sockets
2649          * - free allocated spawn data array
2650          * - free the Infiniband device list
2651          */
2652         if (nl_rdma >= 0)
2653                 close(nl_rdma);
2654         if (nl_route >= 0)
2655                 close(nl_route);
2656         if (list)
2657                 mlx5_free(list);
2658         MLX5_ASSERT(ibv_list);
2659         mlx5_glue->free_device_list(ibv_list);
2660         return ret;
2661 }
2662
2663 static int
2664 mlx5_os_parse_eth_devargs(struct rte_device *dev,
2665                           struct rte_eth_devargs *eth_da)
2666 {
2667         int ret = 0;
2668
2669         if (dev->devargs == NULL)
2670                 return 0;
2671         memset(eth_da, 0, sizeof(*eth_da));
2672         /* Parse representor information first from class argument. */
2673         if (dev->devargs->cls_str)
2674                 ret = rte_eth_devargs_parse(dev->devargs->cls_str, eth_da);
2675         if (ret != 0) {
2676                 DRV_LOG(ERR, "failed to parse device arguments: %s",
2677                         dev->devargs->cls_str);
2678                 return -rte_errno;
2679         }
2680         if (eth_da->type == RTE_ETH_REPRESENTOR_NONE) {
2681                 /* Parse legacy device argument */
2682                 ret = rte_eth_devargs_parse(dev->devargs->args, eth_da);
2683                 if (ret) {
2684                         DRV_LOG(ERR, "failed to parse device arguments: %s",
2685                                 dev->devargs->args);
2686                         return -rte_errno;
2687                 }
2688         }
2689         return 0;
2690 }
2691
2692 /**
2693  * Callback to register a PCI device.
2694  *
2695  * This function spawns Ethernet devices out of a given PCI device.
2696  *
2697  * @param[in] cdev
2698  *   Pointer to common mlx5 device structure.
2699  *
2700  * @return
2701  *   0 on success, a negative errno value otherwise and rte_errno is set.
2702  */
2703 static int
2704 mlx5_os_pci_probe(struct mlx5_common_device *cdev)
2705 {
2706         struct rte_pci_device *pci_dev = RTE_DEV_TO_PCI(cdev->dev);
2707         struct rte_eth_devargs eth_da = { .nb_ports = 0 };
2708         int ret = 0;
2709         uint16_t p;
2710
2711         ret = mlx5_os_parse_eth_devargs(cdev->dev, &eth_da);
2712         if (ret != 0)
2713                 return ret;
2714
2715         if (eth_da.nb_ports > 0) {
2716                 /* Iterate all port if devargs pf is range: "pf[0-1]vf[...]". */
2717                 for (p = 0; p < eth_da.nb_ports; p++) {
2718                         ret = mlx5_os_pci_probe_pf(cdev, &eth_da,
2719                                                    eth_da.ports[p]);
2720                         if (ret)
2721                                 break;
2722                 }
2723                 if (ret) {
2724                         DRV_LOG(ERR, "Probe of PCI device " PCI_PRI_FMT " "
2725                                 "aborted due to proding failure of PF %u",
2726                                 pci_dev->addr.domain, pci_dev->addr.bus,
2727                                 pci_dev->addr.devid, pci_dev->addr.function,
2728                                 eth_da.ports[p]);
2729                         mlx5_net_remove(cdev);
2730                 }
2731         } else {
2732                 ret = mlx5_os_pci_probe_pf(cdev, &eth_da, 0);
2733         }
2734         return ret;
2735 }
2736
2737 /* Probe a single SF device on auxiliary bus, no representor support. */
2738 static int
2739 mlx5_os_auxiliary_probe(struct mlx5_common_device *cdev)
2740 {
2741         struct rte_eth_devargs eth_da = { .nb_ports = 0 };
2742         struct mlx5_dev_config config;
2743         struct mlx5_dev_spawn_data spawn = { .pf_bond = -1 };
2744         struct rte_device *dev = cdev->dev;
2745         struct rte_auxiliary_device *adev = RTE_DEV_TO_AUXILIARY(dev);
2746         struct rte_eth_dev *eth_dev;
2747         int ret = 0;
2748
2749         /* Parse ethdev devargs. */
2750         ret = mlx5_os_parse_eth_devargs(dev, &eth_da);
2751         if (ret != 0)
2752                 return ret;
2753         /* Set default config data. */
2754         mlx5_os_config_default(&config);
2755         config.sf = 1;
2756         /* Init spawn data. */
2757         spawn.max_port = 1;
2758         spawn.phys_port = 1;
2759         spawn.phys_dev = mlx5_os_get_ibv_dev(dev);
2760         if (spawn.phys_dev == NULL)
2761                 return -rte_errno;
2762         ret = mlx5_auxiliary_get_ifindex(dev->name);
2763         if (ret < 0) {
2764                 DRV_LOG(ERR, "failed to get ethdev ifindex: %s", dev->name);
2765                 return ret;
2766         }
2767         spawn.ifindex = ret;
2768         spawn.cdev = cdev;
2769         /* Spawn device. */
2770         eth_dev = mlx5_dev_spawn(dev, &spawn, &config, &eth_da);
2771         if (eth_dev == NULL)
2772                 return -rte_errno;
2773         /* Post create. */
2774         eth_dev->intr_handle = &adev->intr_handle;
2775         if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
2776                 eth_dev->data->dev_flags |= RTE_ETH_DEV_INTR_LSC;
2777                 eth_dev->data->dev_flags |= RTE_ETH_DEV_INTR_RMV;
2778                 eth_dev->data->numa_node = dev->numa_node;
2779         }
2780         rte_eth_dev_probing_finish(eth_dev);
2781         return 0;
2782 }
2783
2784 /**
2785  * Net class driver callback to probe a device.
2786  *
2787  * This function probe PCI bus device(s) or a single SF on auxiliary bus.
2788  *
2789  * @param[in] cdev
2790  *   Pointer to the common mlx5 device.
2791  *
2792  * @return
2793  *   0 on success, a negative errno value otherwise and rte_errno is set.
2794  */
2795 int
2796 mlx5_os_net_probe(struct mlx5_common_device *cdev)
2797 {
2798         int ret;
2799
2800         if (rte_eal_process_type() == RTE_PROC_PRIMARY)
2801                 mlx5_pmd_socket_init();
2802         ret = mlx5_init_once();
2803         if (ret) {
2804                 DRV_LOG(ERR, "Unable to init PMD global data: %s",
2805                         strerror(rte_errno));
2806                 return -rte_errno;
2807         }
2808         if (mlx5_dev_is_pci(cdev->dev))
2809                 return mlx5_os_pci_probe(cdev);
2810         else
2811                 return mlx5_os_auxiliary_probe(cdev);
2812 }
2813
2814 static int
2815 mlx5_config_doorbell_mapping_env(const struct mlx5_common_dev_config *config)
2816 {
2817         char *env;
2818         int value;
2819
2820         MLX5_ASSERT(rte_eal_process_type() == RTE_PROC_PRIMARY);
2821         /* Get environment variable to store. */
2822         env = getenv(MLX5_SHUT_UP_BF);
2823         value = env ? !!strcmp(env, "0") : MLX5_ARG_UNSET;
2824         if (config->dbnc == MLX5_ARG_UNSET)
2825                 setenv(MLX5_SHUT_UP_BF, MLX5_SHUT_UP_BF_DEFAULT, 1);
2826         else
2827                 setenv(MLX5_SHUT_UP_BF,
2828                        config->dbnc == MLX5_TXDB_NCACHED ? "1" : "0", 1);
2829         return value;
2830 }
2831
2832 static void
2833 mlx5_restore_doorbell_mapping_env(int value)
2834 {
2835         MLX5_ASSERT(rte_eal_process_type() == RTE_PROC_PRIMARY);
2836         /* Restore the original environment variable state. */
2837         if (value == MLX5_ARG_UNSET)
2838                 unsetenv(MLX5_SHUT_UP_BF);
2839         else
2840                 setenv(MLX5_SHUT_UP_BF, value ? "1" : "0", 1);
2841 }
2842
2843 /**
2844  * Extract pdn of PD object using DV API.
2845  *
2846  * @param[in] pd
2847  *   Pointer to the verbs PD object.
2848  * @param[out] pdn
2849  *   Pointer to the PD object number variable.
2850  *
2851  * @return
2852  *   0 on success, error value otherwise.
2853  */
2854 int
2855 mlx5_os_get_pdn(void *pd, uint32_t *pdn)
2856 {
2857 #ifdef HAVE_IBV_FLOW_DV_SUPPORT
2858         struct mlx5dv_obj obj;
2859         struct mlx5dv_pd pd_info;
2860         int ret = 0;
2861
2862         obj.pd.in = pd;
2863         obj.pd.out = &pd_info;
2864         ret = mlx5_glue->dv_init_obj(&obj, MLX5DV_OBJ_PD);
2865         if (ret) {
2866                 DRV_LOG(DEBUG, "Fail to get PD object info");
2867                 return ret;
2868         }
2869         *pdn = pd_info.pdn;
2870         return 0;
2871 #else
2872         (void)pd;
2873         (void)pdn;
2874         return -ENOTSUP;
2875 #endif /* HAVE_IBV_FLOW_DV_SUPPORT */
2876 }
2877
2878 /**
2879  * Function API to open IB device.
2880  *
2881  * This function calls the Linux glue APIs to open a device.
2882  *
2883  * @param[in] spawn
2884  *   Pointer to the IB device attributes (name, port, etc).
2885  * @param[out] sh
2886  *   Pointer to shared context structure.
2887  *
2888  * @return
2889  *   0 on success, a positive error value otherwise.
2890  */
2891 int
2892 mlx5_os_open_device(const struct mlx5_dev_spawn_data *spawn,
2893                      struct mlx5_dev_ctx_shared *sh)
2894 {
2895         int dbmap_env;
2896         int err = 0;
2897
2898         pthread_mutex_init(&sh->txpp.mutex, NULL);
2899         /*
2900          * Configure environment variable "MLX5_BF_SHUT_UP"
2901          * before the device creation. The rdma_core library
2902          * checks the variable at device creation and
2903          * stores the result internally.
2904          */
2905         dbmap_env = mlx5_config_doorbell_mapping_env(&spawn->cdev->config);
2906         /* Try to open IB device with DV first, then usual Verbs. */
2907         errno = 0;
2908         sh->ctx = mlx5_glue->dv_open_device(spawn->phys_dev);
2909         if (sh->ctx) {
2910                 sh->devx = 1;
2911                 DRV_LOG(DEBUG, "DevX is supported");
2912                 /* The device is created, no need for environment. */
2913                 mlx5_restore_doorbell_mapping_env(dbmap_env);
2914         } else {
2915                 /* The environment variable is still configured. */
2916                 sh->ctx = mlx5_glue->open_device(spawn->phys_dev);
2917                 err = errno ? errno : ENODEV;
2918                 /*
2919                  * The environment variable is not needed anymore,
2920                  * all device creation attempts are completed.
2921                  */
2922                 mlx5_restore_doorbell_mapping_env(dbmap_env);
2923                 if (!sh->ctx)
2924                         return err;
2925                 DRV_LOG(DEBUG, "DevX is NOT supported");
2926                 err = 0;
2927         }
2928         if (!err && sh->ctx) {
2929                 /* Hint libmlx5 to use PMD allocator for data plane resources */
2930                 mlx5_glue->dv_set_context_attr(sh->ctx,
2931                         MLX5DV_CTX_ATTR_BUF_ALLOCATORS,
2932                         (void *)((uintptr_t)&(struct mlx5dv_ctx_allocators){
2933                                 .alloc = &mlx5_alloc_verbs_buf,
2934                                 .free = &mlx5_free_verbs_buf,
2935                                 .data = sh,
2936                         }));
2937         }
2938         return err;
2939 }
2940
2941 /**
2942  * Install shared asynchronous device events handler.
2943  * This function is implemented to support event sharing
2944  * between multiple ports of single IB device.
2945  *
2946  * @param sh
2947  *   Pointer to mlx5_dev_ctx_shared object.
2948  */
2949 void
2950 mlx5_os_dev_shared_handler_install(struct mlx5_dev_ctx_shared *sh)
2951 {
2952         int ret;
2953         int flags;
2954
2955         sh->intr_handle.fd = -1;
2956         flags = fcntl(((struct ibv_context *)sh->ctx)->async_fd, F_GETFL);
2957         ret = fcntl(((struct ibv_context *)sh->ctx)->async_fd,
2958                     F_SETFL, flags | O_NONBLOCK);
2959         if (ret) {
2960                 DRV_LOG(INFO, "failed to change file descriptor async event"
2961                         " queue");
2962         } else {
2963                 sh->intr_handle.fd = ((struct ibv_context *)sh->ctx)->async_fd;
2964                 sh->intr_handle.type = RTE_INTR_HANDLE_EXT;
2965                 if (rte_intr_callback_register(&sh->intr_handle,
2966                                         mlx5_dev_interrupt_handler, sh)) {
2967                         DRV_LOG(INFO, "Fail to install the shared interrupt.");
2968                         sh->intr_handle.fd = -1;
2969                 }
2970         }
2971         if (sh->devx) {
2972 #ifdef HAVE_IBV_DEVX_ASYNC
2973                 sh->intr_handle_devx.fd = -1;
2974                 sh->devx_comp =
2975                         (void *)mlx5_glue->devx_create_cmd_comp(sh->ctx);
2976                 struct mlx5dv_devx_cmd_comp *devx_comp = sh->devx_comp;
2977                 if (!devx_comp) {
2978                         DRV_LOG(INFO, "failed to allocate devx_comp.");
2979                         return;
2980                 }
2981                 flags = fcntl(devx_comp->fd, F_GETFL);
2982                 ret = fcntl(devx_comp->fd, F_SETFL, flags | O_NONBLOCK);
2983                 if (ret) {
2984                         DRV_LOG(INFO, "failed to change file descriptor"
2985                                 " devx comp");
2986                         return;
2987                 }
2988                 sh->intr_handle_devx.fd = devx_comp->fd;
2989                 sh->intr_handle_devx.type = RTE_INTR_HANDLE_EXT;
2990                 if (rte_intr_callback_register(&sh->intr_handle_devx,
2991                                         mlx5_dev_interrupt_handler_devx, sh)) {
2992                         DRV_LOG(INFO, "Fail to install the devx shared"
2993                                 " interrupt.");
2994                         sh->intr_handle_devx.fd = -1;
2995                 }
2996 #endif /* HAVE_IBV_DEVX_ASYNC */
2997         }
2998 }
2999
3000 /**
3001  * Uninstall shared asynchronous device events handler.
3002  * This function is implemented to support event sharing
3003  * between multiple ports of single IB device.
3004  *
3005  * @param dev
3006  *   Pointer to mlx5_dev_ctx_shared object.
3007  */
3008 void
3009 mlx5_os_dev_shared_handler_uninstall(struct mlx5_dev_ctx_shared *sh)
3010 {
3011         if (sh->intr_handle.fd >= 0)
3012                 mlx5_intr_callback_unregister(&sh->intr_handle,
3013                                               mlx5_dev_interrupt_handler, sh);
3014 #ifdef HAVE_IBV_DEVX_ASYNC
3015         if (sh->intr_handle_devx.fd >= 0)
3016                 rte_intr_callback_unregister(&sh->intr_handle_devx,
3017                                   mlx5_dev_interrupt_handler_devx, sh);
3018         if (sh->devx_comp)
3019                 mlx5_glue->devx_destroy_cmd_comp(sh->devx_comp);
3020 #endif
3021 }
3022
3023 /**
3024  * Read statistics by a named counter.
3025  *
3026  * @param[in] priv
3027  *   Pointer to the private device data structure.
3028  * @param[in] ctr_name
3029  *   Pointer to the name of the statistic counter to read
3030  * @param[out] stat
3031  *   Pointer to read statistic value.
3032  * @return
3033  *   0 on success and stat is valud, 1 if failed to read the value
3034  *   rte_errno is set.
3035  *
3036  */
3037 int
3038 mlx5_os_read_dev_stat(struct mlx5_priv *priv, const char *ctr_name,
3039                       uint64_t *stat)
3040 {
3041         int fd;
3042
3043         if (priv->sh) {
3044                 if (priv->q_counters != NULL &&
3045                     strcmp(ctr_name, "out_of_buffer") == 0)
3046                         return mlx5_devx_cmd_queue_counter_query
3047                                         (priv->q_counters, 0, (uint32_t *)stat);
3048                 MKSTR(path, "%s/ports/%d/hw_counters/%s",
3049                       priv->sh->ibdev_path,
3050                       priv->dev_port,
3051                       ctr_name);
3052                 fd = open(path, O_RDONLY);
3053                 /*
3054                  * in switchdev the file location is not per port
3055                  * but rather in <ibdev_path>/hw_counters/<file_name>.
3056                  */
3057                 if (fd == -1) {
3058                         MKSTR(path1, "%s/hw_counters/%s",
3059                               priv->sh->ibdev_path,
3060                               ctr_name);
3061                         fd = open(path1, O_RDONLY);
3062                 }
3063                 if (fd != -1) {
3064                         char buf[21] = {'\0'};
3065                         ssize_t n = read(fd, buf, sizeof(buf));
3066
3067                         close(fd);
3068                         if (n != -1) {
3069                                 *stat = strtoull(buf, NULL, 10);
3070                                 return 0;
3071                         }
3072                 }
3073         }
3074         *stat = 0;
3075         return 1;
3076 }
3077
3078 /**
3079  * Set the reg_mr and dereg_mr call backs
3080  *
3081  * @param reg_mr_cb[out]
3082  *   Pointer to reg_mr func
3083  * @param dereg_mr_cb[out]
3084  *   Pointer to dereg_mr func
3085  *
3086  */
3087 void
3088 mlx5_os_set_reg_mr_cb(mlx5_reg_mr_t *reg_mr_cb,
3089                       mlx5_dereg_mr_t *dereg_mr_cb)
3090 {
3091         *reg_mr_cb = mlx5_mr_verbs_ops.reg_mr;
3092         *dereg_mr_cb = mlx5_mr_verbs_ops.dereg_mr;
3093 }
3094
3095 /**
3096  * Remove a MAC address from device
3097  *
3098  * @param dev
3099  *   Pointer to Ethernet device structure.
3100  * @param index
3101  *   MAC address index.
3102  */
3103 void
3104 mlx5_os_mac_addr_remove(struct rte_eth_dev *dev, uint32_t index)
3105 {
3106         struct mlx5_priv *priv = dev->data->dev_private;
3107         const int vf = priv->config.vf;
3108
3109         if (vf)
3110                 mlx5_nl_mac_addr_remove(priv->nl_socket_route,
3111                                         mlx5_ifindex(dev), priv->mac_own,
3112                                         &dev->data->mac_addrs[index], index);
3113 }
3114
3115 /**
3116  * Adds a MAC address to the device
3117  *
3118  * @param dev
3119  *   Pointer to Ethernet device structure.
3120  * @param mac_addr
3121  *   MAC address to register.
3122  * @param index
3123  *   MAC address index.
3124  *
3125  * @return
3126  *   0 on success, a negative errno value otherwise
3127  */
3128 int
3129 mlx5_os_mac_addr_add(struct rte_eth_dev *dev, struct rte_ether_addr *mac,
3130                      uint32_t index)
3131 {
3132         struct mlx5_priv *priv = dev->data->dev_private;
3133         const int vf = priv->config.vf;
3134         int ret = 0;
3135
3136         if (vf)
3137                 ret = mlx5_nl_mac_addr_add(priv->nl_socket_route,
3138                                            mlx5_ifindex(dev), priv->mac_own,
3139                                            mac, index);
3140         return ret;
3141 }
3142
3143 /**
3144  * Modify a VF MAC address
3145  *
3146  * @param priv
3147  *   Pointer to device private data.
3148  * @param mac_addr
3149  *   MAC address to modify into.
3150  * @param iface_idx
3151  *   Net device interface index
3152  * @param vf_index
3153  *   VF index
3154  *
3155  * @return
3156  *   0 on success, a negative errno value otherwise
3157  */
3158 int
3159 mlx5_os_vf_mac_addr_modify(struct mlx5_priv *priv,
3160                            unsigned int iface_idx,
3161                            struct rte_ether_addr *mac_addr,
3162                            int vf_index)
3163 {
3164         return mlx5_nl_vf_mac_addr_modify
3165                 (priv->nl_socket_route, iface_idx, mac_addr, vf_index);
3166 }
3167
3168 /**
3169  * Set device promiscuous mode
3170  *
3171  * @param dev
3172  *   Pointer to Ethernet device structure.
3173  * @param enable
3174  *   0 - promiscuous is disabled, otherwise - enabled
3175  *
3176  * @return
3177  *   0 on success, a negative error value otherwise
3178  */
3179 int
3180 mlx5_os_set_promisc(struct rte_eth_dev *dev, int enable)
3181 {
3182         struct mlx5_priv *priv = dev->data->dev_private;
3183
3184         return mlx5_nl_promisc(priv->nl_socket_route,
3185                                mlx5_ifindex(dev), !!enable);
3186 }
3187
3188 /**
3189  * Set device promiscuous mode
3190  *
3191  * @param dev
3192  *   Pointer to Ethernet device structure.
3193  * @param enable
3194  *   0 - all multicase is disabled, otherwise - enabled
3195  *
3196  * @return
3197  *   0 on success, a negative error value otherwise
3198  */
3199 int
3200 mlx5_os_set_allmulti(struct rte_eth_dev *dev, int enable)
3201 {
3202         struct mlx5_priv *priv = dev->data->dev_private;
3203
3204         return mlx5_nl_allmulti(priv->nl_socket_route,
3205                                 mlx5_ifindex(dev), !!enable);
3206 }
3207
3208 /**
3209  * Flush device MAC addresses
3210  *
3211  * @param dev
3212  *   Pointer to Ethernet device structure.
3213  *
3214  */
3215 void
3216 mlx5_os_mac_addr_flush(struct rte_eth_dev *dev)
3217 {
3218         struct mlx5_priv *priv = dev->data->dev_private;
3219
3220         mlx5_nl_mac_addr_flush(priv->nl_socket_route, mlx5_ifindex(dev),
3221                                dev->data->mac_addrs,
3222                                MLX5_MAX_MAC_ADDRESSES, priv->mac_own);
3223 }