fix this stuff...
[model-checker.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 <map>
7 #include <set>
8 #include <cstring>
9 #include <cstdio>
10 #include "snapshot.h"
11 #include "snapshotimp.h"
12 #include "mymemory.h"
13 #include <fcntl.h>
14 #include <assert.h>
15 #include <pthread.h>
16 #include <semaphore.h>
17 #include <errno.h>
18 #include <sys/wait.h>
19 #include <ucontext.h>
20 #include <sys/time.h>
21 //extern declaration definition
22 #define FAILURE(mesg) { printf("failed in the API: %s with errno relative message: %s\n", mesg, strerror( errno ) ); exit( -1 ); }
23 #if USE_CHECKPOINTING
24 struct SnapShot * snapshotrecord = NULL;
25 struct Snapshot_t * sTheRecord = NULL;
26 #else
27 struct Snapshot_t * sTheRecord = NULL;
28 #endif
29 void BeginOperation( struct timeval * theStartTime ){
30 #if 1
31         gettimeofday( theStartTime, NULL );
32 #endif
33 }
34 #if DEBUG
35 struct timeval *starttime = NULL;
36 #endif
37 void DumpIntoLog( const char * filename, const char * message ){
38 #if DEBUG
39    static pid_t thePID = getpid();
40    char newFn[ 1024 ] ={ 0 };
41    sprintf( newFn,"%s-%d.txt", filename, thePID );
42    FILE * myFile = fopen( newFn, "w+" );
43    struct timeval theEndTime;
44    BeginOperation( &theEndTime );
45    double elapsed = ( theEndTime.tv_sec - starttime->tv_sec ) + ( theEndTime.tv_usec - starttime->tv_usec ) / 1000000.0;
46    fprintf( myFile, "The timestamp %f:--> the message %s: the process id %d\n", elapsed, message, thePID );
47    fflush( myFile );
48    fclose( myFile );
49    myFile = NULL;
50 #endif
51 }
52 #if !USE_CHECKPOINTING
53 static ucontext_t savedSnapshotContext;
54 static ucontext_t savedUserSnapshotContext;
55 static int snapshotid = 0;
56 #endif
57 /* Initialize snapshot data structure */
58 #if USE_CHECKPOINTING
59 void initSnapShotRecord(unsigned int numbackingpages, unsigned int numsnapshots, unsigned int nummemoryregions) {
60   snapshotrecord=( struct SnapShot * )MYMALLOC(sizeof(struct SnapShot));
61   snapshotrecord->regionsToSnapShot=( struct MemoryRegion * )MYMALLOC(sizeof(struct MemoryRegion)*nummemoryregions);
62   snapshotrecord->backingStoreBasePtr= ( struct SnapShotPage * )MYMALLOC( sizeof( struct SnapShotPage ) * (numbackingpages + 1) );
63   //Page align the backingstorepages
64   snapshotrecord->backingStore=( struct SnapShotPage * )ReturnPageAlignedAddress((void*) ((uintptr_t)(snapshotrecord->backingStoreBasePtr)+sizeof(struct SnapShotPage)-1));
65   snapshotrecord->backingRecords=( struct BackingPageRecord * )MYMALLOC(sizeof(struct BackingPageRecord)*numbackingpages);
66   snapshotrecord->snapShots= ( struct SnapShotRecord * )MYMALLOC(sizeof(struct SnapShotRecord)*numsnapshots);
67   snapshotrecord->lastSnapShot=0;
68   snapshotrecord->lastBackingPage=0;
69   snapshotrecord->lastRegion=0;
70   snapshotrecord->maxRegions=nummemoryregions;
71   snapshotrecord->maxBackingPages=numbackingpages;
72   snapshotrecord->maxSnapShots=numsnapshots;
73 }
74 #endif //nothing to initialize for the fork based snapshotting.
75
76 void HandlePF( int sig, siginfo_t *si, void * unused){
77 #if USE_CHECKPOINTING
78   if( si->si_code == SEGV_MAPERR ){
79     printf("Real Fault at %llx\n", ( long long )si->si_addr);
80     exit( EXIT_FAILURE );       
81   }
82   void* addr = ReturnPageAlignedAddress(si->si_addr);
83   unsigned int backingpage=snapshotrecord->lastBackingPage++; //Could run out of pages...
84   if (backingpage==snapshotrecord->maxBackingPages) {
85     printf("Out of backing pages at %llx\n", ( long long )si->si_addr);
86     exit( EXIT_FAILURE );       
87   }
88
89   //copy page
90   memcpy(&(snapshotrecord->backingStore[backingpage]), addr, sizeof(struct SnapShotPage));
91   //remember where to copy page back to
92   snapshotrecord->backingRecords[backingpage].basePtrOfPage=addr;
93   //set protection to read/write
94   mprotect( addr, sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE );  
95 #endif //nothing to handle for non snapshotting case.
96 }
97
98 //Return a page aligned address for the address being added
99 //as a side effect the numBytes are also changed.
100 void * ReturnPageAlignedAddress(void * addr) {
101   return (void *)(((uintptr_t)addr)&~(PAGESIZE-1));
102 }
103 #ifdef __cplusplus
104 extern "C" {
105 #endif
106 void createSharedLibrary(){
107 #if !USE_CHECKPOINTING
108           //step 1. create shared memory.
109   if( sTheRecord ) return;
110   int fd = shm_open( "/ModelChecker-Snapshotter", O_RDWR | O_CREAT, 0777 ); //universal permissions.
111   if( -1 == fd ) FAILURE("shm_open");
112   if( -1 == ftruncate( fd, ( size_t )SHARED_MEMORY_DEFAULT + ( size_t )STACK_SIZE_DEFAULT ) ) FAILURE( "ftruncate" );
113   char * memMapBase = ( char * ) mmap( 0, ( size_t )SHARED_MEMORY_DEFAULT + ( size_t )STACK_SIZE_DEFAULT, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 );
114   if( MAP_FAILED == memMapBase ) FAILURE("mmap");
115   sTheRecord = ( struct Snapshot_t * )memMapBase;
116   sTheRecord->mSharedMemoryBase = memMapBase + sizeof( struct Snapshot_t );
117   sTheRecord->mStackBase = ( char * )memMapBase + ( size_t )SHARED_MEMORY_DEFAULT;
118   sTheRecord->mStackSize = STACK_SIZE_DEFAULT;
119   sTheRecord->mIDToRollback = -1;
120   sTheRecord->currSnapShotID = 0;
121 #endif
122 }
123 #ifdef __cplusplus
124 }
125 #endif
126 void initSnapShotLibrary(unsigned int numbackingpages, unsigned int numsnapshots, unsigned int nummemoryregions , MyFuncPtr entryPoint){
127 #if USE_CHECKPOINTING
128   struct sigaction sa;
129   sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART;
130   sigemptyset( &sa.sa_mask );
131   sa.sa_sigaction = HandlePF;
132   if( sigaction( SIGSEGV, &sa, NULL ) == -1 ){
133     printf("SIGACTION CANNOT BE INSTALLED\n");
134     exit(-1);
135   }
136   initSnapShotRecord(numbackingpages, numsnapshots, nummemoryregions);
137   entryPoint();
138 #else
139   //add a signal to indicate that the process is going to terminate.
140   struct sigaction sa;
141   sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART;
142   sigemptyset( &sa.sa_mask );
143   sa.sa_sigaction = HandlePF;
144   if( sigaction( SIGUSR1, &sa, NULL ) == -1 ){
145     printf("SIGACTION CANNOT BE INSTALLED\n");
146     exit(-1);
147   }
148   createSharedLibrary();
149  #if DEBUG
150   starttime = &(sTheRecord->startTimeGlobal);
151   gettimeofday( starttime, NULL );
152 #endif
153   //step 2 setup the stack context.
154  
155   int alreadySwapped = 0;
156   getcontext( &savedSnapshotContext );
157   if( !alreadySwapped ){
158     alreadySwapped = 1;
159     ucontext_t currentContext, swappedContext, newContext;
160     getcontext( &newContext );
161     newContext.uc_stack.ss_sp = sTheRecord->mStackBase;
162     newContext.uc_stack.ss_size = STACK_SIZE_DEFAULT;
163     newContext.uc_link = &currentContext;
164     makecontext( &newContext, entryPoint, 0 );
165     swapcontext( &swappedContext, &newContext );
166   }
167   
168    //add the code to take a snapshot here...
169         //to return to user process, do a second swapcontext...
170   pid_t forkedID = 0;
171   snapshotid = sTheRecord->currSnapShotID;
172   bool swapContext = false;
173   while( !sTheRecord->mbFinalize ){
174     sTheRecord->currSnapShotID=snapshotid+1;
175     forkedID = fork();
176     if( 0 == forkedID ){ 
177       ucontext_t currentContext;
178 #if 0
179       int dbg = 0;
180       while( !dbg );
181 #endif
182       if( swapContext )
183         swapcontext( &currentContext, &( sTheRecord->mContextToRollback ) );
184                         else{
185                                 swapcontext( &currentContext, &savedUserSnapshotContext );      
186                         }
187     } else {
188       int status;
189       int retVal;
190 #if DEBUG
191       char mesg[ 1024 ] = { 0 };
192       sprintf( mesg, "The process id of child is %d and the process id of this process is %d and snapshot id is %d", forkedID, getpid(), snapshotid );
193       DumpIntoLog( "ModelSnapshot", mesg );
194 #endif
195       do { 
196                                 retVal=waitpid( forkedID, &status, 0 );
197       } while( -1 == retVal && errno == EINTR );
198
199       if( sTheRecord->mIDToRollback != snapshotid )
200                           exit(0);
201       else{
202          swapContext = true;
203       }
204     }
205   }
206   
207 #endif
208 }
209 /* This function assumes that addr is page aligned */
210 void addMemoryRegionToSnapShot( void * addr, unsigned int numPages) {
211 #if USE_CHECKPOINTING
212   unsigned int memoryregion=snapshotrecord->lastRegion++;
213   if (memoryregion==snapshotrecord->maxRegions) {
214     printf("Exceeded supported number of memory regions!\n");
215     exit(-1);
216   }
217   
218   snapshotrecord->regionsToSnapShot[ memoryregion ].basePtr=addr;
219   snapshotrecord->regionsToSnapShot[ memoryregion ].sizeInPages=numPages;
220 #endif //NOT REQUIRED IN THE CASE OF FORK BASED SNAPSHOTS.
221 }
222 //take snapshot
223 snapshot_id takeSnapshot( ){
224 #if USE_CHECKPOINTING
225   for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
226     if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ ) == -1 ){
227       printf("Failed to mprotect inside of takeSnapShot\n");
228       exit(-1);
229     }           
230   }
231   unsigned int snapshot=snapshotrecord->lastSnapShot++;
232   if (snapshot==snapshotrecord->maxSnapShots) {
233     printf("Out of snapshots\n");
234     exit(-1);
235   }
236   snapshotrecord->snapShots[snapshot].firstBackingPage=snapshotrecord->lastBackingPage;
237   
238   return snapshot;
239 #else
240   swapcontext( &savedUserSnapshotContext, &savedSnapshotContext );
241   return snapshotid;
242 #endif
243 }
244 void rollBack( snapshot_id theID ){
245 #if USE_CHECKPOINTING
246   std::map< void *, bool, std::less< void * >, MyAlloc< std::pair< const void *, bool > > > duplicateMap;
247   for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
248   if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE ) == -1 ){
249       printf("Failed to mprotect inside of takeSnapShot\n");
250       exit(-1);
251     }           
252   }
253   for(unsigned int page=snapshotrecord->snapShots[theID].firstBackingPage; page<snapshotrecord->lastBackingPage; page++) {
254     bool oldVal = false;
255     if( duplicateMap.find( snapshotrecord->backingRecords[page].basePtrOfPage ) != duplicateMap.end() ){
256       oldVal = true;          
257     }
258     else{
259       duplicateMap[ snapshotrecord->backingRecords[page].basePtrOfPage ] = true;    
260     }
261     if(  !oldVal ){
262       memcpy(snapshotrecord->backingRecords[page].basePtrOfPage, &snapshotrecord->backingStore[page], sizeof(struct SnapShotPage));
263     }
264   }
265   snapshotrecord->lastSnapShot=theID;
266   snapshotrecord->lastBackingPage=snapshotrecord->snapShots[theID].firstBackingPage;
267   takeSnapshot(); //Make sure current snapshot is still good...All later ones are cleared
268 #else
269   sTheRecord->mIDToRollback = theID;
270   int sTemp = 0;
271   getcontext( &sTheRecord->mContextToRollback );
272   if( !sTemp ){
273     sTemp = 1;
274 #if DEBUG
275         DumpIntoLog( "ModelSnapshot", "Invoked rollback" ); 
276 #endif
277         exit( 0 );
278   }
279 #endif
280 }
281
282 void finalize(){
283 #if !USE_CHECKPOINTING
284   sTheRecord->mbFinalize = true;
285 #endif
286 }
287