move shm code out of trinity.c into own file
[trinity.git] / shm.c
blob2d535222ba0346197e49278d498048c385bd0087
1 /*
2 * Shared mapping creation.
3 */
5 #include <stdlib.h>
6 #include <string.h>
7 #include <unistd.h>
8 #include <sys/mman.h>
9 #include "arch.h"
10 #include "log.h"
11 #include "params.h"
12 #include "pids.h"
13 #include "random.h"
14 #include "shm.h"
16 void * alloc_shared(unsigned int size)
18 void *ret;
20 ret = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_ANON | MAP_SHARED, -1, 0);
21 if (ret == MAP_FAILED)
22 return NULL;
24 return ret;
27 struct shm_s *shm;
29 #define SHM_PROT_PAGES 30
31 int create_shm(void)
33 void *p;
34 unsigned int shm_pages;
36 shm_pages = ((sizeof(struct shm_s) + page_size - 1) & ~(page_size - 1)) / page_size;
38 /* Waste some address space to set up some "protection" near the SHM location. */
39 p = alloc_shared((SHM_PROT_PAGES + shm_pages + SHM_PROT_PAGES) * page_size);
40 if (p == NULL) {
41 perror("mmap");
42 return -1;
45 mprotect(p, SHM_PROT_PAGES * page_size, PROT_NONE);
46 mprotect(p + (SHM_PROT_PAGES + shm_pages) * page_size,
47 SHM_PROT_PAGES * page_size, PROT_NONE);
49 shm = p + SHM_PROT_PAGES * page_size;
51 memset(shm, 0, sizeof(struct shm_s));
53 shm->total_syscalls_done = 1;
54 shm->regenerate = 0;
56 memset(shm->pids, EMPTY_PIDSLOT, sizeof(shm->pids));
58 shm->nr_active_syscalls = 0;
59 shm->nr_active_32bit_syscalls = 0;
60 shm->nr_active_64bit_syscalls = 0;
61 memset(shm->active_syscalls, 0, sizeof(shm->active_syscalls));
62 memset(shm->active_syscalls32, 0, sizeof(shm->active_syscalls32));
63 memset(shm->active_syscalls64, 0, sizeof(shm->active_syscalls64));
65 /* Overwritten later in setup_shm_postargs if user passed -s */
66 shm->seed = new_seed();
68 /* Set seed in parent thread */
69 set_seed(0);
71 return 0;
74 void setup_shm_postargs(void)
76 if (user_set_seed == TRUE) {
77 shm->seed = init_seed(seed);
78 /* Set seed in parent thread */
79 set_seed(0);
82 if (user_specified_children != 0)
83 shm->max_children = user_specified_children;
84 else
85 shm->max_children = sysconf(_SC_NPROCESSORS_ONLN);
87 if (shm->max_children > MAX_NR_CHILDREN) {
88 outputerr("Increase MAX_NR_CHILDREN!\n");
89 exit(EXIT_FAILURE);