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