aae67b28f0b585352bdf317593fc61e57e65919a
[dpdk.git] / lib / librte_eal / linux / eal / eal.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2010-2018 Intel Corporation.
3  * Copyright(c) 2012-2014 6WIND S.A.
4  */
5
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <stdint.h>
9 #include <string.h>
10 #include <stdarg.h>
11 #include <unistd.h>
12 #include <pthread.h>
13 #include <syslog.h>
14 #include <getopt.h>
15 #include <sys/file.h>
16 #include <dirent.h>
17 #include <fcntl.h>
18 #include <fnmatch.h>
19 #include <stddef.h>
20 #include <errno.h>
21 #include <limits.h>
22 #include <sys/mman.h>
23 #include <sys/queue.h>
24 #include <sys/stat.h>
25 #if defined(RTE_ARCH_X86)
26 #include <sys/io.h>
27 #endif
28
29 #include <rte_compat.h>
30 #include <rte_common.h>
31 #include <rte_debug.h>
32 #include <rte_memory.h>
33 #include <rte_launch.h>
34 #include <rte_eal.h>
35 #include <rte_errno.h>
36 #include <rte_per_lcore.h>
37 #include <rte_lcore.h>
38 #include <rte_service_component.h>
39 #include <rte_log.h>
40 #include <rte_random.h>
41 #include <rte_cycles.h>
42 #include <rte_string_fns.h>
43 #include <rte_cpuflags.h>
44 #include <rte_interrupts.h>
45 #include <rte_bus.h>
46 #include <rte_dev.h>
47 #include <rte_devargs.h>
48 #include <rte_version.h>
49 #include <rte_atomic.h>
50 #include <malloc_heap.h>
51 #include <rte_vfio.h>
52 #include <rte_option.h>
53
54 #include "eal_private.h"
55 #include "eal_thread.h"
56 #include "eal_internal_cfg.h"
57 #include "eal_filesystem.h"
58 #include "eal_hugepages.h"
59 #include "eal_memcfg.h"
60 #include "eal_options.h"
61 #include "eal_vfio.h"
62 #include "hotplug_mp.h"
63
64 #define MEMSIZE_IF_NO_HUGE_PAGE (64ULL * 1024ULL * 1024ULL)
65
66 #define SOCKET_MEM_STRLEN (RTE_MAX_NUMA_NODES * 10)
67
68 #define KERNEL_IOMMU_GROUPS_PATH "/sys/kernel/iommu_groups"
69
70 /* Allow the application to print its usage message too if set */
71 static rte_usage_hook_t rte_application_usage_hook = NULL;
72
73 /* early configuration structure, when memory config is not mmapped */
74 static struct rte_mem_config early_mem_config;
75
76 /* define fd variable here, because file needs to be kept open for the
77  * duration of the program, as we hold a write lock on it in the primary proc */
78 static int mem_cfg_fd = -1;
79
80 static struct flock wr_lock = {
81                 .l_type = F_WRLCK,
82                 .l_whence = SEEK_SET,
83                 .l_start = offsetof(struct rte_mem_config, memsegs),
84                 .l_len = sizeof(early_mem_config.memsegs),
85 };
86
87 /* Address of global and public configuration */
88 static struct rte_config rte_config = {
89                 .mem_config = &early_mem_config,
90 };
91
92 /* internal configuration (per-core) */
93 struct lcore_config lcore_config[RTE_MAX_LCORE];
94
95 /* internal configuration */
96 struct internal_config internal_config;
97
98 /* used by rte_rdtsc() */
99 int rte_cycles_vmware_tsc_map;
100
101 /* platform-specific runtime dir */
102 static char runtime_dir[PATH_MAX];
103
104 static const char *default_runtime_dir = "/var/run";
105
106 int
107 eal_create_runtime_dir(void)
108 {
109         const char *directory = default_runtime_dir;
110         const char *xdg_runtime_dir = getenv("XDG_RUNTIME_DIR");
111         const char *fallback = "/tmp";
112         char tmp[PATH_MAX];
113         int ret;
114
115         if (getuid() != 0) {
116                 /* try XDG path first, fall back to /tmp */
117                 if (xdg_runtime_dir != NULL)
118                         directory = xdg_runtime_dir;
119                 else
120                         directory = fallback;
121         }
122         /* create DPDK subdirectory under runtime dir */
123         ret = snprintf(tmp, sizeof(tmp), "%s/dpdk", directory);
124         if (ret < 0 || ret == sizeof(tmp)) {
125                 RTE_LOG(ERR, EAL, "Error creating DPDK runtime path name\n");
126                 return -1;
127         }
128
129         /* create prefix-specific subdirectory under DPDK runtime dir */
130         ret = snprintf(runtime_dir, sizeof(runtime_dir), "%s/%s",
131                         tmp, eal_get_hugefile_prefix());
132         if (ret < 0 || ret == sizeof(runtime_dir)) {
133                 RTE_LOG(ERR, EAL, "Error creating prefix-specific runtime path name\n");
134                 return -1;
135         }
136
137         /* create the path if it doesn't exist. no "mkdir -p" here, so do it
138          * step by step.
139          */
140         ret = mkdir(tmp, 0700);
141         if (ret < 0 && errno != EEXIST) {
142                 RTE_LOG(ERR, EAL, "Error creating '%s': %s\n",
143                         tmp, strerror(errno));
144                 return -1;
145         }
146
147         ret = mkdir(runtime_dir, 0700);
148         if (ret < 0 && errno != EEXIST) {
149                 RTE_LOG(ERR, EAL, "Error creating '%s': %s\n",
150                         runtime_dir, strerror(errno));
151                 return -1;
152         }
153
154         return 0;
155 }
156
157 int
158 eal_clean_runtime_dir(void)
159 {
160         DIR *dir;
161         struct dirent *dirent;
162         int dir_fd, fd, lck_result;
163         static const char * const filters[] = {
164                 "fbarray_*",
165                 "mp_socket_*"
166         };
167
168         /* open directory */
169         dir = opendir(runtime_dir);
170         if (!dir) {
171                 RTE_LOG(ERR, EAL, "Unable to open runtime directory %s\n",
172                                 runtime_dir);
173                 goto error;
174         }
175         dir_fd = dirfd(dir);
176
177         /* lock the directory before doing anything, to avoid races */
178         if (flock(dir_fd, LOCK_EX) < 0) {
179                 RTE_LOG(ERR, EAL, "Unable to lock runtime directory %s\n",
180                         runtime_dir);
181                 goto error;
182         }
183
184         dirent = readdir(dir);
185         if (!dirent) {
186                 RTE_LOG(ERR, EAL, "Unable to read runtime directory %s\n",
187                                 runtime_dir);
188                 goto error;
189         }
190
191         while (dirent != NULL) {
192                 unsigned int f_idx;
193                 bool skip = true;
194
195                 /* skip files that don't match the patterns */
196                 for (f_idx = 0; f_idx < RTE_DIM(filters); f_idx++) {
197                         const char *filter = filters[f_idx];
198
199                         if (fnmatch(filter, dirent->d_name, 0) == 0) {
200                                 skip = false;
201                                 break;
202                         }
203                 }
204                 if (skip) {
205                         dirent = readdir(dir);
206                         continue;
207                 }
208
209                 /* try and lock the file */
210                 fd = openat(dir_fd, dirent->d_name, O_RDONLY);
211
212                 /* skip to next file */
213                 if (fd == -1) {
214                         dirent = readdir(dir);
215                         continue;
216                 }
217
218                 /* non-blocking lock */
219                 lck_result = flock(fd, LOCK_EX | LOCK_NB);
220
221                 /* if lock succeeds, remove the file */
222                 if (lck_result != -1)
223                         unlinkat(dir_fd, dirent->d_name, 0);
224                 close(fd);
225                 dirent = readdir(dir);
226         }
227
228         /* closedir closes dir_fd and drops the lock */
229         closedir(dir);
230         return 0;
231
232 error:
233         if (dir)
234                 closedir(dir);
235
236         RTE_LOG(ERR, EAL, "Error while clearing runtime dir: %s\n",
237                 strerror(errno));
238
239         return -1;
240 }
241
242 const char *
243 rte_eal_get_runtime_dir(void)
244 {
245         return runtime_dir;
246 }
247
248 /* Return user provided mbuf pool ops name */
249 const char *
250 rte_eal_mbuf_user_pool_ops(void)
251 {
252         return internal_config.user_mbuf_pool_ops_name;
253 }
254
255 /* Return a pointer to the configuration structure */
256 struct rte_config *
257 rte_eal_get_configuration(void)
258 {
259         return &rte_config;
260 }
261
262 enum rte_iova_mode
263 rte_eal_iova_mode(void)
264 {
265         return rte_eal_get_configuration()->iova_mode;
266 }
267
268 /* parse a sysfs (or other) file containing one integer value */
269 int
270 eal_parse_sysfs_value(const char *filename, unsigned long *val)
271 {
272         FILE *f;
273         char buf[BUFSIZ];
274         char *end = NULL;
275
276         if ((f = fopen(filename, "r")) == NULL) {
277                 RTE_LOG(ERR, EAL, "%s(): cannot open sysfs value %s\n",
278                         __func__, filename);
279                 return -1;
280         }
281
282         if (fgets(buf, sizeof(buf), f) == NULL) {
283                 RTE_LOG(ERR, EAL, "%s(): cannot read sysfs value %s\n",
284                         __func__, filename);
285                 fclose(f);
286                 return -1;
287         }
288         *val = strtoul(buf, &end, 0);
289         if ((buf[0] == '\0') || (end == NULL) || (*end != '\n')) {
290                 RTE_LOG(ERR, EAL, "%s(): cannot parse sysfs value %s\n",
291                                 __func__, filename);
292                 fclose(f);
293                 return -1;
294         }
295         fclose(f);
296         return 0;
297 }
298
299
300 /* create memory configuration in shared/mmap memory. Take out
301  * a write lock on the memsegs, so we can auto-detect primary/secondary.
302  * This means we never close the file while running (auto-close on exit).
303  * We also don't lock the whole file, so that in future we can use read-locks
304  * on other parts, e.g. memzones, to detect if there are running secondary
305  * processes. */
306 static int
307 rte_eal_config_create(void)
308 {
309         void *rte_mem_cfg_addr;
310         int retval;
311
312         const char *pathname = eal_runtime_config_path();
313
314         if (internal_config.no_shconf)
315                 return 0;
316
317         /* map the config before hugepage address so that we don't waste a page */
318         if (internal_config.base_virtaddr != 0)
319                 rte_mem_cfg_addr = (void *)
320                         RTE_ALIGN_FLOOR(internal_config.base_virtaddr -
321                         sizeof(struct rte_mem_config), sysconf(_SC_PAGE_SIZE));
322         else
323                 rte_mem_cfg_addr = NULL;
324
325         if (mem_cfg_fd < 0){
326                 mem_cfg_fd = open(pathname, O_RDWR | O_CREAT, 0600);
327                 if (mem_cfg_fd < 0) {
328                         RTE_LOG(ERR, EAL, "Cannot open '%s' for rte_mem_config\n",
329                                 pathname);
330                         return -1;
331                 }
332         }
333
334         retval = ftruncate(mem_cfg_fd, sizeof(*rte_config.mem_config));
335         if (retval < 0){
336                 close(mem_cfg_fd);
337                 mem_cfg_fd = -1;
338                 RTE_LOG(ERR, EAL, "Cannot resize '%s' for rte_mem_config\n",
339                         pathname);
340                 return -1;
341         }
342
343         retval = fcntl(mem_cfg_fd, F_SETLK, &wr_lock);
344         if (retval < 0){
345                 close(mem_cfg_fd);
346                 mem_cfg_fd = -1;
347                 RTE_LOG(ERR, EAL, "Cannot create lock on '%s'. Is another primary "
348                         "process running?\n", pathname);
349                 return -1;
350         }
351
352         rte_mem_cfg_addr = mmap(rte_mem_cfg_addr, sizeof(*rte_config.mem_config),
353                                 PROT_READ | PROT_WRITE, MAP_SHARED, mem_cfg_fd, 0);
354
355         if (rte_mem_cfg_addr == MAP_FAILED){
356                 close(mem_cfg_fd);
357                 mem_cfg_fd = -1;
358                 RTE_LOG(ERR, EAL, "Cannot mmap memory for rte_config\n");
359                 return -1;
360         }
361
362         memcpy(rte_mem_cfg_addr, &early_mem_config, sizeof(early_mem_config));
363         rte_config.mem_config = rte_mem_cfg_addr;
364
365         /* store address of the config in the config itself so that secondary
366          * processes could later map the config into this exact location */
367         rte_config.mem_config->mem_cfg_addr = (uintptr_t) rte_mem_cfg_addr;
368
369         rte_config.mem_config->dma_maskbits = 0;
370
371         return 0;
372 }
373
374 /* attach to an existing shared memory config */
375 static int
376 rte_eal_config_attach(void)
377 {
378         struct rte_mem_config *mem_config;
379
380         const char *pathname = eal_runtime_config_path();
381
382         if (internal_config.no_shconf)
383                 return 0;
384
385         if (mem_cfg_fd < 0){
386                 mem_cfg_fd = open(pathname, O_RDWR);
387                 if (mem_cfg_fd < 0) {
388                         RTE_LOG(ERR, EAL, "Cannot open '%s' for rte_mem_config\n",
389                                 pathname);
390                         return -1;
391                 }
392         }
393
394         /* map it as read-only first */
395         mem_config = (struct rte_mem_config *) mmap(NULL, sizeof(*mem_config),
396                         PROT_READ, MAP_SHARED, mem_cfg_fd, 0);
397         if (mem_config == MAP_FAILED) {
398                 close(mem_cfg_fd);
399                 mem_cfg_fd = -1;
400                 RTE_LOG(ERR, EAL, "Cannot mmap memory for rte_config! error %i (%s)\n",
401                         errno, strerror(errno));
402                 return -1;
403         }
404
405         rte_config.mem_config = mem_config;
406
407         return 0;
408 }
409
410 /* reattach the shared config at exact memory location primary process has it */
411 static int
412 rte_eal_config_reattach(void)
413 {
414         struct rte_mem_config *mem_config;
415         void *rte_mem_cfg_addr;
416
417         if (internal_config.no_shconf)
418                 return 0;
419
420         /* save the address primary process has mapped shared config to */
421         rte_mem_cfg_addr = (void *) (uintptr_t) rte_config.mem_config->mem_cfg_addr;
422
423         /* unmap original config */
424         munmap(rte_config.mem_config, sizeof(struct rte_mem_config));
425
426         /* remap the config at proper address */
427         mem_config = (struct rte_mem_config *) mmap(rte_mem_cfg_addr,
428                         sizeof(*mem_config), PROT_READ | PROT_WRITE, MAP_SHARED,
429                         mem_cfg_fd, 0);
430
431         close(mem_cfg_fd);
432         mem_cfg_fd = -1;
433
434         if (mem_config == MAP_FAILED || mem_config != rte_mem_cfg_addr) {
435                 if (mem_config != MAP_FAILED) {
436                         /* errno is stale, don't use */
437                         RTE_LOG(ERR, EAL, "Cannot mmap memory for rte_config at [%p], got [%p]"
438                                 " - please use '--" OPT_BASE_VIRTADDR
439                                 "' option\n", rte_mem_cfg_addr, mem_config);
440                         munmap(mem_config, sizeof(struct rte_mem_config));
441                         return -1;
442                 }
443                 RTE_LOG(ERR, EAL, "Cannot mmap memory for rte_config! error %i (%s)\n",
444                         errno, strerror(errno));
445                 return -1;
446         }
447
448         rte_config.mem_config = mem_config;
449
450         return 0;
451 }
452
453 /* Detect if we are a primary or a secondary process */
454 enum rte_proc_type_t
455 eal_proc_type_detect(void)
456 {
457         enum rte_proc_type_t ptype = RTE_PROC_PRIMARY;
458         const char *pathname = eal_runtime_config_path();
459
460         /* if there no shared config, there can be no secondary processes */
461         if (!internal_config.no_shconf) {
462                 /* if we can open the file but not get a write-lock we are a
463                  * secondary process. NOTE: if we get a file handle back, we
464                  * keep that open and don't close it to prevent a race condition
465                  * between multiple opens.
466                  */
467                 if (((mem_cfg_fd = open(pathname, O_RDWR)) >= 0) &&
468                                 (fcntl(mem_cfg_fd, F_SETLK, &wr_lock) < 0))
469                         ptype = RTE_PROC_SECONDARY;
470         }
471
472         RTE_LOG(INFO, EAL, "Auto-detected process type: %s\n",
473                         ptype == RTE_PROC_PRIMARY ? "PRIMARY" : "SECONDARY");
474
475         return ptype;
476 }
477
478 /* Sets up rte_config structure with the pointer to shared memory config.*/
479 static int
480 rte_config_init(void)
481 {
482         rte_config.process_type = internal_config.process_type;
483
484         switch (rte_config.process_type){
485         case RTE_PROC_PRIMARY:
486                 if (rte_eal_config_create() < 0)
487                         return -1;
488                 eal_mcfg_update_from_internal();
489                 break;
490         case RTE_PROC_SECONDARY:
491                 if (rte_eal_config_attach() < 0)
492                         return -1;
493                 eal_mcfg_wait_complete();
494                 if (eal_mcfg_check_version() < 0) {
495                         RTE_LOG(ERR, EAL, "Primary and secondary process DPDK version mismatch\n");
496                         return -1;
497                 }
498                 if (rte_eal_config_reattach() < 0)
499                         return -1;
500                 eal_mcfg_update_internal();
501                 break;
502         case RTE_PROC_AUTO:
503         case RTE_PROC_INVALID:
504                 RTE_LOG(ERR, EAL, "Invalid process type %d\n",
505                         rte_config.process_type);
506                 return -1;
507         }
508
509         return 0;
510 }
511
512 /* Unlocks hugepage directories that were locked by eal_hugepage_info_init */
513 static void
514 eal_hugedirs_unlock(void)
515 {
516         int i;
517
518         for (i = 0; i < MAX_HUGEPAGE_SIZES; i++)
519         {
520                 /* skip uninitialized */
521                 if (internal_config.hugepage_info[i].lock_descriptor < 0)
522                         continue;
523                 /* unlock hugepage file */
524                 flock(internal_config.hugepage_info[i].lock_descriptor, LOCK_UN);
525                 close(internal_config.hugepage_info[i].lock_descriptor);
526                 /* reset the field */
527                 internal_config.hugepage_info[i].lock_descriptor = -1;
528         }
529 }
530
531 /* display usage */
532 static void
533 eal_usage(const char *prgname)
534 {
535         printf("\nUsage: %s ", prgname);
536         eal_common_usage();
537         printf("EAL Linux options:\n"
538                "  --"OPT_SOCKET_MEM"        Memory to allocate on sockets (comma separated values)\n"
539                "  --"OPT_SOCKET_LIMIT"      Limit memory allocation on sockets (comma separated values)\n"
540                "  --"OPT_HUGE_DIR"          Directory where hugetlbfs is mounted\n"
541                "  --"OPT_FILE_PREFIX"       Prefix for hugepage filenames\n"
542                "  --"OPT_CREATE_UIO_DEV"    Create /dev/uioX (usually done by hotplug)\n"
543                "  --"OPT_VFIO_INTR"         Interrupt mode for VFIO (legacy|msi|msix)\n"
544                "  --"OPT_LEGACY_MEM"        Legacy memory mode (no dynamic allocation, contiguous segments)\n"
545                "  --"OPT_SINGLE_FILE_SEGMENTS" Put all hugepage memory in single files\n"
546                "  --"OPT_MATCH_ALLOCATIONS" Free hugepages exactly as allocated\n"
547                "\n");
548         /* Allow the application to print its usage message too if hook is set */
549         if ( rte_application_usage_hook ) {
550                 printf("===== Application Usage =====\n\n");
551                 rte_application_usage_hook(prgname);
552         }
553 }
554
555 /* Set a per-application usage message */
556 rte_usage_hook_t
557 rte_set_application_usage_hook( rte_usage_hook_t usage_func )
558 {
559         rte_usage_hook_t        old_func;
560
561         /* Will be NULL on the first call to denote the last usage routine. */
562         old_func                                        = rte_application_usage_hook;
563         rte_application_usage_hook      = usage_func;
564
565         return old_func;
566 }
567
568 static int
569 eal_parse_socket_arg(char *strval, volatile uint64_t *socket_arg)
570 {
571         char * arg[RTE_MAX_NUMA_NODES];
572         char *end;
573         int arg_num, i, len;
574         uint64_t total_mem = 0;
575
576         len = strnlen(strval, SOCKET_MEM_STRLEN);
577         if (len == SOCKET_MEM_STRLEN) {
578                 RTE_LOG(ERR, EAL, "--socket-mem is too long\n");
579                 return -1;
580         }
581
582         /* all other error cases will be caught later */
583         if (!isdigit(strval[len-1]))
584                 return -1;
585
586         /* split the optarg into separate socket values */
587         arg_num = rte_strsplit(strval, len,
588                         arg, RTE_MAX_NUMA_NODES, ',');
589
590         /* if split failed, or 0 arguments */
591         if (arg_num <= 0)
592                 return -1;
593
594         /* parse each defined socket option */
595         errno = 0;
596         for (i = 0; i < arg_num; i++) {
597                 uint64_t val;
598                 end = NULL;
599                 val = strtoull(arg[i], &end, 10);
600
601                 /* check for invalid input */
602                 if ((errno != 0)  ||
603                                 (arg[i][0] == '\0') || (end == NULL) || (*end != '\0'))
604                         return -1;
605                 val <<= 20;
606                 total_mem += val;
607                 socket_arg[i] = val;
608         }
609
610         return 0;
611 }
612
613 static int
614 eal_parse_vfio_intr(const char *mode)
615 {
616         unsigned i;
617         static struct {
618                 const char *name;
619                 enum rte_intr_mode value;
620         } map[] = {
621                 { "legacy", RTE_INTR_MODE_LEGACY },
622                 { "msi", RTE_INTR_MODE_MSI },
623                 { "msix", RTE_INTR_MODE_MSIX },
624         };
625
626         for (i = 0; i < RTE_DIM(map); i++) {
627                 if (!strcmp(mode, map[i].name)) {
628                         internal_config.vfio_intr_mode = map[i].value;
629                         return 0;
630                 }
631         }
632         return -1;
633 }
634
635 /* Parse the arguments for --log-level only */
636 static void
637 eal_log_level_parse(int argc, char **argv)
638 {
639         int opt;
640         char **argvopt;
641         int option_index;
642         const int old_optind = optind;
643         const int old_optopt = optopt;
644         char * const old_optarg = optarg;
645
646         argvopt = argv;
647         optind = 1;
648
649         while ((opt = getopt_long(argc, argvopt, eal_short_options,
650                                   eal_long_options, &option_index)) != EOF) {
651
652                 int ret;
653
654                 /* getopt is not happy, stop right now */
655                 if (opt == '?')
656                         break;
657
658                 ret = (opt == OPT_LOG_LEVEL_NUM) ?
659                         eal_parse_common_option(opt, optarg, &internal_config) : 0;
660
661                 /* common parser is not happy */
662                 if (ret < 0)
663                         break;
664         }
665
666         /* restore getopt lib */
667         optind = old_optind;
668         optopt = old_optopt;
669         optarg = old_optarg;
670 }
671
672 /* Parse the argument given in the command line of the application */
673 static int
674 eal_parse_args(int argc, char **argv)
675 {
676         int opt, ret;
677         char **argvopt;
678         int option_index;
679         char *prgname = argv[0];
680         const int old_optind = optind;
681         const int old_optopt = optopt;
682         char * const old_optarg = optarg;
683
684         argvopt = argv;
685         optind = 1;
686         opterr = 0;
687
688         while ((opt = getopt_long(argc, argvopt, eal_short_options,
689                                   eal_long_options, &option_index)) != EOF) {
690
691                 /*
692                  * getopt didn't recognise the option, lets parse the
693                  * registered options to see if the flag is valid
694                  */
695                 if (opt == '?') {
696                         ret = rte_option_parse(argv[optind-1]);
697                         if (ret == 0)
698                                 continue;
699
700                         eal_usage(prgname);
701                         ret = -1;
702                         goto out;
703                 }
704
705                 ret = eal_parse_common_option(opt, optarg, &internal_config);
706                 /* common parser is not happy */
707                 if (ret < 0) {
708                         eal_usage(prgname);
709                         ret = -1;
710                         goto out;
711                 }
712                 /* common parser handled this option */
713                 if (ret == 0)
714                         continue;
715
716                 switch (opt) {
717                 case 'h':
718                         eal_usage(prgname);
719                         exit(EXIT_SUCCESS);
720
721                 case OPT_HUGE_DIR_NUM:
722                 {
723                         char *hdir = strdup(optarg);
724                         if (hdir == NULL)
725                                 RTE_LOG(ERR, EAL, "Could not store hugepage directory\n");
726                         else {
727                                 /* free old hugepage dir */
728                                 if (internal_config.hugepage_dir != NULL)
729                                         free(internal_config.hugepage_dir);
730                                 internal_config.hugepage_dir = hdir;
731                         }
732                         break;
733                 }
734                 case OPT_FILE_PREFIX_NUM:
735                 {
736                         char *prefix = strdup(optarg);
737                         if (prefix == NULL)
738                                 RTE_LOG(ERR, EAL, "Could not store file prefix\n");
739                         else {
740                                 /* free old prefix */
741                                 if (internal_config.hugefile_prefix != NULL)
742                                         free(internal_config.hugefile_prefix);
743                                 internal_config.hugefile_prefix = prefix;
744                         }
745                         break;
746                 }
747                 case OPT_SOCKET_MEM_NUM:
748                         if (eal_parse_socket_arg(optarg,
749                                         internal_config.socket_mem) < 0) {
750                                 RTE_LOG(ERR, EAL, "invalid parameters for --"
751                                                 OPT_SOCKET_MEM "\n");
752                                 eal_usage(prgname);
753                                 ret = -1;
754                                 goto out;
755                         }
756                         internal_config.force_sockets = 1;
757                         break;
758
759                 case OPT_SOCKET_LIMIT_NUM:
760                         if (eal_parse_socket_arg(optarg,
761                                         internal_config.socket_limit) < 0) {
762                                 RTE_LOG(ERR, EAL, "invalid parameters for --"
763                                                 OPT_SOCKET_LIMIT "\n");
764                                 eal_usage(prgname);
765                                 ret = -1;
766                                 goto out;
767                         }
768                         internal_config.force_socket_limits = 1;
769                         break;
770
771                 case OPT_VFIO_INTR_NUM:
772                         if (eal_parse_vfio_intr(optarg) < 0) {
773                                 RTE_LOG(ERR, EAL, "invalid parameters for --"
774                                                 OPT_VFIO_INTR "\n");
775                                 eal_usage(prgname);
776                                 ret = -1;
777                                 goto out;
778                         }
779                         break;
780
781                 case OPT_CREATE_UIO_DEV_NUM:
782                         internal_config.create_uio_dev = 1;
783                         break;
784
785                 case OPT_MBUF_POOL_OPS_NAME_NUM:
786                 {
787                         char *ops_name = strdup(optarg);
788                         if (ops_name == NULL)
789                                 RTE_LOG(ERR, EAL, "Could not store mbuf pool ops name\n");
790                         else {
791                                 /* free old ops name */
792                                 if (internal_config.user_mbuf_pool_ops_name !=
793                                                 NULL)
794                                         free(internal_config.user_mbuf_pool_ops_name);
795
796                                 internal_config.user_mbuf_pool_ops_name =
797                                                 ops_name;
798                         }
799                         break;
800                 }
801                 case OPT_MATCH_ALLOCATIONS_NUM:
802                         internal_config.match_allocations = 1;
803                         break;
804
805                 default:
806                         if (opt < OPT_LONG_MIN_NUM && isprint(opt)) {
807                                 RTE_LOG(ERR, EAL, "Option %c is not supported "
808                                         "on Linux\n", opt);
809                         } else if (opt >= OPT_LONG_MIN_NUM &&
810                                    opt < OPT_LONG_MAX_NUM) {
811                                 RTE_LOG(ERR, EAL, "Option %s is not supported "
812                                         "on Linux\n",
813                                         eal_long_options[option_index].name);
814                         } else {
815                                 RTE_LOG(ERR, EAL, "Option %d is not supported "
816                                         "on Linux\n", opt);
817                         }
818                         eal_usage(prgname);
819                         ret = -1;
820                         goto out;
821                 }
822         }
823
824         /* create runtime data directory */
825         if (internal_config.no_shconf == 0 &&
826                         eal_create_runtime_dir() < 0) {
827                 RTE_LOG(ERR, EAL, "Cannot create runtime directory\n");
828                 ret = -1;
829                 goto out;
830         }
831
832         if (eal_adjust_config(&internal_config) != 0) {
833                 ret = -1;
834                 goto out;
835         }
836
837         /* sanity checks */
838         if (eal_check_common_options(&internal_config) != 0) {
839                 eal_usage(prgname);
840                 ret = -1;
841                 goto out;
842         }
843
844         if (optind >= 0)
845                 argv[optind-1] = prgname;
846         ret = optind-1;
847
848 out:
849         /* restore getopt lib */
850         optind = old_optind;
851         optopt = old_optopt;
852         optarg = old_optarg;
853
854         return ret;
855 }
856
857 static int
858 check_socket(const struct rte_memseg_list *msl, void *arg)
859 {
860         int *socket_id = arg;
861
862         if (msl->external)
863                 return 0;
864
865         return *socket_id == msl->socket_id;
866 }
867
868 static void
869 eal_check_mem_on_local_socket(void)
870 {
871         int socket_id;
872
873         socket_id = rte_lcore_to_socket_id(rte_config.master_lcore);
874
875         if (rte_memseg_list_walk(check_socket, &socket_id) == 0)
876                 RTE_LOG(WARNING, EAL, "WARNING: Master core has no memory on local socket!\n");
877 }
878
879 static int
880 sync_func(__attribute__((unused)) void *arg)
881 {
882         return 0;
883 }
884
885 /*
886  * Request iopl privilege for all RPL, returns 0 on success
887  * iopl() call is mostly for the i386 architecture. For other architectures,
888  * return -1 to indicate IO privilege can't be changed in this way.
889  */
890 int
891 rte_eal_iopl_init(void)
892 {
893 #if defined(RTE_ARCH_X86)
894         if (iopl(3) != 0)
895                 return -1;
896 #endif
897         return 0;
898 }
899
900 #ifdef VFIO_PRESENT
901 static int rte_eal_vfio_setup(void)
902 {
903         if (rte_vfio_enable("vfio"))
904                 return -1;
905
906         return 0;
907 }
908 #endif
909
910 static void rte_eal_init_alert(const char *msg)
911 {
912         fprintf(stderr, "EAL: FATAL: %s\n", msg);
913         RTE_LOG(ERR, EAL, "%s\n", msg);
914 }
915
916 /*
917  * On Linux 3.6+, even if VFIO is not loaded, whenever IOMMU is enabled in the
918  * BIOS and in the kernel, /sys/kernel/iommu_groups path will contain kernel
919  * IOMMU groups. If IOMMU is not enabled, that path would be empty.
920  * Therefore, checking if the path is empty will tell us if IOMMU is enabled.
921  */
922 static bool
923 is_iommu_enabled(void)
924 {
925         DIR *dir = opendir(KERNEL_IOMMU_GROUPS_PATH);
926         struct dirent *d;
927         int n = 0;
928
929         /* if directory doesn't exist, assume IOMMU is not enabled */
930         if (dir == NULL)
931                 return false;
932
933         while ((d = readdir(dir)) != NULL) {
934                 /* skip dot and dot-dot */
935                 if (++n > 2)
936                         break;
937         }
938         closedir(dir);
939
940         return n > 2;
941 }
942
943 /* Launch threads, called at application init(). */
944 int
945 rte_eal_init(int argc, char **argv)
946 {
947         int i, fctret, ret;
948         pthread_t thread_id;
949         static rte_atomic32_t run_once = RTE_ATOMIC32_INIT(0);
950         const char *p;
951         static char logid[PATH_MAX];
952         char cpuset[RTE_CPU_AFFINITY_STR_LEN];
953         char thread_name[RTE_MAX_THREAD_NAME_LEN];
954         bool phys_addrs;
955
956         /* checks if the machine is adequate */
957         if (!rte_cpu_is_supported()) {
958                 rte_eal_init_alert("unsupported cpu type.");
959                 rte_errno = ENOTSUP;
960                 return -1;
961         }
962
963         if (!rte_atomic32_test_and_set(&run_once)) {
964                 rte_eal_init_alert("already called initialization.");
965                 rte_errno = EALREADY;
966                 return -1;
967         }
968
969         p = strrchr(argv[0], '/');
970         strlcpy(logid, p ? p + 1 : argv[0], sizeof(logid));
971         thread_id = pthread_self();
972
973         eal_reset_internal_config(&internal_config);
974
975         /* set log level as early as possible */
976         eal_log_level_parse(argc, argv);
977
978         if (rte_eal_cpu_init() < 0) {
979                 rte_eal_init_alert("Cannot detect lcores.");
980                 rte_errno = ENOTSUP;
981                 return -1;
982         }
983
984         fctret = eal_parse_args(argc, argv);
985         if (fctret < 0) {
986                 rte_eal_init_alert("Invalid 'command line' arguments.");
987                 rte_errno = EINVAL;
988                 rte_atomic32_clear(&run_once);
989                 return -1;
990         }
991
992         if (eal_plugins_init() < 0) {
993                 rte_eal_init_alert("Cannot init plugins");
994                 rte_errno = EINVAL;
995                 rte_atomic32_clear(&run_once);
996                 return -1;
997         }
998
999         if (eal_option_device_parse()) {
1000                 rte_errno = ENODEV;
1001                 rte_atomic32_clear(&run_once);
1002                 return -1;
1003         }
1004
1005         if (rte_config_init() < 0) {
1006                 rte_eal_init_alert("Cannot init config");
1007                 return -1;
1008         }
1009
1010         if (rte_eal_intr_init() < 0) {
1011                 rte_eal_init_alert("Cannot init interrupt-handling thread");
1012                 return -1;
1013         }
1014
1015         if (rte_eal_alarm_init() < 0) {
1016                 rte_eal_init_alert("Cannot init alarm");
1017                 /* rte_eal_alarm_init sets rte_errno on failure. */
1018                 return -1;
1019         }
1020
1021         /* Put mp channel init before bus scan so that we can init the vdev
1022          * bus through mp channel in the secondary process before the bus scan.
1023          */
1024         if (rte_mp_channel_init() < 0 && rte_errno != ENOTSUP) {
1025                 rte_eal_init_alert("failed to init mp channel");
1026                 if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
1027                         rte_errno = EFAULT;
1028                         return -1;
1029                 }
1030         }
1031
1032         /* register multi-process action callbacks for hotplug */
1033         if (eal_mp_dev_hotplug_init() < 0) {
1034                 rte_eal_init_alert("failed to register mp callback for hotplug");
1035                 return -1;
1036         }
1037
1038         if (rte_bus_scan()) {
1039                 rte_eal_init_alert("Cannot scan the buses for devices");
1040                 rte_errno = ENODEV;
1041                 rte_atomic32_clear(&run_once);
1042                 return -1;
1043         }
1044
1045         phys_addrs = rte_eal_using_phys_addrs() != 0;
1046
1047         /* if no EAL option "--iova-mode=<pa|va>", use bus IOVA scheme */
1048         if (internal_config.iova_mode == RTE_IOVA_DC) {
1049                 /* autodetect the IOVA mapping mode */
1050                 enum rte_iova_mode iova_mode = rte_bus_get_iommu_class();
1051
1052                 if (iova_mode == RTE_IOVA_DC) {
1053                         RTE_LOG(DEBUG, EAL, "Buses did not request a specific IOVA mode.\n");
1054
1055                         if (!phys_addrs) {
1056                                 /* if we have no access to physical addresses,
1057                                  * pick IOVA as VA mode.
1058                                  */
1059                                 iova_mode = RTE_IOVA_VA;
1060                                 RTE_LOG(DEBUG, EAL, "Physical addresses are unavailable, selecting IOVA as VA mode.\n");
1061                         } else if (is_iommu_enabled()) {
1062                                 /* we have an IOMMU, pick IOVA as VA mode */
1063                                 iova_mode = RTE_IOVA_VA;
1064                                 RTE_LOG(DEBUG, EAL, "IOMMU is available, selecting IOVA as VA mode.\n");
1065                         } else {
1066                                 /* physical addresses available, and no IOMMU
1067                                  * found, so pick IOVA as PA.
1068                                  */
1069                                 iova_mode = RTE_IOVA_PA;
1070                                 RTE_LOG(DEBUG, EAL, "IOMMU is not available, selecting IOVA as PA mode.\n");
1071                         }
1072                 }
1073 #ifdef RTE_LIBRTE_KNI
1074                 /* Workaround for KNI which requires physical address to work */
1075                 if (iova_mode == RTE_IOVA_VA &&
1076                                 rte_eal_check_module("rte_kni") == 1) {
1077                         if (phys_addrs) {
1078                                 iova_mode = RTE_IOVA_PA;
1079                                 RTE_LOG(WARNING, EAL, "Forcing IOVA as 'PA' because KNI module is loaded\n");
1080                         } else {
1081                                 RTE_LOG(DEBUG, EAL, "KNI can not work since physical addresses are unavailable\n");
1082                         }
1083                 }
1084 #endif
1085                 rte_eal_get_configuration()->iova_mode = iova_mode;
1086         } else {
1087                 rte_eal_get_configuration()->iova_mode =
1088                         internal_config.iova_mode;
1089         }
1090
1091         if (rte_eal_iova_mode() == RTE_IOVA_PA && !phys_addrs) {
1092                 rte_eal_init_alert("Cannot use IOVA as 'PA' since physical addresses are not available");
1093                 rte_errno = EINVAL;
1094                 return -1;
1095         }
1096
1097         RTE_LOG(INFO, EAL, "Selected IOVA mode '%s'\n",
1098                 rte_eal_iova_mode() == RTE_IOVA_PA ? "PA" : "VA");
1099
1100         if (internal_config.no_hugetlbfs == 0) {
1101                 /* rte_config isn't initialized yet */
1102                 ret = internal_config.process_type == RTE_PROC_PRIMARY ?
1103                                 eal_hugepage_info_init() :
1104                                 eal_hugepage_info_read();
1105                 if (ret < 0) {
1106                         rte_eal_init_alert("Cannot get hugepage information.");
1107                         rte_errno = EACCES;
1108                         rte_atomic32_clear(&run_once);
1109                         return -1;
1110                 }
1111         }
1112
1113         if (internal_config.memory == 0 && internal_config.force_sockets == 0) {
1114                 if (internal_config.no_hugetlbfs)
1115                         internal_config.memory = MEMSIZE_IF_NO_HUGE_PAGE;
1116         }
1117
1118         if (internal_config.vmware_tsc_map == 1) {
1119 #ifdef RTE_LIBRTE_EAL_VMWARE_TSC_MAP_SUPPORT
1120                 rte_cycles_vmware_tsc_map = 1;
1121                 RTE_LOG (DEBUG, EAL, "Using VMWARE TSC MAP, "
1122                                 "you must have monitor_control.pseudo_perfctr = TRUE\n");
1123 #else
1124                 RTE_LOG (WARNING, EAL, "Ignoring --vmware-tsc-map because "
1125                                 "RTE_LIBRTE_EAL_VMWARE_TSC_MAP_SUPPORT is not set\n");
1126 #endif
1127         }
1128
1129         if (rte_eal_log_init(logid, internal_config.syslog_facility) < 0) {
1130                 rte_eal_init_alert("Cannot init logging.");
1131                 rte_errno = ENOMEM;
1132                 rte_atomic32_clear(&run_once);
1133                 return -1;
1134         }
1135
1136 #ifdef VFIO_PRESENT
1137         if (rte_eal_vfio_setup() < 0) {
1138                 rte_eal_init_alert("Cannot init VFIO");
1139                 rte_errno = EAGAIN;
1140                 rte_atomic32_clear(&run_once);
1141                 return -1;
1142         }
1143 #endif
1144         /* in secondary processes, memory init may allocate additional fbarrays
1145          * not present in primary processes, so to avoid any potential issues,
1146          * initialize memzones first.
1147          */
1148         if (rte_eal_memzone_init() < 0) {
1149                 rte_eal_init_alert("Cannot init memzone");
1150                 rte_errno = ENODEV;
1151                 return -1;
1152         }
1153
1154         if (rte_eal_memory_init() < 0) {
1155                 rte_eal_init_alert("Cannot init memory");
1156                 rte_errno = ENOMEM;
1157                 return -1;
1158         }
1159
1160         /* the directories are locked during eal_hugepage_info_init */
1161         eal_hugedirs_unlock();
1162
1163         if (rte_eal_malloc_heap_init() < 0) {
1164                 rte_eal_init_alert("Cannot init malloc heap");
1165                 rte_errno = ENODEV;
1166                 return -1;
1167         }
1168
1169         if (rte_eal_tailqs_init() < 0) {
1170                 rte_eal_init_alert("Cannot init tail queues for objects");
1171                 rte_errno = EFAULT;
1172                 return -1;
1173         }
1174
1175         if (rte_eal_timer_init() < 0) {
1176                 rte_eal_init_alert("Cannot init HPET or TSC timers");
1177                 rte_errno = ENOTSUP;
1178                 return -1;
1179         }
1180
1181         eal_check_mem_on_local_socket();
1182
1183         eal_thread_init_master(rte_config.master_lcore);
1184
1185         ret = eal_thread_dump_affinity(cpuset, sizeof(cpuset));
1186
1187         RTE_LOG(DEBUG, EAL, "Master lcore %u is ready (tid=%zx;cpuset=[%s%s])\n",
1188                 rte_config.master_lcore, (uintptr_t)thread_id, cpuset,
1189                 ret == 0 ? "" : "...");
1190
1191         RTE_LCORE_FOREACH_SLAVE(i) {
1192
1193                 /*
1194                  * create communication pipes between master thread
1195                  * and children
1196                  */
1197                 if (pipe(lcore_config[i].pipe_master2slave) < 0)
1198                         rte_panic("Cannot create pipe\n");
1199                 if (pipe(lcore_config[i].pipe_slave2master) < 0)
1200                         rte_panic("Cannot create pipe\n");
1201
1202                 lcore_config[i].state = WAIT;
1203
1204                 /* create a thread for each lcore */
1205                 ret = pthread_create(&lcore_config[i].thread_id, NULL,
1206                                      eal_thread_loop, NULL);
1207                 if (ret != 0)
1208                         rte_panic("Cannot create thread\n");
1209
1210                 /* Set thread_name for aid in debugging. */
1211                 snprintf(thread_name, sizeof(thread_name),
1212                         "lcore-slave-%d", i);
1213                 ret = rte_thread_setname(lcore_config[i].thread_id,
1214                                                 thread_name);
1215                 if (ret != 0)
1216                         RTE_LOG(DEBUG, EAL,
1217                                 "Cannot set name for lcore thread\n");
1218         }
1219
1220         /*
1221          * Launch a dummy function on all slave lcores, so that master lcore
1222          * knows they are all ready when this function returns.
1223          */
1224         rte_eal_mp_remote_launch(sync_func, NULL, SKIP_MASTER);
1225         rte_eal_mp_wait_lcore();
1226
1227         /* initialize services so vdevs register service during bus_probe. */
1228         ret = rte_service_init();
1229         if (ret) {
1230                 rte_eal_init_alert("rte_service_init() failed");
1231                 rte_errno = ENOEXEC;
1232                 return -1;
1233         }
1234
1235         /* Probe all the buses and devices/drivers on them */
1236         if (rte_bus_probe()) {
1237                 rte_eal_init_alert("Cannot probe devices");
1238                 rte_errno = ENOTSUP;
1239                 return -1;
1240         }
1241
1242 #ifdef VFIO_PRESENT
1243         /* Register mp action after probe() so that we got enough info */
1244         if (rte_vfio_is_enabled("vfio") && vfio_mp_sync_setup() < 0)
1245                 return -1;
1246 #endif
1247
1248         /* initialize default service/lcore mappings and start running. Ignore
1249          * -ENOTSUP, as it indicates no service coremask passed to EAL.
1250          */
1251         ret = rte_service_start_with_defaults();
1252         if (ret < 0 && ret != -ENOTSUP) {
1253                 rte_errno = ENOEXEC;
1254                 return -1;
1255         }
1256
1257         /*
1258          * Clean up unused files in runtime directory. We do this at the end of
1259          * init and not at the beginning because we want to clean stuff up
1260          * whether we are primary or secondary process, but we cannot remove
1261          * primary process' files because secondary should be able to run even
1262          * if primary process is dead.
1263          *
1264          * In no_shconf mode, no runtime directory is created in the first
1265          * place, so no cleanup needed.
1266          */
1267         if (!internal_config.no_shconf && eal_clean_runtime_dir() < 0) {
1268                 rte_eal_init_alert("Cannot clear runtime directory\n");
1269                 return -1;
1270         }
1271
1272         eal_mcfg_complete();
1273
1274         /* Call each registered callback, if enabled */
1275         rte_option_init();
1276
1277         return fctret;
1278 }
1279
1280 static int
1281 mark_freeable(const struct rte_memseg_list *msl, const struct rte_memseg *ms,
1282                 void *arg __rte_unused)
1283 {
1284         /* ms is const, so find this memseg */
1285         struct rte_memseg *found;
1286
1287         if (msl->external)
1288                 return 0;
1289
1290         found = rte_mem_virt2memseg(ms->addr, msl);
1291
1292         found->flags &= ~RTE_MEMSEG_FLAG_DO_NOT_FREE;
1293
1294         return 0;
1295 }
1296
1297 int
1298 rte_eal_cleanup(void)
1299 {
1300         /* if we're in a primary process, we need to mark hugepages as freeable
1301          * so that finalization can release them back to the system.
1302          */
1303         if (rte_eal_process_type() == RTE_PROC_PRIMARY)
1304                 rte_memseg_walk(mark_freeable, NULL);
1305         rte_service_finalize();
1306         rte_mp_channel_cleanup();
1307         eal_cleanup_config(&internal_config);
1308         return 0;
1309 }
1310
1311 /* get core role */
1312 enum rte_lcore_role_t
1313 rte_eal_lcore_role(unsigned lcore_id)
1314 {
1315         return rte_config.lcore_role[lcore_id];
1316 }
1317
1318 enum rte_proc_type_t
1319 rte_eal_process_type(void)
1320 {
1321         return rte_config.process_type;
1322 }
1323
1324 int rte_eal_has_hugepages(void)
1325 {
1326         return ! internal_config.no_hugetlbfs;
1327 }
1328
1329 int rte_eal_has_pci(void)
1330 {
1331         return !internal_config.no_pci;
1332 }
1333
1334 int rte_eal_create_uio_dev(void)
1335 {
1336         return internal_config.create_uio_dev;
1337 }
1338
1339 enum rte_intr_mode
1340 rte_eal_vfio_intr_mode(void)
1341 {
1342         return internal_config.vfio_intr_mode;
1343 }
1344
1345 int
1346 rte_eal_check_module(const char *module_name)
1347 {
1348         char sysfs_mod_name[PATH_MAX];
1349         struct stat st;
1350         int n;
1351
1352         if (NULL == module_name)
1353                 return -1;
1354
1355         /* Check if there is sysfs mounted */
1356         if (stat("/sys/module", &st) != 0) {
1357                 RTE_LOG(DEBUG, EAL, "sysfs is not mounted! error %i (%s)\n",
1358                         errno, strerror(errno));
1359                 return -1;
1360         }
1361
1362         /* A module might be built-in, therefore try sysfs */
1363         n = snprintf(sysfs_mod_name, PATH_MAX, "/sys/module/%s", module_name);
1364         if (n < 0 || n > PATH_MAX) {
1365                 RTE_LOG(DEBUG, EAL, "Could not format module path\n");
1366                 return -1;
1367         }
1368
1369         if (stat(sysfs_mod_name, &st) != 0) {
1370                 RTE_LOG(DEBUG, EAL, "Module %s not found! error %i (%s)\n",
1371                         sysfs_mod_name, errno, strerror(errno));
1372                 return 0;
1373         }
1374
1375         /* Module has been found */
1376         return 1;
1377 }