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