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