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