eal: correct log for alarm error
[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_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 int
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 0;
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_LOG(ERR, EAL, "Cannot open '%s' for rte_mem_config\n",
326                                 pathname);
327                         return -1;
328                 }
329         }
330
331         retval = ftruncate(mem_cfg_fd, sizeof(*rte_config.mem_config));
332         if (retval < 0){
333                 close(mem_cfg_fd);
334                 mem_cfg_fd = -1;
335                 RTE_LOG(ERR, EAL, "Cannot resize '%s' for rte_mem_config\n",
336                         pathname);
337                 return -1;
338         }
339
340         retval = fcntl(mem_cfg_fd, F_SETLK, &wr_lock);
341         if (retval < 0){
342                 close(mem_cfg_fd);
343                 mem_cfg_fd = -1;
344                 RTE_LOG(ERR, EAL, "Cannot create lock on '%s'. Is another primary "
345                         "process running?\n", pathname);
346                 return -1;
347         }
348
349         rte_mem_cfg_addr = mmap(rte_mem_cfg_addr, sizeof(*rte_config.mem_config),
350                                 PROT_READ | PROT_WRITE, MAP_SHARED, mem_cfg_fd, 0);
351
352         if (rte_mem_cfg_addr == MAP_FAILED){
353                 close(mem_cfg_fd);
354                 mem_cfg_fd = -1;
355                 RTE_LOG(ERR, EAL, "Cannot mmap memory for rte_config\n");
356                 return -1;
357         }
358
359         memcpy(rte_mem_cfg_addr, &early_mem_config, sizeof(early_mem_config));
360         rte_config.mem_config = rte_mem_cfg_addr;
361
362         /* store address of the config in the config itself so that secondary
363          * processes could later map the config into this exact location */
364         rte_config.mem_config->mem_cfg_addr = (uintptr_t) rte_mem_cfg_addr;
365
366         rte_config.mem_config->dma_maskbits = 0;
367
368         return 0;
369 }
370
371 /* attach to an existing shared memory config */
372 static int
373 rte_eal_config_attach(void)
374 {
375         struct rte_mem_config *mem_config;
376
377         const char *pathname = eal_runtime_config_path();
378
379         if (internal_config.no_shconf)
380                 return 0;
381
382         if (mem_cfg_fd < 0){
383                 mem_cfg_fd = open(pathname, O_RDWR);
384                 if (mem_cfg_fd < 0) {
385                         RTE_LOG(ERR, EAL, "Cannot open '%s' for rte_mem_config\n",
386                                 pathname);
387                         return -1;
388                 }
389         }
390
391         /* map it as read-only first */
392         mem_config = (struct rte_mem_config *) mmap(NULL, sizeof(*mem_config),
393                         PROT_READ, MAP_SHARED, mem_cfg_fd, 0);
394         if (mem_config == MAP_FAILED) {
395                 close(mem_cfg_fd);
396                 mem_cfg_fd = -1;
397                 RTE_LOG(ERR, EAL, "Cannot mmap memory for rte_config! error %i (%s)\n",
398                         errno, strerror(errno));
399                 return -1;
400         }
401
402         rte_config.mem_config = mem_config;
403
404         return 0;
405 }
406
407 /* reattach the shared config at exact memory location primary process has it */
408 static int
409 rte_eal_config_reattach(void)
410 {
411         struct rte_mem_config *mem_config;
412         void *rte_mem_cfg_addr;
413
414         if (internal_config.no_shconf)
415                 return 0;
416
417         /* save the address primary process has mapped shared config to */
418         rte_mem_cfg_addr = (void *) (uintptr_t) rte_config.mem_config->mem_cfg_addr;
419
420         /* unmap original config */
421         munmap(rte_config.mem_config, sizeof(struct rte_mem_config));
422
423         /* remap the config at proper address */
424         mem_config = (struct rte_mem_config *) mmap(rte_mem_cfg_addr,
425                         sizeof(*mem_config), PROT_READ | PROT_WRITE, MAP_SHARED,
426                         mem_cfg_fd, 0);
427
428         close(mem_cfg_fd);
429         mem_cfg_fd = -1;
430
431         if (mem_config == MAP_FAILED || mem_config != rte_mem_cfg_addr) {
432                 if (mem_config != MAP_FAILED) {
433                         /* errno is stale, don't use */
434                         RTE_LOG(ERR, EAL, "Cannot mmap memory for rte_config at [%p], got [%p]"
435                                 " - please use '--base-virtaddr' option\n",
436                                 rte_mem_cfg_addr, mem_config);
437                         return -1;
438                 }
439                 RTE_LOG(ERR, EAL, "Cannot mmap memory for rte_config! error %i (%s)\n",
440                         errno, strerror(errno));
441                 return -1;
442         }
443
444         rte_config.mem_config = mem_config;
445
446         return 0;
447 }
448
449 /* Detect if we are a primary or a secondary process */
450 enum rte_proc_type_t
451 eal_proc_type_detect(void)
452 {
453         enum rte_proc_type_t ptype = RTE_PROC_PRIMARY;
454         const char *pathname = eal_runtime_config_path();
455
456         /* if there no shared config, there can be no secondary processes */
457         if (!internal_config.no_shconf) {
458                 /* if we can open the file but not get a write-lock we are a
459                  * secondary process. NOTE: if we get a file handle back, we
460                  * keep that open and don't close it to prevent a race condition
461                  * between multiple opens.
462                  */
463                 if (((mem_cfg_fd = open(pathname, O_RDWR)) >= 0) &&
464                                 (fcntl(mem_cfg_fd, F_SETLK, &wr_lock) < 0))
465                         ptype = RTE_PROC_SECONDARY;
466         }
467
468         RTE_LOG(INFO, EAL, "Auto-detected process type: %s\n",
469                         ptype == RTE_PROC_PRIMARY ? "PRIMARY" : "SECONDARY");
470
471         return ptype;
472 }
473
474 /* copies data from internal config to shared config */
475 static void
476 eal_update_mem_config(void)
477 {
478         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
479         mcfg->legacy_mem = internal_config.legacy_mem;
480         mcfg->single_file_segments = internal_config.single_file_segments;
481 }
482
483 /* copies data from shared config to internal config */
484 static void
485 eal_update_internal_config(void)
486 {
487         struct rte_mem_config *mcfg = rte_eal_get_configuration()->mem_config;
488         internal_config.legacy_mem = mcfg->legacy_mem;
489         internal_config.single_file_segments = mcfg->single_file_segments;
490 }
491
492 /* Sets up rte_config structure with the pointer to shared memory config.*/
493 static int
494 rte_config_init(void)
495 {
496         rte_config.process_type = internal_config.process_type;
497
498         switch (rte_config.process_type){
499         case RTE_PROC_PRIMARY:
500                 if (rte_eal_config_create() < 0)
501                         return -1;
502                 eal_update_mem_config();
503                 break;
504         case RTE_PROC_SECONDARY:
505                 if (rte_eal_config_attach() < 0)
506                         return -1;
507                 rte_eal_mcfg_wait_complete(rte_config.mem_config);
508                 if (rte_eal_config_reattach() < 0)
509                         return -1;
510                 eal_update_internal_config();
511                 break;
512         case RTE_PROC_AUTO:
513         case RTE_PROC_INVALID:
514                 RTE_LOG(ERR, EAL, "Invalid process type %d\n",
515                         rte_config.process_type);
516                 return -1;
517         }
518
519         return 0;
520 }
521
522 /* Unlocks hugepage directories that were locked by eal_hugepage_info_init */
523 static void
524 eal_hugedirs_unlock(void)
525 {
526         int i;
527
528         for (i = 0; i < MAX_HUGEPAGE_SIZES; i++)
529         {
530                 /* skip uninitialized */
531                 if (internal_config.hugepage_info[i].lock_descriptor < 0)
532                         continue;
533                 /* unlock hugepage file */
534                 flock(internal_config.hugepage_info[i].lock_descriptor, LOCK_UN);
535                 close(internal_config.hugepage_info[i].lock_descriptor);
536                 /* reset the field */
537                 internal_config.hugepage_info[i].lock_descriptor = -1;
538         }
539 }
540
541 /* display usage */
542 static void
543 eal_usage(const char *prgname)
544 {
545         printf("\nUsage: %s ", prgname);
546         eal_common_usage();
547         printf("EAL Linux options:\n"
548                "  --"OPT_SOCKET_MEM"        Memory to allocate on sockets (comma separated values)\n"
549                "  --"OPT_SOCKET_LIMIT"      Limit memory allocation on sockets (comma separated values)\n"
550                "  --"OPT_HUGE_DIR"          Directory where hugetlbfs is mounted\n"
551                "  --"OPT_FILE_PREFIX"       Prefix for hugepage filenames\n"
552                "  --"OPT_BASE_VIRTADDR"     Base virtual address\n"
553                "  --"OPT_CREATE_UIO_DEV"    Create /dev/uioX (usually done by hotplug)\n"
554                "  --"OPT_VFIO_INTR"         Interrupt mode for VFIO (legacy|msi|msix)\n"
555                "  --"OPT_LEGACY_MEM"        Legacy memory mode (no dynamic allocation, contiguous segments)\n"
556                "  --"OPT_SINGLE_FILE_SEGMENTS" Put all hugepage memory in single files\n"
557                "  --"OPT_MATCH_ALLOCATIONS" Free hugepages exactly as allocated\n"
558                "\n");
559         /* Allow the application to print its usage message too if hook is set */
560         if ( rte_application_usage_hook ) {
561                 printf("===== Application Usage =====\n\n");
562                 rte_application_usage_hook(prgname);
563         }
564 }
565
566 /* Set a per-application usage message */
567 rte_usage_hook_t
568 rte_set_application_usage_hook( rte_usage_hook_t usage_func )
569 {
570         rte_usage_hook_t        old_func;
571
572         /* Will be NULL on the first call to denote the last usage routine. */
573         old_func                                        = rte_application_usage_hook;
574         rte_application_usage_hook      = usage_func;
575
576         return old_func;
577 }
578
579 static int
580 eal_parse_socket_arg(char *strval, volatile uint64_t *socket_arg)
581 {
582         char * arg[RTE_MAX_NUMA_NODES];
583         char *end;
584         int arg_num, i, len;
585         uint64_t total_mem = 0;
586
587         len = strnlen(strval, SOCKET_MEM_STRLEN);
588         if (len == SOCKET_MEM_STRLEN) {
589                 RTE_LOG(ERR, EAL, "--socket-mem is too long\n");
590                 return -1;
591         }
592
593         /* all other error cases will be caught later */
594         if (!isdigit(strval[len-1]))
595                 return -1;
596
597         /* split the optarg into separate socket values */
598         arg_num = rte_strsplit(strval, len,
599                         arg, RTE_MAX_NUMA_NODES, ',');
600
601         /* if split failed, or 0 arguments */
602         if (arg_num <= 0)
603                 return -1;
604
605         /* parse each defined socket option */
606         errno = 0;
607         for (i = 0; i < arg_num; i++) {
608                 uint64_t val;
609                 end = NULL;
610                 val = strtoull(arg[i], &end, 10);
611
612                 /* check for invalid input */
613                 if ((errno != 0)  ||
614                                 (arg[i][0] == '\0') || (end == NULL) || (*end != '\0'))
615                         return -1;
616                 val <<= 20;
617                 total_mem += val;
618                 socket_arg[i] = val;
619         }
620
621         return 0;
622 }
623
624 static int
625 eal_parse_base_virtaddr(const char *arg)
626 {
627         char *end;
628         uint64_t addr;
629
630         errno = 0;
631         addr = strtoull(arg, &end, 16);
632
633         /* check for errors */
634         if ((errno != 0) || (arg[0] == '\0') || end == NULL || (*end != '\0'))
635                 return -1;
636
637         /* make sure we don't exceed 32-bit boundary on 32-bit target */
638 #ifndef RTE_ARCH_64
639         if (addr >= UINTPTR_MAX)
640                 return -1;
641 #endif
642
643         /* align the addr on 16M boundary, 16MB is the minimum huge page
644          * size on IBM Power architecture. If the addr is aligned to 16MB,
645          * it can align to 2MB for x86. So this alignment can also be used
646          * on x86 */
647         internal_config.base_virtaddr =
648                 RTE_PTR_ALIGN_CEIL((uintptr_t)addr, (size_t)RTE_PGSIZE_16M);
649
650         return 0;
651 }
652
653 static int
654 eal_parse_vfio_intr(const char *mode)
655 {
656         unsigned i;
657         static struct {
658                 const char *name;
659                 enum rte_intr_mode value;
660         } map[] = {
661                 { "legacy", RTE_INTR_MODE_LEGACY },
662                 { "msi", RTE_INTR_MODE_MSI },
663                 { "msix", RTE_INTR_MODE_MSIX },
664         };
665
666         for (i = 0; i < RTE_DIM(map); i++) {
667                 if (!strcmp(mode, map[i].name)) {
668                         internal_config.vfio_intr_mode = map[i].value;
669                         return 0;
670                 }
671         }
672         return -1;
673 }
674
675 /* Parse the arguments for --log-level only */
676 static void
677 eal_log_level_parse(int argc, char **argv)
678 {
679         int opt;
680         char **argvopt;
681         int option_index;
682         const int old_optind = optind;
683         const int old_optopt = optopt;
684         char * const old_optarg = optarg;
685
686         argvopt = argv;
687         optind = 1;
688
689         while ((opt = getopt_long(argc, argvopt, eal_short_options,
690                                   eal_long_options, &option_index)) != EOF) {
691
692                 int ret;
693
694                 /* getopt is not happy, stop right now */
695                 if (opt == '?')
696                         break;
697
698                 ret = (opt == OPT_LOG_LEVEL_NUM) ?
699                         eal_parse_common_option(opt, optarg, &internal_config) : 0;
700
701                 /* common parser is not happy */
702                 if (ret < 0)
703                         break;
704         }
705
706         /* restore getopt lib */
707         optind = old_optind;
708         optopt = old_optopt;
709         optarg = old_optarg;
710 }
711
712 /* Parse the argument given in the command line of the application */
713 static int
714 eal_parse_args(int argc, char **argv)
715 {
716         int opt, ret;
717         char **argvopt;
718         int option_index;
719         char *prgname = argv[0];
720         const int old_optind = optind;
721         const int old_optopt = optopt;
722         char * const old_optarg = optarg;
723
724         argvopt = argv;
725         optind = 1;
726         opterr = 0;
727
728         while ((opt = getopt_long(argc, argvopt, eal_short_options,
729                                   eal_long_options, &option_index)) != EOF) {
730
731                 /*
732                  * getopt didn't recognise the option, lets parse the
733                  * registered options to see if the flag is valid
734                  */
735                 if (opt == '?') {
736                         ret = rte_option_parse(argv[optind-1]);
737                         if (ret == 0)
738                                 continue;
739
740                         eal_usage(prgname);
741                         ret = -1;
742                         goto out;
743                 }
744
745                 ret = eal_parse_common_option(opt, optarg, &internal_config);
746                 /* common parser is not happy */
747                 if (ret < 0) {
748                         eal_usage(prgname);
749                         ret = -1;
750                         goto out;
751                 }
752                 /* common parser handled this option */
753                 if (ret == 0)
754                         continue;
755
756                 switch (opt) {
757                 case 'h':
758                         eal_usage(prgname);
759                         exit(EXIT_SUCCESS);
760
761                 case OPT_HUGE_DIR_NUM:
762                 {
763                         char *hdir = strdup(optarg);
764                         if (hdir == NULL)
765                                 RTE_LOG(ERR, EAL, "Could not store hugepage directory\n");
766                         else {
767                                 /* free old hugepage dir */
768                                 if (internal_config.hugepage_dir != NULL)
769                                         free(internal_config.hugepage_dir);
770                                 internal_config.hugepage_dir = hdir;
771                         }
772                         break;
773                 }
774                 case OPT_FILE_PREFIX_NUM:
775                 {
776                         char *prefix = strdup(optarg);
777                         if (prefix == NULL)
778                                 RTE_LOG(ERR, EAL, "Could not store file prefix\n");
779                         else {
780                                 /* free old prefix */
781                                 if (internal_config.hugefile_prefix != NULL)
782                                         free(internal_config.hugefile_prefix);
783                                 internal_config.hugefile_prefix = prefix;
784                         }
785                         break;
786                 }
787                 case OPT_SOCKET_MEM_NUM:
788                         if (eal_parse_socket_arg(optarg,
789                                         internal_config.socket_mem) < 0) {
790                                 RTE_LOG(ERR, EAL, "invalid parameters for --"
791                                                 OPT_SOCKET_MEM "\n");
792                                 eal_usage(prgname);
793                                 ret = -1;
794                                 goto out;
795                         }
796                         internal_config.force_sockets = 1;
797                         break;
798
799                 case OPT_SOCKET_LIMIT_NUM:
800                         if (eal_parse_socket_arg(optarg,
801                                         internal_config.socket_limit) < 0) {
802                                 RTE_LOG(ERR, EAL, "invalid parameters for --"
803                                                 OPT_SOCKET_LIMIT "\n");
804                                 eal_usage(prgname);
805                                 ret = -1;
806                                 goto out;
807                         }
808                         internal_config.force_socket_limits = 1;
809                         break;
810
811                 case OPT_BASE_VIRTADDR_NUM:
812                         if (eal_parse_base_virtaddr(optarg) < 0) {
813                                 RTE_LOG(ERR, EAL, "invalid parameter for --"
814                                                 OPT_BASE_VIRTADDR "\n");
815                                 eal_usage(prgname);
816                                 ret = -1;
817                                 goto out;
818                         }
819                         break;
820
821                 case OPT_VFIO_INTR_NUM:
822                         if (eal_parse_vfio_intr(optarg) < 0) {
823                                 RTE_LOG(ERR, EAL, "invalid parameters for --"
824                                                 OPT_VFIO_INTR "\n");
825                                 eal_usage(prgname);
826                                 ret = -1;
827                                 goto out;
828                         }
829                         break;
830
831                 case OPT_CREATE_UIO_DEV_NUM:
832                         internal_config.create_uio_dev = 1;
833                         break;
834
835                 case OPT_MBUF_POOL_OPS_NAME_NUM:
836                 {
837                         char *ops_name = strdup(optarg);
838                         if (ops_name == NULL)
839                                 RTE_LOG(ERR, EAL, "Could not store mbuf pool ops name\n");
840                         else {
841                                 /* free old ops name */
842                                 if (internal_config.user_mbuf_pool_ops_name !=
843                                                 NULL)
844                                         free(internal_config.user_mbuf_pool_ops_name);
845
846                                 internal_config.user_mbuf_pool_ops_name =
847                                                 ops_name;
848                         }
849                         break;
850                 }
851                 case OPT_MATCH_ALLOCATIONS_NUM:
852                         internal_config.match_allocations = 1;
853                         break;
854
855                 default:
856                         if (opt < OPT_LONG_MIN_NUM && isprint(opt)) {
857                                 RTE_LOG(ERR, EAL, "Option %c is not supported "
858                                         "on Linux\n", opt);
859                         } else if (opt >= OPT_LONG_MIN_NUM &&
860                                    opt < OPT_LONG_MAX_NUM) {
861                                 RTE_LOG(ERR, EAL, "Option %s is not supported "
862                                         "on Linux\n",
863                                         eal_long_options[option_index].name);
864                         } else {
865                                 RTE_LOG(ERR, EAL, "Option %d is not supported "
866                                         "on Linux\n", opt);
867                         }
868                         eal_usage(prgname);
869                         ret = -1;
870                         goto out;
871                 }
872         }
873
874         /* create runtime data directory */
875         if (internal_config.no_shconf == 0 &&
876                         eal_create_runtime_dir() < 0) {
877                 RTE_LOG(ERR, EAL, "Cannot create runtime directory\n");
878                 ret = -1;
879                 goto out;
880         }
881
882         if (eal_adjust_config(&internal_config) != 0) {
883                 ret = -1;
884                 goto out;
885         }
886
887         /* sanity checks */
888         if (eal_check_common_options(&internal_config) != 0) {
889                 eal_usage(prgname);
890                 ret = -1;
891                 goto out;
892         }
893
894         if (optind >= 0)
895                 argv[optind-1] = prgname;
896         ret = optind-1;
897
898 out:
899         /* restore getopt lib */
900         optind = old_optind;
901         optopt = old_optopt;
902         optarg = old_optarg;
903
904         return ret;
905 }
906
907 static int
908 check_socket(const struct rte_memseg_list *msl, void *arg)
909 {
910         int *socket_id = arg;
911
912         if (msl->external)
913                 return 0;
914
915         return *socket_id == msl->socket_id;
916 }
917
918 static void
919 eal_check_mem_on_local_socket(void)
920 {
921         int socket_id;
922
923         socket_id = rte_lcore_to_socket_id(rte_config.master_lcore);
924
925         if (rte_memseg_list_walk(check_socket, &socket_id) == 0)
926                 RTE_LOG(WARNING, EAL, "WARNING: Master core has no memory on local socket!\n");
927 }
928
929 static int
930 sync_func(__attribute__((unused)) void *arg)
931 {
932         return 0;
933 }
934
935 inline static void
936 rte_eal_mcfg_complete(void)
937 {
938         /* ALL shared mem_config related INIT DONE */
939         if (rte_config.process_type == RTE_PROC_PRIMARY)
940                 rte_config.mem_config->magic = RTE_MAGIC;
941
942         internal_config.init_complete = 1;
943 }
944
945 /*
946  * Request iopl privilege for all RPL, returns 0 on success
947  * iopl() call is mostly for the i386 architecture. For other architectures,
948  * return -1 to indicate IO privilege can't be changed in this way.
949  */
950 int
951 rte_eal_iopl_init(void)
952 {
953 #if defined(RTE_ARCH_X86)
954         if (iopl(3) != 0)
955                 return -1;
956 #endif
957         return 0;
958 }
959
960 #ifdef VFIO_PRESENT
961 static int rte_eal_vfio_setup(void)
962 {
963         if (rte_vfio_enable("vfio"))
964                 return -1;
965
966         return 0;
967 }
968 #endif
969
970 static void rte_eal_init_alert(const char *msg)
971 {
972         fprintf(stderr, "EAL: FATAL: %s\n", msg);
973         RTE_LOG(ERR, EAL, "%s\n", msg);
974 }
975
976 /* Launch threads, called at application init(). */
977 int
978 rte_eal_init(int argc, char **argv)
979 {
980         int i, fctret, ret;
981         pthread_t thread_id;
982         static rte_atomic32_t run_once = RTE_ATOMIC32_INIT(0);
983         const char *p;
984         static char logid[PATH_MAX];
985         char cpuset[RTE_CPU_AFFINITY_STR_LEN];
986         char thread_name[RTE_MAX_THREAD_NAME_LEN];
987
988         /* checks if the machine is adequate */
989         if (!rte_cpu_is_supported()) {
990                 rte_eal_init_alert("unsupported cpu type.");
991                 rte_errno = ENOTSUP;
992                 return -1;
993         }
994
995         if (!rte_atomic32_test_and_set(&run_once)) {
996                 rte_eal_init_alert("already called initialization.");
997                 rte_errno = EALREADY;
998                 return -1;
999         }
1000
1001         p = strrchr(argv[0], '/');
1002         strlcpy(logid, p ? p + 1 : argv[0], sizeof(logid));
1003         thread_id = pthread_self();
1004
1005         eal_reset_internal_config(&internal_config);
1006
1007         /* set log level as early as possible */
1008         eal_log_level_parse(argc, argv);
1009
1010         if (rte_eal_cpu_init() < 0) {
1011                 rte_eal_init_alert("Cannot detect lcores.");
1012                 rte_errno = ENOTSUP;
1013                 return -1;
1014         }
1015
1016         fctret = eal_parse_args(argc, argv);
1017         if (fctret < 0) {
1018                 rte_eal_init_alert("Invalid 'command line' arguments.");
1019                 rte_errno = EINVAL;
1020                 rte_atomic32_clear(&run_once);
1021                 return -1;
1022         }
1023
1024         if (eal_plugins_init() < 0) {
1025                 rte_eal_init_alert("Cannot init plugins");
1026                 rte_errno = EINVAL;
1027                 rte_atomic32_clear(&run_once);
1028                 return -1;
1029         }
1030
1031         if (eal_option_device_parse()) {
1032                 rte_errno = ENODEV;
1033                 rte_atomic32_clear(&run_once);
1034                 return -1;
1035         }
1036
1037         if (rte_config_init() < 0) {
1038                 rte_eal_init_alert("Cannot init config");
1039                 return -1;
1040         }
1041
1042         if (rte_eal_intr_init() < 0) {
1043                 rte_eal_init_alert("Cannot init interrupt-handling thread");
1044                 return -1;
1045         }
1046
1047         if (rte_eal_alarm_init() < 0) {
1048                 rte_eal_init_alert("Cannot init alarm");
1049                 /* rte_eal_alarm_init sets rte_errno on failure. */
1050                 return -1;
1051         }
1052
1053         /* Put mp channel init before bus scan so that we can init the vdev
1054          * bus through mp channel in the secondary process before the bus scan.
1055          */
1056         if (rte_mp_channel_init() < 0 && rte_errno != ENOTSUP) {
1057                 rte_eal_init_alert("failed to init mp channel");
1058                 if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
1059                         rte_errno = EFAULT;
1060                         return -1;
1061                 }
1062         }
1063
1064         /* register multi-process action callbacks for hotplug */
1065         if (rte_mp_dev_hotplug_init() < 0) {
1066                 rte_eal_init_alert("failed to register mp callback for hotplug");
1067                 return -1;
1068         }
1069
1070         if (rte_bus_scan()) {
1071                 rte_eal_init_alert("Cannot scan the buses for devices");
1072                 rte_errno = ENODEV;
1073                 rte_atomic32_clear(&run_once);
1074                 return -1;
1075         }
1076
1077         /* if no EAL option "--iova-mode=<pa|va>", use bus IOVA scheme */
1078         if (internal_config.iova_mode == RTE_IOVA_DC) {
1079                 /* autodetect the IOVA mapping mode (default is RTE_IOVA_PA) */
1080                 rte_eal_get_configuration()->iova_mode =
1081                         rte_bus_get_iommu_class();
1082
1083                 /* Workaround for KNI which requires physical address to work */
1084                 if (rte_eal_get_configuration()->iova_mode == RTE_IOVA_VA &&
1085                                 rte_eal_check_module("rte_kni") == 1) {
1086                         rte_eal_get_configuration()->iova_mode = RTE_IOVA_PA;
1087                         RTE_LOG(WARNING, EAL,
1088                                 "Some devices want IOVA as VA but PA will be used because.. "
1089                                 "KNI module inserted\n");
1090                 }
1091         } else {
1092                 rte_eal_get_configuration()->iova_mode =
1093                         internal_config.iova_mode;
1094         }
1095
1096         if (internal_config.no_hugetlbfs == 0) {
1097                 /* rte_config isn't initialized yet */
1098                 ret = internal_config.process_type == RTE_PROC_PRIMARY ?
1099                                 eal_hugepage_info_init() :
1100                                 eal_hugepage_info_read();
1101                 if (ret < 0) {
1102                         rte_eal_init_alert("Cannot get hugepage information.");
1103                         rte_errno = EACCES;
1104                         rte_atomic32_clear(&run_once);
1105                         return -1;
1106                 }
1107         }
1108
1109         if (internal_config.memory == 0 && internal_config.force_sockets == 0) {
1110                 if (internal_config.no_hugetlbfs)
1111                         internal_config.memory = MEMSIZE_IF_NO_HUGE_PAGE;
1112         }
1113
1114         if (internal_config.vmware_tsc_map == 1) {
1115 #ifdef RTE_LIBRTE_EAL_VMWARE_TSC_MAP_SUPPORT
1116                 rte_cycles_vmware_tsc_map = 1;
1117                 RTE_LOG (DEBUG, EAL, "Using VMWARE TSC MAP, "
1118                                 "you must have monitor_control.pseudo_perfctr = TRUE\n");
1119 #else
1120                 RTE_LOG (WARNING, EAL, "Ignoring --vmware-tsc-map because "
1121                                 "RTE_LIBRTE_EAL_VMWARE_TSC_MAP_SUPPORT is not set\n");
1122 #endif
1123         }
1124
1125         rte_srand(rte_rdtsc());
1126
1127         if (rte_eal_log_init(logid, internal_config.syslog_facility) < 0) {
1128                 rte_eal_init_alert("Cannot init logging.");
1129                 rte_errno = ENOMEM;
1130                 rte_atomic32_clear(&run_once);
1131                 return -1;
1132         }
1133
1134 #ifdef VFIO_PRESENT
1135         if (rte_eal_vfio_setup() < 0) {
1136                 rte_eal_init_alert("Cannot init VFIO");
1137                 rte_errno = EAGAIN;
1138                 rte_atomic32_clear(&run_once);
1139                 return -1;
1140         }
1141 #endif
1142         /* in secondary processes, memory init may allocate additional fbarrays
1143          * not present in primary processes, so to avoid any potential issues,
1144          * initialize memzones first.
1145          */
1146         if (rte_eal_memzone_init() < 0) {
1147                 rte_eal_init_alert("Cannot init memzone");
1148                 rte_errno = ENODEV;
1149                 return -1;
1150         }
1151
1152         if (rte_eal_memory_init() < 0) {
1153                 rte_eal_init_alert("Cannot init memory");
1154                 rte_errno = ENOMEM;
1155                 return -1;
1156         }
1157
1158         /* the directories are locked during eal_hugepage_info_init */
1159         eal_hugedirs_unlock();
1160
1161         if (rte_eal_malloc_heap_init() < 0) {
1162                 rte_eal_init_alert("Cannot init malloc heap");
1163                 rte_errno = ENODEV;
1164                 return -1;
1165         }
1166
1167         if (rte_eal_tailqs_init() < 0) {
1168                 rte_eal_init_alert("Cannot init tail queues for objects");
1169                 rte_errno = EFAULT;
1170                 return -1;
1171         }
1172
1173         if (rte_eal_timer_init() < 0) {
1174                 rte_eal_init_alert("Cannot init HPET or TSC timers");
1175                 rte_errno = ENOTSUP;
1176                 return -1;
1177         }
1178
1179         eal_check_mem_on_local_socket();
1180
1181         eal_thread_init_master(rte_config.master_lcore);
1182
1183         ret = eal_thread_dump_affinity(cpuset, sizeof(cpuset));
1184
1185         RTE_LOG(DEBUG, EAL, "Master lcore %u is ready (tid=%zx;cpuset=[%s%s])\n",
1186                 rte_config.master_lcore, (uintptr_t)thread_id, cpuset,
1187                 ret == 0 ? "" : "...");
1188
1189         RTE_LCORE_FOREACH_SLAVE(i) {
1190
1191                 /*
1192                  * create communication pipes between master thread
1193                  * and children
1194                  */
1195                 if (pipe(lcore_config[i].pipe_master2slave) < 0)
1196                         rte_panic("Cannot create pipe\n");
1197                 if (pipe(lcore_config[i].pipe_slave2master) < 0)
1198                         rte_panic("Cannot create pipe\n");
1199
1200                 lcore_config[i].state = WAIT;
1201
1202                 /* create a thread for each lcore */
1203                 ret = pthread_create(&lcore_config[i].thread_id, NULL,
1204                                      eal_thread_loop, NULL);
1205                 if (ret != 0)
1206                         rte_panic("Cannot create thread\n");
1207
1208                 /* Set thread_name for aid in debugging. */
1209                 snprintf(thread_name, sizeof(thread_name),
1210                         "lcore-slave-%d", i);
1211                 ret = rte_thread_setname(lcore_config[i].thread_id,
1212                                                 thread_name);
1213                 if (ret != 0)
1214                         RTE_LOG(DEBUG, EAL,
1215                                 "Cannot set name for lcore thread\n");
1216         }
1217
1218         /*
1219          * Launch a dummy function on all slave lcores, so that master lcore
1220          * knows they are all ready when this function returns.
1221          */
1222         rte_eal_mp_remote_launch(sync_func, NULL, SKIP_MASTER);
1223         rte_eal_mp_wait_lcore();
1224
1225         /* initialize services so vdevs register service during bus_probe. */
1226         ret = rte_service_init();
1227         if (ret) {
1228                 rte_eal_init_alert("rte_service_init() failed");
1229                 rte_errno = ENOEXEC;
1230                 return -1;
1231         }
1232
1233         /* Probe all the buses and devices/drivers on them */
1234         if (rte_bus_probe()) {
1235                 rte_eal_init_alert("Cannot probe devices");
1236                 rte_errno = ENOTSUP;
1237                 return -1;
1238         }
1239
1240 #ifdef VFIO_PRESENT
1241         /* Register mp action after probe() so that we got enough info */
1242         if (rte_vfio_is_enabled("vfio") && vfio_mp_sync_setup() < 0)
1243                 return -1;
1244 #endif
1245
1246         /* initialize default service/lcore mappings and start running. Ignore
1247          * -ENOTSUP, as it indicates no service coremask passed to EAL.
1248          */
1249         ret = rte_service_start_with_defaults();
1250         if (ret < 0 && ret != -ENOTSUP) {
1251                 rte_errno = ENOEXEC;
1252                 return -1;
1253         }
1254
1255         /*
1256          * Clean up unused files in runtime directory. We do this at the end of
1257          * init and not at the beginning because we want to clean stuff up
1258          * whether we are primary or secondary process, but we cannot remove
1259          * primary process' files because secondary should be able to run even
1260          * if primary process is dead.
1261          *
1262          * In no_shconf mode, no runtime directory is created in the first
1263          * place, so no cleanup needed.
1264          */
1265         if (!internal_config.no_shconf && eal_clean_runtime_dir() < 0) {
1266                 rte_eal_init_alert("Cannot clear runtime directory\n");
1267                 return -1;
1268         }
1269
1270         rte_eal_mcfg_complete();
1271
1272         /* Call each registered callback, if enabled */
1273         rte_option_init();
1274
1275         return fctret;
1276 }
1277
1278 static int
1279 mark_freeable(const struct rte_memseg_list *msl, const struct rte_memseg *ms,
1280                 void *arg __rte_unused)
1281 {
1282         /* ms is const, so find this memseg */
1283         struct rte_memseg *found;
1284
1285         if (msl->external)
1286                 return 0;
1287
1288         found = rte_mem_virt2memseg(ms->addr, msl);
1289
1290         found->flags &= ~RTE_MEMSEG_FLAG_DO_NOT_FREE;
1291
1292         return 0;
1293 }
1294
1295 int
1296 rte_eal_cleanup(void)
1297 {
1298         /* if we're in a primary process, we need to mark hugepages as freeable
1299          * so that finalization can release them back to the system.
1300          */
1301         if (rte_eal_process_type() == RTE_PROC_PRIMARY)
1302                 rte_memseg_walk(mark_freeable, NULL);
1303         rte_service_finalize();
1304         rte_mp_channel_cleanup();
1305         eal_cleanup_config(&internal_config);
1306         return 0;
1307 }
1308
1309 /* get core role */
1310 enum rte_lcore_role_t
1311 rte_eal_lcore_role(unsigned lcore_id)
1312 {
1313         return rte_config.lcore_role[lcore_id];
1314 }
1315
1316 enum rte_proc_type_t
1317 rte_eal_process_type(void)
1318 {
1319         return rte_config.process_type;
1320 }
1321
1322 int rte_eal_has_hugepages(void)
1323 {
1324         return ! internal_config.no_hugetlbfs;
1325 }
1326
1327 int rte_eal_has_pci(void)
1328 {
1329         return !internal_config.no_pci;
1330 }
1331
1332 int rte_eal_create_uio_dev(void)
1333 {
1334         return internal_config.create_uio_dev;
1335 }
1336
1337 enum rte_intr_mode
1338 rte_eal_vfio_intr_mode(void)
1339 {
1340         return internal_config.vfio_intr_mode;
1341 }
1342
1343 int
1344 rte_eal_check_module(const char *module_name)
1345 {
1346         char sysfs_mod_name[PATH_MAX];
1347         struct stat st;
1348         int n;
1349
1350         if (NULL == module_name)
1351                 return -1;
1352
1353         /* Check if there is sysfs mounted */
1354         if (stat("/sys/module", &st) != 0) {
1355                 RTE_LOG(DEBUG, EAL, "sysfs is not mounted! error %i (%s)\n",
1356                         errno, strerror(errno));
1357                 return -1;
1358         }
1359
1360         /* A module might be built-in, therefore try sysfs */
1361         n = snprintf(sysfs_mod_name, PATH_MAX, "/sys/module/%s", module_name);
1362         if (n < 0 || n > PATH_MAX) {
1363                 RTE_LOG(DEBUG, EAL, "Could not format module path\n");
1364                 return -1;
1365         }
1366
1367         if (stat(sysfs_mod_name, &st) != 0) {
1368                 RTE_LOG(DEBUG, EAL, "Module %s not found! error %i (%s)\n",
1369                         sysfs_mod_name, errno, strerror(errno));
1370                 return 0;
1371         }
1372
1373         /* Module has been found */
1374         return 1;
1375 }