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