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