ivshmem: fix errors identified by hardening
[dpdk.git] / lib / librte_eal / linuxapp / eal / eal.c
1 /*-
2  *   BSD LICENSE
3  * 
4  *   Copyright(c) 2010-2014 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 <dlfcn.h>
47 #include <stddef.h>
48 #include <errno.h>
49 #include <limits.h>
50 #include <errno.h>
51 #include <sys/mman.h>
52 #include <sys/queue.h>
53 #include <sys/io.h>
54
55 #include <rte_common.h>
56 #include <rte_debug.h>
57 #include <rte_memory.h>
58 #include <rte_memzone.h>
59 #include <rte_launch.h>
60 #include <rte_tailq.h>
61 #include <rte_eal.h>
62 #include <rte_eal_memconfig.h>
63 #include <rte_per_lcore.h>
64 #include <rte_lcore.h>
65 #include <rte_log.h>
66 #include <rte_random.h>
67 #include <rte_cycles.h>
68 #include <rte_string_fns.h>
69 #include <rte_cpuflags.h>
70 #include <rte_interrupts.h>
71 #include <rte_pci.h>
72 #include <rte_devargs.h>
73 #include <rte_common.h>
74 #include <rte_version.h>
75 #include <rte_atomic.h>
76 #include <malloc_heap.h>
77 #include <rte_eth_ring.h>
78
79 #include "eal_private.h"
80 #include "eal_thread.h"
81 #include "eal_internal_cfg.h"
82 #include "eal_filesystem.h"
83 #include "eal_hugepages.h"
84
85 #define OPT_HUGE_DIR    "huge-dir"
86 #define OPT_PROC_TYPE   "proc-type"
87 #define OPT_NO_SHCONF   "no-shconf"
88 #define OPT_NO_HPET     "no-hpet"
89 #define OPT_VMWARE_TSC_MAP   "vmware-tsc-map"
90 #define OPT_NO_PCI      "no-pci"
91 #define OPT_NO_HUGE     "no-huge"
92 #define OPT_FILE_PREFIX "file-prefix"
93 #define OPT_SOCKET_MEM  "socket-mem"
94 #define OPT_USE_DEVICE  "use-device"
95 #define OPT_PCI_WHITELIST "pci-whitelist"
96 #define OPT_PCI_BLACKLIST "pci-blacklist"
97 #define OPT_VDEV        "vdev"
98 #define OPT_SYSLOG      "syslog"
99 #define OPT_BASE_VIRTADDR   "base-virtaddr"
100 #define OPT_XEN_DOM0    "xen-dom0"
101 #define OPT_CREATE_UIO_DEV "create-uio-dev"
102
103 #define RTE_EAL_BLACKLIST_SIZE  0x100
104
105 #define MEMSIZE_IF_NO_HUGE_PAGE (64ULL * 1024ULL * 1024ULL)
106
107 #define SOCKET_MEM_STRLEN (RTE_MAX_NUMA_NODES * 10)
108
109 #define HIGHEST_RPL 3
110
111 #define BITS_PER_HEX 4
112
113 /* Allow the application to print its usage message too if set */
114 static rte_usage_hook_t rte_application_usage_hook = NULL;
115
116 TAILQ_HEAD(shared_driver_list, shared_driver);
117
118 /* Definition for shared object drivers. */
119 struct shared_driver {
120         TAILQ_ENTRY(shared_driver) next;
121
122         char    name[PATH_MAX];
123         void*   lib_handle;
124 };
125
126 /* List of external loadable drivers */
127 static struct shared_driver_list solib_list =
128 TAILQ_HEAD_INITIALIZER(solib_list);
129
130 /* early configuration structure, when memory config is not mmapped */
131 static struct rte_mem_config early_mem_config;
132
133 /* define fd variable here, because file needs to be kept open for the
134  * duration of the program, as we hold a write lock on it in the primary proc */
135 static int mem_cfg_fd = -1;
136
137 static struct flock wr_lock = {
138                 .l_type = F_WRLCK,
139                 .l_whence = SEEK_SET,
140                 .l_start = offsetof(struct rte_mem_config, memseg),
141                 .l_len = sizeof(early_mem_config.memseg),
142 };
143
144 /* Address of global and public configuration */
145 static struct rte_config rte_config = {
146                 .mem_config = &early_mem_config,
147 };
148
149 /* internal configuration (per-core) */
150 struct lcore_config lcore_config[RTE_MAX_LCORE];
151
152 /* internal configuration */
153 struct internal_config internal_config;
154
155 /* used by rte_rdtsc() */
156 int rte_cycles_vmware_tsc_map;
157
158 /* Return a pointer to the configuration structure */
159 struct rte_config *
160 rte_eal_get_configuration(void)
161 {
162         return &rte_config;
163 }
164
165 /* parse a sysfs (or other) file containing one integer value */
166 int
167 eal_parse_sysfs_value(const char *filename, unsigned long *val)
168 {
169         FILE *f;
170         char buf[BUFSIZ];
171         char *end = NULL;
172
173         if ((f = fopen(filename, "r")) == NULL) {
174                 RTE_LOG(ERR, EAL, "%s(): cannot open sysfs value %s\n",
175                         __func__, filename);
176                 return -1;
177         }
178
179         if (fgets(buf, sizeof(buf), f) == NULL) {
180                 RTE_LOG(ERR, EAL, "%s(): cannot read sysfs value %s\n",
181                         __func__, filename);
182                 fclose(f);
183                 return -1;
184         }
185         *val = strtoul(buf, &end, 0);
186         if ((buf[0] == '\0') || (end == NULL) || (*end != '\n')) {
187                 RTE_LOG(ERR, EAL, "%s(): cannot parse sysfs value %s\n",
188                                 __func__, filename);
189                 fclose(f);
190                 return -1;
191         }
192         fclose(f);
193         return 0;
194 }
195
196
197 /* create memory configuration in shared/mmap memory. Take out
198  * a write lock on the memsegs, so we can auto-detect primary/secondary.
199  * This means we never close the file while running (auto-close on exit).
200  * We also don't lock the whole file, so that in future we can use read-locks
201  * on other parts, e.g. memzones, to detect if there are running secondary
202  * processes. */
203 static void
204 rte_eal_config_create(void)
205 {
206         void *rte_mem_cfg_addr;
207         int retval;
208
209         const char *pathname = eal_runtime_config_path();
210
211         if (internal_config.no_shconf)
212                 return;
213
214         if (mem_cfg_fd < 0){
215                 mem_cfg_fd = open(pathname, O_RDWR | O_CREAT, 0660);
216                 if (mem_cfg_fd < 0)
217                         rte_panic("Cannot open '%s' for rte_mem_config\n", pathname);
218         }
219
220         retval = ftruncate(mem_cfg_fd, sizeof(*rte_config.mem_config));
221         if (retval < 0){
222                 close(mem_cfg_fd);
223                 rte_panic("Cannot resize '%s' for rte_mem_config\n", pathname);
224         }
225
226         retval = fcntl(mem_cfg_fd, F_SETLK, &wr_lock);
227         if (retval < 0){
228                 close(mem_cfg_fd);
229                 rte_exit(EXIT_FAILURE, "Cannot create lock on '%s'. Is another primary "
230                                 "process running?\n", pathname);
231         }
232
233         rte_mem_cfg_addr = mmap(NULL, sizeof(*rte_config.mem_config),
234                                 PROT_READ | PROT_WRITE, MAP_SHARED, mem_cfg_fd, 0);
235
236         if (rte_mem_cfg_addr == MAP_FAILED){
237                 rte_panic("Cannot mmap memory for rte_config\n");
238         }
239         memcpy(rte_mem_cfg_addr, &early_mem_config, sizeof(early_mem_config));
240         rte_config.mem_config = (struct rte_mem_config *) rte_mem_cfg_addr;
241 }
242
243 /* attach to an existing shared memory config */
244 static void
245 rte_eal_config_attach(void)
246 {
247         void *rte_mem_cfg_addr;
248         const char *pathname = eal_runtime_config_path();
249
250         if (internal_config.no_shconf)
251                 return;
252
253         if (mem_cfg_fd < 0){
254                 mem_cfg_fd = open(pathname, O_RDWR);
255                 if (mem_cfg_fd < 0)
256                         rte_panic("Cannot open '%s' for rte_mem_config\n", pathname);
257         }
258
259         rte_mem_cfg_addr = mmap(NULL, sizeof(*rte_config.mem_config), 
260                                 PROT_READ | PROT_WRITE, MAP_SHARED, mem_cfg_fd, 0);
261         close(mem_cfg_fd);
262         if (rte_mem_cfg_addr == MAP_FAILED)
263                 rte_panic("Cannot mmap memory for rte_config\n");
264
265         rte_config.mem_config = (struct rte_mem_config *) rte_mem_cfg_addr;
266 }
267
268 /* Detect if we are a primary or a secondary process */
269 static enum rte_proc_type_t
270 eal_proc_type_detect(void)
271 {
272         enum rte_proc_type_t ptype = RTE_PROC_PRIMARY;
273         const char *pathname = eal_runtime_config_path();
274
275         /* if we can open the file but not get a write-lock we are a secondary
276          * process. NOTE: if we get a file handle back, we keep that open
277          * and don't close it to prevent a race condition between multiple opens */
278         if (((mem_cfg_fd = open(pathname, O_RDWR)) >= 0) &&
279                         (fcntl(mem_cfg_fd, F_SETLK, &wr_lock) < 0))
280                 ptype = RTE_PROC_SECONDARY;
281
282         RTE_LOG(INFO, EAL, "Auto-detected process type: %s\n",
283                         ptype == RTE_PROC_PRIMARY ? "PRIMARY" : "SECONDARY");
284
285         return ptype;
286 }
287
288 /* Sets up rte_config structure with the pointer to shared memory config.*/
289 static void
290 rte_config_init(void)
291 {
292         /* set the magic in configuration structure */
293         rte_config.magic = RTE_MAGIC;
294         rte_config.process_type = (internal_config.process_type == RTE_PROC_AUTO) ?
295                         eal_proc_type_detect() : /* for auto, detect the type */
296                         internal_config.process_type; /* otherwise use what's already set */
297
298         switch (rte_config.process_type){
299         case RTE_PROC_PRIMARY:
300                 rte_eal_config_create();
301                 break;
302         case RTE_PROC_SECONDARY:
303                 rte_eal_config_attach();
304                 rte_eal_mcfg_wait_complete(rte_config.mem_config);
305                 break;
306         case RTE_PROC_AUTO:
307         case RTE_PROC_INVALID:
308                 rte_panic("Invalid process type\n");
309         }
310 }
311
312 /* Unlocks hugepage directories that were locked by eal_hugepage_info_init */
313 static void
314 eal_hugedirs_unlock(void)
315 {
316         int i;
317
318         for (i = 0; i < MAX_HUGEPAGE_SIZES; i++)
319         {
320                 /* skip uninitialized */
321                 if (internal_config.hugepage_info[i].lock_descriptor < 0)
322                         continue;
323                 /* unlock hugepage file */
324                 flock(internal_config.hugepage_info[i].lock_descriptor, LOCK_UN);
325                 close(internal_config.hugepage_info[i].lock_descriptor);
326                 /* reset the field */
327                 internal_config.hugepage_info[i].lock_descriptor = -1;
328         }
329 }
330
331 /* display usage */
332 static void
333 eal_usage(const char *prgname)
334 {
335         printf("\nUsage: %s -c COREMASK -n NUM [-m NB] [-r NUM] [-b <domain:bus:devid.func>]"
336                "[--proc-type primary|secondary|auto] \n\n"
337                "EAL options:\n"
338                "  -c COREMASK  : A hexadecimal bitmask of cores to run on\n"
339                "  -n NUM       : Number of memory channels\n"
340                    "  -v           : Display version information on startup\n"
341                "  -d LIB.so    : add driver (can be used multiple times)\n"
342                "  -m MB        : memory to allocate (see also --"OPT_SOCKET_MEM")\n"
343                "  -r NUM       : force number of memory ranks (don't detect)\n"
344                "  --"OPT_XEN_DOM0" : support application running on Xen Domain0 "
345                            "without hugetlbfs\n"
346                "  --"OPT_SYSLOG"     : set syslog facility\n"
347                "  --"OPT_SOCKET_MEM" : memory to allocate on specific \n"
348                    "                 sockets (use comma separated values)\n"
349                "  --"OPT_HUGE_DIR"   : directory where hugetlbfs is mounted\n"
350                "  --"OPT_PROC_TYPE"  : type of this process\n"
351                "  --"OPT_FILE_PREFIX": prefix for hugepage filenames\n"
352                "  --"OPT_PCI_BLACKLIST", -b: add a PCI device in black list.\n"
353                "               Prevent EAL from using this PCI device. The argument\n"
354                "               format is <domain:bus:devid.func>.\n"
355                "  --"OPT_PCI_WHITELIST", -w: add a PCI device in white list.\n"
356                "               Only use the specified PCI devices. The argument format\n"
357                "               is <[domain:]bus:devid.func>. This option can be present\n"
358                "               several times (once per device).\n"
359                "               [NOTE: PCI whitelist cannot be used with -b option]\n"
360                "  --"OPT_VDEV": add a virtual device.\n"
361                "               The argument format is <driver><id>[,key=val,...]\n"
362                "               (ex: --vdev=eth_pcap0,iface=eth2).\n"
363                "  --"OPT_VMWARE_TSC_MAP": use VMware TSC map instead of "
364                            "native RDTSC\n"
365                "  --"OPT_BASE_VIRTADDR": specify base virtual address\n"
366                "  --"OPT_CREATE_UIO_DEV": create /dev/uioX (usually done by hotplug)\n"
367                "\nEAL options for DEBUG use only:\n"
368                "  --"OPT_NO_HUGE"  : use malloc instead of hugetlbfs\n"
369                "  --"OPT_NO_PCI"   : disable pci\n"
370                "  --"OPT_NO_HPET"  : disable hpet\n"
371                "  --"OPT_NO_SHCONF": no shared config (mmap'd files)\n"
372                "\n",
373                prgname);
374         /* Allow the application to print its usage message too if hook is set */
375         if ( rte_application_usage_hook ) {
376                 printf("===== Application Usage =====\n\n");
377                 rte_application_usage_hook(prgname);
378         }
379 }
380
381 /* Set a per-application usage message */
382 rte_usage_hook_t
383 rte_set_application_usage_hook( rte_usage_hook_t usage_func )
384 {
385         rte_usage_hook_t        old_func;
386
387         /* Will be NULL on the first call to denote the last usage routine. */
388         old_func                                        = rte_application_usage_hook;
389         rte_application_usage_hook      = usage_func;
390
391         return old_func;
392 }
393
394 /*
395  * Parse the coremask given as argument (hexadecimal string) and fill
396  * the global configuration (core role and core count) with the parsed
397  * value.
398  */
399 static int xdigit2val(unsigned char c)
400 {
401         int val;
402         if(isdigit(c)) 
403                 val = c - '0';
404         else if(isupper(c))
405                 val = c - 'A' + 10;
406         else 
407                 val = c - 'a' + 10;
408         return val;
409 }
410 static int
411 eal_parse_coremask(const char *coremask)
412 {
413         struct rte_config *cfg = rte_eal_get_configuration();
414         int i, j, idx = 0 ;
415         unsigned count = 0;
416         char c;
417         int val;
418
419         if (coremask == NULL)
420                 return -1;
421         /* Remove all blank characters ahead and after .
422          * Remove 0x/0X if exists.
423          */
424         while (isblank(*coremask))
425                 coremask++;
426         if (coremask[0] == '0' && ((coremask[1] == 'x')
427                 ||  (coremask[1] == 'X')) )
428                 coremask += 2;
429         i = strnlen(coremask, PATH_MAX);
430         while ((i > 0) && isblank(coremask[i - 1]))
431                 i--;
432         if (i == 0)
433                 return -1;
434
435         for (i = i - 1; i >= 0 && idx < RTE_MAX_LCORE; i--) {
436                 c = coremask[i];
437                 if (isxdigit(c) == 0) {
438                         /* invalid characters */
439                         return (-1);
440                 }
441                 val = xdigit2val(c);
442                 for(j = 0; j < BITS_PER_HEX && idx < RTE_MAX_LCORE; j++, idx++) {
443                         if((1 << j) & val) {
444                                 cfg->lcore_role[idx] = ROLE_RTE;
445                                 if(count == 0)
446                                         cfg->master_lcore = idx;
447                                 count++;
448                         } else  {
449                                 cfg->lcore_role[idx] = ROLE_OFF;
450                         }
451                 }
452         }
453         for(; i >= 0; i--)
454                 if(coremask[i] != '0')
455                         return -1;
456         for(; idx < RTE_MAX_LCORE; idx++)
457                 cfg->lcore_role[idx] = ROLE_OFF;
458         if(count == 0)
459                 return -1;
460         /* Update the count of enabled logical cores of the EAL configuration */
461         cfg->lcore_count = count;
462         return 0;
463 }
464
465 static int
466 eal_parse_syslog(const char *facility)
467 {
468         int i;
469         static struct {
470                 const char *name;
471                 int value;
472         } map[] = {
473                 { "auth", LOG_AUTH },
474                 { "cron", LOG_CRON },
475                 { "daemon", LOG_DAEMON },
476                 { "ftp", LOG_FTP },
477                 { "kern", LOG_KERN },
478                 { "lpr", LOG_LPR },
479                 { "mail", LOG_MAIL },
480                 { "news", LOG_NEWS },
481                 { "syslog", LOG_SYSLOG },
482                 { "user", LOG_USER },
483                 { "uucp", LOG_UUCP },
484                 { "local0", LOG_LOCAL0 },
485                 { "local1", LOG_LOCAL1 },
486                 { "local2", LOG_LOCAL2 },
487                 { "local3", LOG_LOCAL3 },
488                 { "local4", LOG_LOCAL4 },
489                 { "local5", LOG_LOCAL5 },
490                 { "local6", LOG_LOCAL6 },
491                 { "local7", LOG_LOCAL7 },
492                 { NULL, 0 }
493         };
494
495         for (i = 0; map[i].name; i++) {
496                 if (!strcmp(facility, map[i].name)) {
497                         internal_config.syslog_facility = map[i].value;
498                         return 0;
499                 }
500         }
501         return -1;
502 }
503
504 static int
505 eal_parse_socket_mem(char *socket_mem)
506 {
507         char * arg[RTE_MAX_NUMA_NODES];
508         char *end;
509         int arg_num, i, len;
510         uint64_t total_mem = 0;
511
512         len = strnlen(socket_mem, SOCKET_MEM_STRLEN);
513         if (len == SOCKET_MEM_STRLEN) {
514                 RTE_LOG(ERR, EAL, "--socket-mem is too long\n");
515                 return -1;
516         }
517
518         /* all other error cases will be caught later */
519         if (!isdigit(socket_mem[len-1]))
520                 return -1;
521
522         /* split the optarg into separate socket values */
523         arg_num = rte_strsplit(socket_mem, len,
524                         arg, RTE_MAX_NUMA_NODES, ',');
525
526         /* if split failed, or 0 arguments */
527         if (arg_num <= 0)
528                 return -1;
529
530         internal_config.force_sockets = 1;
531
532         /* parse each defined socket option */
533         errno = 0;
534         for (i = 0; i < arg_num; i++) {
535                 end = NULL;
536                 internal_config.socket_mem[i] = strtoull(arg[i], &end, 10);
537
538                 /* check for invalid input */
539                 if ((errno != 0)  ||
540                                 (arg[i][0] == '\0') || (end == NULL) || (*end != '\0'))
541                         return -1;
542                 internal_config.socket_mem[i] *= 1024ULL;
543                 internal_config.socket_mem[i] *= 1024ULL;
544                 total_mem += internal_config.socket_mem[i];
545         }
546
547         /* check if we have a positive amount of total memory */
548         if (total_mem == 0)
549                 return -1;
550
551         return 0;
552 }
553
554 static int
555 eal_parse_base_virtaddr(const char *arg)
556 {
557         char *end;
558         uint64_t addr;
559
560         addr = strtoull(arg, &end, 16);
561
562         /* check for errors */
563         if ((errno != 0) || (arg[0] == '\0') || end == NULL || (*end != '\0'))
564                 return -1;
565
566         /* make sure we don't exceed 32-bit boundary on 32-bit target */
567 #ifndef RTE_ARCH_X86_64
568         if (addr >= UINTPTR_MAX)
569                 return -1;
570 #endif
571
572         /* align the addr on 2M boundary */
573         internal_config.base_virtaddr = RTE_PTR_ALIGN_CEIL((uintptr_t)addr,
574                                                            RTE_PGSIZE_2M);
575
576         return 0;
577 }
578
579 static inline size_t
580 eal_get_hugepage_mem_size(void)
581 {
582         uint64_t size = 0;
583         unsigned i, j;
584
585         for (i = 0; i < internal_config.num_hugepage_sizes; i++) {
586                 struct hugepage_info *hpi = &internal_config.hugepage_info[i];
587                 if (hpi->hugedir != NULL) {
588                         for (j = 0; j < RTE_MAX_NUMA_NODES; j++) {
589                                 size += hpi->hugepage_sz * hpi->num_pages[j];
590                         }
591                 }
592         }
593
594         return (size < SIZE_MAX) ? (size_t)(size) : SIZE_MAX;
595 }
596
597 static enum rte_proc_type_t
598 eal_parse_proc_type(const char *arg)
599 {
600         if (strncasecmp(arg, "primary", sizeof("primary")) == 0)
601                 return RTE_PROC_PRIMARY;
602         if (strncasecmp(arg, "secondary", sizeof("secondary")) == 0)
603                 return RTE_PROC_SECONDARY;
604         if (strncasecmp(arg, "auto", sizeof("auto")) == 0)
605                 return RTE_PROC_AUTO;
606
607         return RTE_PROC_INVALID;
608 }
609
610 /* Parse the argument given in the command line of the application */
611 static int
612 eal_parse_args(int argc, char **argv)
613 {
614         int opt, ret, i;
615         char **argvopt;
616         int option_index;
617         int coremask_ok = 0;
618         char *prgname = argv[0];
619         static struct option lgopts[] = {
620                 {OPT_NO_HUGE, 0, 0, 0},
621                 {OPT_NO_PCI, 0, 0, 0},
622                 {OPT_NO_HPET, 0, 0, 0},
623                 {OPT_VMWARE_TSC_MAP, 0, 0, 0},
624                 {OPT_HUGE_DIR, 1, 0, 0},
625                 {OPT_NO_SHCONF, 0, 0, 0},
626                 {OPT_PROC_TYPE, 1, 0, 0},
627                 {OPT_FILE_PREFIX, 1, 0, 0},
628                 {OPT_SOCKET_MEM, 1, 0, 0},
629                 {OPT_PCI_WHITELIST, 1, 0, 0},
630                 {OPT_PCI_BLACKLIST, 1, 0, 0},
631                 {OPT_VDEV, 1, 0, 0},
632                 {OPT_SYSLOG, 1, NULL, 0},
633                 {OPT_BASE_VIRTADDR, 1, 0, 0},
634                 {OPT_XEN_DOM0, 0, 0, 0},
635                 {OPT_CREATE_UIO_DEV, 1, NULL, 0},
636                 {0, 0, 0, 0}
637         };
638         struct shared_driver *solib;
639
640         argvopt = argv;
641
642         internal_config.memory = 0;
643         internal_config.force_nrank = 0;
644         internal_config.force_nchannel = 0;
645         internal_config.hugefile_prefix = HUGEFILE_PREFIX_DEFAULT;
646         internal_config.hugepage_dir = NULL;
647         internal_config.force_sockets = 0;
648         internal_config.syslog_facility = LOG_DAEMON;
649         internal_config.xen_dom0_support = 0;
650 #ifdef RTE_LIBEAL_USE_HPET
651         internal_config.no_hpet = 0;
652 #else
653         internal_config.no_hpet = 1;
654 #endif
655         /* zero out the NUMA config */
656         for (i = 0; i < RTE_MAX_NUMA_NODES; i++)
657                 internal_config.socket_mem[i] = 0;
658
659         /* zero out hugedir descriptors */
660         for (i = 0; i < MAX_HUGEPAGE_SIZES; i++)
661                 internal_config.hugepage_info[i].lock_descriptor = -1;
662
663         internal_config.vmware_tsc_map = 0;
664         internal_config.base_virtaddr = 0;
665
666         while ((opt = getopt_long(argc, argvopt, "b:w:c:d:m:n:r:v",
667                                   lgopts, &option_index)) != EOF) {
668
669                 switch (opt) {
670                 /* blacklist */
671                 case 'b':
672                         if (rte_eal_devargs_add(RTE_DEVTYPE_BLACKLISTED_PCI,
673                                         optarg) < 0) {
674                                 eal_usage(prgname);
675                                 return (-1);
676                         }
677                         break;
678                 /* whitelist */
679                 case 'w':
680                         if (rte_eal_devargs_add(RTE_DEVTYPE_WHITELISTED_PCI,
681                                         optarg) < 0) {
682                                 eal_usage(prgname);
683                                 return -1;
684                         }
685                         break;
686                 /* coremask */
687                 case 'c':
688                         if (eal_parse_coremask(optarg) < 0) {
689                                 RTE_LOG(ERR, EAL, "invalid coremask\n");
690                                 eal_usage(prgname);
691                                 return -1;
692                         }
693                         coremask_ok = 1;
694                         break;
695                 /* force loading of external driver */
696                 case 'd':
697                         solib = malloc(sizeof(*solib));
698                         if (solib == NULL) {
699                                 RTE_LOG(ERR, EAL, "malloc(solib) failed\n");
700                                 return -1;
701                         }
702                         memset(solib, 0, sizeof(*solib));
703                         strncpy(solib->name, optarg, PATH_MAX-1);
704                         solib->name[PATH_MAX-1] = 0;
705                         TAILQ_INSERT_TAIL(&solib_list, solib, next);
706                         break;
707                 /* size of memory */
708                 case 'm':
709                         internal_config.memory = atoi(optarg);
710                         internal_config.memory *= 1024ULL;
711                         internal_config.memory *= 1024ULL;
712                         break;
713                 /* force number of channels */
714                 case 'n':
715                         internal_config.force_nchannel = atoi(optarg);
716                         if (internal_config.force_nchannel == 0 ||
717                             internal_config.force_nchannel > 4) {
718                                 RTE_LOG(ERR, EAL, "invalid channel number\n");
719                                 eal_usage(prgname);
720                                 return -1;
721                         }
722                         break;
723                 /* force number of ranks */
724                 case 'r':
725                         internal_config.force_nrank = atoi(optarg);
726                         if (internal_config.force_nrank == 0 ||
727                             internal_config.force_nrank > 16) {
728                                 RTE_LOG(ERR, EAL, "invalid rank number\n");
729                                 eal_usage(prgname);
730                                 return -1;
731                         }
732                         break;
733                 case 'v':
734                         /* since message is explicitly requested by user, we
735                          * write message at highest log level so it can always be seen
736                          * even if info or warning messages are disabled */
737                         RTE_LOG(CRIT, EAL, "RTE Version: '%s'\n", rte_version());
738                         break;
739
740                 /* long options */
741                 case 0:
742                         if (!strcmp(lgopts[option_index].name, OPT_NO_HUGE)) {
743                                 internal_config.no_hugetlbfs = 1;
744                         }
745                         if (!strcmp(lgopts[option_index].name, OPT_XEN_DOM0)) {
746                 #ifdef RTE_LIBRTE_XEN_DOM0
747                                 internal_config.xen_dom0_support = 1;
748                 #else
749                                 RTE_LOG(ERR, EAL, "Can't support DPDK app "
750                                         "running on Dom0, please configure"
751                                         " RTE_LIBRTE_XEN_DOM0=y\n");
752                                 return -1;
753                 #endif 
754                         }
755                         else if (!strcmp(lgopts[option_index].name, OPT_NO_PCI)) {
756                                 internal_config.no_pci = 1;
757                         }
758                         else if (!strcmp(lgopts[option_index].name, OPT_NO_HPET)) {
759                                 internal_config.no_hpet = 1;
760                         }
761                         else if (!strcmp(lgopts[option_index].name, OPT_VMWARE_TSC_MAP)) {
762                                 internal_config.vmware_tsc_map = 1;
763                         }
764                         else if (!strcmp(lgopts[option_index].name, OPT_NO_SHCONF)) {
765                                 internal_config.no_shconf = 1;
766                         }
767                         else if (!strcmp(lgopts[option_index].name, OPT_HUGE_DIR)) {
768                                 internal_config.hugepage_dir = optarg;
769                         }
770                         else if (!strcmp(lgopts[option_index].name, OPT_PROC_TYPE)) {
771                                 internal_config.process_type = eal_parse_proc_type(optarg);
772                         }
773                         else if (!strcmp(lgopts[option_index].name, OPT_FILE_PREFIX)) {
774                                 internal_config.hugefile_prefix = optarg;
775                         }
776                         else if (!strcmp(lgopts[option_index].name, OPT_SOCKET_MEM)) {
777                                 if (eal_parse_socket_mem(optarg) < 0) {
778                                         RTE_LOG(ERR, EAL, "invalid parameters for --"
779                                                         OPT_SOCKET_MEM "\n");
780                                         eal_usage(prgname);
781                                         return -1;
782                                 }
783                         }
784                         else if (!strcmp(lgopts[option_index].name, OPT_USE_DEVICE)) {
785                                 printf("The --use-device option is deprecated, please use\n"
786                                         "--whitelist or --vdev instead.\n");
787                                 eal_usage(prgname);
788                                 return -1;
789                         }
790                         else if (!strcmp(lgopts[option_index].name, OPT_PCI_BLACKLIST)) {
791                                 if (rte_eal_devargs_add(RTE_DEVTYPE_BLACKLISTED_PCI,
792                                                 optarg) < 0) {
793                                         eal_usage(prgname);
794                                         return -1;
795                                 }
796                         }
797                         else if (!strcmp(lgopts[option_index].name, OPT_PCI_WHITELIST)) {
798                                 if (rte_eal_devargs_add(RTE_DEVTYPE_WHITELISTED_PCI,
799                                                 optarg) < 0) {
800                                         eal_usage(prgname);
801                                         return -1;
802                                 }
803                         }
804                         else if (!strcmp(lgopts[option_index].name, OPT_VDEV)) {
805                                 if (rte_eal_devargs_add(RTE_DEVTYPE_VIRTUAL,
806                                                 optarg) < 0) {
807                                         eal_usage(prgname);
808                                         return -1;
809                                 }
810                         }
811                         else if (!strcmp(lgopts[option_index].name, OPT_SYSLOG)) {
812                                 if (eal_parse_syslog(optarg) < 0) {
813                                         RTE_LOG(ERR, EAL, "invalid parameters for --"
814                                                         OPT_SYSLOG "\n");
815                                         eal_usage(prgname);
816                                         return -1;
817                                 }
818                         }
819                         else if (!strcmp(lgopts[option_index].name, OPT_BASE_VIRTADDR)) {
820                                 if (eal_parse_base_virtaddr(optarg) < 0) {
821                                         RTE_LOG(ERR, EAL, "invalid parameter for --"
822                                                         OPT_BASE_VIRTADDR "\n");
823                                         eal_usage(prgname);
824                                         return -1;
825                                 }
826                         }
827                         else if (!strcmp(lgopts[option_index].name, OPT_CREATE_UIO_DEV)) {
828                                 internal_config.create_uio_dev = 1;
829                         }
830                         break;
831
832                 default:
833                         eal_usage(prgname);
834                         return -1;
835                 }
836         }
837
838         /* sanity checks */
839         if (!coremask_ok) {
840                 RTE_LOG(ERR, EAL, "coremask not specified\n");
841                 eal_usage(prgname);
842                 return -1;
843         }
844         if (internal_config.process_type == RTE_PROC_AUTO){
845                 internal_config.process_type = eal_proc_type_detect();
846         }
847         if (internal_config.process_type == RTE_PROC_INVALID){
848                 RTE_LOG(ERR, EAL, "Invalid process type specified\n");
849                 eal_usage(prgname);
850                 return -1;
851         }
852         if (internal_config.process_type == RTE_PROC_PRIMARY &&
853                         internal_config.force_nchannel == 0) {
854                 RTE_LOG(ERR, EAL, "Number of memory channels (-n) not specified\n");
855                 eal_usage(prgname);
856                 return -1;
857         }
858         if (index(internal_config.hugefile_prefix,'%') != NULL){
859                 RTE_LOG(ERR, EAL, "Invalid char, '%%', in '"OPT_FILE_PREFIX"' option\n");
860                 eal_usage(prgname);
861                 return -1;
862         }
863         if (internal_config.memory > 0 && internal_config.force_sockets == 1) {
864                 RTE_LOG(ERR, EAL, "Options -m and --socket-mem cannot be specified "
865                                 "at the same time\n");
866                 eal_usage(prgname);
867                 return -1;
868         }
869         /* --no-huge doesn't make sense with either -m or --socket-mem */
870         if (internal_config.no_hugetlbfs &&
871                         (internal_config.memory > 0 ||
872                                         internal_config.force_sockets == 1)) {
873                 RTE_LOG(ERR, EAL, "Options -m or --socket-mem cannot be specified "
874                                 "together with --no-huge!\n");
875                 eal_usage(prgname);
876                 return -1;
877         }
878         /* --xen-dom0 doesn't make sense with --socket-mem */
879         if (internal_config.xen_dom0_support && internal_config.force_sockets == 1) {
880                 RTE_LOG(ERR, EAL, "Options --socket-mem cannot be specified "
881                                         "together with --xen_dom0!\n");
882                 eal_usage(prgname);
883                 return -1;
884         }
885
886         if (rte_eal_devargs_type_count(RTE_DEVTYPE_WHITELISTED_PCI) != 0 &&
887                 rte_eal_devargs_type_count(RTE_DEVTYPE_BLACKLISTED_PCI) != 0) {
888                 RTE_LOG(ERR, EAL, "Error: blacklist [-b] and whitelist "
889                         "[-w] options cannot be used at the same time\n");
890                 eal_usage(prgname);
891                 return -1;
892         }
893
894         if (optind >= 0)
895                 argv[optind-1] = prgname;
896
897         /* if no memory amounts were requested, this will result in 0 and
898          * will be overriden later, right after eal_hugepage_info_init() */
899         for (i = 0; i < RTE_MAX_NUMA_NODES; i++)
900                 internal_config.memory += internal_config.socket_mem[i];
901
902         ret = optind-1;
903         optind = 0; /* reset getopt lib */
904         return ret;
905 }
906
907 static void
908 eal_check_mem_on_local_socket(void)
909 {
910         const struct rte_memseg *ms;
911         int i, socket_id;
912
913         socket_id = rte_lcore_to_socket_id(rte_config.master_lcore);
914
915         ms = rte_eal_get_physmem_layout();
916
917         for (i = 0; i < RTE_MAX_MEMSEG; i++)
918                 if (ms[i].socket_id == socket_id &&
919                                 ms[i].len > 0)
920                         return;
921
922         RTE_LOG(WARNING, EAL, "WARNING: Master core has no "
923                         "memory on local socket!\n");
924 }
925
926 static int
927 sync_func(__attribute__((unused)) void *arg)
928 {
929         return 0;
930 }
931
932 inline static void 
933 rte_eal_mcfg_complete(void)
934 {
935         /* ALL shared mem_config related INIT DONE */
936         if (rte_config.process_type == RTE_PROC_PRIMARY)
937                 rte_config.mem_config->magic = RTE_MAGIC;
938 }
939
940 /*
941  * Request iopl priviledge for all RPL, returns 0 on success
942  */
943 static int
944 rte_eal_iopl_init(void)
945 {
946         return iopl(HIGHEST_RPL);
947 }
948
949 /* Launch threads, called at application init(). */
950 int
951 rte_eal_init(int argc, char **argv)
952 {
953         int i, fctret, ret;
954         pthread_t thread_id;
955         static rte_atomic32_t run_once = RTE_ATOMIC32_INIT(0);
956         struct shared_driver *solib = NULL;
957         const char *logid;
958
959         if (!rte_atomic32_test_and_set(&run_once))
960                 return -1;
961
962         logid = strrchr(argv[0], '/');
963         logid = strdup(logid ? logid + 1: argv[0]);
964
965         thread_id = pthread_self();
966
967         if (rte_eal_log_early_init() < 0)
968                 rte_panic("Cannot init early logs\n");
969
970         if (rte_eal_cpu_init() < 0)
971                 rte_panic("Cannot detect lcores\n");
972
973         fctret = eal_parse_args(argc, argv);
974         if (fctret < 0)
975                 exit(1);
976
977         if (internal_config.no_hugetlbfs == 0 &&
978                         internal_config.process_type != RTE_PROC_SECONDARY &&
979                         internal_config.xen_dom0_support == 0 &&
980                         eal_hugepage_info_init() < 0)
981                 rte_panic("Cannot get hugepage information\n");
982
983         if (internal_config.memory == 0 && internal_config.force_sockets == 0) {
984                 if (internal_config.no_hugetlbfs)
985                         internal_config.memory = MEMSIZE_IF_NO_HUGE_PAGE;
986                 else
987                         internal_config.memory = eal_get_hugepage_mem_size();
988         }
989
990         if (internal_config.vmware_tsc_map == 1) {
991 #ifdef RTE_LIBRTE_EAL_VMWARE_TSC_MAP_SUPPORT
992                 rte_cycles_vmware_tsc_map = 1;
993                 RTE_LOG (DEBUG, EAL, "Using VMWARE TSC MAP, "
994                                 "you must have monitor_control.pseudo_perfctr = TRUE\n");
995 #else
996                 RTE_LOG (WARNING, EAL, "Ignoring --vmware-tsc-map because "
997                                 "RTE_LIBRTE_EAL_VMWARE_TSC_MAP_SUPPORT is not set\n");
998 #endif
999         }
1000
1001         rte_srand(rte_rdtsc());
1002
1003         rte_config_init();
1004
1005         if (rte_eal_iopl_init() == 0)
1006                 rte_config.flags |= EAL_FLG_HIGH_IOPL;
1007         
1008         if (rte_eal_pci_init() < 0)
1009                 rte_panic("Cannot init PCI\n");
1010
1011 #ifdef RTE_LIBRTE_IVSHMEM
1012         if (rte_eal_ivshmem_init() < 0)
1013                 rte_panic("Cannot init IVSHMEM\n");
1014 #endif
1015
1016         if (rte_eal_memory_init() < 0)
1017                 rte_panic("Cannot init memory\n");
1018
1019         /* the directories are locked during eal_hugepage_info_init */
1020         eal_hugedirs_unlock();
1021         
1022         if (rte_eal_memzone_init() < 0)
1023                 rte_panic("Cannot init memzone\n");
1024
1025         if (rte_eal_tailqs_init() < 0)
1026                 rte_panic("Cannot init tail queues for objects\n");
1027
1028 #ifdef RTE_LIBRTE_IVSHMEM
1029         if (rte_eal_ivshmem_obj_init() < 0)
1030                 rte_panic("Cannot init IVSHMEM objects\n");
1031 #endif
1032
1033         if (rte_eal_log_init(logid, internal_config.syslog_facility) < 0)
1034                 rte_panic("Cannot init logs\n");
1035
1036         if (rte_eal_alarm_init() < 0)
1037                 rte_panic("Cannot init interrupt-handling thread\n");
1038
1039         if (rte_eal_intr_init() < 0)
1040                 rte_panic("Cannot init interrupt-handling thread\n");
1041
1042         if (rte_eal_timer_init() < 0)
1043                 rte_panic("Cannot init HPET or TSC timers\n");
1044
1045         eal_check_mem_on_local_socket();
1046
1047         rte_eal_mcfg_complete();
1048
1049         TAILQ_FOREACH(solib, &solib_list, next) {
1050                 RTE_LOG(INFO, EAL, "open shared lib %s\n", solib->name);
1051                 solib->lib_handle = dlopen(solib->name, RTLD_NOW);
1052                 if ((solib->lib_handle == NULL) && (solib->name[0] != '/')) {
1053                         /* relative path: try again with "./" prefix */
1054                         char sopath[PATH_MAX];
1055                         snprintf(sopath, sizeof(sopath), "./%s", solib->name);
1056                         solib->lib_handle = dlopen(sopath, RTLD_NOW);
1057                 }
1058                 if (solib->lib_handle == NULL)
1059                         RTE_LOG(WARNING, EAL, "%s\n", dlerror());
1060         }
1061
1062         if (rte_eal_vdev_init() < 0)
1063                 rte_panic("Cannot init virtual devices\n");
1064
1065         RTE_LOG(DEBUG, EAL, "Master core %u is ready (tid=%x)\n",
1066                 rte_config.master_lcore, (int)thread_id);
1067
1068         RTE_LCORE_FOREACH_SLAVE(i) {
1069
1070                 /*
1071                  * create communication pipes between master thread
1072                  * and children
1073                  */
1074                 if (pipe(lcore_config[i].pipe_master2slave) < 0)
1075                         rte_panic("Cannot create pipe\n");
1076                 if (pipe(lcore_config[i].pipe_slave2master) < 0)
1077                         rte_panic("Cannot create pipe\n");
1078
1079                 lcore_config[i].state = WAIT;
1080
1081                 /* create a thread for each lcore */
1082                 ret = pthread_create(&lcore_config[i].thread_id, NULL,
1083                                      eal_thread_loop, NULL);
1084                 if (ret != 0)
1085                         rte_panic("Cannot create thread\n");
1086         }
1087
1088         eal_thread_init_master(rte_config.master_lcore);
1089
1090         /*
1091          * Launch a dummy function on all slave lcores, so that master lcore
1092          * knows they are all ready when this function returns.
1093          */
1094         rte_eal_mp_remote_launch(sync_func, NULL, SKIP_MASTER);
1095         rte_eal_mp_wait_lcore();
1096
1097         return fctret;
1098 }
1099
1100 /* get core role */
1101 enum rte_lcore_role_t
1102 rte_eal_lcore_role(unsigned lcore_id)
1103 {
1104         return (rte_config.lcore_role[lcore_id]);
1105 }
1106
1107 enum rte_proc_type_t
1108 rte_eal_process_type(void)
1109 {
1110         return (rte_config.process_type);
1111 }
1112
1113 int rte_eal_has_hugepages(void)
1114 {
1115         return ! internal_config.no_hugetlbfs;
1116 }