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