d017c23e8ad76a467ebd597fbf1c9b9412da16ef
[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 <rte_ethdev_driver.h>
20 #include <rte_ethdev_pci.h>
21 #include <rte_pci.h>
22 #include <rte_bus_pci.h>
23 #include <rte_common.h>
24 #include <rte_kvargs.h>
25 #include <rte_rwlock.h>
26 #include <rte_spinlock.h>
27 #include <rte_string_fns.h>
28 #include <rte_alarm.h>
29 #include <rte_eal_paging.h>
30
31 #include <mlx5_glue.h>
32 #include <mlx5_devx_cmds.h>
33 #include <mlx5_common.h>
34 #include <mlx5_common_mp.h>
35 #include <mlx5_common_mr.h>
36 #include <mlx5_malloc.h>
37
38 #include "mlx5_defs.h"
39 #include "mlx5.h"
40 #include "mlx5_common_os.h"
41 #include "mlx5_utils.h"
42 #include "mlx5_rxtx.h"
43 #include "mlx5_autoconf.h"
44 #include "mlx5_mr.h"
45 #include "mlx5_flow.h"
46 #include "rte_pmd_mlx5.h"
47 #include "mlx5_verbs.h"
48 #include "mlx5_nl.h"
49 #include "mlx5_devx.h"
50
51 #define MLX5_TAGS_HLIST_ARRAY_SIZE 8192
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 /**
71  * Set the completion channel file descriptor interrupt as non-blocking.
72  *
73  * @param[in] rxq_obj
74  *   Pointer to RQ channel object, which includes the channel fd
75  *
76  * @param[out] fd
77  *   The file descriptor (representing the intetrrupt) used in this channel.
78  *
79  * @return
80  *   0 on successfully setting the fd to non-blocking, non-zero otherwise.
81  */
82 int
83 mlx5_os_set_nonblock_channel_fd(int fd)
84 {
85         int flags;
86
87         flags = fcntl(fd, F_GETFL);
88         return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
89 }
90
91 /**
92  * Get mlx5 device attributes. The glue function query_device_ex() is called
93  * with out parameter of type 'struct ibv_device_attr_ex *'. Then fill in mlx5
94  * device attributes from the glue out parameter.
95  *
96  * @param dev
97  *   Pointer to ibv context.
98  *
99  * @param device_attr
100  *   Pointer to mlx5 device attributes.
101  *
102  * @return
103  *   0 on success, non zero error number otherwise
104  */
105 int
106 mlx5_os_get_dev_attr(void *ctx, struct mlx5_dev_attr *device_attr)
107 {
108         int err;
109         struct ibv_device_attr_ex attr_ex;
110         memset(device_attr, 0, sizeof(*device_attr));
111         err = mlx5_glue->query_device_ex(ctx, NULL, &attr_ex);
112         if (err)
113                 return err;
114
115         device_attr->device_cap_flags_ex = attr_ex.device_cap_flags_ex;
116         device_attr->max_qp_wr = attr_ex.orig_attr.max_qp_wr;
117         device_attr->max_sge = attr_ex.orig_attr.max_sge;
118         device_attr->max_cq = attr_ex.orig_attr.max_cq;
119         device_attr->max_qp = attr_ex.orig_attr.max_qp;
120         device_attr->raw_packet_caps = attr_ex.raw_packet_caps;
121         device_attr->max_rwq_indirection_table_size =
122                 attr_ex.rss_caps.max_rwq_indirection_table_size;
123         device_attr->max_tso = attr_ex.tso_caps.max_tso;
124         device_attr->tso_supported_qpts = attr_ex.tso_caps.supported_qpts;
125
126         struct mlx5dv_context dv_attr = { .comp_mask = 0 };
127         err = mlx5_glue->dv_query_device(ctx, &dv_attr);
128         if (err)
129                 return err;
130
131         device_attr->flags = dv_attr.flags;
132         device_attr->comp_mask = dv_attr.comp_mask;
133 #ifdef HAVE_IBV_MLX5_MOD_SWP
134         device_attr->sw_parsing_offloads =
135                 dv_attr.sw_parsing_caps.sw_parsing_offloads;
136 #endif
137         device_attr->min_single_stride_log_num_of_bytes =
138                 dv_attr.striding_rq_caps.min_single_stride_log_num_of_bytes;
139         device_attr->max_single_stride_log_num_of_bytes =
140                 dv_attr.striding_rq_caps.max_single_stride_log_num_of_bytes;
141         device_attr->min_single_wqe_log_num_of_strides =
142                 dv_attr.striding_rq_caps.min_single_wqe_log_num_of_strides;
143         device_attr->max_single_wqe_log_num_of_strides =
144                 dv_attr.striding_rq_caps.max_single_wqe_log_num_of_strides;
145         device_attr->stride_supported_qpts =
146                 dv_attr.striding_rq_caps.supported_qpts;
147 #ifdef HAVE_IBV_DEVICE_TUNNEL_SUPPORT
148         device_attr->tunnel_offloads_caps = dv_attr.tunnel_offloads_caps;
149 #endif
150
151         return err;
152 }
153
154 /**
155  * Verbs callback to allocate a memory. This function should allocate the space
156  * according to the size provided residing inside a huge page.
157  * Please note that all allocation must respect the alignment from libmlx5
158  * (i.e. currently rte_mem_page_size()).
159  *
160  * @param[in] size
161  *   The size in bytes of the memory to allocate.
162  * @param[in] data
163  *   A pointer to the callback data.
164  *
165  * @return
166  *   Allocated buffer, NULL otherwise and rte_errno is set.
167  */
168 static void *
169 mlx5_alloc_verbs_buf(size_t size, void *data)
170 {
171         struct mlx5_priv *priv = data;
172         void *ret;
173         unsigned int socket = SOCKET_ID_ANY;
174         size_t alignment = rte_mem_page_size();
175         if (alignment == (size_t)-1) {
176                 DRV_LOG(ERR, "Failed to get mem page size");
177                 rte_errno = ENOMEM;
178                 return NULL;
179         }
180
181         if (priv->verbs_alloc_ctx.type == MLX5_VERBS_ALLOC_TYPE_TX_QUEUE) {
182                 const struct mlx5_txq_ctrl *ctrl = priv->verbs_alloc_ctx.obj;
183
184                 socket = ctrl->socket;
185         } else if (priv->verbs_alloc_ctx.type ==
186                    MLX5_VERBS_ALLOC_TYPE_RX_QUEUE) {
187                 const struct mlx5_rxq_ctrl *ctrl = priv->verbs_alloc_ctx.obj;
188
189                 socket = ctrl->socket;
190         }
191         MLX5_ASSERT(data != NULL);
192         ret = mlx5_malloc(0, size, alignment, socket);
193         if (!ret && size)
194                 rte_errno = ENOMEM;
195         return ret;
196 }
197
198 /**
199  * Verbs callback to free a memory.
200  *
201  * @param[in] ptr
202  *   A pointer to the memory to free.
203  * @param[in] data
204  *   A pointer to the callback data.
205  */
206 static void
207 mlx5_free_verbs_buf(void *ptr, void *data __rte_unused)
208 {
209         MLX5_ASSERT(data != NULL);
210         mlx5_free(ptr);
211 }
212
213 /**
214  * Initialize DR related data within private structure.
215  * Routine checks the reference counter and does actual
216  * resources creation/initialization only if counter is zero.
217  *
218  * @param[in] priv
219  *   Pointer to the private device data structure.
220  *
221  * @return
222  *   Zero on success, positive error code otherwise.
223  */
224 static int
225 mlx5_alloc_shared_dr(struct mlx5_priv *priv)
226 {
227         struct mlx5_dev_ctx_shared *sh = priv->sh;
228         char s[MLX5_HLIST_NAMESIZE] __rte_unused;
229         int err;
230
231         MLX5_ASSERT(sh && sh->refcnt);
232         if (sh->refcnt > 1)
233                 return 0;
234         err = mlx5_alloc_table_hash_list(priv);
235         if (err)
236                 goto error;
237         /* The resources below are only valid with DV support. */
238 #ifdef HAVE_IBV_FLOW_DV_SUPPORT
239         /* Create tags hash list table. */
240         snprintf(s, sizeof(s), "%s_tags", sh->ibdev_name);
241         sh->tag_table = mlx5_hlist_create(s, MLX5_TAGS_HLIST_ARRAY_SIZE, 0,
242                                           MLX5_HLIST_WRITE_MOST,
243                                           flow_dv_tag_create_cb, NULL,
244                                           flow_dv_tag_remove_cb);
245         if (!sh->tag_table) {
246                 DRV_LOG(ERR, "tags with hash creation failed.");
247                 err = ENOMEM;
248                 goto error;
249         }
250         sh->tag_table->ctx = sh;
251         snprintf(s, sizeof(s), "%s_hdr_modify", sh->ibdev_name);
252         sh->modify_cmds = mlx5_hlist_create(s, MLX5_FLOW_HDR_MODIFY_HTABLE_SZ,
253                                             0, MLX5_HLIST_WRITE_MOST |
254                                             MLX5_HLIST_DIRECT_KEY,
255                                             flow_dv_modify_create_cb,
256                                             flow_dv_modify_match_cb,
257                                             flow_dv_modify_remove_cb);
258         if (!sh->modify_cmds) {
259                 DRV_LOG(ERR, "hdr modify hash creation failed");
260                 err = ENOMEM;
261                 goto error;
262         }
263         sh->modify_cmds->ctx = sh;
264         snprintf(s, sizeof(s), "%s_encaps_decaps", sh->ibdev_name);
265         sh->encaps_decaps = mlx5_hlist_create(s,
266                                               MLX5_FLOW_ENCAP_DECAP_HTABLE_SZ,
267                                               0, MLX5_HLIST_DIRECT_KEY |
268                                               MLX5_HLIST_WRITE_MOST,
269                                               flow_dv_encap_decap_create_cb,
270                                               flow_dv_encap_decap_match_cb,
271                                               flow_dv_encap_decap_remove_cb);
272         if (!sh->encaps_decaps) {
273                 DRV_LOG(ERR, "encap decap hash creation failed");
274                 err = ENOMEM;
275                 goto error;
276         }
277         sh->encaps_decaps->ctx = sh;
278 #endif
279 #ifdef HAVE_MLX5DV_DR
280         void *domain;
281
282         /* Reference counter is zero, we should initialize structures. */
283         domain = mlx5_glue->dr_create_domain(sh->ctx,
284                                              MLX5DV_DR_DOMAIN_TYPE_NIC_RX);
285         if (!domain) {
286                 DRV_LOG(ERR, "ingress mlx5dv_dr_create_domain failed");
287                 err = errno;
288                 goto error;
289         }
290         sh->rx_domain = domain;
291         domain = mlx5_glue->dr_create_domain(sh->ctx,
292                                              MLX5DV_DR_DOMAIN_TYPE_NIC_TX);
293         if (!domain) {
294                 DRV_LOG(ERR, "egress mlx5dv_dr_create_domain failed");
295                 err = errno;
296                 goto error;
297         }
298         pthread_mutex_init(&sh->dv_mutex, NULL);
299         sh->tx_domain = domain;
300 #ifdef HAVE_MLX5DV_DR_ESWITCH
301         if (priv->config.dv_esw_en) {
302                 domain  = mlx5_glue->dr_create_domain
303                         (sh->ctx, MLX5DV_DR_DOMAIN_TYPE_FDB);
304                 if (!domain) {
305                         DRV_LOG(ERR, "FDB mlx5dv_dr_create_domain failed");
306                         err = errno;
307                         goto error;
308                 }
309                 sh->fdb_domain = domain;
310                 sh->esw_drop_action = mlx5_glue->dr_create_flow_action_drop();
311         }
312 #endif
313         if (!sh->tunnel_hub)
314                 err = mlx5_alloc_tunnel_hub(sh);
315         if (err) {
316                 DRV_LOG(ERR, "mlx5_alloc_tunnel_hub failed err=%d", err);
317                 goto error;
318         }
319         if (priv->config.reclaim_mode == MLX5_RCM_AGGR) {
320                 mlx5_glue->dr_reclaim_domain_memory(sh->rx_domain, 1);
321                 mlx5_glue->dr_reclaim_domain_memory(sh->tx_domain, 1);
322                 if (sh->fdb_domain)
323                         mlx5_glue->dr_reclaim_domain_memory(sh->fdb_domain, 1);
324         }
325         sh->pop_vlan_action = mlx5_glue->dr_create_flow_action_pop_vlan();
326 #endif /* HAVE_MLX5DV_DR */
327         sh->default_miss_action =
328                         mlx5_glue->dr_create_flow_action_default_miss();
329         if (!sh->default_miss_action)
330                 DRV_LOG(WARNING, "Default miss action is not supported.");
331         return 0;
332 error:
333         /* Rollback the created objects. */
334         if (sh->rx_domain) {
335                 mlx5_glue->dr_destroy_domain(sh->rx_domain);
336                 sh->rx_domain = NULL;
337         }
338         if (sh->tx_domain) {
339                 mlx5_glue->dr_destroy_domain(sh->tx_domain);
340                 sh->tx_domain = NULL;
341         }
342         if (sh->fdb_domain) {
343                 mlx5_glue->dr_destroy_domain(sh->fdb_domain);
344                 sh->fdb_domain = NULL;
345         }
346         if (sh->esw_drop_action) {
347                 mlx5_glue->destroy_flow_action(sh->esw_drop_action);
348                 sh->esw_drop_action = NULL;
349         }
350         if (sh->pop_vlan_action) {
351                 mlx5_glue->destroy_flow_action(sh->pop_vlan_action);
352                 sh->pop_vlan_action = NULL;
353         }
354         if (sh->encaps_decaps) {
355                 mlx5_hlist_destroy(sh->encaps_decaps);
356                 sh->encaps_decaps = NULL;
357         }
358         if (sh->modify_cmds) {
359                 mlx5_hlist_destroy(sh->modify_cmds);
360                 sh->modify_cmds = NULL;
361         }
362         if (sh->tag_table) {
363                 /* tags should be destroyed with flow before. */
364                 mlx5_hlist_destroy(sh->tag_table);
365                 sh->tag_table = NULL;
366         }
367         if (sh->tunnel_hub) {
368                 mlx5_release_tunnel_hub(sh, priv->dev_port);
369                 sh->tunnel_hub = NULL;
370         }
371         mlx5_free_table_hash_list(priv);
372         return err;
373 }
374
375 /**
376  * Destroy DR related data within private structure.
377  *
378  * @param[in] priv
379  *   Pointer to the private device data structure.
380  */
381 void
382 mlx5_os_free_shared_dr(struct mlx5_priv *priv)
383 {
384         struct mlx5_dev_ctx_shared *sh = priv->sh;
385
386         MLX5_ASSERT(sh && sh->refcnt);
387         if (sh->refcnt > 1)
388                 return;
389 #ifdef HAVE_MLX5DV_DR
390         if (sh->rx_domain) {
391                 mlx5_glue->dr_destroy_domain(sh->rx_domain);
392                 sh->rx_domain = NULL;
393         }
394         if (sh->tx_domain) {
395                 mlx5_glue->dr_destroy_domain(sh->tx_domain);
396                 sh->tx_domain = NULL;
397         }
398 #ifdef HAVE_MLX5DV_DR_ESWITCH
399         if (sh->fdb_domain) {
400                 mlx5_glue->dr_destroy_domain(sh->fdb_domain);
401                 sh->fdb_domain = NULL;
402         }
403         if (sh->esw_drop_action) {
404                 mlx5_glue->destroy_flow_action(sh->esw_drop_action);
405                 sh->esw_drop_action = NULL;
406         }
407 #endif
408         if (sh->pop_vlan_action) {
409                 mlx5_glue->destroy_flow_action(sh->pop_vlan_action);
410                 sh->pop_vlan_action = NULL;
411         }
412         pthread_mutex_destroy(&sh->dv_mutex);
413 #endif /* HAVE_MLX5DV_DR */
414         if (sh->default_miss_action)
415                 mlx5_glue->destroy_flow_action
416                                 (sh->default_miss_action);
417         if (sh->encaps_decaps) {
418                 mlx5_hlist_destroy(sh->encaps_decaps);
419                 sh->encaps_decaps = NULL;
420         }
421         if (sh->modify_cmds) {
422                 mlx5_hlist_destroy(sh->modify_cmds);
423                 sh->modify_cmds = NULL;
424         }
425         if (sh->tag_table) {
426                 /* tags should be destroyed with flow before. */
427                 mlx5_hlist_destroy(sh->tag_table);
428                 sh->tag_table = NULL;
429         }
430         if (sh->tunnel_hub) {
431                 mlx5_release_tunnel_hub(sh, priv->dev_port);
432                 sh->tunnel_hub = NULL;
433         }
434         mlx5_free_table_hash_list(priv);
435 }
436
437 /**
438  * Initialize shared data between primary and secondary process.
439  *
440  * A memzone is reserved by primary process and secondary processes attach to
441  * the memzone.
442  *
443  * @return
444  *   0 on success, a negative errno value otherwise and rte_errno is set.
445  */
446 static int
447 mlx5_init_shared_data(void)
448 {
449         const struct rte_memzone *mz;
450         int ret = 0;
451
452         rte_spinlock_lock(&mlx5_shared_data_lock);
453         if (mlx5_shared_data == NULL) {
454                 if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
455                         /* Allocate shared memory. */
456                         mz = rte_memzone_reserve(MZ_MLX5_PMD_SHARED_DATA,
457                                                  sizeof(*mlx5_shared_data),
458                                                  SOCKET_ID_ANY, 0);
459                         if (mz == NULL) {
460                                 DRV_LOG(ERR,
461                                         "Cannot allocate mlx5 shared data");
462                                 ret = -rte_errno;
463                                 goto error;
464                         }
465                         mlx5_shared_data = mz->addr;
466                         memset(mlx5_shared_data, 0, sizeof(*mlx5_shared_data));
467                         rte_spinlock_init(&mlx5_shared_data->lock);
468                 } else {
469                         /* Lookup allocated shared memory. */
470                         mz = rte_memzone_lookup(MZ_MLX5_PMD_SHARED_DATA);
471                         if (mz == NULL) {
472                                 DRV_LOG(ERR,
473                                         "Cannot attach mlx5 shared data");
474                                 ret = -rte_errno;
475                                 goto error;
476                         }
477                         mlx5_shared_data = mz->addr;
478                         memset(&mlx5_local_data, 0, sizeof(mlx5_local_data));
479                 }
480         }
481 error:
482         rte_spinlock_unlock(&mlx5_shared_data_lock);
483         return ret;
484 }
485
486 /**
487  * PMD global initialization.
488  *
489  * Independent from individual device, this function initializes global
490  * per-PMD data structures distinguishing primary and secondary processes.
491  * Hence, each initialization is called once per a process.
492  *
493  * @return
494  *   0 on success, a negative errno value otherwise and rte_errno is set.
495  */
496 static int
497 mlx5_init_once(void)
498 {
499         struct mlx5_shared_data *sd;
500         struct mlx5_local_data *ld = &mlx5_local_data;
501         int ret = 0;
502
503         if (mlx5_init_shared_data())
504                 return -rte_errno;
505         sd = mlx5_shared_data;
506         MLX5_ASSERT(sd);
507         rte_spinlock_lock(&sd->lock);
508         switch (rte_eal_process_type()) {
509         case RTE_PROC_PRIMARY:
510                 if (sd->init_done)
511                         break;
512                 LIST_INIT(&sd->mem_event_cb_list);
513                 rte_rwlock_init(&sd->mem_event_rwlock);
514                 rte_mem_event_callback_register("MLX5_MEM_EVENT_CB",
515                                                 mlx5_mr_mem_event_cb, NULL);
516                 ret = mlx5_mp_init_primary(MLX5_MP_NAME,
517                                            mlx5_mp_os_primary_handle);
518                 if (ret)
519                         goto out;
520                 sd->init_done = true;
521                 break;
522         case RTE_PROC_SECONDARY:
523                 if (ld->init_done)
524                         break;
525                 ret = mlx5_mp_init_secondary(MLX5_MP_NAME,
526                                              mlx5_mp_os_secondary_handle);
527                 if (ret)
528                         goto out;
529                 ++sd->secondary_cnt;
530                 ld->init_done = true;
531                 break;
532         default:
533                 break;
534         }
535 out:
536         rte_spinlock_unlock(&sd->lock);
537         return ret;
538 }
539
540 /**
541  * Create the Tx queue DevX/Verbs object.
542  *
543  * @param dev
544  *   Pointer to Ethernet device.
545  * @param idx
546  *   Queue index in DPDK Tx queue array.
547  *
548  * @return
549  *   0 on success, a negative errno value otherwise and rte_errno is set.
550  */
551 static int
552 mlx5_os_txq_obj_new(struct rte_eth_dev *dev, uint16_t idx)
553 {
554         struct mlx5_priv *priv = dev->data->dev_private;
555         struct mlx5_txq_data *txq_data = (*priv->txqs)[idx];
556         struct mlx5_txq_ctrl *txq_ctrl =
557                         container_of(txq_data, struct mlx5_txq_ctrl, txq);
558
559         if (txq_ctrl->type == MLX5_TXQ_TYPE_HAIRPIN)
560                 return mlx5_txq_devx_obj_new(dev, idx);
561 #ifdef HAVE_MLX5DV_DEVX_UAR_OFFSET
562         if (!priv->config.dv_esw_en)
563                 return mlx5_txq_devx_obj_new(dev, idx);
564 #endif
565         return mlx5_txq_ibv_obj_new(dev, idx);
566 }
567
568 /**
569  * Release an Tx DevX/verbs queue object.
570  *
571  * @param txq_obj
572  *   DevX/Verbs Tx queue object.
573  */
574 static void
575 mlx5_os_txq_obj_release(struct mlx5_txq_obj *txq_obj)
576 {
577         if (txq_obj->txq_ctrl->type == MLX5_TXQ_TYPE_HAIRPIN) {
578                 mlx5_txq_devx_obj_release(txq_obj);
579                 return;
580         }
581 #ifdef HAVE_MLX5DV_DEVX_UAR_OFFSET
582         if (!txq_obj->txq_ctrl->priv->config.dv_esw_en) {
583                 mlx5_txq_devx_obj_release(txq_obj);
584                 return;
585         }
586 #endif
587         mlx5_txq_ibv_obj_release(txq_obj);
588 }
589
590 /**
591  * DV flow counter mode detect and config.
592  *
593  * @param dev
594  *   Pointer to rte_eth_dev structure.
595  *
596  */
597 static void
598 mlx5_flow_counter_mode_config(struct rte_eth_dev *dev __rte_unused)
599 {
600 #ifdef HAVE_IBV_FLOW_DV_SUPPORT
601         struct mlx5_priv *priv = dev->data->dev_private;
602         struct mlx5_dev_ctx_shared *sh = priv->sh;
603         bool fallback;
604
605 #ifndef HAVE_IBV_DEVX_ASYNC
606         fallback = true;
607 #else
608         fallback = false;
609         if (!priv->config.devx || !priv->config.dv_flow_en ||
610             !priv->config.hca_attr.flow_counters_dump ||
611             !(priv->config.hca_attr.flow_counter_bulk_alloc_bitmap & 0x4) ||
612             (mlx5_flow_dv_discover_counter_offset_support(dev) == -ENOTSUP))
613                 fallback = true;
614 #endif
615         if (fallback)
616                 DRV_LOG(INFO, "Use fall-back DV counter management. Flow "
617                         "counter dump:%d, bulk_alloc_bitmap:0x%hhx.",
618                         priv->config.hca_attr.flow_counters_dump,
619                         priv->config.hca_attr.flow_counter_bulk_alloc_bitmap);
620         /* Initialize fallback mode only on the port initializes sh. */
621         if (sh->refcnt == 1)
622                 sh->cmng.counter_fallback = fallback;
623         else if (fallback != sh->cmng.counter_fallback)
624                 DRV_LOG(WARNING, "Port %d in sh has different fallback mode "
625                         "with others:%d.", PORT_ID(priv), fallback);
626 #endif
627 }
628
629 /**
630  * Spawn an Ethernet device from Verbs information.
631  *
632  * @param dpdk_dev
633  *   Backing DPDK device.
634  * @param spawn
635  *   Verbs device parameters (name, port, switch_info) to spawn.
636  * @param config
637  *   Device configuration parameters.
638  *
639  * @return
640  *   A valid Ethernet device object on success, NULL otherwise and rte_errno
641  *   is set. The following errors are defined:
642  *
643  *   EBUSY: device is not supposed to be spawned.
644  *   EEXIST: device is already spawned
645  */
646 static struct rte_eth_dev *
647 mlx5_dev_spawn(struct rte_device *dpdk_dev,
648                struct mlx5_dev_spawn_data *spawn,
649                struct mlx5_dev_config *config)
650 {
651         const struct mlx5_switch_info *switch_info = &spawn->info;
652         struct mlx5_dev_ctx_shared *sh = NULL;
653         struct ibv_port_attr port_attr;
654         struct mlx5dv_context dv_attr = { .comp_mask = 0 };
655         struct rte_eth_dev *eth_dev = NULL;
656         struct mlx5_priv *priv = NULL;
657         int err = 0;
658         unsigned int hw_padding = 0;
659         unsigned int mps;
660         unsigned int cqe_comp;
661         unsigned int cqe_pad = 0;
662         unsigned int tunnel_en = 0;
663         unsigned int mpls_en = 0;
664         unsigned int swp = 0;
665         unsigned int mprq = 0;
666         unsigned int mprq_min_stride_size_n = 0;
667         unsigned int mprq_max_stride_size_n = 0;
668         unsigned int mprq_min_stride_num_n = 0;
669         unsigned int mprq_max_stride_num_n = 0;
670         struct rte_ether_addr mac;
671         char name[RTE_ETH_NAME_MAX_LEN];
672         int own_domain_id = 0;
673         uint16_t port_id;
674         unsigned int i;
675 #ifdef HAVE_MLX5DV_DR_DEVX_PORT
676         struct mlx5dv_devx_port devx_port = { .comp_mask = 0 };
677 #endif
678
679         /* Determine if this port representor is supposed to be spawned. */
680         if (switch_info->representor && dpdk_dev->devargs) {
681                 struct rte_eth_devargs eth_da;
682
683                 err = rte_eth_devargs_parse(dpdk_dev->devargs->args, &eth_da);
684                 if (err) {
685                         rte_errno = -err;
686                         DRV_LOG(ERR, "failed to process device arguments: %s",
687                                 strerror(rte_errno));
688                         return NULL;
689                 }
690                 for (i = 0; i < eth_da.nb_representor_ports; ++i)
691                         if (eth_da.representor_ports[i] ==
692                             (uint16_t)switch_info->port_name)
693                                 break;
694                 if (i == eth_da.nb_representor_ports) {
695                         rte_errno = EBUSY;
696                         return NULL;
697                 }
698         }
699         /* Build device name. */
700         if (spawn->pf_bond <  0) {
701                 /* Single device. */
702                 if (!switch_info->representor)
703                         strlcpy(name, dpdk_dev->name, sizeof(name));
704                 else
705                         snprintf(name, sizeof(name), "%s_representor_%u",
706                                  dpdk_dev->name, switch_info->port_name);
707         } else {
708                 /* Bonding device. */
709                 if (!switch_info->representor)
710                         snprintf(name, sizeof(name), "%s_%s",
711                                  dpdk_dev->name,
712                                  mlx5_os_get_dev_device_name(spawn->phys_dev));
713                 else
714                         snprintf(name, sizeof(name), "%s_%s_representor_%u",
715                                  dpdk_dev->name,
716                                  mlx5_os_get_dev_device_name(spawn->phys_dev),
717                                  switch_info->port_name);
718         }
719         /* check if the device is already spawned */
720         if (rte_eth_dev_get_port_by_name(name, &port_id) == 0) {
721                 rte_errno = EEXIST;
722                 return NULL;
723         }
724         DRV_LOG(DEBUG, "naming Ethernet device \"%s\"", name);
725         if (rte_eal_process_type() == RTE_PROC_SECONDARY) {
726                 struct mlx5_mp_id mp_id;
727
728                 eth_dev = rte_eth_dev_attach_secondary(name);
729                 if (eth_dev == NULL) {
730                         DRV_LOG(ERR, "can not attach rte ethdev");
731                         rte_errno = ENOMEM;
732                         return NULL;
733                 }
734                 eth_dev->device = dpdk_dev;
735                 eth_dev->dev_ops = &mlx5_os_dev_sec_ops;
736                 eth_dev->rx_descriptor_status = mlx5_rx_descriptor_status;
737                 eth_dev->tx_descriptor_status = mlx5_tx_descriptor_status;
738                 err = mlx5_proc_priv_init(eth_dev);
739                 if (err)
740                         return NULL;
741                 mp_id.port_id = eth_dev->data->port_id;
742                 strlcpy(mp_id.name, MLX5_MP_NAME, RTE_MP_MAX_NAME_LEN);
743                 /* Receive command fd from primary process */
744                 err = mlx5_mp_req_verbs_cmd_fd(&mp_id);
745                 if (err < 0)
746                         goto err_secondary;
747                 /* Remap UAR for Tx queues. */
748                 err = mlx5_tx_uar_init_secondary(eth_dev, err);
749                 if (err)
750                         goto err_secondary;
751                 /*
752                  * Ethdev pointer is still required as input since
753                  * the primary device is not accessible from the
754                  * secondary process.
755                  */
756                 eth_dev->rx_pkt_burst = mlx5_select_rx_function(eth_dev);
757                 eth_dev->tx_pkt_burst = mlx5_select_tx_function(eth_dev);
758                 return eth_dev;
759 err_secondary:
760                 mlx5_dev_close(eth_dev);
761                 return NULL;
762         }
763         /*
764          * Some parameters ("tx_db_nc" in particularly) are needed in
765          * advance to create dv/verbs device context. We proceed the
766          * devargs here to get ones, and later proceed devargs again
767          * to override some hardware settings.
768          */
769         err = mlx5_args(config, dpdk_dev->devargs);
770         if (err) {
771                 err = rte_errno;
772                 DRV_LOG(ERR, "failed to process device arguments: %s",
773                         strerror(rte_errno));
774                 goto error;
775         }
776         if (config->dv_miss_info) {
777                 if (switch_info->master || switch_info->representor)
778                         config->dv_xmeta_en = MLX5_XMETA_MODE_META16;
779         }
780         mlx5_malloc_mem_select(config->sys_mem_en);
781         sh = mlx5_alloc_shared_dev_ctx(spawn, config);
782         if (!sh)
783                 return NULL;
784         config->devx = sh->devx;
785 #ifdef HAVE_MLX5DV_DR_ACTION_DEST_DEVX_TIR
786         config->dest_tir = 1;
787 #endif
788 #ifdef HAVE_IBV_MLX5_MOD_SWP
789         dv_attr.comp_mask |= MLX5DV_CONTEXT_MASK_SWP;
790 #endif
791         /*
792          * Multi-packet send is supported by ConnectX-4 Lx PF as well
793          * as all ConnectX-5 devices.
794          */
795 #ifdef HAVE_IBV_DEVICE_TUNNEL_SUPPORT
796         dv_attr.comp_mask |= MLX5DV_CONTEXT_MASK_TUNNEL_OFFLOADS;
797 #endif
798 #ifdef HAVE_IBV_DEVICE_STRIDING_RQ_SUPPORT
799         dv_attr.comp_mask |= MLX5DV_CONTEXT_MASK_STRIDING_RQ;
800 #endif
801         mlx5_glue->dv_query_device(sh->ctx, &dv_attr);
802         if (dv_attr.flags & MLX5DV_CONTEXT_FLAGS_MPW_ALLOWED) {
803                 if (dv_attr.flags & MLX5DV_CONTEXT_FLAGS_ENHANCED_MPW) {
804                         DRV_LOG(DEBUG, "enhanced MPW is supported");
805                         mps = MLX5_MPW_ENHANCED;
806                 } else {
807                         DRV_LOG(DEBUG, "MPW is supported");
808                         mps = MLX5_MPW;
809                 }
810         } else {
811                 DRV_LOG(DEBUG, "MPW isn't supported");
812                 mps = MLX5_MPW_DISABLED;
813         }
814 #ifdef HAVE_IBV_MLX5_MOD_SWP
815         if (dv_attr.comp_mask & MLX5DV_CONTEXT_MASK_SWP)
816                 swp = dv_attr.sw_parsing_caps.sw_parsing_offloads;
817         DRV_LOG(DEBUG, "SWP support: %u", swp);
818 #endif
819         config->swp = !!swp;
820 #ifdef HAVE_IBV_DEVICE_STRIDING_RQ_SUPPORT
821         if (dv_attr.comp_mask & MLX5DV_CONTEXT_MASK_STRIDING_RQ) {
822                 struct mlx5dv_striding_rq_caps mprq_caps =
823                         dv_attr.striding_rq_caps;
824
825                 DRV_LOG(DEBUG, "\tmin_single_stride_log_num_of_bytes: %d",
826                         mprq_caps.min_single_stride_log_num_of_bytes);
827                 DRV_LOG(DEBUG, "\tmax_single_stride_log_num_of_bytes: %d",
828                         mprq_caps.max_single_stride_log_num_of_bytes);
829                 DRV_LOG(DEBUG, "\tmin_single_wqe_log_num_of_strides: %d",
830                         mprq_caps.min_single_wqe_log_num_of_strides);
831                 DRV_LOG(DEBUG, "\tmax_single_wqe_log_num_of_strides: %d",
832                         mprq_caps.max_single_wqe_log_num_of_strides);
833                 DRV_LOG(DEBUG, "\tsupported_qpts: %d",
834                         mprq_caps.supported_qpts);
835                 DRV_LOG(DEBUG, "device supports Multi-Packet RQ");
836                 mprq = 1;
837                 mprq_min_stride_size_n =
838                         mprq_caps.min_single_stride_log_num_of_bytes;
839                 mprq_max_stride_size_n =
840                         mprq_caps.max_single_stride_log_num_of_bytes;
841                 mprq_min_stride_num_n =
842                         mprq_caps.min_single_wqe_log_num_of_strides;
843                 mprq_max_stride_num_n =
844                         mprq_caps.max_single_wqe_log_num_of_strides;
845         }
846 #endif
847         if (RTE_CACHE_LINE_SIZE == 128 &&
848             !(dv_attr.flags & MLX5DV_CONTEXT_FLAGS_CQE_128B_COMP))
849                 cqe_comp = 0;
850         else
851                 cqe_comp = 1;
852         config->cqe_comp = cqe_comp;
853 #ifdef HAVE_IBV_MLX5_MOD_CQE_128B_PAD
854         /* Whether device supports 128B Rx CQE padding. */
855         cqe_pad = RTE_CACHE_LINE_SIZE == 128 &&
856                   (dv_attr.flags & MLX5DV_CONTEXT_FLAGS_CQE_128B_PAD);
857 #endif
858 #ifdef HAVE_IBV_DEVICE_TUNNEL_SUPPORT
859         if (dv_attr.comp_mask & MLX5DV_CONTEXT_MASK_TUNNEL_OFFLOADS) {
860                 tunnel_en = ((dv_attr.tunnel_offloads_caps &
861                               MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_VXLAN) &&
862                              (dv_attr.tunnel_offloads_caps &
863                               MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_GRE) &&
864                              (dv_attr.tunnel_offloads_caps &
865                               MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_GENEVE));
866         }
867         DRV_LOG(DEBUG, "tunnel offloading is %ssupported",
868                 tunnel_en ? "" : "not ");
869 #else
870         DRV_LOG(WARNING,
871                 "tunnel offloading disabled due to old OFED/rdma-core version");
872 #endif
873         config->tunnel_en = tunnel_en;
874 #ifdef HAVE_IBV_DEVICE_MPLS_SUPPORT
875         mpls_en = ((dv_attr.tunnel_offloads_caps &
876                     MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_CW_MPLS_OVER_GRE) &&
877                    (dv_attr.tunnel_offloads_caps &
878                     MLX5DV_RAW_PACKET_CAP_TUNNELED_OFFLOAD_CW_MPLS_OVER_UDP));
879         DRV_LOG(DEBUG, "MPLS over GRE/UDP tunnel offloading is %ssupported",
880                 mpls_en ? "" : "not ");
881 #else
882         DRV_LOG(WARNING, "MPLS over GRE/UDP tunnel offloading disabled due to"
883                 " old OFED/rdma-core version or firmware configuration");
884 #endif
885         config->mpls_en = mpls_en;
886         /* Check port status. */
887         err = mlx5_glue->query_port(sh->ctx, spawn->phys_port, &port_attr);
888         if (err) {
889                 DRV_LOG(ERR, "port query failed: %s", strerror(err));
890                 goto error;
891         }
892         if (port_attr.link_layer != IBV_LINK_LAYER_ETHERNET) {
893                 DRV_LOG(ERR, "port is not configured in Ethernet mode");
894                 err = EINVAL;
895                 goto error;
896         }
897         if (port_attr.state != IBV_PORT_ACTIVE)
898                 DRV_LOG(DEBUG, "port is not active: \"%s\" (%d)",
899                         mlx5_glue->port_state_str(port_attr.state),
900                         port_attr.state);
901         /* Allocate private eth device data. */
902         priv = mlx5_malloc(MLX5_MEM_ZERO | MLX5_MEM_RTE,
903                            sizeof(*priv),
904                            RTE_CACHE_LINE_SIZE, SOCKET_ID_ANY);
905         if (priv == NULL) {
906                 DRV_LOG(ERR, "priv allocation failure");
907                 err = ENOMEM;
908                 goto error;
909         }
910         priv->sh = sh;
911         priv->dev_port = spawn->phys_port;
912         priv->pci_dev = spawn->pci_dev;
913         priv->mtu = RTE_ETHER_MTU;
914         priv->mp_id.port_id = port_id;
915         strlcpy(priv->mp_id.name, MLX5_MP_NAME, RTE_MP_MAX_NAME_LEN);
916         /* Some internal functions rely on Netlink sockets, open them now. */
917         priv->nl_socket_rdma = mlx5_nl_init(NETLINK_RDMA);
918         priv->nl_socket_route = mlx5_nl_init(NETLINK_ROUTE);
919         priv->representor = !!switch_info->representor;
920         priv->master = !!switch_info->master;
921         priv->domain_id = RTE_ETH_DEV_SWITCH_DOMAIN_ID_INVALID;
922         priv->vport_meta_tag = 0;
923         priv->vport_meta_mask = 0;
924         priv->pf_bond = spawn->pf_bond;
925 #ifdef HAVE_MLX5DV_DR_DEVX_PORT
926         /*
927          * The DevX port query API is implemented. E-Switch may use
928          * either vport or reg_c[0] metadata register to match on
929          * vport index. The engaged part of metadata register is
930          * defined by mask.
931          */
932         if (switch_info->representor || switch_info->master) {
933                 devx_port.comp_mask = MLX5DV_DEVX_PORT_VPORT |
934                                       MLX5DV_DEVX_PORT_MATCH_REG_C_0;
935                 err = mlx5_glue->devx_port_query(sh->ctx, spawn->phys_port,
936                                                  &devx_port);
937                 if (err) {
938                         DRV_LOG(WARNING,
939                                 "can't query devx port %d on device %s",
940                                 spawn->phys_port,
941                                 mlx5_os_get_dev_device_name(spawn->phys_dev));
942                         devx_port.comp_mask = 0;
943                 }
944         }
945         if (devx_port.comp_mask & MLX5DV_DEVX_PORT_MATCH_REG_C_0) {
946                 priv->vport_meta_tag = devx_port.reg_c_0.value;
947                 priv->vport_meta_mask = devx_port.reg_c_0.mask;
948                 if (!priv->vport_meta_mask) {
949                         DRV_LOG(ERR, "vport zero mask for port %d"
950                                      " on bonding device %s",
951                                      spawn->phys_port,
952                                      mlx5_os_get_dev_device_name
953                                                         (spawn->phys_dev));
954                         err = ENOTSUP;
955                         goto error;
956                 }
957                 if (priv->vport_meta_tag & ~priv->vport_meta_mask) {
958                         DRV_LOG(ERR, "invalid vport tag for port %d"
959                                      " on bonding device %s",
960                                      spawn->phys_port,
961                                      mlx5_os_get_dev_device_name
962                                                         (spawn->phys_dev));
963                         err = ENOTSUP;
964                         goto error;
965                 }
966         }
967         if (devx_port.comp_mask & MLX5DV_DEVX_PORT_VPORT) {
968                 priv->vport_id = devx_port.vport_num;
969         } else if (spawn->pf_bond >= 0) {
970                 DRV_LOG(ERR, "can't deduce vport index for port %d"
971                              " on bonding device %s",
972                              spawn->phys_port,
973                              mlx5_os_get_dev_device_name(spawn->phys_dev));
974                 err = ENOTSUP;
975                 goto error;
976         } else {
977                 /* Suppose vport index in compatible way. */
978                 priv->vport_id = switch_info->representor ?
979                                  switch_info->port_name + 1 : -1;
980         }
981 #else
982         /*
983          * Kernel/rdma_core support single E-Switch per PF configurations
984          * only and vport_id field contains the vport index for
985          * associated VF, which is deduced from representor port name.
986          * For example, let's have the IB device port 10, it has
987          * attached network device eth0, which has port name attribute
988          * pf0vf2, we can deduce the VF number as 2, and set vport index
989          * as 3 (2+1). This assigning schema should be changed if the
990          * multiple E-Switch instances per PF configurations or/and PCI
991          * subfunctions are added.
992          */
993         priv->vport_id = switch_info->representor ?
994                          switch_info->port_name + 1 : -1;
995 #endif
996         /* representor_id field keeps the unmodified VF index. */
997         priv->representor_id = switch_info->representor ?
998                                switch_info->port_name : -1;
999         /*
1000          * Look for sibling devices in order to reuse their switch domain
1001          * if any, otherwise allocate one.
1002          */
1003         MLX5_ETH_FOREACH_DEV(port_id, priv->pci_dev) {
1004                 const struct mlx5_priv *opriv =
1005                         rte_eth_devices[port_id].data->dev_private;
1006
1007                 if (!opriv ||
1008                     opriv->sh != priv->sh ||
1009                         opriv->domain_id ==
1010                         RTE_ETH_DEV_SWITCH_DOMAIN_ID_INVALID)
1011                         continue;
1012                 priv->domain_id = opriv->domain_id;
1013                 break;
1014         }
1015         if (priv->domain_id == RTE_ETH_DEV_SWITCH_DOMAIN_ID_INVALID) {
1016                 err = rte_eth_switch_domain_alloc(&priv->domain_id);
1017                 if (err) {
1018                         err = rte_errno;
1019                         DRV_LOG(ERR, "unable to allocate switch domain: %s",
1020                                 strerror(rte_errno));
1021                         goto error;
1022                 }
1023                 own_domain_id = 1;
1024         }
1025         /* Override some values set by hardware configuration. */
1026         mlx5_args(config, dpdk_dev->devargs);
1027         err = mlx5_dev_check_sibling_config(priv, config);
1028         if (err)
1029                 goto error;
1030         config->hw_csum = !!(sh->device_attr.device_cap_flags_ex &
1031                             IBV_DEVICE_RAW_IP_CSUM);
1032         DRV_LOG(DEBUG, "checksum offloading is %ssupported",
1033                 (config->hw_csum ? "" : "not "));
1034 #if !defined(HAVE_IBV_DEVICE_COUNTERS_SET_V42) && \
1035         !defined(HAVE_IBV_DEVICE_COUNTERS_SET_V45)
1036         DRV_LOG(DEBUG, "counters are not supported");
1037 #endif
1038 #if !defined(HAVE_IBV_FLOW_DV_SUPPORT) || !defined(HAVE_MLX5DV_DR)
1039         if (config->dv_flow_en) {
1040                 DRV_LOG(WARNING, "DV flow is not supported");
1041                 config->dv_flow_en = 0;
1042         }
1043 #endif
1044         config->ind_table_max_size =
1045                 sh->device_attr.max_rwq_indirection_table_size;
1046         /*
1047          * Remove this check once DPDK supports larger/variable
1048          * indirection tables.
1049          */
1050         if (config->ind_table_max_size > (unsigned int)ETH_RSS_RETA_SIZE_512)
1051                 config->ind_table_max_size = ETH_RSS_RETA_SIZE_512;
1052         DRV_LOG(DEBUG, "maximum Rx indirection table size is %u",
1053                 config->ind_table_max_size);
1054         config->hw_vlan_strip = !!(sh->device_attr.raw_packet_caps &
1055                                   IBV_RAW_PACKET_CAP_CVLAN_STRIPPING);
1056         DRV_LOG(DEBUG, "VLAN stripping is %ssupported",
1057                 (config->hw_vlan_strip ? "" : "not "));
1058         config->hw_fcs_strip = !!(sh->device_attr.raw_packet_caps &
1059                                  IBV_RAW_PACKET_CAP_SCATTER_FCS);
1060 #if defined(HAVE_IBV_WQ_FLAG_RX_END_PADDING)
1061         hw_padding = !!sh->device_attr.rx_pad_end_addr_align;
1062 #elif defined(HAVE_IBV_WQ_FLAGS_PCI_WRITE_END_PADDING)
1063         hw_padding = !!(sh->device_attr.device_cap_flags_ex &
1064                         IBV_DEVICE_PCI_WRITE_END_PADDING);
1065 #endif
1066         if (config->hw_padding && !hw_padding) {
1067                 DRV_LOG(DEBUG, "Rx end alignment padding isn't supported");
1068                 config->hw_padding = 0;
1069         } else if (config->hw_padding) {
1070                 DRV_LOG(DEBUG, "Rx end alignment padding is enabled");
1071         }
1072         config->tso = (sh->device_attr.max_tso > 0 &&
1073                       (sh->device_attr.tso_supported_qpts &
1074                        (1 << IBV_QPT_RAW_PACKET)));
1075         if (config->tso)
1076                 config->tso_max_payload_sz = sh->device_attr.max_tso;
1077         /*
1078          * MPW is disabled by default, while the Enhanced MPW is enabled
1079          * by default.
1080          */
1081         if (config->mps == MLX5_ARG_UNSET)
1082                 config->mps = (mps == MLX5_MPW_ENHANCED) ? MLX5_MPW_ENHANCED :
1083                                                           MLX5_MPW_DISABLED;
1084         else
1085                 config->mps = config->mps ? mps : MLX5_MPW_DISABLED;
1086         DRV_LOG(INFO, "%sMPS is %s",
1087                 config->mps == MLX5_MPW_ENHANCED ? "enhanced " :
1088                 config->mps == MLX5_MPW ? "legacy " : "",
1089                 config->mps != MLX5_MPW_DISABLED ? "enabled" : "disabled");
1090         if (config->cqe_comp && !cqe_comp) {
1091                 DRV_LOG(WARNING, "Rx CQE compression isn't supported");
1092                 config->cqe_comp = 0;
1093         }
1094         if (config->cqe_pad && !cqe_pad) {
1095                 DRV_LOG(WARNING, "Rx CQE padding isn't supported");
1096                 config->cqe_pad = 0;
1097         } else if (config->cqe_pad) {
1098                 DRV_LOG(INFO, "Rx CQE padding is enabled");
1099         }
1100         if (config->devx) {
1101                 err = mlx5_devx_cmd_query_hca_attr(sh->ctx, &config->hca_attr);
1102                 if (err) {
1103                         err = -err;
1104                         goto error;
1105                 }
1106                 /* Check relax ordering support. */
1107                 if (config->hca_attr.relaxed_ordering_write &&
1108                     config->hca_attr.relaxed_ordering_read  &&
1109                     !haswell_broadwell_cpu)
1110                         sh->cmng.relaxed_ordering = 1;
1111                 /* Check for LRO support. */
1112                 if (config->dest_tir && config->hca_attr.lro_cap &&
1113                     config->dv_flow_en) {
1114                         /* TBD check tunnel lro caps. */
1115                         config->lro.supported = config->hca_attr.lro_cap;
1116                         DRV_LOG(DEBUG, "Device supports LRO");
1117                         /*
1118                          * If LRO timeout is not configured by application,
1119                          * use the minimal supported value.
1120                          */
1121                         if (!config->lro.timeout)
1122                                 config->lro.timeout =
1123                                 config->hca_attr.lro_timer_supported_periods[0];
1124                         DRV_LOG(DEBUG, "LRO session timeout set to %d usec",
1125                                 config->lro.timeout);
1126                         DRV_LOG(DEBUG, "LRO minimal size of TCP segment "
1127                                 "required for coalescing is %d bytes",
1128                                 config->hca_attr.lro_min_mss_size);
1129                 }
1130 #if defined(HAVE_MLX5DV_DR) && defined(HAVE_MLX5_DR_CREATE_ACTION_FLOW_METER)
1131                 if (config->hca_attr.qos.sup &&
1132                     config->hca_attr.qos.srtcm_sup &&
1133                     config->dv_flow_en) {
1134                         uint8_t reg_c_mask =
1135                                 config->hca_attr.qos.flow_meter_reg_c_ids;
1136                         /*
1137                          * Meter needs two REG_C's for color match and pre-sfx
1138                          * flow match. Here get the REG_C for color match.
1139                          * REG_C_0 and REG_C_1 is reserved for metadata feature.
1140                          */
1141                         reg_c_mask &= 0xfc;
1142                         if (__builtin_popcount(reg_c_mask) < 1) {
1143                                 priv->mtr_en = 0;
1144                                 DRV_LOG(WARNING, "No available register for"
1145                                         " meter.");
1146                         } else {
1147                                 priv->mtr_color_reg = ffs(reg_c_mask) - 1 +
1148                                                       REG_C_0;
1149                                 priv->mtr_en = 1;
1150                                 priv->mtr_reg_share =
1151                                       config->hca_attr.qos.flow_meter_reg_share;
1152                                 DRV_LOG(DEBUG, "The REG_C meter uses is %d",
1153                                         priv->mtr_color_reg);
1154                         }
1155                 }
1156 #endif
1157 #if defined(HAVE_MLX5DV_DR) && defined(HAVE_MLX5_DR_CREATE_ACTION_FLOW_SAMPLE)
1158                 if (config->hca_attr.log_max_ft_sampler_num > 0  &&
1159                     config->dv_flow_en) {
1160                         priv->sampler_en = 1;
1161                         DRV_LOG(DEBUG, "The Sampler enabled!\n");
1162                 } else {
1163                         priv->sampler_en = 0;
1164                         if (!config->hca_attr.log_max_ft_sampler_num)
1165                                 DRV_LOG(WARNING, "No available register for"
1166                                                 " Sampler.");
1167                         else
1168                                 DRV_LOG(DEBUG, "DV flow is not supported!\n");
1169                 }
1170 #endif
1171         }
1172         if (config->tx_pp) {
1173                 DRV_LOG(DEBUG, "Timestamp counter frequency %u kHz",
1174                         config->hca_attr.dev_freq_khz);
1175                 DRV_LOG(DEBUG, "Packet pacing is %ssupported",
1176                         config->hca_attr.qos.packet_pacing ? "" : "not ");
1177                 DRV_LOG(DEBUG, "Cross channel ops are %ssupported",
1178                         config->hca_attr.cross_channel ? "" : "not ");
1179                 DRV_LOG(DEBUG, "WQE index ignore is %ssupported",
1180                         config->hca_attr.wqe_index_ignore ? "" : "not ");
1181                 DRV_LOG(DEBUG, "Non-wire SQ feature is %ssupported",
1182                         config->hca_attr.non_wire_sq ? "" : "not ");
1183                 DRV_LOG(DEBUG, "Static WQE SQ feature is %ssupported (%d)",
1184                         config->hca_attr.log_max_static_sq_wq ? "" : "not ",
1185                         config->hca_attr.log_max_static_sq_wq);
1186                 DRV_LOG(DEBUG, "WQE rate PP mode is %ssupported",
1187                         config->hca_attr.qos.wqe_rate_pp ? "" : "not ");
1188                 if (!config->devx) {
1189                         DRV_LOG(ERR, "DevX is required for packet pacing");
1190                         err = ENODEV;
1191                         goto error;
1192                 }
1193                 if (!config->hca_attr.qos.packet_pacing) {
1194                         DRV_LOG(ERR, "Packet pacing is not supported");
1195                         err = ENODEV;
1196                         goto error;
1197                 }
1198                 if (!config->hca_attr.cross_channel) {
1199                         DRV_LOG(ERR, "Cross channel operations are"
1200                                      " required for packet pacing");
1201                         err = ENODEV;
1202                         goto error;
1203                 }
1204                 if (!config->hca_attr.wqe_index_ignore) {
1205                         DRV_LOG(ERR, "WQE index ignore feature is"
1206                                      " required for packet pacing");
1207                         err = ENODEV;
1208                         goto error;
1209                 }
1210                 if (!config->hca_attr.non_wire_sq) {
1211                         DRV_LOG(ERR, "Non-wire SQ feature is"
1212                                      " required for packet pacing");
1213                         err = ENODEV;
1214                         goto error;
1215                 }
1216                 if (!config->hca_attr.log_max_static_sq_wq) {
1217                         DRV_LOG(ERR, "Static WQE SQ feature is"
1218                                      " required for packet pacing");
1219                         err = ENODEV;
1220                         goto error;
1221                 }
1222                 if (!config->hca_attr.qos.wqe_rate_pp) {
1223                         DRV_LOG(ERR, "WQE rate mode is required"
1224                                      " for packet pacing");
1225                         err = ENODEV;
1226                         goto error;
1227                 }
1228 #ifndef HAVE_MLX5DV_DEVX_UAR_OFFSET
1229                 DRV_LOG(ERR, "DevX does not provide UAR offset,"
1230                              " can't create queues for packet pacing");
1231                 err = ENODEV;
1232                 goto error;
1233 #endif
1234         }
1235         if (config->devx) {
1236                 uint32_t reg[MLX5_ST_SZ_DW(register_mtutc)];
1237
1238                 err = config->hca_attr.access_register_user ?
1239                         mlx5_devx_cmd_register_read
1240                                 (sh->ctx, MLX5_REGISTER_ID_MTUTC, 0,
1241                                 reg, MLX5_ST_SZ_DW(register_mtutc)) : ENOTSUP;
1242                 if (!err) {
1243                         uint32_t ts_mode;
1244
1245                         /* MTUTC register is read successfully. */
1246                         ts_mode = MLX5_GET(register_mtutc, reg,
1247                                            time_stamp_mode);
1248                         if (ts_mode == MLX5_MTUTC_TIMESTAMP_MODE_REAL_TIME)
1249                                 config->rt_timestamp = 1;
1250                 } else {
1251                         /* Kernel does not support register reading. */
1252                         if (config->hca_attr.dev_freq_khz ==
1253                                                  (NS_PER_S / MS_PER_S))
1254                                 config->rt_timestamp = 1;
1255                 }
1256         }
1257         /*
1258          * If HW has bug working with tunnel packet decapsulation and
1259          * scatter FCS, and decapsulation is needed, clear the hw_fcs_strip
1260          * bit. Then DEV_RX_OFFLOAD_KEEP_CRC bit will not be set anymore.
1261          */
1262         if (config->hca_attr.scatter_fcs_w_decap_disable && config->decap_en)
1263                 config->hw_fcs_strip = 0;
1264         DRV_LOG(DEBUG, "FCS stripping configuration is %ssupported",
1265                 (config->hw_fcs_strip ? "" : "not "));
1266         if (config->mprq.enabled && mprq) {
1267                 if (config->mprq.stride_num_n &&
1268                     (config->mprq.stride_num_n > mprq_max_stride_num_n ||
1269                      config->mprq.stride_num_n < mprq_min_stride_num_n)) {
1270                         config->mprq.stride_num_n =
1271                                 RTE_MIN(RTE_MAX(MLX5_MPRQ_STRIDE_NUM_N,
1272                                                 mprq_min_stride_num_n),
1273                                         mprq_max_stride_num_n);
1274                         DRV_LOG(WARNING,
1275                                 "the number of strides"
1276                                 " for Multi-Packet RQ is out of range,"
1277                                 " setting default value (%u)",
1278                                 1 << config->mprq.stride_num_n);
1279                 }
1280                 if (config->mprq.stride_size_n &&
1281                     (config->mprq.stride_size_n > mprq_max_stride_size_n ||
1282                      config->mprq.stride_size_n < mprq_min_stride_size_n)) {
1283                         config->mprq.stride_size_n =
1284                                 RTE_MIN(RTE_MAX(MLX5_MPRQ_STRIDE_SIZE_N,
1285                                                 mprq_min_stride_size_n),
1286                                         mprq_max_stride_size_n);
1287                         DRV_LOG(WARNING,
1288                                 "the size of a stride"
1289                                 " for Multi-Packet RQ is out of range,"
1290                                 " setting default value (%u)",
1291                                 1 << config->mprq.stride_size_n);
1292                 }
1293                 config->mprq.min_stride_size_n = mprq_min_stride_size_n;
1294                 config->mprq.max_stride_size_n = mprq_max_stride_size_n;
1295         } else if (config->mprq.enabled && !mprq) {
1296                 DRV_LOG(WARNING, "Multi-Packet RQ isn't supported");
1297                 config->mprq.enabled = 0;
1298         }
1299         if (config->max_dump_files_num == 0)
1300                 config->max_dump_files_num = 128;
1301         eth_dev = rte_eth_dev_allocate(name);
1302         if (eth_dev == NULL) {
1303                 DRV_LOG(ERR, "can not allocate rte ethdev");
1304                 err = ENOMEM;
1305                 goto error;
1306         }
1307         if (priv->representor) {
1308                 eth_dev->data->dev_flags |= RTE_ETH_DEV_REPRESENTOR;
1309                 eth_dev->data->representor_id = priv->representor_id;
1310         }
1311         /*
1312          * Store associated network device interface index. This index
1313          * is permanent throughout the lifetime of device. So, we may store
1314          * the ifindex here and use the cached value further.
1315          */
1316         MLX5_ASSERT(spawn->ifindex);
1317         priv->if_index = spawn->ifindex;
1318         if (priv->pf_bond >= 0 && priv->master) {
1319                 /* Get bond interface info */
1320                 err = mlx5_sysfs_bond_info(priv->if_index,
1321                                      &priv->bond_ifindex,
1322                                      priv->bond_name);
1323                 if (err)
1324                         DRV_LOG(ERR, "unable to get bond info: %s",
1325                                 strerror(rte_errno));
1326                 else
1327                         DRV_LOG(INFO, "PF device %u, bond device %u(%s)",
1328                                 priv->if_index, priv->bond_ifindex,
1329                                 priv->bond_name);
1330         }
1331         eth_dev->data->dev_private = priv;
1332         priv->dev_data = eth_dev->data;
1333         eth_dev->data->mac_addrs = priv->mac;
1334         eth_dev->device = dpdk_dev;
1335         eth_dev->data->dev_flags |= RTE_ETH_DEV_AUTOFILL_QUEUE_XSTATS;
1336         /* Configure the first MAC address by default. */
1337         if (mlx5_get_mac(eth_dev, &mac.addr_bytes)) {
1338                 DRV_LOG(ERR,
1339                         "port %u cannot get MAC address, is mlx5_en"
1340                         " loaded? (errno: %s)",
1341                         eth_dev->data->port_id, strerror(rte_errno));
1342                 err = ENODEV;
1343                 goto error;
1344         }
1345         DRV_LOG(INFO,
1346                 "port %u MAC address is %02x:%02x:%02x:%02x:%02x:%02x",
1347                 eth_dev->data->port_id,
1348                 mac.addr_bytes[0], mac.addr_bytes[1],
1349                 mac.addr_bytes[2], mac.addr_bytes[3],
1350                 mac.addr_bytes[4], mac.addr_bytes[5]);
1351 #ifdef RTE_LIBRTE_MLX5_DEBUG
1352         {
1353                 char ifname[IF_NAMESIZE];
1354
1355                 if (mlx5_get_ifname(eth_dev, &ifname) == 0)
1356                         DRV_LOG(DEBUG, "port %u ifname is \"%s\"",
1357                                 eth_dev->data->port_id, ifname);
1358                 else
1359                         DRV_LOG(DEBUG, "port %u ifname is unknown",
1360                                 eth_dev->data->port_id);
1361         }
1362 #endif
1363         /* Get actual MTU if possible. */
1364         err = mlx5_get_mtu(eth_dev, &priv->mtu);
1365         if (err) {
1366                 err = rte_errno;
1367                 goto error;
1368         }
1369         DRV_LOG(DEBUG, "port %u MTU is %u", eth_dev->data->port_id,
1370                 priv->mtu);
1371         /* Initialize burst functions to prevent crashes before link-up. */
1372         eth_dev->rx_pkt_burst = removed_rx_burst;
1373         eth_dev->tx_pkt_burst = removed_tx_burst;
1374         eth_dev->dev_ops = &mlx5_os_dev_ops;
1375         eth_dev->rx_descriptor_status = mlx5_rx_descriptor_status;
1376         eth_dev->tx_descriptor_status = mlx5_tx_descriptor_status;
1377         eth_dev->rx_queue_count = mlx5_rx_queue_count;
1378         /* Register MAC address. */
1379         claim_zero(mlx5_mac_addr_add(eth_dev, &mac, 0, 0));
1380         if (config->vf && config->vf_nl_en)
1381                 mlx5_nl_mac_addr_sync(priv->nl_socket_route,
1382                                       mlx5_ifindex(eth_dev),
1383                                       eth_dev->data->mac_addrs,
1384                                       MLX5_MAX_MAC_ADDRESSES);
1385         priv->flows = 0;
1386         priv->ctrl_flows = 0;
1387         rte_spinlock_init(&priv->flow_list_lock);
1388         TAILQ_INIT(&priv->flow_meters);
1389         TAILQ_INIT(&priv->flow_meter_profiles);
1390         /* Hint libmlx5 to use PMD allocator for data plane resources */
1391         mlx5_glue->dv_set_context_attr(sh->ctx,
1392                         MLX5DV_CTX_ATTR_BUF_ALLOCATORS,
1393                         (void *)((uintptr_t)&(struct mlx5dv_ctx_allocators){
1394                                 .alloc = &mlx5_alloc_verbs_buf,
1395                                 .free = &mlx5_free_verbs_buf,
1396                                 .data = priv,
1397                         }));
1398         /* Bring Ethernet device up. */
1399         DRV_LOG(DEBUG, "port %u forcing Ethernet interface up",
1400                 eth_dev->data->port_id);
1401         mlx5_set_link_up(eth_dev);
1402         /*
1403          * Even though the interrupt handler is not installed yet,
1404          * interrupts will still trigger on the async_fd from
1405          * Verbs context returned by ibv_open_device().
1406          */
1407         mlx5_link_update(eth_dev, 0);
1408 #ifdef HAVE_MLX5DV_DR_ESWITCH
1409         if (!(config->hca_attr.eswitch_manager && config->dv_flow_en &&
1410               (switch_info->representor || switch_info->master)))
1411                 config->dv_esw_en = 0;
1412 #else
1413         config->dv_esw_en = 0;
1414 #endif
1415         /* Detect minimal data bytes to inline. */
1416         mlx5_set_min_inline(spawn, config);
1417         /* Store device configuration on private structure. */
1418         priv->config = *config;
1419         /* Create context for virtual machine VLAN workaround. */
1420         priv->vmwa_context = mlx5_vlan_vmwa_init(eth_dev, spawn->ifindex);
1421         if (config->dv_flow_en) {
1422                 err = mlx5_alloc_shared_dr(priv);
1423                 if (err)
1424                         goto error;
1425         }
1426         if (config->devx && config->dv_flow_en && config->dest_tir) {
1427                 priv->obj_ops = devx_obj_ops;
1428                 priv->obj_ops.drop_action_create =
1429                                                 ibv_obj_ops.drop_action_create;
1430                 priv->obj_ops.drop_action_destroy =
1431                                                 ibv_obj_ops.drop_action_destroy;
1432 #ifndef HAVE_MLX5DV_DEVX_UAR_OFFSET
1433                 priv->obj_ops.txq_obj_modify = ibv_obj_ops.txq_obj_modify;
1434 #else
1435                 if (config->dv_esw_en)
1436                         priv->obj_ops.txq_obj_modify =
1437                                                 ibv_obj_ops.txq_obj_modify;
1438 #endif
1439                 /* Use specific wrappers for Tx object. */
1440                 priv->obj_ops.txq_obj_new = mlx5_os_txq_obj_new;
1441                 priv->obj_ops.txq_obj_release = mlx5_os_txq_obj_release;
1442
1443         } else {
1444                 priv->obj_ops = ibv_obj_ops;
1445         }
1446         priv->drop_queue.hrxq = mlx5_drop_action_create(eth_dev);
1447         if (!priv->drop_queue.hrxq)
1448                 goto error;
1449         /* Supported Verbs flow priority number detection. */
1450         err = mlx5_flow_discover_priorities(eth_dev);
1451         if (err < 0) {
1452                 err = -err;
1453                 goto error;
1454         }
1455         priv->config.flow_prio = err;
1456         if (!priv->config.dv_esw_en &&
1457             priv->config.dv_xmeta_en != MLX5_XMETA_MODE_LEGACY) {
1458                 DRV_LOG(WARNING, "metadata mode %u is not supported "
1459                                  "(no E-Switch)", priv->config.dv_xmeta_en);
1460                 priv->config.dv_xmeta_en = MLX5_XMETA_MODE_LEGACY;
1461         }
1462         mlx5_set_metadata_mask(eth_dev);
1463         if (priv->config.dv_xmeta_en != MLX5_XMETA_MODE_LEGACY &&
1464             !priv->sh->dv_regc0_mask) {
1465                 DRV_LOG(ERR, "metadata mode %u is not supported "
1466                              "(no metadata reg_c[0] is available)",
1467                              priv->config.dv_xmeta_en);
1468                         err = ENOTSUP;
1469                         goto error;
1470         }
1471         /* Query availability of metadata reg_c's. */
1472         err = mlx5_flow_discover_mreg_c(eth_dev);
1473         if (err < 0) {
1474                 err = -err;
1475                 goto error;
1476         }
1477         if (!mlx5_flow_ext_mreg_supported(eth_dev)) {
1478                 DRV_LOG(DEBUG,
1479                         "port %u extensive metadata register is not supported",
1480                         eth_dev->data->port_id);
1481                 if (priv->config.dv_xmeta_en != MLX5_XMETA_MODE_LEGACY) {
1482                         DRV_LOG(ERR, "metadata mode %u is not supported "
1483                                      "(no metadata registers available)",
1484                                      priv->config.dv_xmeta_en);
1485                         err = ENOTSUP;
1486                         goto error;
1487                 }
1488         }
1489         if (priv->config.dv_flow_en &&
1490             priv->config.dv_xmeta_en != MLX5_XMETA_MODE_LEGACY &&
1491             mlx5_flow_ext_mreg_supported(eth_dev) &&
1492             priv->sh->dv_regc0_mask) {
1493                 priv->mreg_cp_tbl = mlx5_hlist_create(MLX5_FLOW_MREG_HNAME,
1494                                                       MLX5_FLOW_MREG_HTABLE_SZ,
1495                                                       0, 0,
1496                                                       flow_dv_mreg_create_cb,
1497                                                       NULL,
1498                                                       flow_dv_mreg_remove_cb);
1499                 if (!priv->mreg_cp_tbl) {
1500                         err = ENOMEM;
1501                         goto error;
1502                 }
1503                 priv->mreg_cp_tbl->ctx = eth_dev;
1504         }
1505         mlx5_flow_counter_mode_config(eth_dev);
1506         return eth_dev;
1507 error:
1508         if (priv) {
1509                 if (priv->mreg_cp_tbl)
1510                         mlx5_hlist_destroy(priv->mreg_cp_tbl);
1511                 if (priv->sh)
1512                         mlx5_os_free_shared_dr(priv);
1513                 if (priv->nl_socket_route >= 0)
1514                         close(priv->nl_socket_route);
1515                 if (priv->nl_socket_rdma >= 0)
1516                         close(priv->nl_socket_rdma);
1517                 if (priv->vmwa_context)
1518                         mlx5_vlan_vmwa_exit(priv->vmwa_context);
1519                 if (eth_dev && priv->drop_queue.hrxq)
1520                         mlx5_drop_action_destroy(eth_dev);
1521                 if (own_domain_id)
1522                         claim_zero(rte_eth_switch_domain_free(priv->domain_id));
1523                 mlx5_free(priv);
1524                 if (eth_dev != NULL)
1525                         eth_dev->data->dev_private = NULL;
1526         }
1527         if (eth_dev != NULL) {
1528                 /* mac_addrs must not be freed alone because part of
1529                  * dev_private
1530                  **/
1531                 eth_dev->data->mac_addrs = NULL;
1532                 rte_eth_dev_release_port(eth_dev);
1533         }
1534         if (sh)
1535                 mlx5_free_shared_dev_ctx(sh);
1536         MLX5_ASSERT(err > 0);
1537         rte_errno = err;
1538         return NULL;
1539 }
1540
1541 /**
1542  * Comparison callback to sort device data.
1543  *
1544  * This is meant to be used with qsort().
1545  *
1546  * @param a[in]
1547  *   Pointer to pointer to first data object.
1548  * @param b[in]
1549  *   Pointer to pointer to second data object.
1550  *
1551  * @return
1552  *   0 if both objects are equal, less than 0 if the first argument is less
1553  *   than the second, greater than 0 otherwise.
1554  */
1555 static int
1556 mlx5_dev_spawn_data_cmp(const void *a, const void *b)
1557 {
1558         const struct mlx5_switch_info *si_a =
1559                 &((const struct mlx5_dev_spawn_data *)a)->info;
1560         const struct mlx5_switch_info *si_b =
1561                 &((const struct mlx5_dev_spawn_data *)b)->info;
1562         int ret;
1563
1564         /* Master device first. */
1565         ret = si_b->master - si_a->master;
1566         if (ret)
1567                 return ret;
1568         /* Then representor devices. */
1569         ret = si_b->representor - si_a->representor;
1570         if (ret)
1571                 return ret;
1572         /* Unidentified devices come last in no specific order. */
1573         if (!si_a->representor)
1574                 return 0;
1575         /* Order representors by name. */
1576         return si_a->port_name - si_b->port_name;
1577 }
1578
1579 /**
1580  * Match PCI information for possible slaves of bonding device.
1581  *
1582  * @param[in] ibv_dev
1583  *   Pointer to Infiniband device structure.
1584  * @param[in] pci_dev
1585  *   Pointer to PCI device structure to match PCI address.
1586  * @param[in] nl_rdma
1587  *   Netlink RDMA group socket handle.
1588  *
1589  * @return
1590  *   negative value if no bonding device found, otherwise
1591  *   positive index of slave PF in bonding.
1592  */
1593 static int
1594 mlx5_device_bond_pci_match(const struct ibv_device *ibv_dev,
1595                            const struct rte_pci_device *pci_dev,
1596                            int nl_rdma)
1597 {
1598         char ifname[IF_NAMESIZE + 1];
1599         unsigned int ifindex;
1600         unsigned int np, i;
1601         FILE *file = NULL;
1602         int pf = -1;
1603
1604         /*
1605          * Try to get master device name. If something goes
1606          * wrong suppose the lack of kernel support and no
1607          * bonding devices.
1608          */
1609         if (nl_rdma < 0)
1610                 return -1;
1611         if (!strstr(ibv_dev->name, "bond"))
1612                 return -1;
1613         np = mlx5_nl_portnum(nl_rdma, ibv_dev->name);
1614         if (!np)
1615                 return -1;
1616         /*
1617          * The Master device might not be on the predefined
1618          * port (not on port index 1, it is not garanted),
1619          * we have to scan all Infiniband device port and
1620          * find master.
1621          */
1622         for (i = 1; i <= np; ++i) {
1623                 /* Check whether Infiniband port is populated. */
1624                 ifindex = mlx5_nl_ifindex(nl_rdma, ibv_dev->name, i);
1625                 if (!ifindex)
1626                         continue;
1627                 if (!if_indextoname(ifindex, ifname))
1628                         continue;
1629                 /* Try to read bonding slave names from sysfs. */
1630                 MKSTR(slaves,
1631                       "/sys/class/net/%s/master/bonding/slaves", ifname);
1632                 file = fopen(slaves, "r");
1633                 if (file)
1634                         break;
1635         }
1636         if (!file)
1637                 return -1;
1638         /* Use safe format to check maximal buffer length. */
1639         MLX5_ASSERT(atol(RTE_STR(IF_NAMESIZE)) == IF_NAMESIZE);
1640         while (fscanf(file, "%" RTE_STR(IF_NAMESIZE) "s", ifname) == 1) {
1641                 char tmp_str[IF_NAMESIZE + 32];
1642                 struct rte_pci_addr pci_addr;
1643                 struct mlx5_switch_info info;
1644
1645                 /* Process slave interface names in the loop. */
1646                 snprintf(tmp_str, sizeof(tmp_str),
1647                          "/sys/class/net/%s", ifname);
1648                 if (mlx5_dev_to_pci_addr(tmp_str, &pci_addr)) {
1649                         DRV_LOG(WARNING, "can not get PCI address"
1650                                          " for netdev \"%s\"", ifname);
1651                         continue;
1652                 }
1653                 if (pci_dev->addr.domain != pci_addr.domain ||
1654                     pci_dev->addr.bus != pci_addr.bus ||
1655                     pci_dev->addr.devid != pci_addr.devid ||
1656                     pci_dev->addr.function != pci_addr.function)
1657                         continue;
1658                 /* Slave interface PCI address match found. */
1659                 fclose(file);
1660                 snprintf(tmp_str, sizeof(tmp_str),
1661                          "/sys/class/net/%s/phys_port_name", ifname);
1662                 file = fopen(tmp_str, "rb");
1663                 if (!file)
1664                         break;
1665                 info.name_type = MLX5_PHYS_PORT_NAME_TYPE_NOTSET;
1666                 if (fscanf(file, "%32s", tmp_str) == 1)
1667                         mlx5_translate_port_name(tmp_str, &info);
1668                 if (info.name_type == MLX5_PHYS_PORT_NAME_TYPE_LEGACY ||
1669                     info.name_type == MLX5_PHYS_PORT_NAME_TYPE_UPLINK)
1670                         pf = info.port_name;
1671                 break;
1672         }
1673         if (file)
1674                 fclose(file);
1675         return pf;
1676 }
1677
1678 /**
1679  * DPDK callback to register a PCI device.
1680  *
1681  * This function spawns Ethernet devices out of a given PCI device.
1682  *
1683  * @param[in] pci_drv
1684  *   PCI driver structure (mlx5_driver).
1685  * @param[in] pci_dev
1686  *   PCI device information.
1687  *
1688  * @return
1689  *   0 on success, a negative errno value otherwise and rte_errno is set.
1690  */
1691 int
1692 mlx5_os_pci_probe(struct rte_pci_driver *pci_drv __rte_unused,
1693                   struct rte_pci_device *pci_dev)
1694 {
1695         struct ibv_device **ibv_list;
1696         /*
1697          * Number of found IB Devices matching with requested PCI BDF.
1698          * nd != 1 means there are multiple IB devices over the same
1699          * PCI device and we have representors and master.
1700          */
1701         unsigned int nd = 0;
1702         /*
1703          * Number of found IB device Ports. nd = 1 and np = 1..n means
1704          * we have the single multiport IB device, and there may be
1705          * representors attached to some of found ports.
1706          */
1707         unsigned int np = 0;
1708         /*
1709          * Number of DPDK ethernet devices to Spawn - either over
1710          * multiple IB devices or multiple ports of single IB device.
1711          * Actually this is the number of iterations to spawn.
1712          */
1713         unsigned int ns = 0;
1714         /*
1715          * Bonding device
1716          *   < 0 - no bonding device (single one)
1717          *  >= 0 - bonding device (value is slave PF index)
1718          */
1719         int bd = -1;
1720         struct mlx5_dev_spawn_data *list = NULL;
1721         struct mlx5_dev_config dev_config;
1722         unsigned int dev_config_vf;
1723         int ret;
1724
1725         if (rte_eal_process_type() == RTE_PROC_PRIMARY)
1726                 mlx5_pmd_socket_init();
1727         ret = mlx5_init_once();
1728         if (ret) {
1729                 DRV_LOG(ERR, "unable to init PMD global data: %s",
1730                         strerror(rte_errno));
1731                 return -rte_errno;
1732         }
1733         errno = 0;
1734         ibv_list = mlx5_glue->get_device_list(&ret);
1735         if (!ibv_list) {
1736                 rte_errno = errno ? errno : ENOSYS;
1737                 DRV_LOG(ERR, "cannot list devices, is ib_uverbs loaded?");
1738                 return -rte_errno;
1739         }
1740         /*
1741          * First scan the list of all Infiniband devices to find
1742          * matching ones, gathering into the list.
1743          */
1744         struct ibv_device *ibv_match[ret + 1];
1745         int nl_route = mlx5_nl_init(NETLINK_ROUTE);
1746         int nl_rdma = mlx5_nl_init(NETLINK_RDMA);
1747         unsigned int i;
1748
1749         while (ret-- > 0) {
1750                 struct rte_pci_addr pci_addr;
1751
1752                 DRV_LOG(DEBUG, "checking device \"%s\"", ibv_list[ret]->name);
1753                 bd = mlx5_device_bond_pci_match
1754                                 (ibv_list[ret], pci_dev, nl_rdma);
1755                 if (bd >= 0) {
1756                         /*
1757                          * Bonding device detected. Only one match is allowed,
1758                          * the bonding is supported over multi-port IB device,
1759                          * there should be no matches on representor PCI
1760                          * functions or non VF LAG bonding devices with
1761                          * specified address.
1762                          */
1763                         if (nd) {
1764                                 DRV_LOG(ERR,
1765                                         "multiple PCI match on bonding device"
1766                                         "\"%s\" found", ibv_list[ret]->name);
1767                                 rte_errno = ENOENT;
1768                                 ret = -rte_errno;
1769                                 goto exit;
1770                         }
1771                         DRV_LOG(INFO, "PCI information matches for"
1772                                       " slave %d bonding device \"%s\"",
1773                                       bd, ibv_list[ret]->name);
1774                         ibv_match[nd++] = ibv_list[ret];
1775                         break;
1776                 }
1777                 if (mlx5_dev_to_pci_addr
1778                         (ibv_list[ret]->ibdev_path, &pci_addr))
1779                         continue;
1780                 if (pci_dev->addr.domain != pci_addr.domain ||
1781                     pci_dev->addr.bus != pci_addr.bus ||
1782                     pci_dev->addr.devid != pci_addr.devid ||
1783                     pci_dev->addr.function != pci_addr.function)
1784                         continue;
1785                 DRV_LOG(INFO, "PCI information matches for device \"%s\"",
1786                         ibv_list[ret]->name);
1787                 ibv_match[nd++] = ibv_list[ret];
1788         }
1789         ibv_match[nd] = NULL;
1790         if (!nd) {
1791                 /* No device matches, just complain and bail out. */
1792                 DRV_LOG(WARNING,
1793                         "no Verbs device matches PCI device " PCI_PRI_FMT ","
1794                         " are kernel drivers loaded?",
1795                         pci_dev->addr.domain, pci_dev->addr.bus,
1796                         pci_dev->addr.devid, pci_dev->addr.function);
1797                 rte_errno = ENOENT;
1798                 ret = -rte_errno;
1799                 goto exit;
1800         }
1801         if (nd == 1) {
1802                 /*
1803                  * Found single matching device may have multiple ports.
1804                  * Each port may be representor, we have to check the port
1805                  * number and check the representors existence.
1806                  */
1807                 if (nl_rdma >= 0)
1808                         np = mlx5_nl_portnum(nl_rdma, ibv_match[0]->name);
1809                 if (!np)
1810                         DRV_LOG(WARNING, "can not get IB device \"%s\""
1811                                          " ports number", ibv_match[0]->name);
1812                 if (bd >= 0 && !np) {
1813                         DRV_LOG(ERR, "can not get ports"
1814                                      " for bonding device");
1815                         rte_errno = ENOENT;
1816                         ret = -rte_errno;
1817                         goto exit;
1818                 }
1819         }
1820 #ifndef HAVE_MLX5DV_DR_DEVX_PORT
1821         if (bd >= 0) {
1822                 /*
1823                  * This may happen if there is VF LAG kernel support and
1824                  * application is compiled with older rdma_core library.
1825                  */
1826                 DRV_LOG(ERR,
1827                         "No kernel/verbs support for VF LAG bonding found.");
1828                 rte_errno = ENOTSUP;
1829                 ret = -rte_errno;
1830                 goto exit;
1831         }
1832 #endif
1833         /*
1834          * Now we can determine the maximal
1835          * amount of devices to be spawned.
1836          */
1837         list = mlx5_malloc(MLX5_MEM_ZERO,
1838                            sizeof(struct mlx5_dev_spawn_data) *
1839                            (np ? np : nd),
1840                            RTE_CACHE_LINE_SIZE, SOCKET_ID_ANY);
1841         if (!list) {
1842                 DRV_LOG(ERR, "spawn data array allocation failure");
1843                 rte_errno = ENOMEM;
1844                 ret = -rte_errno;
1845                 goto exit;
1846         }
1847         if (bd >= 0 || np > 1) {
1848                 /*
1849                  * Single IB device with multiple ports found,
1850                  * it may be E-Switch master device and representors.
1851                  * We have to perform identification through the ports.
1852                  */
1853                 MLX5_ASSERT(nl_rdma >= 0);
1854                 MLX5_ASSERT(ns == 0);
1855                 MLX5_ASSERT(nd == 1);
1856                 MLX5_ASSERT(np);
1857                 for (i = 1; i <= np; ++i) {
1858                         list[ns].max_port = np;
1859                         list[ns].phys_port = i;
1860                         list[ns].phys_dev = ibv_match[0];
1861                         list[ns].eth_dev = NULL;
1862                         list[ns].pci_dev = pci_dev;
1863                         list[ns].pf_bond = bd;
1864                         list[ns].ifindex = mlx5_nl_ifindex
1865                                 (nl_rdma,
1866                                 mlx5_os_get_dev_device_name
1867                                                 (list[ns].phys_dev), i);
1868                         if (!list[ns].ifindex) {
1869                                 /*
1870                                  * No network interface index found for the
1871                                  * specified port, it means there is no
1872                                  * representor on this port. It's OK,
1873                                  * there can be disabled ports, for example
1874                                  * if sriov_numvfs < sriov_totalvfs.
1875                                  */
1876                                 continue;
1877                         }
1878                         ret = -1;
1879                         if (nl_route >= 0)
1880                                 ret = mlx5_nl_switch_info
1881                                                (nl_route,
1882                                                 list[ns].ifindex,
1883                                                 &list[ns].info);
1884                         if (ret || (!list[ns].info.representor &&
1885                                     !list[ns].info.master)) {
1886                                 /*
1887                                  * We failed to recognize representors with
1888                                  * Netlink, let's try to perform the task
1889                                  * with sysfs.
1890                                  */
1891                                 ret =  mlx5_sysfs_switch_info
1892                                                 (list[ns].ifindex,
1893                                                  &list[ns].info);
1894                         }
1895                         if (!ret && bd >= 0) {
1896                                 switch (list[ns].info.name_type) {
1897                                 case MLX5_PHYS_PORT_NAME_TYPE_UPLINK:
1898                                         if (list[ns].info.port_name == bd)
1899                                                 ns++;
1900                                         break;
1901                                 case MLX5_PHYS_PORT_NAME_TYPE_PFHPF:
1902                                         /* Fallthrough */
1903                                 case MLX5_PHYS_PORT_NAME_TYPE_PFVF:
1904                                         if (list[ns].info.pf_num == bd)
1905                                                 ns++;
1906                                         break;
1907                                 default:
1908                                         break;
1909                                 }
1910                                 continue;
1911                         }
1912                         if (!ret && (list[ns].info.representor ^
1913                                      list[ns].info.master))
1914                                 ns++;
1915                 }
1916                 if (!ns) {
1917                         DRV_LOG(ERR,
1918                                 "unable to recognize master/representors"
1919                                 " on the IB device with multiple ports");
1920                         rte_errno = ENOENT;
1921                         ret = -rte_errno;
1922                         goto exit;
1923                 }
1924         } else {
1925                 /*
1926                  * The existence of several matching entries (nd > 1) means
1927                  * port representors have been instantiated. No existing Verbs
1928                  * call nor sysfs entries can tell them apart, this can only
1929                  * be done through Netlink calls assuming kernel drivers are
1930                  * recent enough to support them.
1931                  *
1932                  * In the event of identification failure through Netlink,
1933                  * try again through sysfs, then:
1934                  *
1935                  * 1. A single IB device matches (nd == 1) with single
1936                  *    port (np=0/1) and is not a representor, assume
1937                  *    no switch support.
1938                  *
1939                  * 2. Otherwise no safe assumptions can be made;
1940                  *    complain louder and bail out.
1941                  */
1942                 for (i = 0; i != nd; ++i) {
1943                         memset(&list[ns].info, 0, sizeof(list[ns].info));
1944                         list[ns].max_port = 1;
1945                         list[ns].phys_port = 1;
1946                         list[ns].phys_dev = ibv_match[i];
1947                         list[ns].eth_dev = NULL;
1948                         list[ns].pci_dev = pci_dev;
1949                         list[ns].pf_bond = -1;
1950                         list[ns].ifindex = 0;
1951                         if (nl_rdma >= 0)
1952                                 list[ns].ifindex = mlx5_nl_ifindex
1953                                 (nl_rdma,
1954                                 mlx5_os_get_dev_device_name
1955                                                 (list[ns].phys_dev), 1);
1956                         if (!list[ns].ifindex) {
1957                                 char ifname[IF_NAMESIZE];
1958
1959                                 /*
1960                                  * Netlink failed, it may happen with old
1961                                  * ib_core kernel driver (before 4.16).
1962                                  * We can assume there is old driver because
1963                                  * here we are processing single ports IB
1964                                  * devices. Let's try sysfs to retrieve
1965                                  * the ifindex. The method works for
1966                                  * master device only.
1967                                  */
1968                                 if (nd > 1) {
1969                                         /*
1970                                          * Multiple devices found, assume
1971                                          * representors, can not distinguish
1972                                          * master/representor and retrieve
1973                                          * ifindex via sysfs.
1974                                          */
1975                                         continue;
1976                                 }
1977                                 ret = mlx5_get_ifname_sysfs
1978                                         (ibv_match[i]->ibdev_path, ifname);
1979                                 if (!ret)
1980                                         list[ns].ifindex =
1981                                                 if_nametoindex(ifname);
1982                                 if (!list[ns].ifindex) {
1983                                         /*
1984                                          * No network interface index found
1985                                          * for the specified device, it means
1986                                          * there it is neither representor
1987                                          * nor master.
1988                                          */
1989                                         continue;
1990                                 }
1991                         }
1992                         ret = -1;
1993                         if (nl_route >= 0)
1994                                 ret = mlx5_nl_switch_info
1995                                                (nl_route,
1996                                                 list[ns].ifindex,
1997                                                 &list[ns].info);
1998                         if (ret || (!list[ns].info.representor &&
1999                                     !list[ns].info.master)) {
2000                                 /*
2001                                  * We failed to recognize representors with
2002                                  * Netlink, let's try to perform the task
2003                                  * with sysfs.
2004                                  */
2005                                 ret =  mlx5_sysfs_switch_info
2006                                                 (list[ns].ifindex,
2007                                                  &list[ns].info);
2008                         }
2009                         if (!ret && (list[ns].info.representor ^
2010                                      list[ns].info.master)) {
2011                                 ns++;
2012                         } else if ((nd == 1) &&
2013                                    !list[ns].info.representor &&
2014                                    !list[ns].info.master) {
2015                                 /*
2016                                  * Single IB device with
2017                                  * one physical port and
2018                                  * attached network device.
2019                                  * May be SRIOV is not enabled
2020                                  * or there is no representors.
2021                                  */
2022                                 DRV_LOG(INFO, "no E-Switch support detected");
2023                                 ns++;
2024                                 break;
2025                         }
2026                 }
2027                 if (!ns) {
2028                         DRV_LOG(ERR,
2029                                 "unable to recognize master/representors"
2030                                 " on the multiple IB devices");
2031                         rte_errno = ENOENT;
2032                         ret = -rte_errno;
2033                         goto exit;
2034                 }
2035         }
2036         MLX5_ASSERT(ns);
2037         /*
2038          * Sort list to probe devices in natural order for users convenience
2039          * (i.e. master first, then representors from lowest to highest ID).
2040          */
2041         qsort(list, ns, sizeof(*list), mlx5_dev_spawn_data_cmp);
2042         /* Device specific configuration. */
2043         switch (pci_dev->id.device_id) {
2044         case PCI_DEVICE_ID_MELLANOX_CONNECTX4VF:
2045         case PCI_DEVICE_ID_MELLANOX_CONNECTX4LXVF:
2046         case PCI_DEVICE_ID_MELLANOX_CONNECTX5VF:
2047         case PCI_DEVICE_ID_MELLANOX_CONNECTX5EXVF:
2048         case PCI_DEVICE_ID_MELLANOX_CONNECTX5BFVF:
2049         case PCI_DEVICE_ID_MELLANOX_CONNECTX6VF:
2050         case PCI_DEVICE_ID_MELLANOX_CONNECTX6DXVF:
2051                 dev_config_vf = 1;
2052                 break;
2053         default:
2054                 dev_config_vf = 0;
2055                 break;
2056         }
2057         for (i = 0; i != ns; ++i) {
2058                 uint32_t restore;
2059
2060                 /* Default configuration. */
2061                 memset(&dev_config, 0, sizeof(struct mlx5_dev_config));
2062                 dev_config.vf = dev_config_vf;
2063                 dev_config.mps = MLX5_ARG_UNSET;
2064                 dev_config.dbnc = MLX5_ARG_UNSET;
2065                 dev_config.rx_vec_en = 1;
2066                 dev_config.txq_inline_max = MLX5_ARG_UNSET;
2067                 dev_config.txq_inline_min = MLX5_ARG_UNSET;
2068                 dev_config.txq_inline_mpw = MLX5_ARG_UNSET;
2069                 dev_config.txqs_inline = MLX5_ARG_UNSET;
2070                 dev_config.vf_nl_en = 1;
2071                 dev_config.mr_ext_memseg_en = 1;
2072                 dev_config.mprq.max_memcpy_len = MLX5_MPRQ_MEMCPY_DEFAULT_LEN;
2073                 dev_config.mprq.min_rxqs_num = MLX5_MPRQ_MIN_RXQS;
2074                 dev_config.dv_esw_en = 1;
2075                 dev_config.dv_flow_en = 1;
2076                 dev_config.decap_en = 1;
2077                 dev_config.log_hp_size = MLX5_ARG_UNSET;
2078                 list[i].eth_dev = mlx5_dev_spawn(&pci_dev->device,
2079                                                  &list[i],
2080                                                  &dev_config);
2081                 if (!list[i].eth_dev) {
2082                         if (rte_errno != EBUSY && rte_errno != EEXIST)
2083                                 break;
2084                         /* Device is disabled or already spawned. Ignore it. */
2085                         continue;
2086                 }
2087                 restore = list[i].eth_dev->data->dev_flags;
2088                 rte_eth_copy_pci_info(list[i].eth_dev, pci_dev);
2089                 /* Restore non-PCI flags cleared by the above call. */
2090                 list[i].eth_dev->data->dev_flags |= restore;
2091                 rte_eth_dev_probing_finish(list[i].eth_dev);
2092         }
2093         if (i != ns) {
2094                 DRV_LOG(ERR,
2095                         "probe of PCI device " PCI_PRI_FMT " aborted after"
2096                         " encountering an error: %s",
2097                         pci_dev->addr.domain, pci_dev->addr.bus,
2098                         pci_dev->addr.devid, pci_dev->addr.function,
2099                         strerror(rte_errno));
2100                 ret = -rte_errno;
2101                 /* Roll back. */
2102                 while (i--) {
2103                         if (!list[i].eth_dev)
2104                                 continue;
2105                         mlx5_dev_close(list[i].eth_dev);
2106                         /* mac_addrs must not be freed because in dev_private */
2107                         list[i].eth_dev->data->mac_addrs = NULL;
2108                         claim_zero(rte_eth_dev_release_port(list[i].eth_dev));
2109                 }
2110                 /* Restore original error. */
2111                 rte_errno = -ret;
2112         } else {
2113                 ret = 0;
2114         }
2115 exit:
2116         /*
2117          * Do the routine cleanup:
2118          * - close opened Netlink sockets
2119          * - free allocated spawn data array
2120          * - free the Infiniband device list
2121          */
2122         if (nl_rdma >= 0)
2123                 close(nl_rdma);
2124         if (nl_route >= 0)
2125                 close(nl_route);
2126         if (list)
2127                 mlx5_free(list);
2128         MLX5_ASSERT(ibv_list);
2129         mlx5_glue->free_device_list(ibv_list);
2130         return ret;
2131 }
2132
2133 static int
2134 mlx5_config_doorbell_mapping_env(const struct mlx5_dev_config *config)
2135 {
2136         char *env;
2137         int value;
2138
2139         MLX5_ASSERT(rte_eal_process_type() == RTE_PROC_PRIMARY);
2140         /* Get environment variable to store. */
2141         env = getenv(MLX5_SHUT_UP_BF);
2142         value = env ? !!strcmp(env, "0") : MLX5_ARG_UNSET;
2143         if (config->dbnc == MLX5_ARG_UNSET)
2144                 setenv(MLX5_SHUT_UP_BF, MLX5_SHUT_UP_BF_DEFAULT, 1);
2145         else
2146                 setenv(MLX5_SHUT_UP_BF,
2147                        config->dbnc == MLX5_TXDB_NCACHED ? "1" : "0", 1);
2148         return value;
2149 }
2150
2151 static void
2152 mlx5_restore_doorbell_mapping_env(int value)
2153 {
2154         MLX5_ASSERT(rte_eal_process_type() == RTE_PROC_PRIMARY);
2155         /* Restore the original environment variable state. */
2156         if (value == MLX5_ARG_UNSET)
2157                 unsetenv(MLX5_SHUT_UP_BF);
2158         else
2159                 setenv(MLX5_SHUT_UP_BF, value ? "1" : "0", 1);
2160 }
2161
2162 /**
2163  * Extract pdn of PD object using DV API.
2164  *
2165  * @param[in] pd
2166  *   Pointer to the verbs PD object.
2167  * @param[out] pdn
2168  *   Pointer to the PD object number variable.
2169  *
2170  * @return
2171  *   0 on success, error value otherwise.
2172  */
2173 int
2174 mlx5_os_get_pdn(void *pd, uint32_t *pdn)
2175 {
2176 #ifdef HAVE_IBV_FLOW_DV_SUPPORT
2177         struct mlx5dv_obj obj;
2178         struct mlx5dv_pd pd_info;
2179         int ret = 0;
2180
2181         obj.pd.in = pd;
2182         obj.pd.out = &pd_info;
2183         ret = mlx5_glue->dv_init_obj(&obj, MLX5DV_OBJ_PD);
2184         if (ret) {
2185                 DRV_LOG(DEBUG, "Fail to get PD object info");
2186                 return ret;
2187         }
2188         *pdn = pd_info.pdn;
2189         return 0;
2190 #else
2191         (void)pd;
2192         (void)pdn;
2193         return -ENOTSUP;
2194 #endif /* HAVE_IBV_FLOW_DV_SUPPORT */
2195 }
2196
2197 /**
2198  * Function API to open IB device.
2199  *
2200  * This function calls the Linux glue APIs to open a device.
2201  *
2202  * @param[in] spawn
2203  *   Pointer to the IB device attributes (name, port, etc).
2204  * @param[out] config
2205  *   Pointer to device configuration structure.
2206  * @param[out] sh
2207  *   Pointer to shared context structure.
2208  *
2209  * @return
2210  *   0 on success, a positive error value otherwise.
2211  */
2212 int
2213 mlx5_os_open_device(const struct mlx5_dev_spawn_data *spawn,
2214                      const struct mlx5_dev_config *config,
2215                      struct mlx5_dev_ctx_shared *sh)
2216 {
2217         int dbmap_env;
2218         int err = 0;
2219
2220         sh->numa_node = spawn->pci_dev->device.numa_node;
2221         pthread_mutex_init(&sh->txpp.mutex, NULL);
2222         /*
2223          * Configure environment variable "MLX5_BF_SHUT_UP"
2224          * before the device creation. The rdma_core library
2225          * checks the variable at device creation and
2226          * stores the result internally.
2227          */
2228         dbmap_env = mlx5_config_doorbell_mapping_env(config);
2229         /* Try to open IB device with DV first, then usual Verbs. */
2230         errno = 0;
2231         sh->ctx = mlx5_glue->dv_open_device(spawn->phys_dev);
2232         if (sh->ctx) {
2233                 sh->devx = 1;
2234                 DRV_LOG(DEBUG, "DevX is supported");
2235                 /* The device is created, no need for environment. */
2236                 mlx5_restore_doorbell_mapping_env(dbmap_env);
2237         } else {
2238                 /* The environment variable is still configured. */
2239                 sh->ctx = mlx5_glue->open_device(spawn->phys_dev);
2240                 err = errno ? errno : ENODEV;
2241                 /*
2242                  * The environment variable is not needed anymore,
2243                  * all device creation attempts are completed.
2244                  */
2245                 mlx5_restore_doorbell_mapping_env(dbmap_env);
2246                 if (!sh->ctx)
2247                         return err;
2248                 DRV_LOG(DEBUG, "DevX is NOT supported");
2249                 err = 0;
2250         }
2251         return err;
2252 }
2253
2254 /**
2255  * Install shared asynchronous device events handler.
2256  * This function is implemented to support event sharing
2257  * between multiple ports of single IB device.
2258  *
2259  * @param sh
2260  *   Pointer to mlx5_dev_ctx_shared object.
2261  */
2262 void
2263 mlx5_os_dev_shared_handler_install(struct mlx5_dev_ctx_shared *sh)
2264 {
2265         int ret;
2266         int flags;
2267
2268         sh->intr_handle.fd = -1;
2269         flags = fcntl(((struct ibv_context *)sh->ctx)->async_fd, F_GETFL);
2270         ret = fcntl(((struct ibv_context *)sh->ctx)->async_fd,
2271                     F_SETFL, flags | O_NONBLOCK);
2272         if (ret) {
2273                 DRV_LOG(INFO, "failed to change file descriptor async event"
2274                         " queue");
2275         } else {
2276                 sh->intr_handle.fd = ((struct ibv_context *)sh->ctx)->async_fd;
2277                 sh->intr_handle.type = RTE_INTR_HANDLE_EXT;
2278                 if (rte_intr_callback_register(&sh->intr_handle,
2279                                         mlx5_dev_interrupt_handler, sh)) {
2280                         DRV_LOG(INFO, "Fail to install the shared interrupt.");
2281                         sh->intr_handle.fd = -1;
2282                 }
2283         }
2284         if (sh->devx) {
2285 #ifdef HAVE_IBV_DEVX_ASYNC
2286                 sh->intr_handle_devx.fd = -1;
2287                 sh->devx_comp =
2288                         (void *)mlx5_glue->devx_create_cmd_comp(sh->ctx);
2289                 struct mlx5dv_devx_cmd_comp *devx_comp = sh->devx_comp;
2290                 if (!devx_comp) {
2291                         DRV_LOG(INFO, "failed to allocate devx_comp.");
2292                         return;
2293                 }
2294                 flags = fcntl(devx_comp->fd, F_GETFL);
2295                 ret = fcntl(devx_comp->fd, F_SETFL, flags | O_NONBLOCK);
2296                 if (ret) {
2297                         DRV_LOG(INFO, "failed to change file descriptor"
2298                                 " devx comp");
2299                         return;
2300                 }
2301                 sh->intr_handle_devx.fd = devx_comp->fd;
2302                 sh->intr_handle_devx.type = RTE_INTR_HANDLE_EXT;
2303                 if (rte_intr_callback_register(&sh->intr_handle_devx,
2304                                         mlx5_dev_interrupt_handler_devx, sh)) {
2305                         DRV_LOG(INFO, "Fail to install the devx shared"
2306                                 " interrupt.");
2307                         sh->intr_handle_devx.fd = -1;
2308                 }
2309 #endif /* HAVE_IBV_DEVX_ASYNC */
2310         }
2311 }
2312
2313 /**
2314  * Uninstall shared asynchronous device events handler.
2315  * This function is implemented to support event sharing
2316  * between multiple ports of single IB device.
2317  *
2318  * @param dev
2319  *   Pointer to mlx5_dev_ctx_shared object.
2320  */
2321 void
2322 mlx5_os_dev_shared_handler_uninstall(struct mlx5_dev_ctx_shared *sh)
2323 {
2324         if (sh->intr_handle.fd >= 0)
2325                 mlx5_intr_callback_unregister(&sh->intr_handle,
2326                                               mlx5_dev_interrupt_handler, sh);
2327 #ifdef HAVE_IBV_DEVX_ASYNC
2328         if (sh->intr_handle_devx.fd >= 0)
2329                 rte_intr_callback_unregister(&sh->intr_handle_devx,
2330                                   mlx5_dev_interrupt_handler_devx, sh);
2331         if (sh->devx_comp)
2332                 mlx5_glue->devx_destroy_cmd_comp(sh->devx_comp);
2333 #endif
2334 }
2335
2336 /**
2337  * Read statistics by a named counter.
2338  *
2339  * @param[in] priv
2340  *   Pointer to the private device data structure.
2341  * @param[in] ctr_name
2342  *   Pointer to the name of the statistic counter to read
2343  * @param[out] stat
2344  *   Pointer to read statistic value.
2345  * @return
2346  *   0 on success and stat is valud, 1 if failed to read the value
2347  *   rte_errno is set.
2348  *
2349  */
2350 int
2351 mlx5_os_read_dev_stat(struct mlx5_priv *priv, const char *ctr_name,
2352                       uint64_t *stat)
2353 {
2354         int fd;
2355
2356         if (priv->sh) {
2357                 MKSTR(path, "%s/ports/%d/hw_counters/%s",
2358                       priv->sh->ibdev_path,
2359                       priv->dev_port,
2360                       ctr_name);
2361                 fd = open(path, O_RDONLY);
2362                 /*
2363                  * in switchdev the file location is not per port
2364                  * but rather in <ibdev_path>/hw_counters/<file_name>.
2365                  */
2366                 if (fd == -1) {
2367                         MKSTR(path1, "%s/hw_counters/%s",
2368                               priv->sh->ibdev_path,
2369                               ctr_name);
2370                         fd = open(path1, O_RDONLY);
2371                 }
2372                 if (fd != -1) {
2373                         char buf[21] = {'\0'};
2374                         ssize_t n = read(fd, buf, sizeof(buf));
2375
2376                         close(fd);
2377                         if (n != -1) {
2378                                 *stat = strtoull(buf, NULL, 10);
2379                                 return 0;
2380                         }
2381                 }
2382         }
2383         *stat = 0;
2384         return 1;
2385 }
2386
2387 /**
2388  * Set the reg_mr and dereg_mr call backs
2389  *
2390  * @param reg_mr_cb[out]
2391  *   Pointer to reg_mr func
2392  * @param dereg_mr_cb[out]
2393  *   Pointer to dereg_mr func
2394  *
2395  */
2396 void
2397 mlx5_os_set_reg_mr_cb(mlx5_reg_mr_t *reg_mr_cb,
2398                       mlx5_dereg_mr_t *dereg_mr_cb)
2399 {
2400         *reg_mr_cb = mlx5_verbs_ops.reg_mr;
2401         *dereg_mr_cb = mlx5_verbs_ops.dereg_mr;
2402 }
2403
2404 /**
2405  * Remove a MAC address from device
2406  *
2407  * @param dev
2408  *   Pointer to Ethernet device structure.
2409  * @param index
2410  *   MAC address index.
2411  */
2412 void
2413 mlx5_os_mac_addr_remove(struct rte_eth_dev *dev, uint32_t index)
2414 {
2415         struct mlx5_priv *priv = dev->data->dev_private;
2416         const int vf = priv->config.vf;
2417
2418         if (vf)
2419                 mlx5_nl_mac_addr_remove(priv->nl_socket_route,
2420                                         mlx5_ifindex(dev), priv->mac_own,
2421                                         &dev->data->mac_addrs[index], index);
2422 }
2423
2424 /**
2425  * Adds a MAC address to the device
2426  *
2427  * @param dev
2428  *   Pointer to Ethernet device structure.
2429  * @param mac_addr
2430  *   MAC address to register.
2431  * @param index
2432  *   MAC address index.
2433  *
2434  * @return
2435  *   0 on success, a negative errno value otherwise
2436  */
2437 int
2438 mlx5_os_mac_addr_add(struct rte_eth_dev *dev, struct rte_ether_addr *mac,
2439                      uint32_t index)
2440 {
2441         struct mlx5_priv *priv = dev->data->dev_private;
2442         const int vf = priv->config.vf;
2443         int ret = 0;
2444
2445         if (vf)
2446                 ret = mlx5_nl_mac_addr_add(priv->nl_socket_route,
2447                                            mlx5_ifindex(dev), priv->mac_own,
2448                                            mac, index);
2449         return ret;
2450 }
2451
2452 /**
2453  * Modify a VF MAC address
2454  *
2455  * @param priv
2456  *   Pointer to device private data.
2457  * @param mac_addr
2458  *   MAC address to modify into.
2459  * @param iface_idx
2460  *   Net device interface index
2461  * @param vf_index
2462  *   VF index
2463  *
2464  * @return
2465  *   0 on success, a negative errno value otherwise
2466  */
2467 int
2468 mlx5_os_vf_mac_addr_modify(struct mlx5_priv *priv,
2469                            unsigned int iface_idx,
2470                            struct rte_ether_addr *mac_addr,
2471                            int vf_index)
2472 {
2473         return mlx5_nl_vf_mac_addr_modify
2474                 (priv->nl_socket_route, iface_idx, mac_addr, vf_index);
2475 }
2476
2477 /**
2478  * Set device promiscuous mode
2479  *
2480  * @param dev
2481  *   Pointer to Ethernet device structure.
2482  * @param enable
2483  *   0 - promiscuous is disabled, otherwise - enabled
2484  *
2485  * @return
2486  *   0 on success, a negative error value otherwise
2487  */
2488 int
2489 mlx5_os_set_promisc(struct rte_eth_dev *dev, int enable)
2490 {
2491         struct mlx5_priv *priv = dev->data->dev_private;
2492
2493         return mlx5_nl_promisc(priv->nl_socket_route,
2494                                mlx5_ifindex(dev), !!enable);
2495 }
2496
2497 /**
2498  * Set device promiscuous mode
2499  *
2500  * @param dev
2501  *   Pointer to Ethernet device structure.
2502  * @param enable
2503  *   0 - all multicase is disabled, otherwise - enabled
2504  *
2505  * @return
2506  *   0 on success, a negative error value otherwise
2507  */
2508 int
2509 mlx5_os_set_allmulti(struct rte_eth_dev *dev, int enable)
2510 {
2511         struct mlx5_priv *priv = dev->data->dev_private;
2512
2513         return mlx5_nl_allmulti(priv->nl_socket_route,
2514                                 mlx5_ifindex(dev), !!enable);
2515 }
2516
2517 /**
2518  * Flush device MAC addresses
2519  *
2520  * @param dev
2521  *   Pointer to Ethernet device structure.
2522  *
2523  */
2524 void
2525 mlx5_os_mac_addr_flush(struct rte_eth_dev *dev)
2526 {
2527         struct mlx5_priv *priv = dev->data->dev_private;
2528
2529         mlx5_nl_mac_addr_flush(priv->nl_socket_route, mlx5_ifindex(dev),
2530                                dev->data->mac_addrs,
2531                                MLX5_MAX_MAC_ADDRESSES, priv->mac_own);
2532 }
2533
2534 const struct eth_dev_ops mlx5_os_dev_ops = {
2535         .dev_configure = mlx5_dev_configure,
2536         .dev_start = mlx5_dev_start,
2537         .dev_stop = mlx5_dev_stop,
2538         .dev_set_link_down = mlx5_set_link_down,
2539         .dev_set_link_up = mlx5_set_link_up,
2540         .dev_close = mlx5_dev_close,
2541         .promiscuous_enable = mlx5_promiscuous_enable,
2542         .promiscuous_disable = mlx5_promiscuous_disable,
2543         .allmulticast_enable = mlx5_allmulticast_enable,
2544         .allmulticast_disable = mlx5_allmulticast_disable,
2545         .link_update = mlx5_link_update,
2546         .stats_get = mlx5_stats_get,
2547         .stats_reset = mlx5_stats_reset,
2548         .xstats_get = mlx5_xstats_get,
2549         .xstats_reset = mlx5_xstats_reset,
2550         .xstats_get_names = mlx5_xstats_get_names,
2551         .fw_version_get = mlx5_fw_version_get,
2552         .dev_infos_get = mlx5_dev_infos_get,
2553         .read_clock = mlx5_txpp_read_clock,
2554         .dev_supported_ptypes_get = mlx5_dev_supported_ptypes_get,
2555         .vlan_filter_set = mlx5_vlan_filter_set,
2556         .rx_queue_setup = mlx5_rx_queue_setup,
2557         .rx_hairpin_queue_setup = mlx5_rx_hairpin_queue_setup,
2558         .tx_queue_setup = mlx5_tx_queue_setup,
2559         .tx_hairpin_queue_setup = mlx5_tx_hairpin_queue_setup,
2560         .rx_queue_release = mlx5_rx_queue_release,
2561         .tx_queue_release = mlx5_tx_queue_release,
2562         .rx_queue_start = mlx5_rx_queue_start,
2563         .rx_queue_stop = mlx5_rx_queue_stop,
2564         .tx_queue_start = mlx5_tx_queue_start,
2565         .tx_queue_stop = mlx5_tx_queue_stop,
2566         .flow_ctrl_get = mlx5_dev_get_flow_ctrl,
2567         .flow_ctrl_set = mlx5_dev_set_flow_ctrl,
2568         .mac_addr_remove = mlx5_mac_addr_remove,
2569         .mac_addr_add = mlx5_mac_addr_add,
2570         .mac_addr_set = mlx5_mac_addr_set,
2571         .set_mc_addr_list = mlx5_set_mc_addr_list,
2572         .mtu_set = mlx5_dev_set_mtu,
2573         .vlan_strip_queue_set = mlx5_vlan_strip_queue_set,
2574         .vlan_offload_set = mlx5_vlan_offload_set,
2575         .reta_update = mlx5_dev_rss_reta_update,
2576         .reta_query = mlx5_dev_rss_reta_query,
2577         .rss_hash_update = mlx5_rss_hash_update,
2578         .rss_hash_conf_get = mlx5_rss_hash_conf_get,
2579         .filter_ctrl = mlx5_dev_filter_ctrl,
2580         .rxq_info_get = mlx5_rxq_info_get,
2581         .txq_info_get = mlx5_txq_info_get,
2582         .rx_burst_mode_get = mlx5_rx_burst_mode_get,
2583         .tx_burst_mode_get = mlx5_tx_burst_mode_get,
2584         .rx_queue_intr_enable = mlx5_rx_intr_enable,
2585         .rx_queue_intr_disable = mlx5_rx_intr_disable,
2586         .is_removed = mlx5_is_removed,
2587         .udp_tunnel_port_add  = mlx5_udp_tunnel_port_add,
2588         .get_module_info = mlx5_get_module_info,
2589         .get_module_eeprom = mlx5_get_module_eeprom,
2590         .hairpin_cap_get = mlx5_hairpin_cap_get,
2591         .mtr_ops_get = mlx5_flow_meter_ops_get,
2592         .hairpin_bind = mlx5_hairpin_bind,
2593         .hairpin_unbind = mlx5_hairpin_unbind,
2594         .hairpin_get_peer_ports = mlx5_hairpin_get_peer_ports,
2595         .hairpin_queue_peer_update = mlx5_hairpin_queue_peer_update,
2596         .hairpin_queue_peer_bind = mlx5_hairpin_queue_peer_bind,
2597         .hairpin_queue_peer_unbind = mlx5_hairpin_queue_peer_unbind,
2598 };
2599
2600 /* Available operations from secondary process. */
2601 const struct eth_dev_ops mlx5_os_dev_sec_ops = {
2602         .stats_get = mlx5_stats_get,
2603         .stats_reset = mlx5_stats_reset,
2604         .xstats_get = mlx5_xstats_get,
2605         .xstats_reset = mlx5_xstats_reset,
2606         .xstats_get_names = mlx5_xstats_get_names,
2607         .fw_version_get = mlx5_fw_version_get,
2608         .dev_infos_get = mlx5_dev_infos_get,
2609         .read_clock = mlx5_txpp_read_clock,
2610         .rx_queue_start = mlx5_rx_queue_start,
2611         .rx_queue_stop = mlx5_rx_queue_stop,
2612         .tx_queue_start = mlx5_tx_queue_start,
2613         .tx_queue_stop = mlx5_tx_queue_stop,
2614         .rxq_info_get = mlx5_rxq_info_get,
2615         .txq_info_get = mlx5_txq_info_get,
2616         .rx_burst_mode_get = mlx5_rx_burst_mode_get,
2617         .tx_burst_mode_get = mlx5_tx_burst_mode_get,
2618         .get_module_info = mlx5_get_module_info,
2619         .get_module_eeprom = mlx5_get_module_eeprom,
2620 };
2621
2622 /* Available operations in flow isolated mode. */
2623 const struct eth_dev_ops mlx5_os_dev_ops_isolate = {
2624         .dev_configure = mlx5_dev_configure,
2625         .dev_start = mlx5_dev_start,
2626         .dev_stop = mlx5_dev_stop,
2627         .dev_set_link_down = mlx5_set_link_down,
2628         .dev_set_link_up = mlx5_set_link_up,
2629         .dev_close = mlx5_dev_close,
2630         .promiscuous_enable = mlx5_promiscuous_enable,
2631         .promiscuous_disable = mlx5_promiscuous_disable,
2632         .allmulticast_enable = mlx5_allmulticast_enable,
2633         .allmulticast_disable = mlx5_allmulticast_disable,
2634         .link_update = mlx5_link_update,
2635         .stats_get = mlx5_stats_get,
2636         .stats_reset = mlx5_stats_reset,
2637         .xstats_get = mlx5_xstats_get,
2638         .xstats_reset = mlx5_xstats_reset,
2639         .xstats_get_names = mlx5_xstats_get_names,
2640         .fw_version_get = mlx5_fw_version_get,
2641         .dev_infos_get = mlx5_dev_infos_get,
2642         .read_clock = mlx5_txpp_read_clock,
2643         .dev_supported_ptypes_get = mlx5_dev_supported_ptypes_get,
2644         .vlan_filter_set = mlx5_vlan_filter_set,
2645         .rx_queue_setup = mlx5_rx_queue_setup,
2646         .rx_hairpin_queue_setup = mlx5_rx_hairpin_queue_setup,
2647         .tx_queue_setup = mlx5_tx_queue_setup,
2648         .tx_hairpin_queue_setup = mlx5_tx_hairpin_queue_setup,
2649         .rx_queue_release = mlx5_rx_queue_release,
2650         .tx_queue_release = mlx5_tx_queue_release,
2651         .rx_queue_start = mlx5_rx_queue_start,
2652         .rx_queue_stop = mlx5_rx_queue_stop,
2653         .tx_queue_start = mlx5_tx_queue_start,
2654         .tx_queue_stop = mlx5_tx_queue_stop,
2655         .flow_ctrl_get = mlx5_dev_get_flow_ctrl,
2656         .flow_ctrl_set = mlx5_dev_set_flow_ctrl,
2657         .mac_addr_remove = mlx5_mac_addr_remove,
2658         .mac_addr_add = mlx5_mac_addr_add,
2659         .mac_addr_set = mlx5_mac_addr_set,
2660         .set_mc_addr_list = mlx5_set_mc_addr_list,
2661         .mtu_set = mlx5_dev_set_mtu,
2662         .vlan_strip_queue_set = mlx5_vlan_strip_queue_set,
2663         .vlan_offload_set = mlx5_vlan_offload_set,
2664         .filter_ctrl = mlx5_dev_filter_ctrl,
2665         .rxq_info_get = mlx5_rxq_info_get,
2666         .txq_info_get = mlx5_txq_info_get,
2667         .rx_burst_mode_get = mlx5_rx_burst_mode_get,
2668         .tx_burst_mode_get = mlx5_tx_burst_mode_get,
2669         .rx_queue_intr_enable = mlx5_rx_intr_enable,
2670         .rx_queue_intr_disable = mlx5_rx_intr_disable,
2671         .is_removed = mlx5_is_removed,
2672         .get_module_info = mlx5_get_module_info,
2673         .get_module_eeprom = mlx5_get_module_eeprom,
2674         .hairpin_cap_get = mlx5_hairpin_cap_get,
2675         .mtr_ops_get = mlx5_flow_meter_ops_get,
2676         .hairpin_bind = mlx5_hairpin_bind,
2677         .hairpin_unbind = mlx5_hairpin_unbind,
2678         .hairpin_get_peer_ports = mlx5_hairpin_get_peer_ports,
2679         .hairpin_queue_peer_update = mlx5_hairpin_queue_peer_update,
2680         .hairpin_queue_peer_bind = mlx5_hairpin_queue_peer_bind,
2681         .hairpin_queue_peer_unbind = mlx5_hairpin_queue_peer_unbind,
2682 };