net/mlx4: add control of excessive memory pinning by kernel
[dpdk.git] / drivers / net / mlx4 / mlx4.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright 2012 6WIND S.A.
3  * Copyright 2012 Mellanox Technologies, Ltd
4  */
5
6 /**
7  * @file
8  * mlx4 driver initialization.
9  */
10
11 #include <assert.h>
12 #include <dlfcn.h>
13 #include <errno.h>
14 #include <inttypes.h>
15 #include <stddef.h>
16 #include <stdint.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <sys/mman.h>
21 #include <unistd.h>
22
23 /* Verbs headers do not support -pedantic. */
24 #ifdef PEDANTIC
25 #pragma GCC diagnostic ignored "-Wpedantic"
26 #endif
27 #include <infiniband/verbs.h>
28 #ifdef PEDANTIC
29 #pragma GCC diagnostic error "-Wpedantic"
30 #endif
31
32 #include <rte_common.h>
33 #include <rte_config.h>
34 #include <rte_dev.h>
35 #include <rte_errno.h>
36 #include <rte_ethdev_driver.h>
37 #include <rte_ethdev_pci.h>
38 #include <rte_ether.h>
39 #include <rte_flow.h>
40 #include <rte_interrupts.h>
41 #include <rte_kvargs.h>
42 #include <rte_malloc.h>
43 #include <rte_mbuf.h>
44
45 #include "mlx4.h"
46 #include "mlx4_glue.h"
47 #include "mlx4_flow.h"
48 #include "mlx4_mr.h"
49 #include "mlx4_rxtx.h"
50 #include "mlx4_utils.h"
51
52 static const char *MZ_MLX4_PMD_SHARED_DATA = "mlx4_pmd_shared_data";
53
54 /* Shared memory between primary and secondary processes. */
55 struct mlx4_shared_data *mlx4_shared_data;
56
57 /* Spinlock for mlx4_shared_data allocation. */
58 static rte_spinlock_t mlx4_shared_data_lock = RTE_SPINLOCK_INITIALIZER;
59
60 /* Process local data for secondary processes. */
61 static struct mlx4_local_data mlx4_local_data;
62
63 /** Configuration structure for device arguments. */
64 struct mlx4_conf {
65         struct {
66                 uint32_t present; /**< Bit-field for existing ports. */
67                 uint32_t enabled; /**< Bit-field for user-enabled ports. */
68         } ports;
69         int mr_ext_memseg_en;
70         /** Whether memseg should be extended for MR creation. */
71 };
72
73 /* Available parameters list. */
74 const char *pmd_mlx4_init_params[] = {
75         MLX4_PMD_PORT_KVARG,
76         MLX4_MR_EXT_MEMSEG_EN_KVARG,
77         NULL,
78 };
79
80 static void mlx4_dev_stop(struct rte_eth_dev *dev);
81
82 /**
83  * Initialize shared data between primary and secondary process.
84  *
85  * A memzone is reserved by primary process and secondary processes attach to
86  * the memzone.
87  *
88  * @return
89  *   0 on success, a negative errno value otherwise and rte_errno is set.
90  */
91 static int
92 mlx4_init_shared_data(void)
93 {
94         const struct rte_memzone *mz;
95         int ret = 0;
96
97         rte_spinlock_lock(&mlx4_shared_data_lock);
98         if (mlx4_shared_data == NULL) {
99                 if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
100                         /* Allocate shared memory. */
101                         mz = rte_memzone_reserve(MZ_MLX4_PMD_SHARED_DATA,
102                                                  sizeof(*mlx4_shared_data),
103                                                  SOCKET_ID_ANY, 0);
104                         if (mz == NULL) {
105                                 ERROR("Cannot allocate mlx4 shared data\n");
106                                 ret = -rte_errno;
107                                 goto error;
108                         }
109                         mlx4_shared_data = mz->addr;
110                         memset(mlx4_shared_data, 0, sizeof(*mlx4_shared_data));
111                         rte_spinlock_init(&mlx4_shared_data->lock);
112                 } else {
113                         /* Lookup allocated shared memory. */
114                         mz = rte_memzone_lookup(MZ_MLX4_PMD_SHARED_DATA);
115                         if (mz == NULL) {
116                                 ERROR("Cannot attach mlx4 shared data\n");
117                                 ret = -rte_errno;
118                                 goto error;
119                         }
120                         mlx4_shared_data = mz->addr;
121                         memset(&mlx4_local_data, 0, sizeof(mlx4_local_data));
122                 }
123         }
124 error:
125         rte_spinlock_unlock(&mlx4_shared_data_lock);
126         return ret;
127 }
128
129 /**
130  * Uninitialize shared data between primary and secondary process.
131  *
132  * The pointer of secondary process is dereferenced and primary process frees
133  * the memzone.
134  */
135 static void
136 mlx4_uninit_shared_data(void)
137 {
138         const struct rte_memzone *mz;
139
140         rte_spinlock_lock(&mlx4_shared_data_lock);
141         if (mlx4_shared_data) {
142                 if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
143                         mz = rte_memzone_lookup(MZ_MLX4_PMD_SHARED_DATA);
144                         rte_memzone_free(mz);
145                 } else {
146                         memset(&mlx4_local_data, 0, sizeof(mlx4_local_data));
147                 }
148                 mlx4_shared_data = NULL;
149         }
150         rte_spinlock_unlock(&mlx4_shared_data_lock);
151 }
152
153 #ifdef HAVE_IBV_MLX4_BUF_ALLOCATORS
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 libmlx4
158  * (i.e. currently sysconf(_SC_PAGESIZE)).
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 mlx4_alloc_verbs_buf(size_t size, void *data)
170 {
171         struct mlx4_priv *priv = data;
172         void *ret;
173         size_t alignment = sysconf(_SC_PAGESIZE);
174         unsigned int socket = SOCKET_ID_ANY;
175
176         if (priv->verbs_alloc_ctx.type == MLX4_VERBS_ALLOC_TYPE_TX_QUEUE) {
177                 const struct txq *txq = priv->verbs_alloc_ctx.obj;
178
179                 socket = txq->socket;
180         } else if (priv->verbs_alloc_ctx.type ==
181                    MLX4_VERBS_ALLOC_TYPE_RX_QUEUE) {
182                 const struct rxq *rxq = priv->verbs_alloc_ctx.obj;
183
184                 socket = rxq->socket;
185         }
186         assert(data != NULL);
187         ret = rte_malloc_socket(__func__, size, alignment, socket);
188         if (!ret && size)
189                 rte_errno = ENOMEM;
190         return ret;
191 }
192
193 /**
194  * Verbs callback to free a memory.
195  *
196  * @param[in] ptr
197  *   A pointer to the memory to free.
198  * @param[in] data
199  *   A pointer to the callback data.
200  */
201 static void
202 mlx4_free_verbs_buf(void *ptr, void *data __rte_unused)
203 {
204         assert(data != NULL);
205         rte_free(ptr);
206 }
207 #endif
208
209 /**
210  * DPDK callback for Ethernet device configuration.
211  *
212  * @param dev
213  *   Pointer to Ethernet device structure.
214  *
215  * @return
216  *   0 on success, negative errno value otherwise and rte_errno is set.
217  */
218 static int
219 mlx4_dev_configure(struct rte_eth_dev *dev)
220 {
221         struct mlx4_priv *priv = dev->data->dev_private;
222         struct rte_flow_error error;
223         int ret;
224
225         /* Prepare internal flow rules. */
226         ret = mlx4_flow_sync(priv, &error);
227         if (ret) {
228                 ERROR("cannot set up internal flow rules (code %d, \"%s\"),"
229                       " flow error type %d, cause %p, message: %s",
230                       -ret, strerror(-ret), error.type, error.cause,
231                       error.message ? error.message : "(unspecified)");
232                 goto exit;
233         }
234         ret = mlx4_intr_install(priv);
235         if (ret)
236                 ERROR("%p: interrupt handler installation failed",
237                       (void *)dev);
238 exit:
239         return ret;
240 }
241
242 /**
243  * DPDK callback to start the device.
244  *
245  * Simulate device start by initializing common RSS resources and attaching
246  * all configured flows.
247  *
248  * @param dev
249  *   Pointer to Ethernet device structure.
250  *
251  * @return
252  *   0 on success, negative errno value otherwise and rte_errno is set.
253  */
254 static int
255 mlx4_dev_start(struct rte_eth_dev *dev)
256 {
257         struct mlx4_priv *priv = dev->data->dev_private;
258         struct rte_flow_error error;
259         int ret;
260
261         if (priv->started)
262                 return 0;
263         DEBUG("%p: attaching configured flows to all RX queues", (void *)dev);
264         priv->started = 1;
265         ret = mlx4_tx_uar_remap(dev, priv->ctx->cmd_fd);
266         if (ret) {
267                 ERROR("%p: cannot remap UAR", (void *)dev);
268                 goto err;
269         }
270         ret = mlx4_rss_init(priv);
271         if (ret) {
272                 ERROR("%p: cannot initialize RSS resources: %s",
273                       (void *)dev, strerror(-ret));
274                 goto err;
275         }
276 #ifndef NDEBUG
277         mlx4_mr_dump_dev(dev);
278 #endif
279         ret = mlx4_rxq_intr_enable(priv);
280         if (ret) {
281                 ERROR("%p: interrupt handler installation failed",
282                      (void *)dev);
283                 goto err;
284         }
285         ret = mlx4_flow_sync(priv, &error);
286         if (ret) {
287                 ERROR("%p: cannot attach flow rules (code %d, \"%s\"),"
288                       " flow error type %d, cause %p, message: %s",
289                       (void *)dev,
290                       -ret, strerror(-ret), error.type, error.cause,
291                       error.message ? error.message : "(unspecified)");
292                 goto err;
293         }
294         rte_wmb();
295         dev->tx_pkt_burst = mlx4_tx_burst;
296         dev->rx_pkt_burst = mlx4_rx_burst;
297         /* Enable datapath on secondary process. */
298         mlx4_mp_req_start_rxtx(dev);
299         return 0;
300 err:
301         mlx4_dev_stop(dev);
302         return ret;
303 }
304
305 /**
306  * DPDK callback to stop the device.
307  *
308  * Simulate device stop by detaching all configured flows.
309  *
310  * @param dev
311  *   Pointer to Ethernet device structure.
312  */
313 static void
314 mlx4_dev_stop(struct rte_eth_dev *dev)
315 {
316         struct mlx4_priv *priv = dev->data->dev_private;
317         const size_t page_size = sysconf(_SC_PAGESIZE);
318         int i;
319
320         if (!priv->started)
321                 return;
322         DEBUG("%p: detaching flows from all RX queues", (void *)dev);
323         priv->started = 0;
324         dev->tx_pkt_burst = mlx4_tx_burst_removed;
325         dev->rx_pkt_burst = mlx4_rx_burst_removed;
326         rte_wmb();
327         /* Disable datapath on secondary process. */
328         mlx4_mp_req_stop_rxtx(dev);
329         mlx4_flow_sync(priv, NULL);
330         mlx4_rxq_intr_disable(priv);
331         mlx4_rss_deinit(priv);
332         for (i = 0; i != dev->data->nb_tx_queues; ++i) {
333                 struct txq *txq;
334
335                 txq = dev->data->tx_queues[i];
336                 if (!txq)
337                         continue;
338                 munmap((void *)RTE_ALIGN_FLOOR((uintptr_t)txq->msq.db,
339                                                page_size), page_size);
340         }
341 }
342
343 /**
344  * DPDK callback to close the device.
345  *
346  * Destroy all queues and objects, free memory.
347  *
348  * @param dev
349  *   Pointer to Ethernet device structure.
350  */
351 static void
352 mlx4_dev_close(struct rte_eth_dev *dev)
353 {
354         struct mlx4_priv *priv = dev->data->dev_private;
355         unsigned int i;
356
357         DEBUG("%p: closing device \"%s\"",
358               (void *)dev,
359               ((priv->ctx != NULL) ? priv->ctx->device->name : ""));
360         dev->rx_pkt_burst = mlx4_rx_burst_removed;
361         dev->tx_pkt_burst = mlx4_tx_burst_removed;
362         rte_wmb();
363         /* Disable datapath on secondary process. */
364         mlx4_mp_req_stop_rxtx(dev);
365         mlx4_flow_clean(priv);
366         mlx4_rss_deinit(priv);
367         for (i = 0; i != dev->data->nb_rx_queues; ++i)
368                 mlx4_rx_queue_release(dev->data->rx_queues[i]);
369         for (i = 0; i != dev->data->nb_tx_queues; ++i)
370                 mlx4_tx_queue_release(dev->data->tx_queues[i]);
371         mlx4_mr_release(dev);
372         if (priv->pd != NULL) {
373                 assert(priv->ctx != NULL);
374                 claim_zero(mlx4_glue->dealloc_pd(priv->pd));
375                 claim_zero(mlx4_glue->close_device(priv->ctx));
376         } else
377                 assert(priv->ctx == NULL);
378         mlx4_intr_uninstall(priv);
379         memset(priv, 0, sizeof(*priv));
380 }
381
382 static const struct eth_dev_ops mlx4_dev_ops = {
383         .dev_configure = mlx4_dev_configure,
384         .dev_start = mlx4_dev_start,
385         .dev_stop = mlx4_dev_stop,
386         .dev_set_link_down = mlx4_dev_set_link_down,
387         .dev_set_link_up = mlx4_dev_set_link_up,
388         .dev_close = mlx4_dev_close,
389         .link_update = mlx4_link_update,
390         .promiscuous_enable = mlx4_promiscuous_enable,
391         .promiscuous_disable = mlx4_promiscuous_disable,
392         .allmulticast_enable = mlx4_allmulticast_enable,
393         .allmulticast_disable = mlx4_allmulticast_disable,
394         .mac_addr_remove = mlx4_mac_addr_remove,
395         .mac_addr_add = mlx4_mac_addr_add,
396         .mac_addr_set = mlx4_mac_addr_set,
397         .stats_get = mlx4_stats_get,
398         .stats_reset = mlx4_stats_reset,
399         .fw_version_get = mlx4_fw_version_get,
400         .dev_infos_get = mlx4_dev_infos_get,
401         .dev_supported_ptypes_get = mlx4_dev_supported_ptypes_get,
402         .vlan_filter_set = mlx4_vlan_filter_set,
403         .rx_queue_setup = mlx4_rx_queue_setup,
404         .tx_queue_setup = mlx4_tx_queue_setup,
405         .rx_queue_release = mlx4_rx_queue_release,
406         .tx_queue_release = mlx4_tx_queue_release,
407         .flow_ctrl_get = mlx4_flow_ctrl_get,
408         .flow_ctrl_set = mlx4_flow_ctrl_set,
409         .mtu_set = mlx4_mtu_set,
410         .filter_ctrl = mlx4_filter_ctrl,
411         .rx_queue_intr_enable = mlx4_rx_intr_enable,
412         .rx_queue_intr_disable = mlx4_rx_intr_disable,
413         .is_removed = mlx4_is_removed,
414 };
415
416 /* Available operations from secondary process. */
417 static const struct eth_dev_ops mlx4_dev_sec_ops = {
418         .stats_get = mlx4_stats_get,
419         .stats_reset = mlx4_stats_reset,
420         .fw_version_get = mlx4_fw_version_get,
421         .dev_infos_get = mlx4_dev_infos_get,
422 };
423
424 /**
425  * Get PCI information from struct ibv_device.
426  *
427  * @param device
428  *   Pointer to Ethernet device structure.
429  * @param[out] pci_addr
430  *   PCI bus address output buffer.
431  *
432  * @return
433  *   0 on success, negative errno value otherwise and rte_errno is set.
434  */
435 static int
436 mlx4_ibv_device_to_pci_addr(const struct ibv_device *device,
437                             struct rte_pci_addr *pci_addr)
438 {
439         FILE *file;
440         char line[32];
441         MKSTR(path, "%s/device/uevent", device->ibdev_path);
442
443         file = fopen(path, "rb");
444         if (file == NULL) {
445                 rte_errno = errno;
446                 return -rte_errno;
447         }
448         while (fgets(line, sizeof(line), file) == line) {
449                 size_t len = strlen(line);
450                 int ret;
451
452                 /* Truncate long lines. */
453                 if (len == (sizeof(line) - 1))
454                         while (line[(len - 1)] != '\n') {
455                                 ret = fgetc(file);
456                                 if (ret == EOF)
457                                         break;
458                                 line[(len - 1)] = ret;
459                         }
460                 /* Extract information. */
461                 if (sscanf(line,
462                            "PCI_SLOT_NAME="
463                            "%" SCNx32 ":%" SCNx8 ":%" SCNx8 ".%" SCNx8 "\n",
464                            &pci_addr->domain,
465                            &pci_addr->bus,
466                            &pci_addr->devid,
467                            &pci_addr->function) == 4) {
468                         ret = 0;
469                         break;
470                 }
471         }
472         fclose(file);
473         return 0;
474 }
475
476 /**
477  * Verify and store value for device argument.
478  *
479  * @param[in] key
480  *   Key argument to verify.
481  * @param[in] val
482  *   Value associated with key.
483  * @param[in, out] conf
484  *   Shared configuration data.
485  *
486  * @return
487  *   0 on success, negative errno value otherwise and rte_errno is set.
488  */
489 static int
490 mlx4_arg_parse(const char *key, const char *val, struct mlx4_conf *conf)
491 {
492         unsigned long tmp;
493
494         errno = 0;
495         tmp = strtoul(val, NULL, 0);
496         if (errno) {
497                 rte_errno = errno;
498                 WARN("%s: \"%s\" is not a valid integer", key, val);
499                 return -rte_errno;
500         }
501         if (strcmp(MLX4_PMD_PORT_KVARG, key) == 0) {
502                 uint32_t ports = rte_log2_u32(conf->ports.present + 1);
503
504                 if (tmp >= ports) {
505                         ERROR("port index %lu outside range [0,%" PRIu32 ")",
506                               tmp, ports);
507                         return -EINVAL;
508                 }
509                 if (!(conf->ports.present & (1 << tmp))) {
510                         rte_errno = EINVAL;
511                         ERROR("invalid port index %lu", tmp);
512                         return -rte_errno;
513                 }
514                 conf->ports.enabled |= 1 << tmp;
515         } else if (strcmp(MLX4_MR_EXT_MEMSEG_EN_KVARG, key) == 0) {
516                 conf->mr_ext_memseg_en = !!tmp;
517         } else {
518                 rte_errno = EINVAL;
519                 WARN("%s: unknown parameter", key);
520                 return -rte_errno;
521         }
522         return 0;
523 }
524
525 /**
526  * Parse device parameters.
527  *
528  * @param devargs
529  *   Device arguments structure.
530  *
531  * @return
532  *   0 on success, negative errno value otherwise and rte_errno is set.
533  */
534 static int
535 mlx4_args(struct rte_devargs *devargs, struct mlx4_conf *conf)
536 {
537         struct rte_kvargs *kvlist;
538         unsigned int arg_count;
539         int ret = 0;
540         int i;
541
542         if (devargs == NULL)
543                 return 0;
544         kvlist = rte_kvargs_parse(devargs->args, pmd_mlx4_init_params);
545         if (kvlist == NULL) {
546                 rte_errno = EINVAL;
547                 ERROR("failed to parse kvargs");
548                 return -rte_errno;
549         }
550         /* Process parameters. */
551         for (i = 0; pmd_mlx4_init_params[i]; ++i) {
552                 arg_count = rte_kvargs_count(kvlist, pmd_mlx4_init_params[i]);
553                 while (arg_count-- > 0) {
554                         ret = rte_kvargs_process(kvlist,
555                                                  pmd_mlx4_init_params[i],
556                                                  (int (*)(const char *,
557                                                           const char *,
558                                                           void *))
559                                                  mlx4_arg_parse,
560                                                  conf);
561                         if (ret != 0)
562                                 goto free_kvlist;
563                 }
564         }
565 free_kvlist:
566         rte_kvargs_free(kvlist);
567         return ret;
568 }
569
570 /**
571  * Interpret RSS capabilities reported by device.
572  *
573  * This function returns the set of usable Verbs RSS hash fields, kernel
574  * quirks taken into account.
575  *
576  * @param ctx
577  *   Verbs context.
578  * @param pd
579  *   Verbs protection domain.
580  * @param device_attr_ex
581  *   Extended device attributes to interpret.
582  *
583  * @return
584  *   Usable RSS hash fields mask in Verbs format.
585  */
586 static uint64_t
587 mlx4_hw_rss_sup(struct ibv_context *ctx, struct ibv_pd *pd,
588                 struct ibv_device_attr_ex *device_attr_ex)
589 {
590         uint64_t hw_rss_sup = device_attr_ex->rss_caps.rx_hash_fields_mask;
591         struct ibv_cq *cq = NULL;
592         struct ibv_wq *wq = NULL;
593         struct ibv_rwq_ind_table *ind = NULL;
594         struct ibv_qp *qp = NULL;
595
596         if (!hw_rss_sup) {
597                 WARN("no RSS capabilities reported; disabling support for UDP"
598                      " RSS and inner VXLAN RSS");
599                 return IBV_RX_HASH_SRC_IPV4 | IBV_RX_HASH_DST_IPV4 |
600                         IBV_RX_HASH_SRC_IPV6 | IBV_RX_HASH_DST_IPV6 |
601                         IBV_RX_HASH_SRC_PORT_TCP | IBV_RX_HASH_DST_PORT_TCP;
602         }
603         if (!(hw_rss_sup & IBV_RX_HASH_INNER))
604                 return hw_rss_sup;
605         /*
606          * Although reported as supported, missing code in some Linux
607          * versions (v4.15, v4.16) prevents the creation of hash QPs with
608          * inner capability.
609          *
610          * There is no choice but to attempt to instantiate a temporary RSS
611          * context in order to confirm its support.
612          */
613         cq = mlx4_glue->create_cq(ctx, 1, NULL, NULL, 0);
614         wq = cq ? mlx4_glue->create_wq
615                 (ctx,
616                  &(struct ibv_wq_init_attr){
617                         .wq_type = IBV_WQT_RQ,
618                         .max_wr = 1,
619                         .max_sge = 1,
620                         .pd = pd,
621                         .cq = cq,
622                  }) : NULL;
623         ind = wq ? mlx4_glue->create_rwq_ind_table
624                 (ctx,
625                  &(struct ibv_rwq_ind_table_init_attr){
626                         .log_ind_tbl_size = 0,
627                         .ind_tbl = &wq,
628                         .comp_mask = 0,
629                  }) : NULL;
630         qp = ind ? mlx4_glue->create_qp_ex
631                 (ctx,
632                  &(struct ibv_qp_init_attr_ex){
633                         .comp_mask =
634                                 (IBV_QP_INIT_ATTR_PD |
635                                  IBV_QP_INIT_ATTR_RX_HASH |
636                                  IBV_QP_INIT_ATTR_IND_TABLE),
637                         .qp_type = IBV_QPT_RAW_PACKET,
638                         .pd = pd,
639                         .rwq_ind_tbl = ind,
640                         .rx_hash_conf = {
641                                 .rx_hash_function = IBV_RX_HASH_FUNC_TOEPLITZ,
642                                 .rx_hash_key_len = MLX4_RSS_HASH_KEY_SIZE,
643                                 .rx_hash_key = mlx4_rss_hash_key_default,
644                                 .rx_hash_fields_mask = hw_rss_sup,
645                         },
646                  }) : NULL;
647         if (!qp) {
648                 WARN("disabling unusable inner RSS capability due to kernel"
649                      " quirk");
650                 hw_rss_sup &= ~IBV_RX_HASH_INNER;
651         } else {
652                 claim_zero(mlx4_glue->destroy_qp(qp));
653         }
654         if (ind)
655                 claim_zero(mlx4_glue->destroy_rwq_ind_table(ind));
656         if (wq)
657                 claim_zero(mlx4_glue->destroy_wq(wq));
658         if (cq)
659                 claim_zero(mlx4_glue->destroy_cq(cq));
660         return hw_rss_sup;
661 }
662
663 static struct rte_pci_driver mlx4_driver;
664
665 static int
666 find_lower_va_bound(const struct rte_memseg_list *msl,
667                 const struct rte_memseg *ms, void *arg)
668 {
669         void **addr = arg;
670
671         if (msl->external)
672                 return 0;
673         if (*addr == NULL)
674                 *addr = ms->addr;
675         else
676                 *addr = RTE_MIN(*addr, ms->addr);
677
678         return 0;
679 }
680
681 /**
682  * Reserve UAR address space for primary process.
683  *
684  * Process local resource is used by both primary and secondary to avoid
685  * duplicate reservation. The space has to be available on both primary and
686  * secondary process, TXQ UAR maps to this area using fixed mmap w/o double
687  * check.
688  *
689  * @return
690  *   0 on success, a negative errno value otherwise and rte_errno is set.
691  */
692 static int
693 mlx4_uar_init_primary(void)
694 {
695         struct mlx4_shared_data *sd = mlx4_shared_data;
696         void *addr = (void *)0;
697
698         if (sd->uar_base)
699                 return 0;
700         /* find out lower bound of hugepage segments */
701         rte_memseg_walk(find_lower_va_bound, &addr);
702         /* keep distance to hugepages to minimize potential conflicts. */
703         addr = RTE_PTR_SUB(addr, (uintptr_t)(MLX4_UAR_OFFSET + MLX4_UAR_SIZE));
704         /* anonymous mmap, no real memory consumption. */
705         addr = mmap(addr, MLX4_UAR_SIZE,
706                     PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
707         if (addr == MAP_FAILED) {
708                 ERROR("failed to reserve UAR address space, please"
709                       " adjust MLX4_UAR_SIZE or try --base-virtaddr");
710                 rte_errno = ENOMEM;
711                 return -rte_errno;
712         }
713         /* Accept either same addr or a new addr returned from mmap if target
714          * range occupied.
715          */
716         INFO("reserved UAR address space: %p", addr);
717         sd->uar_base = addr; /* for primary and secondary UAR re-mmap. */
718         return 0;
719 }
720
721 /**
722  * Unmap UAR address space reserved for primary process.
723  */
724 static void
725 mlx4_uar_uninit_primary(void)
726 {
727         struct mlx4_shared_data *sd = mlx4_shared_data;
728
729         if (!sd->uar_base)
730                 return;
731         munmap(sd->uar_base, MLX4_UAR_SIZE);
732         sd->uar_base = NULL;
733 }
734
735 /**
736  * Reserve UAR address space for secondary process, align with primary process.
737  *
738  * @return
739  *   0 on success, a negative errno value otherwise and rte_errno is set.
740  */
741 static int
742 mlx4_uar_init_secondary(void)
743 {
744         struct mlx4_shared_data *sd = mlx4_shared_data;
745         struct mlx4_local_data *ld = &mlx4_local_data;
746         void *addr;
747
748         if (ld->uar_base) { /* Already reserved. */
749                 assert(sd->uar_base == ld->uar_base);
750                 return 0;
751         }
752         assert(sd->uar_base);
753         /* anonymous mmap, no real memory consumption. */
754         addr = mmap(sd->uar_base, MLX4_UAR_SIZE,
755                     PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
756         if (addr == MAP_FAILED) {
757                 ERROR("UAR mmap failed: %p size: %llu",
758                       sd->uar_base, MLX4_UAR_SIZE);
759                 rte_errno = ENXIO;
760                 return -rte_errno;
761         }
762         if (sd->uar_base != addr) {
763                 ERROR("UAR address %p size %llu occupied, please"
764                       " adjust MLX4_UAR_OFFSET or try EAL parameter"
765                       " --base-virtaddr",
766                       sd->uar_base, MLX4_UAR_SIZE);
767                 rte_errno = ENXIO;
768                 return -rte_errno;
769         }
770         ld->uar_base = addr;
771         INFO("reserved UAR address space: %p", addr);
772         return 0;
773 }
774
775 /**
776  * Unmap UAR address space reserved for secondary process.
777  */
778 static void
779 mlx4_uar_uninit_secondary(void)
780 {
781         struct mlx4_local_data *ld = &mlx4_local_data;
782
783         if (!ld->uar_base)
784                 return;
785         munmap(ld->uar_base, MLX4_UAR_SIZE);
786         ld->uar_base = NULL;
787 }
788
789 /**
790  * PMD global initialization.
791  *
792  * Independent from individual device, this function initializes global
793  * per-PMD data structures distinguishing primary and secondary processes.
794  * Hence, each initialization is called once per a process.
795  *
796  * @return
797  *   0 on success, a negative errno value otherwise and rte_errno is set.
798  */
799 static int
800 mlx4_init_once(void)
801 {
802         struct mlx4_shared_data *sd;
803         struct mlx4_local_data *ld = &mlx4_local_data;
804         int ret;
805
806         if (mlx4_init_shared_data())
807                 return -rte_errno;
808         sd = mlx4_shared_data;
809         assert(sd);
810         rte_spinlock_lock(&sd->lock);
811         switch (rte_eal_process_type()) {
812         case RTE_PROC_PRIMARY:
813                 if (sd->init_done)
814                         break;
815                 LIST_INIT(&sd->mem_event_cb_list);
816                 rte_rwlock_init(&sd->mem_event_rwlock);
817                 rte_mem_event_callback_register("MLX4_MEM_EVENT_CB",
818                                                 mlx4_mr_mem_event_cb, NULL);
819                 mlx4_mp_init_primary();
820                 ret = mlx4_uar_init_primary();
821                 if (ret)
822                         goto error;
823                 sd->init_done = true;
824                 break;
825         case RTE_PROC_SECONDARY:
826                 if (ld->init_done)
827                         break;
828                 mlx4_mp_init_secondary();
829                 ret = mlx4_uar_init_secondary();
830                 if (ret)
831                         goto error;
832                 ++sd->secondary_cnt;
833                 ld->init_done = true;
834                 break;
835         default:
836                 break;
837         }
838         rte_spinlock_unlock(&sd->lock);
839         return 0;
840 error:
841         switch (rte_eal_process_type()) {
842         case RTE_PROC_PRIMARY:
843                 mlx4_uar_uninit_primary();
844                 mlx4_mp_uninit_primary();
845                 rte_mem_event_callback_unregister("MLX4_MEM_EVENT_CB", NULL);
846                 break;
847         case RTE_PROC_SECONDARY:
848                 mlx4_uar_uninit_secondary();
849                 mlx4_mp_uninit_secondary();
850                 break;
851         default:
852                 break;
853         }
854         rte_spinlock_unlock(&sd->lock);
855         mlx4_uninit_shared_data();
856         return -rte_errno;
857 }
858
859 /**
860  * DPDK callback to register a PCI device.
861  *
862  * This function creates an Ethernet device for each port of a given
863  * PCI device.
864  *
865  * @param[in] pci_drv
866  *   PCI driver structure (mlx4_driver).
867  * @param[in] pci_dev
868  *   PCI device information.
869  *
870  * @return
871  *   0 on success, negative errno value otherwise and rte_errno is set.
872  */
873 static int
874 mlx4_pci_probe(struct rte_pci_driver *pci_drv, struct rte_pci_device *pci_dev)
875 {
876         struct ibv_device **list;
877         struct ibv_device *ibv_dev;
878         int err = 0;
879         struct ibv_context *attr_ctx = NULL;
880         struct ibv_device_attr device_attr;
881         struct ibv_device_attr_ex device_attr_ex;
882         struct mlx4_conf conf = {
883                 .ports.present = 0,
884                 .mr_ext_memseg_en = 1,
885         };
886         unsigned int vf;
887         int i;
888
889         (void)pci_drv;
890         err = mlx4_init_once();
891         if (err) {
892                 ERROR("unable to init PMD global data: %s",
893                       strerror(rte_errno));
894                 return -rte_errno;
895         }
896         assert(pci_drv == &mlx4_driver);
897         list = mlx4_glue->get_device_list(&i);
898         if (list == NULL) {
899                 rte_errno = errno;
900                 assert(rte_errno);
901                 if (rte_errno == ENOSYS)
902                         ERROR("cannot list devices, is ib_uverbs loaded?");
903                 return -rte_errno;
904         }
905         assert(i >= 0);
906         /*
907          * For each listed device, check related sysfs entry against
908          * the provided PCI ID.
909          */
910         while (i != 0) {
911                 struct rte_pci_addr pci_addr;
912
913                 --i;
914                 DEBUG("checking device \"%s\"", list[i]->name);
915                 if (mlx4_ibv_device_to_pci_addr(list[i], &pci_addr))
916                         continue;
917                 if ((pci_dev->addr.domain != pci_addr.domain) ||
918                     (pci_dev->addr.bus != pci_addr.bus) ||
919                     (pci_dev->addr.devid != pci_addr.devid) ||
920                     (pci_dev->addr.function != pci_addr.function))
921                         continue;
922                 vf = (pci_dev->id.device_id ==
923                       PCI_DEVICE_ID_MELLANOX_CONNECTX3VF);
924                 INFO("PCI information matches, using device \"%s\" (VF: %s)",
925                      list[i]->name, (vf ? "true" : "false"));
926                 attr_ctx = mlx4_glue->open_device(list[i]);
927                 err = errno;
928                 break;
929         }
930         if (attr_ctx == NULL) {
931                 mlx4_glue->free_device_list(list);
932                 switch (err) {
933                 case 0:
934                         rte_errno = ENODEV;
935                         ERROR("cannot access device, is mlx4_ib loaded?");
936                         return -rte_errno;
937                 case EINVAL:
938                         rte_errno = EINVAL;
939                         ERROR("cannot use device, are drivers up to date?");
940                         return -rte_errno;
941                 }
942                 assert(err > 0);
943                 rte_errno = err;
944                 return -rte_errno;
945         }
946         ibv_dev = list[i];
947         DEBUG("device opened");
948         if (mlx4_glue->query_device(attr_ctx, &device_attr)) {
949                 err = ENODEV;
950                 goto error;
951         }
952         INFO("%u port(s) detected", device_attr.phys_port_cnt);
953         conf.ports.present |= (UINT64_C(1) << device_attr.phys_port_cnt) - 1;
954         if (mlx4_args(pci_dev->device.devargs, &conf)) {
955                 ERROR("failed to process device arguments");
956                 err = EINVAL;
957                 goto error;
958         }
959         /* Use all ports when none are defined */
960         if (!conf.ports.enabled)
961                 conf.ports.enabled = conf.ports.present;
962         /* Retrieve extended device attributes. */
963         if (mlx4_glue->query_device_ex(attr_ctx, NULL, &device_attr_ex)) {
964                 err = ENODEV;
965                 goto error;
966         }
967         assert(device_attr.max_sge >= MLX4_MAX_SGE);
968         for (i = 0; i < device_attr.phys_port_cnt; i++) {
969                 uint32_t port = i + 1; /* ports are indexed from one */
970                 struct ibv_context *ctx = NULL;
971                 struct ibv_port_attr port_attr;
972                 struct ibv_pd *pd = NULL;
973                 struct mlx4_priv *priv = NULL;
974                 struct rte_eth_dev *eth_dev = NULL;
975                 struct ether_addr mac;
976                 char name[RTE_ETH_NAME_MAX_LEN];
977
978                 /* If port is not enabled, skip. */
979                 if (!(conf.ports.enabled & (1 << i)))
980                         continue;
981                 DEBUG("using port %u", port);
982                 ctx = mlx4_glue->open_device(ibv_dev);
983                 if (ctx == NULL) {
984                         err = ENODEV;
985                         goto port_error;
986                 }
987                 snprintf(name, sizeof(name), "%s port %u",
988                          mlx4_glue->get_device_name(ibv_dev), port);
989                 if (rte_eal_process_type() == RTE_PROC_SECONDARY) {
990                         eth_dev = rte_eth_dev_attach_secondary(name);
991                         if (eth_dev == NULL) {
992                                 ERROR("can not attach rte ethdev");
993                                 rte_errno = ENOMEM;
994                                 err = rte_errno;
995                                 goto error;
996                         }
997                         priv = eth_dev->data->dev_private;
998                         if (!priv->verbs_alloc_ctx.enabled) {
999                                 ERROR("secondary process is not supported"
1000                                       " due to lack of external allocator"
1001                                       " from Verbs");
1002                                 rte_errno = ENOTSUP;
1003                                 err = rte_errno;
1004                                 goto error;
1005                         }
1006                         eth_dev->device = &pci_dev->device;
1007                         eth_dev->dev_ops = &mlx4_dev_sec_ops;
1008                         /* Receive command fd from primary process. */
1009                         err = mlx4_mp_req_verbs_cmd_fd(eth_dev);
1010                         if (err < 0) {
1011                                 err = rte_errno;
1012                                 goto error;
1013                         }
1014                         /* Remap UAR for Tx queues. */
1015                         err = mlx4_tx_uar_remap(eth_dev, err);
1016                         if (err) {
1017                                 err = rte_errno;
1018                                 goto error;
1019                         }
1020                         /*
1021                          * Ethdev pointer is still required as input since
1022                          * the primary device is not accessible from the
1023                          * secondary process.
1024                          */
1025                         eth_dev->tx_pkt_burst = mlx4_tx_burst;
1026                         eth_dev->rx_pkt_burst = mlx4_rx_burst;
1027                         claim_zero(mlx4_glue->close_device(ctx));
1028                         rte_eth_copy_pci_info(eth_dev, pci_dev);
1029                         rte_eth_dev_probing_finish(eth_dev);
1030                         continue;
1031                 }
1032                 /* Check port status. */
1033                 err = mlx4_glue->query_port(ctx, port, &port_attr);
1034                 if (err) {
1035                         err = ENODEV;
1036                         ERROR("port query failed: %s", strerror(err));
1037                         goto port_error;
1038                 }
1039                 if (port_attr.link_layer != IBV_LINK_LAYER_ETHERNET) {
1040                         err = ENOTSUP;
1041                         ERROR("port %d is not configured in Ethernet mode",
1042                               port);
1043                         goto port_error;
1044                 }
1045                 if (port_attr.state != IBV_PORT_ACTIVE)
1046                         DEBUG("port %d is not active: \"%s\" (%d)",
1047                               port, mlx4_glue->port_state_str(port_attr.state),
1048                               port_attr.state);
1049                 /* Make asynchronous FD non-blocking to handle interrupts. */
1050                 err = mlx4_fd_set_non_blocking(ctx->async_fd);
1051                 if (err) {
1052                         ERROR("cannot make asynchronous FD non-blocking: %s",
1053                               strerror(err));
1054                         goto port_error;
1055                 }
1056                 /* Allocate protection domain. */
1057                 pd = mlx4_glue->alloc_pd(ctx);
1058                 if (pd == NULL) {
1059                         err = ENOMEM;
1060                         ERROR("PD allocation failure");
1061                         goto port_error;
1062                 }
1063                 /* from rte_ethdev.c */
1064                 priv = rte_zmalloc("ethdev private structure",
1065                                    sizeof(*priv),
1066                                    RTE_CACHE_LINE_SIZE);
1067                 if (priv == NULL) {
1068                         err = ENOMEM;
1069                         ERROR("priv allocation failure");
1070                         goto port_error;
1071                 }
1072                 priv->ctx = ctx;
1073                 priv->device_attr = device_attr;
1074                 priv->port = port;
1075                 priv->pd = pd;
1076                 priv->mtu = ETHER_MTU;
1077                 priv->vf = vf;
1078                 priv->hw_csum = !!(device_attr.device_cap_flags &
1079                                    IBV_DEVICE_RAW_IP_CSUM);
1080                 DEBUG("checksum offloading is %ssupported",
1081                       (priv->hw_csum ? "" : "not "));
1082                 /* Only ConnectX-3 Pro supports tunneling. */
1083                 priv->hw_csum_l2tun =
1084                         priv->hw_csum &&
1085                         (device_attr.vendor_part_id ==
1086                          PCI_DEVICE_ID_MELLANOX_CONNECTX3PRO);
1087                 DEBUG("L2 tunnel checksum offloads are %ssupported",
1088                       priv->hw_csum_l2tun ? "" : "not ");
1089                 priv->hw_rss_sup = mlx4_hw_rss_sup(priv->ctx, priv->pd,
1090                                                    &device_attr_ex);
1091                 DEBUG("supported RSS hash fields mask: %016" PRIx64,
1092                       priv->hw_rss_sup);
1093                 priv->hw_rss_max_qps =
1094                         device_attr_ex.rss_caps.max_rwq_indirection_table_size;
1095                 DEBUG("MAX RSS queues %d", priv->hw_rss_max_qps);
1096                 priv->hw_fcs_strip = !!(device_attr_ex.raw_packet_caps &
1097                                         IBV_RAW_PACKET_CAP_SCATTER_FCS);
1098                 DEBUG("FCS stripping toggling is %ssupported",
1099                       priv->hw_fcs_strip ? "" : "not ");
1100                 priv->tso =
1101                         ((device_attr_ex.tso_caps.max_tso > 0) &&
1102                          (device_attr_ex.tso_caps.supported_qpts &
1103                           (1 << IBV_QPT_RAW_PACKET)));
1104                 if (priv->tso)
1105                         priv->tso_max_payload_sz =
1106                                         device_attr_ex.tso_caps.max_tso;
1107                 DEBUG("TSO is %ssupported",
1108                       priv->tso ? "" : "not ");
1109                 priv->mr_ext_memseg_en = conf.mr_ext_memseg_en;
1110                 /* Configure the first MAC address by default. */
1111                 err = mlx4_get_mac(priv, &mac.addr_bytes);
1112                 if (err) {
1113                         ERROR("cannot get MAC address, is mlx4_en loaded?"
1114                               " (error: %s)", strerror(err));
1115                         goto port_error;
1116                 }
1117                 INFO("port %u MAC address is %02x:%02x:%02x:%02x:%02x:%02x",
1118                      priv->port,
1119                      mac.addr_bytes[0], mac.addr_bytes[1],
1120                      mac.addr_bytes[2], mac.addr_bytes[3],
1121                      mac.addr_bytes[4], mac.addr_bytes[5]);
1122                 /* Register MAC address. */
1123                 priv->mac[0] = mac;
1124 #ifndef NDEBUG
1125                 {
1126                         char ifname[IF_NAMESIZE];
1127
1128                         if (mlx4_get_ifname(priv, &ifname) == 0)
1129                                 DEBUG("port %u ifname is \"%s\"",
1130                                       priv->port, ifname);
1131                         else
1132                                 DEBUG("port %u ifname is unknown", priv->port);
1133                 }
1134 #endif
1135                 /* Get actual MTU if possible. */
1136                 mlx4_mtu_get(priv, &priv->mtu);
1137                 DEBUG("port %u MTU is %u", priv->port, priv->mtu);
1138                 eth_dev = rte_eth_dev_allocate(name);
1139                 if (eth_dev == NULL) {
1140                         err = ENOMEM;
1141                         ERROR("can not allocate rte ethdev");
1142                         goto port_error;
1143                 }
1144                 eth_dev->data->dev_private = priv;
1145                 eth_dev->data->mac_addrs = priv->mac;
1146                 eth_dev->device = &pci_dev->device;
1147                 rte_eth_copy_pci_info(eth_dev, pci_dev);
1148                 /* Initialize local interrupt handle for current port. */
1149                 priv->intr_handle = (struct rte_intr_handle){
1150                         .fd = -1,
1151                         .type = RTE_INTR_HANDLE_EXT,
1152                 };
1153                 /*
1154                  * Override ethdev interrupt handle pointer with private
1155                  * handle instead of that of the parent PCI device used by
1156                  * default. This prevents it from being shared between all
1157                  * ports of the same PCI device since each of them is
1158                  * associated its own Verbs context.
1159                  *
1160                  * Rx interrupts in particular require this as the PMD has
1161                  * no control over the registration of queue interrupts
1162                  * besides setting up eth_dev->intr_handle, the rest is
1163                  * handled by rte_intr_rx_ctl().
1164                  */
1165                 eth_dev->intr_handle = &priv->intr_handle;
1166                 priv->dev_data = eth_dev->data;
1167                 eth_dev->dev_ops = &mlx4_dev_ops;
1168 #ifdef HAVE_IBV_MLX4_BUF_ALLOCATORS
1169                 /* Hint libmlx4 to use PMD allocator for data plane resources */
1170                 struct mlx4dv_ctx_allocators alctr = {
1171                         .alloc = &mlx4_alloc_verbs_buf,
1172                         .free = &mlx4_free_verbs_buf,
1173                         .data = priv,
1174                 };
1175                 err = mlx4_glue->dv_set_context_attr
1176                         (ctx, MLX4DV_SET_CTX_ATTR_BUF_ALLOCATORS,
1177                          (void *)((uintptr_t)&alctr));
1178                 if (err)
1179                         WARN("Verbs external allocator is not supported");
1180                 else
1181                         priv->verbs_alloc_ctx.enabled = 1;
1182 #endif
1183                 /* Bring Ethernet device up. */
1184                 DEBUG("forcing Ethernet interface up");
1185                 mlx4_dev_set_link_up(eth_dev);
1186                 /* Update link status once if waiting for LSC. */
1187                 if (eth_dev->data->dev_flags & RTE_ETH_DEV_INTR_LSC)
1188                         mlx4_link_update(eth_dev, 0);
1189                 /*
1190                  * Once the device is added to the list of memory event
1191                  * callback, its global MR cache table cannot be expanded
1192                  * on the fly because of deadlock. If it overflows, lookup
1193                  * should be done by searching MR list linearly, which is slow.
1194                  */
1195                 err = mlx4_mr_btree_init(&priv->mr.cache,
1196                                          MLX4_MR_BTREE_CACHE_N * 2,
1197                                          eth_dev->device->numa_node);
1198                 if (err) {
1199                         /* rte_errno is already set. */
1200                         goto port_error;
1201                 }
1202                 /* Add device to memory callback list. */
1203                 rte_rwlock_write_lock(&mlx4_shared_data->mem_event_rwlock);
1204                 LIST_INSERT_HEAD(&mlx4_shared_data->mem_event_cb_list,
1205                                  priv, mem_event_cb);
1206                 rte_rwlock_write_unlock(&mlx4_shared_data->mem_event_rwlock);
1207                 rte_eth_dev_probing_finish(eth_dev);
1208                 continue;
1209 port_error:
1210                 rte_free(priv);
1211                 if (eth_dev != NULL)
1212                         eth_dev->data->dev_private = NULL;
1213                 if (pd)
1214                         claim_zero(mlx4_glue->dealloc_pd(pd));
1215                 if (ctx)
1216                         claim_zero(mlx4_glue->close_device(ctx));
1217                 if (eth_dev != NULL) {
1218                         /* mac_addrs must not be freed because part of dev_private */
1219                         eth_dev->data->mac_addrs = NULL;
1220                         rte_eth_dev_release_port(eth_dev);
1221                 }
1222                 break;
1223         }
1224         /*
1225          * XXX if something went wrong in the loop above, there is a resource
1226          * leak (ctx, pd, priv, dpdk ethdev) but we can do nothing about it as
1227          * long as the dpdk does not provide a way to deallocate a ethdev and a
1228          * way to enumerate the registered ethdevs to free the previous ones.
1229          */
1230 error:
1231         if (attr_ctx)
1232                 claim_zero(mlx4_glue->close_device(attr_ctx));
1233         if (list)
1234                 mlx4_glue->free_device_list(list);
1235         if (err)
1236                 rte_errno = err;
1237         return -err;
1238 }
1239
1240 static const struct rte_pci_id mlx4_pci_id_map[] = {
1241         {
1242                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
1243                                PCI_DEVICE_ID_MELLANOX_CONNECTX3)
1244         },
1245         {
1246                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
1247                                PCI_DEVICE_ID_MELLANOX_CONNECTX3PRO)
1248         },
1249         {
1250                 RTE_PCI_DEVICE(PCI_VENDOR_ID_MELLANOX,
1251                                PCI_DEVICE_ID_MELLANOX_CONNECTX3VF)
1252         },
1253         {
1254                 .vendor_id = 0
1255         }
1256 };
1257
1258 static struct rte_pci_driver mlx4_driver = {
1259         .driver = {
1260                 .name = MLX4_DRIVER_NAME
1261         },
1262         .id_table = mlx4_pci_id_map,
1263         .probe = mlx4_pci_probe,
1264         .drv_flags = RTE_PCI_DRV_INTR_LSC |
1265                      RTE_PCI_DRV_INTR_RMV,
1266 };
1267
1268 #ifdef RTE_IBVERBS_LINK_DLOPEN
1269
1270 /**
1271  * Suffix RTE_EAL_PMD_PATH with "-glue".
1272  *
1273  * This function performs a sanity check on RTE_EAL_PMD_PATH before
1274  * suffixing its last component.
1275  *
1276  * @param buf[out]
1277  *   Output buffer, should be large enough otherwise NULL is returned.
1278  * @param size
1279  *   Size of @p out.
1280  *
1281  * @return
1282  *   Pointer to @p buf or @p NULL in case suffix cannot be appended.
1283  */
1284 static char *
1285 mlx4_glue_path(char *buf, size_t size)
1286 {
1287         static const char *const bad[] = { "/", ".", "..", NULL };
1288         const char *path = RTE_EAL_PMD_PATH;
1289         size_t len = strlen(path);
1290         size_t off;
1291         int i;
1292
1293         while (len && path[len - 1] == '/')
1294                 --len;
1295         for (off = len; off && path[off - 1] != '/'; --off)
1296                 ;
1297         for (i = 0; bad[i]; ++i)
1298                 if (!strncmp(path + off, bad[i], (int)(len - off)))
1299                         goto error;
1300         i = snprintf(buf, size, "%.*s-glue", (int)len, path);
1301         if (i == -1 || (size_t)i >= size)
1302                 goto error;
1303         return buf;
1304 error:
1305         ERROR("unable to append \"-glue\" to last component of"
1306               " RTE_EAL_PMD_PATH (\"" RTE_EAL_PMD_PATH "\"),"
1307               " please re-configure DPDK");
1308         return NULL;
1309 }
1310
1311 /**
1312  * Initialization routine for run-time dependency on rdma-core.
1313  */
1314 static int
1315 mlx4_glue_init(void)
1316 {
1317         char glue_path[sizeof(RTE_EAL_PMD_PATH) - 1 + sizeof("-glue")];
1318         const char *path[] = {
1319                 /*
1320                  * A basic security check is necessary before trusting
1321                  * MLX4_GLUE_PATH, which may override RTE_EAL_PMD_PATH.
1322                  */
1323                 (geteuid() == getuid() && getegid() == getgid() ?
1324                  getenv("MLX4_GLUE_PATH") : NULL),
1325                 /*
1326                  * When RTE_EAL_PMD_PATH is set, use its glue-suffixed
1327                  * variant, otherwise let dlopen() look up libraries on its
1328                  * own.
1329                  */
1330                 (*RTE_EAL_PMD_PATH ?
1331                  mlx4_glue_path(glue_path, sizeof(glue_path)) : ""),
1332         };
1333         unsigned int i = 0;
1334         void *handle = NULL;
1335         void **sym;
1336         const char *dlmsg;
1337
1338         while (!handle && i != RTE_DIM(path)) {
1339                 const char *end;
1340                 size_t len;
1341                 int ret;
1342
1343                 if (!path[i]) {
1344                         ++i;
1345                         continue;
1346                 }
1347                 end = strpbrk(path[i], ":;");
1348                 if (!end)
1349                         end = path[i] + strlen(path[i]);
1350                 len = end - path[i];
1351                 ret = 0;
1352                 do {
1353                         char name[ret + 1];
1354
1355                         ret = snprintf(name, sizeof(name), "%.*s%s" MLX4_GLUE,
1356                                        (int)len, path[i],
1357                                        (!len || *(end - 1) == '/') ? "" : "/");
1358                         if (ret == -1)
1359                                 break;
1360                         if (sizeof(name) != (size_t)ret + 1)
1361                                 continue;
1362                         DEBUG("looking for rdma-core glue as \"%s\"", name);
1363                         handle = dlopen(name, RTLD_LAZY);
1364                         break;
1365                 } while (1);
1366                 path[i] = end + 1;
1367                 if (!*end)
1368                         ++i;
1369         }
1370         if (!handle) {
1371                 rte_errno = EINVAL;
1372                 dlmsg = dlerror();
1373                 if (dlmsg)
1374                         WARN("cannot load glue library: %s", dlmsg);
1375                 goto glue_error;
1376         }
1377         sym = dlsym(handle, "mlx4_glue");
1378         if (!sym || !*sym) {
1379                 rte_errno = EINVAL;
1380                 dlmsg = dlerror();
1381                 if (dlmsg)
1382                         ERROR("cannot resolve glue symbol: %s", dlmsg);
1383                 goto glue_error;
1384         }
1385         mlx4_glue = *sym;
1386         return 0;
1387 glue_error:
1388         if (handle)
1389                 dlclose(handle);
1390         WARN("cannot initialize PMD due to missing run-time"
1391              " dependency on rdma-core libraries (libibverbs,"
1392              " libmlx4)");
1393         return -rte_errno;
1394 }
1395
1396 #endif
1397
1398 /**
1399  * Driver initialization routine.
1400  */
1401 RTE_INIT(rte_mlx4_pmd_init)
1402 {
1403         /*
1404          * MLX4_DEVICE_FATAL_CLEANUP tells ibv_destroy functions we
1405          * want to get success errno value in case of calling them
1406          * when the device was removed.
1407          */
1408         setenv("MLX4_DEVICE_FATAL_CLEANUP", "1", 1);
1409         /*
1410          * RDMAV_HUGEPAGES_SAFE tells ibv_fork_init() we intend to use
1411          * huge pages. Calling ibv_fork_init() during init allows
1412          * applications to use fork() safely for purposes other than
1413          * using this PMD, which is not supported in forked processes.
1414          */
1415         setenv("RDMAV_HUGEPAGES_SAFE", "1", 1);
1416 #ifdef RTE_IBVERBS_LINK_DLOPEN
1417         if (mlx4_glue_init())
1418                 return;
1419         assert(mlx4_glue);
1420 #endif
1421 #ifndef NDEBUG
1422         /* Glue structure must not contain any NULL pointers. */
1423         {
1424                 unsigned int i;
1425
1426                 for (i = 0; i != sizeof(*mlx4_glue) / sizeof(void *); ++i)
1427                         assert(((const void *const *)mlx4_glue)[i]);
1428         }
1429 #endif
1430         if (strcmp(mlx4_glue->version, MLX4_GLUE_VERSION)) {
1431                 ERROR("rdma-core glue \"%s\" mismatch: \"%s\" is required",
1432                       mlx4_glue->version, MLX4_GLUE_VERSION);
1433                 return;
1434         }
1435         mlx4_glue->fork_init();
1436         rte_pci_register(&mlx4_driver);
1437 }
1438
1439 RTE_PMD_EXPORT_NAME(net_mlx4, __COUNTER__);
1440 RTE_PMD_REGISTER_PCI_TABLE(net_mlx4, mlx4_pci_id_map);
1441 RTE_PMD_REGISTER_KMOD_DEP(net_mlx4,
1442         "* ib_uverbs & mlx4_en & mlx4_core & mlx4_ib");