snapshot: remove SSDEBUG
[c11tester.git] / snapshot.cc
1 #include <inttypes.h>
2 #include <sys/mman.h>
3 #include <unistd.h>
4 #include <signal.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <errno.h>
8 #include <sys/wait.h>
9 #include <ucontext.h>
10
11 #include "hashtable.h"
12 #include "snapshot.h"
13 #include "mymemory.h"
14 #include "common.h"
15
16 #define FAILURE(mesg) { model_print("failed in the API: %s with errno relative message: %s\n", mesg, strerror(errno)); exit(EXIT_FAILURE); }
17
18 #if USE_MPROTECT_SNAPSHOT
19 /* Each snapshotrecord lists the firstbackingpage that must be written to
20  * revert to that snapshot */
21 struct SnapShotRecord {
22         unsigned int firstBackingPage;
23 };
24
25 /** @brief Backing store page */
26 typedef unsigned char snapshot_page_t[PAGESIZE];
27
28 /* List the base address of the corresponding page in the backing store so we
29  * know where to copy it to */
30 struct BackingPageRecord {
31         void *basePtrOfPage;
32 };
33
34 /* Struct for each memory region */
35 struct MemoryRegion {
36         void *basePtr; // base of memory region
37         int sizeInPages; // size of memory region in pages
38 };
39
40 /* Primary struct for snapshotting system */
41 struct SnapShot {
42         struct MemoryRegion *regionsToSnapShot; //This pointer references an array of memory regions to snapshot
43         snapshot_page_t *backingStore; //This pointer references an array of snapshotpage's that form the backing store
44         void *backingStoreBasePtr; //This pointer references an array of snapshotpage's that form the backing store
45         struct BackingPageRecord *backingRecords; //This pointer references an array of backingpagerecord's (same number of elements as backingstore
46         struct SnapShotRecord *snapShots; //This pointer references the snapshot array
47
48         unsigned int lastSnapShot; //Stores the next snapshot record we should use
49         unsigned int lastBackingPage; //Stores the next backingpage we should use
50         unsigned int lastRegion; //Stores the next memory region to be used
51
52         unsigned int maxRegions; //Stores the max number of memory regions we support
53         unsigned int maxBackingPages; //Stores the total number of backing pages
54         unsigned int maxSnapShots; //Stores the total number of snapshots we allow
55 };
56
57 #else
58
59 #include <ucontext.h>
60
61 #define SHARED_MEMORY_DEFAULT  (100 * ((size_t)1 << 20)) // 100mb for the shared memory
62 #define STACK_SIZE_DEFAULT      (((size_t)1 << 20) * 20)  // 20 mb out of the above 100 mb for my stack
63
64 struct SnapShot {
65         void *mSharedMemoryBase;
66         void *mStackBase;
67         size_t mStackSize;
68         volatile snapshot_id mIDToRollback;
69         ucontext_t mContextToRollback;
70         snapshot_id currSnapShotID;
71 };
72 #endif
73
74 static struct SnapShot *snapshotrecord = NULL;
75
76 /** PageAlignedAdressUpdate return a page aligned address for the
77  * address being added as a side effect the numBytes are also changed.
78  */
79 static void * PageAlignAddressUpward(void *addr)
80 {
81         return (void *)((((uintptr_t)addr) + PAGESIZE - 1) & ~(PAGESIZE - 1));
82 }
83
84 #if !USE_MPROTECT_SNAPSHOT
85 /** @statics
86 *   These variables are necessary because the stack is shared region and
87 *   there exists a race between all processes executing the same function.
88 *   To avoid the problem above, we require variables allocated in 'safe' regions.
89 *   The bug was actually observed with the forkID, these variables below are
90 *   used to indicate the various contexts to which to switch to.
91 *
92 *   @savedSnapshotContext: contains the point to which takesnapshot() call should switch to.
93 *   @savedUserSnapshotContext: contains the point to which the process whose snapshotid is equal to the rollbackid should switch to
94 *   @snapshotid: it is a running counter for the various forked processes snapshotid. it is incremented and set in a persistently shared record
95 */
96 static ucontext_t savedSnapshotContext;
97 static ucontext_t savedUserSnapshotContext;
98 static snapshot_id snapshotid = 0;
99
100 #else /* USE_MPROTECT_SNAPSHOT */
101
102 /** ReturnPageAlignedAddress returns a page aligned address for the
103  * address being added as a side effect the numBytes are also changed.
104  */
105 static void * ReturnPageAlignedAddress(void *addr)
106 {
107         return (void *)(((uintptr_t)addr) & ~(PAGESIZE - 1));
108 }
109
110 /** The initSnapShotRecord method initialized the snapshotting data
111  *  structures for the mprotect based snapshot.
112  */
113 static void initSnapShotRecord(unsigned int numbackingpages, unsigned int numsnapshots, unsigned int nummemoryregions)
114 {
115         snapshotrecord = (struct SnapShot *)model_malloc(sizeof(struct SnapShot));
116         snapshotrecord->regionsToSnapShot = (struct MemoryRegion *)model_malloc(sizeof(struct MemoryRegion) * nummemoryregions);
117         snapshotrecord->backingStoreBasePtr = (void *)model_malloc(sizeof(snapshot_page_t) * (numbackingpages + 1));
118         //Page align the backingstorepages
119         snapshotrecord->backingStore = (snapshot_page_t *)PageAlignAddressUpward(snapshotrecord->backingStoreBasePtr);
120         snapshotrecord->backingRecords = (struct BackingPageRecord *)model_malloc(sizeof(struct BackingPageRecord) * numbackingpages);
121         snapshotrecord->snapShots = (struct SnapShotRecord *)model_malloc(sizeof(struct SnapShotRecord) * numsnapshots);
122         snapshotrecord->lastSnapShot = 0;
123         snapshotrecord->lastBackingPage = 0;
124         snapshotrecord->lastRegion = 0;
125         snapshotrecord->maxRegions = nummemoryregions;
126         snapshotrecord->maxBackingPages = numbackingpages;
127         snapshotrecord->maxSnapShots = numsnapshots;
128 }
129
130 /** HandlePF is the page fault handler for mprotect based snapshotting
131  * algorithm.
132  */
133 static void HandlePF(int sig, siginfo_t *si, void *unused)
134 {
135         if (si->si_code == SEGV_MAPERR) {
136                 model_print("Real Fault at %p\n", si->si_addr);
137                 print_trace();
138                 model_print("For debugging, place breakpoint at: %s:%d\n",
139                                 __FILE__, __LINE__);
140                 exit(EXIT_FAILURE);
141         }
142         void* addr = ReturnPageAlignedAddress(si->si_addr);
143
144         unsigned int backingpage = snapshotrecord->lastBackingPage++; //Could run out of pages...
145         if (backingpage == snapshotrecord->maxBackingPages) {
146                 model_print("Out of backing pages at %p\n", si->si_addr);
147                 exit(EXIT_FAILURE);
148         }
149
150         //copy page
151         memcpy(&(snapshotrecord->backingStore[backingpage]), addr, sizeof(snapshot_page_t));
152         //remember where to copy page back to
153         snapshotrecord->backingRecords[backingpage].basePtrOfPage = addr;
154         //set protection to read/write
155         if (mprotect(addr, sizeof(snapshot_page_t), PROT_READ | PROT_WRITE)) {
156                 perror("mprotect");
157                 // Handle error by quitting?
158         }
159 }
160 #endif /* USE_MPROTECT_SNAPSHOT */
161
162 #if !USE_MPROTECT_SNAPSHOT
163 static void createSharedMemory()
164 {
165         //step 1. create shared memory.
166         void *memMapBase = mmap(0, SHARED_MEMORY_DEFAULT + STACK_SIZE_DEFAULT, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0);
167         if (MAP_FAILED == memMapBase)
168                 FAILURE("mmap");
169
170         //Setup snapshot record at top of free region
171         snapshotrecord = (struct SnapShot *)memMapBase;
172         snapshotrecord->mSharedMemoryBase = (void *)((uintptr_t)memMapBase + sizeof(struct SnapShot));
173         snapshotrecord->mStackBase = (void *)((uintptr_t)memMapBase + SHARED_MEMORY_DEFAULT);
174         snapshotrecord->mStackSize = STACK_SIZE_DEFAULT;
175         snapshotrecord->mIDToRollback = -1;
176         snapshotrecord->currSnapShotID = 0;
177 }
178
179 /**
180  * Create a new mspace pointer for the non-snapshotting (i.e., inter-process
181  * shared) memory region. Only for fork-based snapshotting.
182  *
183  * @return The shared memory mspace
184  */
185 mspace create_shared_mspace()
186 {
187         if (!snapshotrecord)
188                 createSharedMemory();
189         return create_mspace_with_base((void *)(snapshotrecord->mSharedMemoryBase), SHARED_MEMORY_DEFAULT - sizeof(struct SnapShot), 1);
190 }
191 #endif
192
193
194 /** The initSnapshotLibrary function initializes the snapshot library.
195  *  @param entryPoint the function that should run the program.
196  */
197 #if USE_MPROTECT_SNAPSHOT
198
199 void initSnapshotLibrary(unsigned int numbackingpages,
200                 unsigned int numsnapshots, unsigned int nummemoryregions,
201                 unsigned int numheappages, VoidFuncPtr entryPoint)
202 {
203         /* Setup a stack for our signal handler....  */
204         stack_t ss;
205         ss.ss_sp = PageAlignAddressUpward(model_malloc(SIGSTACKSIZE + PAGESIZE - 1));
206         ss.ss_size = SIGSTACKSIZE;
207         ss.ss_flags = 0;
208         sigaltstack(&ss, NULL);
209
210         struct sigaction sa;
211         sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK;
212         sigemptyset(&sa.sa_mask);
213         sa.sa_sigaction = HandlePF;
214 #ifdef MAC
215         if (sigaction(SIGBUS, &sa, NULL) == -1) {
216                 model_print("SIGACTION CANNOT BE INSTALLED\n");
217                 exit(EXIT_FAILURE);
218         }
219 #endif
220         if (sigaction(SIGSEGV, &sa, NULL) == -1) {
221                 model_print("SIGACTION CANNOT BE INSTALLED\n");
222                 exit(EXIT_FAILURE);
223         }
224
225         initSnapShotRecord(numbackingpages, numsnapshots, nummemoryregions);
226
227         // EVIL HACK: We need to make sure that calls into the HandlePF method don't cause dynamic links
228         // The problem is that we end up protecting state in the dynamic linker...
229         // Solution is to call our signal handler before we start protecting stuff...
230
231         siginfo_t si;
232         memset(&si, 0, sizeof(si));
233         si.si_addr = ss.ss_sp;
234         HandlePF(SIGSEGV, &si, NULL);
235         snapshotrecord->lastBackingPage--; //remove the fake page we copied
236
237         void *basemySpace = model_malloc((numheappages + 1) * PAGESIZE);
238         void *pagealignedbase = PageAlignAddressUpward(basemySpace);
239         user_snapshot_space = create_mspace_with_base(pagealignedbase, numheappages * PAGESIZE, 1);
240         addMemoryRegionToSnapShot(pagealignedbase, numheappages);
241
242         void *base_model_snapshot_space = model_malloc((numheappages + 1) * PAGESIZE);
243         pagealignedbase = PageAlignAddressUpward(base_model_snapshot_space);
244         model_snapshot_space = create_mspace_with_base(pagealignedbase, numheappages * PAGESIZE, 1);
245         addMemoryRegionToSnapShot(pagealignedbase, numheappages);
246
247         entryPoint();
248 }
249 #else
250 void initSnapshotLibrary(unsigned int numbackingpages,
251                 unsigned int numsnapshots, unsigned int nummemoryregions,
252                 unsigned int numheappages, VoidFuncPtr entryPoint)
253 {
254         if (!snapshotrecord)
255                 createSharedMemory();
256
257         void *base_model_snapshot_space = malloc((numheappages + 1) * PAGESIZE);
258         void *pagealignedbase = PageAlignAddressUpward(base_model_snapshot_space);
259         model_snapshot_space = create_mspace_with_base(pagealignedbase, numheappages * PAGESIZE, 1);
260
261         //step 2 setup the stack context.
262         ucontext_t newContext;
263         getcontext(&newContext);
264         newContext.uc_stack.ss_sp = snapshotrecord->mStackBase;
265         newContext.uc_stack.ss_size = STACK_SIZE_DEFAULT;
266         makecontext(&newContext, entryPoint, 0);
267         /* switch to a new entryPoint context, on a new stack */
268         swapcontext(&savedSnapshotContext, &newContext);
269
270         /* switch back here when takesnapshot is called */
271         pid_t forkedID = 0;
272         snapshotid = snapshotrecord->currSnapShotID;
273         /* This bool indicates that the current process's snapshotid is same
274                  as the id to which the rollback needs to occur */
275
276         bool rollback = false;
277         while (true) {
278                 snapshotrecord->currSnapShotID = snapshotid + 1;
279                 forkedID = fork();
280
281                 if (0 == forkedID) {
282                         /* If the rollback bool is set, switch to the context we need to
283                                  return to during a rollback. */
284                         if (rollback) {
285                                 setcontext(&(snapshotrecord->mContextToRollback));
286                         } else {
287                                 /*Child process which is forked as a result of takesnapshot
288                                         call should switch back to the takesnapshot context*/
289                                 setcontext(&savedUserSnapshotContext);
290                         }
291                 } else {
292                         int status;
293                         int retVal;
294
295                         DEBUG("The process id of child is %d and the process id of this process is %d and snapshot id is %d\n",
296                                 forkedID, getpid(), snapshotid);
297
298                         do {
299                                 retVal = waitpid(forkedID, &status, 0);
300                         } while (-1 == retVal && errno == EINTR);
301
302                         if (snapshotrecord->mIDToRollback != snapshotid) {
303                                 exit(EXIT_SUCCESS);
304                         }
305                         rollback = true;
306                 }
307         }
308 }
309 #endif
310
311 /** The addMemoryRegionToSnapShot function assumes that addr is page aligned.
312  */
313 void addMemoryRegionToSnapShot(void *addr, unsigned int numPages)
314 {
315 #if USE_MPROTECT_SNAPSHOT
316         unsigned int memoryregion = snapshotrecord->lastRegion++;
317         if (memoryregion == snapshotrecord->maxRegions) {
318                 model_print("Exceeded supported number of memory regions!\n");
319                 exit(EXIT_FAILURE);
320         }
321
322         snapshotrecord->regionsToSnapShot[memoryregion].basePtr = addr;
323         snapshotrecord->regionsToSnapShot[memoryregion].sizeInPages = numPages;
324 #endif //NOT REQUIRED IN THE CASE OF FORK BASED SNAPSHOTS.
325 }
326
327 /** The takeSnapshot function takes a snapshot.
328  * @return The snapshot identifier.
329  */
330 snapshot_id takeSnapshot()
331 {
332 #if USE_MPROTECT_SNAPSHOT
333         for (unsigned int region = 0; region < snapshotrecord->lastRegion; region++) {
334                 if (mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages * sizeof(snapshot_page_t), PROT_READ) == -1) {
335                         perror("mprotect");
336                         model_print("Failed to mprotect inside of takeSnapShot\n");
337                         exit(EXIT_FAILURE);
338                 }
339         }
340         unsigned int snapshot = snapshotrecord->lastSnapShot++;
341         if (snapshot == snapshotrecord->maxSnapShots) {
342                 model_print("Out of snapshots\n");
343                 exit(EXIT_FAILURE);
344         }
345         snapshotrecord->snapShots[snapshot].firstBackingPage = snapshotrecord->lastBackingPage;
346
347         return snapshot;
348 #else
349         swapcontext(&savedUserSnapshotContext, &savedSnapshotContext);
350         DEBUG("TAKESNAPSHOT RETURN\n");
351         return snapshotid;
352 #endif
353 }
354
355 /** The rollBack function rollback to the given snapshot identifier.
356  *  @param theID is the snapshot identifier to rollback to.
357  */
358 void rollBack(snapshot_id theID)
359 {
360 #if USE_MPROTECT_SNAPSHOT == 2
361         if (snapshotrecord->lastSnapShot == (theID + 1)) {
362                 for (unsigned int page = snapshotrecord->snapShots[theID].firstBackingPage; page < snapshotrecord->lastBackingPage; page++) {
363                         memcpy(snapshotrecord->backingRecords[page].basePtrOfPage, &snapshotrecord->backingStore[page], sizeof(snapshot_page_t));
364                 }
365                 return;
366         }
367 #endif
368
369 #if USE_MPROTECT_SNAPSHOT
370         HashTable< void *, bool, uintptr_t, 4, model_malloc, model_calloc, model_free> duplicateMap;
371         for (unsigned int region = 0; region < snapshotrecord->lastRegion; region++) {
372                 if (mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages * sizeof(snapshot_page_t), PROT_READ | PROT_WRITE) == -1) {
373                         perror("mprotect");
374                         model_print("Failed to mprotect inside of takeSnapShot\n");
375                         exit(EXIT_FAILURE);
376                 }
377         }
378         for (unsigned int page = snapshotrecord->snapShots[theID].firstBackingPage; page < snapshotrecord->lastBackingPage; page++) {
379                 if (!duplicateMap.contains(snapshotrecord->backingRecords[page].basePtrOfPage)) {
380                         duplicateMap.put(snapshotrecord->backingRecords[page].basePtrOfPage, true);
381                         memcpy(snapshotrecord->backingRecords[page].basePtrOfPage, &snapshotrecord->backingStore[page], sizeof(snapshot_page_t));
382                 }
383         }
384         snapshotrecord->lastSnapShot = theID;
385         snapshotrecord->lastBackingPage = snapshotrecord->snapShots[theID].firstBackingPage;
386         takeSnapshot(); //Make sure current snapshot is still good...All later ones are cleared
387 #else
388         snapshotrecord->mIDToRollback = theID;
389         volatile int sTemp = 0;
390         getcontext(&snapshotrecord->mContextToRollback);
391         /*
392          * This is used to quit the process on rollback, so that the process
393          * which needs to rollback can quit allowing the process whose
394          * snapshotid matches the rollbackid to switch to this context and
395          * continue....
396          */
397         if (!sTemp) {
398                 sTemp = 1;
399                 DEBUG("Invoked rollback\n");
400                 exit(EXIT_SUCCESS);
401         }
402         /*
403          * This fix obviates the need for a finalize call. hence less dependences for model-checker....
404          */
405         snapshotrecord->mIDToRollback = -1;
406 #endif
407 }