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