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