ec1cc82e1a92ab1ccb83ad9fe328bb7e1d6c78fe
[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 /*
938  * Request iopl privilege for all RPL, returns 0 on success
939  * iopl() call is mostly for the i386 architecture. For other architectures,
940  * return -1 to indicate IO privilege can't be changed in this way.
941  */
942 int
943 rte_eal_iopl_init(void)
944 {
945 #if defined(RTE_ARCH_X86)
946         if (iopl(3) != 0)
947                 return -1;
948 #endif
949         return 0;
950 }
951
952 #ifdef VFIO_PRESENT
953 static int rte_eal_vfio_setup(void)
954 {
955         if (rte_vfio_enable("vfio"))
956                 return -1;
957
958         return 0;
959 }
960 #endif
961
962 static void rte_eal_init_alert(const char *msg)
963 {
964         fprintf(stderr, "EAL: FATAL: %s\n", msg);
965         RTE_LOG(ERR, EAL, "%s\n", msg);
966 }
967
968 /* Launch threads, called at application init(). */
969 int
970 rte_eal_init(int argc, char **argv)
971 {
972         int i, fctret, ret;
973         pthread_t thread_id;
974         static rte_atomic32_t run_once = RTE_ATOMIC32_INIT(0);
975         const char *p;
976         static char logid[PATH_MAX];
977         char cpuset[RTE_CPU_AFFINITY_STR_LEN];
978         char thread_name[RTE_MAX_THREAD_NAME_LEN];
979         bool phys_addrs;
980
981         /* checks if the machine is adequate */
982         if (!rte_cpu_is_supported()) {
983                 rte_eal_init_alert("unsupported cpu type.");
984                 rte_errno = ENOTSUP;
985                 return -1;
986         }
987
988         if (!rte_atomic32_test_and_set(&run_once)) {
989                 rte_eal_init_alert("already called initialization.");
990                 rte_errno = EALREADY;
991                 return -1;
992         }
993
994         p = strrchr(argv[0], '/');
995         strlcpy(logid, p ? p + 1 : argv[0], sizeof(logid));
996         thread_id = pthread_self();
997
998         eal_reset_internal_config(&internal_config);
999
1000         /* set log level as early as possible */
1001         eal_log_level_parse(argc, argv);
1002
1003         if (rte_eal_cpu_init() < 0) {
1004                 rte_eal_init_alert("Cannot detect lcores.");
1005                 rte_errno = ENOTSUP;
1006                 return -1;
1007         }
1008
1009         fctret = eal_parse_args(argc, argv);
1010         if (fctret < 0) {
1011                 rte_eal_init_alert("Invalid 'command line' arguments.");
1012                 rte_errno = EINVAL;
1013                 rte_atomic32_clear(&run_once);
1014                 return -1;
1015         }
1016
1017         if (eal_plugins_init() < 0) {
1018                 rte_eal_init_alert("Cannot init plugins");
1019                 rte_errno = EINVAL;
1020                 rte_atomic32_clear(&run_once);
1021                 return -1;
1022         }
1023
1024         if (eal_option_device_parse()) {
1025                 rte_errno = ENODEV;
1026                 rte_atomic32_clear(&run_once);
1027                 return -1;
1028         }
1029
1030         if (rte_config_init() < 0) {
1031                 rte_eal_init_alert("Cannot init config");
1032                 return -1;
1033         }
1034
1035         if (rte_eal_intr_init() < 0) {
1036                 rte_eal_init_alert("Cannot init interrupt-handling thread");
1037                 return -1;
1038         }
1039
1040         if (rte_eal_alarm_init() < 0) {
1041                 rte_eal_init_alert("Cannot init alarm");
1042                 /* rte_eal_alarm_init sets rte_errno on failure. */
1043                 return -1;
1044         }
1045
1046         /* Put mp channel init before bus scan so that we can init the vdev
1047          * bus through mp channel in the secondary process before the bus scan.
1048          */
1049         if (rte_mp_channel_init() < 0 && rte_errno != ENOTSUP) {
1050                 rte_eal_init_alert("failed to init mp channel");
1051                 if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
1052                         rte_errno = EFAULT;
1053                         return -1;
1054                 }
1055         }
1056
1057         /* register multi-process action callbacks for hotplug */
1058         if (eal_mp_dev_hotplug_init() < 0) {
1059                 rte_eal_init_alert("failed to register mp callback for hotplug");
1060                 return -1;
1061         }
1062
1063         if (rte_bus_scan()) {
1064                 rte_eal_init_alert("Cannot scan the buses for devices");
1065                 rte_errno = ENODEV;
1066                 rte_atomic32_clear(&run_once);
1067                 return -1;
1068         }
1069
1070         phys_addrs = rte_eal_using_phys_addrs() != 0;
1071
1072         /* if no EAL option "--iova-mode=<pa|va>", use bus IOVA scheme */
1073         if (internal_config.iova_mode == RTE_IOVA_DC) {
1074                 /* autodetect the IOVA mapping mode */
1075                 enum rte_iova_mode iova_mode = rte_bus_get_iommu_class();
1076
1077                 if (iova_mode == RTE_IOVA_DC) {
1078                         iova_mode = phys_addrs ? RTE_IOVA_PA : RTE_IOVA_VA;
1079                         RTE_LOG(DEBUG, EAL,
1080                                 "Buses did not request a specific IOVA mode, using '%s' based on physical addresses availability.\n",
1081                                 phys_addrs ? "PA" : "VA");
1082                 }
1083 #ifdef RTE_LIBRTE_KNI
1084                 /* Workaround for KNI which requires physical address to work */
1085                 if (iova_mode == RTE_IOVA_VA &&
1086                                 rte_eal_check_module("rte_kni") == 1) {
1087                         if (phys_addrs) {
1088                                 iova_mode = RTE_IOVA_PA;
1089                                 RTE_LOG(WARNING, EAL, "Forcing IOVA as 'PA' because KNI module is loaded\n");
1090                         } else {
1091                                 RTE_LOG(DEBUG, EAL, "KNI can not work since physical addresses are unavailable\n");
1092                         }
1093                 }
1094 #endif
1095                 rte_eal_get_configuration()->iova_mode = iova_mode;
1096         } else {
1097                 rte_eal_get_configuration()->iova_mode =
1098                         internal_config.iova_mode;
1099         }
1100
1101         if (rte_eal_iova_mode() == RTE_IOVA_PA && !phys_addrs) {
1102                 rte_eal_init_alert("Cannot use IOVA as 'PA' since physical addresses are not available");
1103                 rte_errno = EINVAL;
1104                 return -1;
1105         }
1106
1107         RTE_LOG(INFO, EAL, "Selected IOVA mode '%s'\n",
1108                 rte_eal_iova_mode() == RTE_IOVA_PA ? "PA" : "VA");
1109
1110         if (internal_config.no_hugetlbfs == 0) {
1111                 /* rte_config isn't initialized yet */
1112                 ret = internal_config.process_type == RTE_PROC_PRIMARY ?
1113                                 eal_hugepage_info_init() :
1114                                 eal_hugepage_info_read();
1115                 if (ret < 0) {
1116                         rte_eal_init_alert("Cannot get hugepage information.");
1117                         rte_errno = EACCES;
1118                         rte_atomic32_clear(&run_once);
1119                         return -1;
1120                 }
1121         }
1122
1123         if (internal_config.memory == 0 && internal_config.force_sockets == 0) {
1124                 if (internal_config.no_hugetlbfs)
1125                         internal_config.memory = MEMSIZE_IF_NO_HUGE_PAGE;
1126         }
1127
1128         if (internal_config.vmware_tsc_map == 1) {
1129 #ifdef RTE_LIBRTE_EAL_VMWARE_TSC_MAP_SUPPORT
1130                 rte_cycles_vmware_tsc_map = 1;
1131                 RTE_LOG (DEBUG, EAL, "Using VMWARE TSC MAP, "
1132                                 "you must have monitor_control.pseudo_perfctr = TRUE\n");
1133 #else
1134                 RTE_LOG (WARNING, EAL, "Ignoring --vmware-tsc-map because "
1135                                 "RTE_LIBRTE_EAL_VMWARE_TSC_MAP_SUPPORT is not set\n");
1136 #endif
1137         }
1138
1139         if (rte_eal_log_init(logid, internal_config.syslog_facility) < 0) {
1140                 rte_eal_init_alert("Cannot init logging.");
1141                 rte_errno = ENOMEM;
1142                 rte_atomic32_clear(&run_once);
1143                 return -1;
1144         }
1145
1146 #ifdef VFIO_PRESENT
1147         if (rte_eal_vfio_setup() < 0) {
1148                 rte_eal_init_alert("Cannot init VFIO");
1149                 rte_errno = EAGAIN;
1150                 rte_atomic32_clear(&run_once);
1151                 return -1;
1152         }
1153 #endif
1154         /* in secondary processes, memory init may allocate additional fbarrays
1155          * not present in primary processes, so to avoid any potential issues,
1156          * initialize memzones first.
1157          */
1158         if (rte_eal_memzone_init() < 0) {
1159                 rte_eal_init_alert("Cannot init memzone");
1160                 rte_errno = ENODEV;
1161                 return -1;
1162         }
1163
1164         if (rte_eal_memory_init() < 0) {
1165                 rte_eal_init_alert("Cannot init memory");
1166                 rte_errno = ENOMEM;
1167                 return -1;
1168         }
1169
1170         /* the directories are locked during eal_hugepage_info_init */
1171         eal_hugedirs_unlock();
1172
1173         if (rte_eal_malloc_heap_init() < 0) {
1174                 rte_eal_init_alert("Cannot init malloc heap");
1175                 rte_errno = ENODEV;
1176                 return -1;
1177         }
1178
1179         if (rte_eal_tailqs_init() < 0) {
1180                 rte_eal_init_alert("Cannot init tail queues for objects");
1181                 rte_errno = EFAULT;
1182                 return -1;
1183         }
1184
1185         if (rte_eal_timer_init() < 0) {
1186                 rte_eal_init_alert("Cannot init HPET or TSC timers");
1187                 rte_errno = ENOTSUP;
1188                 return -1;
1189         }
1190
1191         eal_check_mem_on_local_socket();
1192
1193         eal_thread_init_master(rte_config.master_lcore);
1194
1195         ret = eal_thread_dump_affinity(cpuset, sizeof(cpuset));
1196
1197         RTE_LOG(DEBUG, EAL, "Master lcore %u is ready (tid=%zx;cpuset=[%s%s])\n",
1198                 rte_config.master_lcore, (uintptr_t)thread_id, cpuset,
1199                 ret == 0 ? "" : "...");
1200
1201         RTE_LCORE_FOREACH_SLAVE(i) {
1202
1203                 /*
1204                  * create communication pipes between master thread
1205                  * and children
1206                  */
1207                 if (pipe(lcore_config[i].pipe_master2slave) < 0)
1208                         rte_panic("Cannot create pipe\n");
1209                 if (pipe(lcore_config[i].pipe_slave2master) < 0)
1210                         rte_panic("Cannot create pipe\n");
1211
1212                 lcore_config[i].state = WAIT;
1213
1214                 /* create a thread for each lcore */
1215                 ret = pthread_create(&lcore_config[i].thread_id, NULL,
1216                                      eal_thread_loop, NULL);
1217                 if (ret != 0)
1218                         rte_panic("Cannot create thread\n");
1219
1220                 /* Set thread_name for aid in debugging. */
1221                 snprintf(thread_name, sizeof(thread_name),
1222                         "lcore-slave-%d", i);
1223                 ret = rte_thread_setname(lcore_config[i].thread_id,
1224                                                 thread_name);
1225                 if (ret != 0)
1226                         RTE_LOG(DEBUG, EAL,
1227                                 "Cannot set name for lcore thread\n");
1228         }
1229
1230         /*
1231          * Launch a dummy function on all slave lcores, so that master lcore
1232          * knows they are all ready when this function returns.
1233          */
1234         rte_eal_mp_remote_launch(sync_func, NULL, SKIP_MASTER);
1235         rte_eal_mp_wait_lcore();
1236
1237         /* initialize services so vdevs register service during bus_probe. */
1238         ret = rte_service_init();
1239         if (ret) {
1240                 rte_eal_init_alert("rte_service_init() failed");
1241                 rte_errno = ENOEXEC;
1242                 return -1;
1243         }
1244
1245         /* Probe all the buses and devices/drivers on them */
1246         if (rte_bus_probe()) {
1247                 rte_eal_init_alert("Cannot probe devices");
1248                 rte_errno = ENOTSUP;
1249                 return -1;
1250         }
1251
1252 #ifdef VFIO_PRESENT
1253         /* Register mp action after probe() so that we got enough info */
1254         if (rte_vfio_is_enabled("vfio") && vfio_mp_sync_setup() < 0)
1255                 return -1;
1256 #endif
1257
1258         /* initialize default service/lcore mappings and start running. Ignore
1259          * -ENOTSUP, as it indicates no service coremask passed to EAL.
1260          */
1261         ret = rte_service_start_with_defaults();
1262         if (ret < 0 && ret != -ENOTSUP) {
1263                 rte_errno = ENOEXEC;
1264                 return -1;
1265         }
1266
1267         /*
1268          * Clean up unused files in runtime directory. We do this at the end of
1269          * init and not at the beginning because we want to clean stuff up
1270          * whether we are primary or secondary process, but we cannot remove
1271          * primary process' files because secondary should be able to run even
1272          * if primary process is dead.
1273          *
1274          * In no_shconf mode, no runtime directory is created in the first
1275          * place, so no cleanup needed.
1276          */
1277         if (!internal_config.no_shconf && eal_clean_runtime_dir() < 0) {
1278                 rte_eal_init_alert("Cannot clear runtime directory\n");
1279                 return -1;
1280         }
1281
1282         eal_mcfg_complete();
1283
1284         /* Call each registered callback, if enabled */
1285         rte_option_init();
1286
1287         return fctret;
1288 }
1289
1290 static int
1291 mark_freeable(const struct rte_memseg_list *msl, const struct rte_memseg *ms,
1292                 void *arg __rte_unused)
1293 {
1294         /* ms is const, so find this memseg */
1295         struct rte_memseg *found;
1296
1297         if (msl->external)
1298                 return 0;
1299
1300         found = rte_mem_virt2memseg(ms->addr, msl);
1301
1302         found->flags &= ~RTE_MEMSEG_FLAG_DO_NOT_FREE;
1303
1304         return 0;
1305 }
1306
1307 int
1308 rte_eal_cleanup(void)
1309 {
1310         /* if we're in a primary process, we need to mark hugepages as freeable
1311          * so that finalization can release them back to the system.
1312          */
1313         if (rte_eal_process_type() == RTE_PROC_PRIMARY)
1314                 rte_memseg_walk(mark_freeable, NULL);
1315         rte_service_finalize();
1316         rte_mp_channel_cleanup();
1317         eal_cleanup_config(&internal_config);
1318         return 0;
1319 }
1320
1321 /* get core role */
1322 enum rte_lcore_role_t
1323 rte_eal_lcore_role(unsigned lcore_id)
1324 {
1325         return rte_config.lcore_role[lcore_id];
1326 }
1327
1328 enum rte_proc_type_t
1329 rte_eal_process_type(void)
1330 {
1331         return rte_config.process_type;
1332 }
1333
1334 int rte_eal_has_hugepages(void)
1335 {
1336         return ! internal_config.no_hugetlbfs;
1337 }
1338
1339 int rte_eal_has_pci(void)
1340 {
1341         return !internal_config.no_pci;
1342 }
1343
1344 int rte_eal_create_uio_dev(void)
1345 {
1346         return internal_config.create_uio_dev;
1347 }
1348
1349 enum rte_intr_mode
1350 rte_eal_vfio_intr_mode(void)
1351 {
1352         return internal_config.vfio_intr_mode;
1353 }
1354
1355 int
1356 rte_eal_check_module(const char *module_name)
1357 {
1358         char sysfs_mod_name[PATH_MAX];
1359         struct stat st;
1360         int n;
1361
1362         if (NULL == module_name)
1363                 return -1;
1364
1365         /* Check if there is sysfs mounted */
1366         if (stat("/sys/module", &st) != 0) {
1367                 RTE_LOG(DEBUG, EAL, "sysfs is not mounted! error %i (%s)\n",
1368                         errno, strerror(errno));
1369                 return -1;
1370         }
1371
1372         /* A module might be built-in, therefore try sysfs */
1373         n = snprintf(sysfs_mod_name, PATH_MAX, "/sys/module/%s", module_name);
1374         if (n < 0 || n > PATH_MAX) {
1375                 RTE_LOG(DEBUG, EAL, "Could not format module path\n");
1376                 return -1;
1377         }
1378
1379         if (stat(sysfs_mod_name, &st) != 0) {
1380                 RTE_LOG(DEBUG, EAL, "Module %s not found! error %i (%s)\n",
1381                         sysfs_mod_name, errno, strerror(errno));
1382                 return 0;
1383         }
1384
1385         /* Module has been found */
1386         return 1;
1387 }