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