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