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