1 /* -*- Mode: C; indent-tabs-mode: t -*- */
12 #include "snapshotimp.h"
17 #include <semaphore.h>
22 //extern declaration definition
23 #define FAILURE(mesg) { printf("failed in the API: %s with errno relative message: %s\n", mesg, strerror( errno ) ); exit( -1 ); }
25 struct SnapShot * snapshotrecord = NULL;
26 struct Snapshot_t * sTheRecord = NULL;
28 struct Snapshot_t * sTheRecord = NULL;
30 void BeginOperation( struct timeval * theStartTime ){
32 gettimeofday( theStartTime, NULL );
36 struct timeval *starttime = NULL;
38 void DumpIntoLog( const char * filename, const char * message ){
40 static pid_t thePID = getpid();
41 char newFn[ 1024 ] ={ 0 };
42 sprintf( newFn,"%s-%d.txt", filename, thePID );
43 FILE * myFile = fopen( newFn, "w+" );
44 struct timeval theEndTime;
45 BeginOperation( &theEndTime );
46 double elapsed = ( theEndTime.tv_sec - starttime->tv_sec ) + ( theEndTime.tv_usec - starttime->tv_usec ) / 1000000.0;
47 fprintf( myFile, "The timestamp %f:--> the message %s: the process id %d\n", elapsed, message, thePID );
53 #if !USE_CHECKPOINTING
54 static ucontext_t savedSnapshotContext;
55 static ucontext_t savedUserSnapshotContext;
56 static int snapshotid = 0;
58 /* Initialize snapshot data structure */
60 void initSnapShotRecord(unsigned int numbackingpages, unsigned int numsnapshots, unsigned int nummemoryregions) {
61 snapshotrecord=( struct SnapShot * )MYMALLOC(sizeof(struct SnapShot));
62 snapshotrecord->regionsToSnapShot=( struct MemoryRegion * )MYMALLOC(sizeof(struct MemoryRegion)*nummemoryregions);
63 snapshotrecord->backingStoreBasePtr= ( struct SnapShotPage * )MYMALLOC( sizeof( struct SnapShotPage ) * (numbackingpages + 1) );
64 //Page align the backingstorepages
65 snapshotrecord->backingStore=( struct SnapShotPage * )ReturnPageAlignedAddress((void*) ((uintptr_t)(snapshotrecord->backingStoreBasePtr)+sizeof(struct SnapShotPage)-1));
66 snapshotrecord->backingRecords=( struct BackingPageRecord * )MYMALLOC(sizeof(struct BackingPageRecord)*numbackingpages);
67 snapshotrecord->snapShots= ( struct SnapShotRecord * )MYMALLOC(sizeof(struct SnapShotRecord)*numsnapshots);
68 snapshotrecord->lastSnapShot=0;
69 snapshotrecord->lastBackingPage=0;
70 snapshotrecord->lastRegion=0;
71 snapshotrecord->maxRegions=nummemoryregions;
72 snapshotrecord->maxBackingPages=numbackingpages;
73 snapshotrecord->maxSnapShots=numsnapshots;
75 #endif //nothing to initialize for the fork based snapshotting.
77 void HandlePF( int sig, siginfo_t *si, void * unused){
79 if( si->si_code == SEGV_MAPERR ){
80 printf("Real Fault at %llx\n", ( long long )si->si_addr);
83 void* addr = ReturnPageAlignedAddress(si->si_addr);
84 unsigned int backingpage=snapshotrecord->lastBackingPage++; //Could run out of pages...
85 if (backingpage==snapshotrecord->maxBackingPages) {
86 printf("Out of backing pages at %llx\n", ( long long )si->si_addr);
91 memcpy(&(snapshotrecord->backingStore[backingpage]), addr, sizeof(struct SnapShotPage));
92 //remember where to copy page back to
93 snapshotrecord->backingRecords[backingpage].basePtrOfPage=addr;
94 //set protection to read/write
95 mprotect( addr, sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE );
96 #endif //nothing to handle for non snapshotting case.
99 //Return a page aligned address for the address being added
100 //as a side effect the numBytes are also changed.
101 void * ReturnPageAlignedAddress(void * addr) {
102 return (void *)(((uintptr_t)addr)&~(PAGESIZE-1));
107 void createSharedLibrary(){
108 #if !USE_CHECKPOINTING
109 //step 1. create shared memory.
110 if( sTheRecord ) return;
111 int fd = shm_open( "/ModelChecker-Snapshotter", O_RDWR | O_CREAT, 0777 ); //universal permissions.
112 if( -1 == fd ) FAILURE("shm_open");
113 if( -1 == ftruncate( fd, ( size_t )SHARED_MEMORY_DEFAULT + ( size_t )STACK_SIZE_DEFAULT ) ) FAILURE( "ftruncate" );
114 char * memMapBase = ( char * ) mmap( 0, ( size_t )SHARED_MEMORY_DEFAULT + ( size_t )STACK_SIZE_DEFAULT, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 );
115 if( MAP_FAILED == memMapBase ) FAILURE("mmap");
116 sTheRecord = ( struct Snapshot_t * )memMapBase;
117 sTheRecord->mSharedMemoryBase = memMapBase + sizeof( struct Snapshot_t );
118 sTheRecord->mStackBase = ( char * )memMapBase + ( size_t )SHARED_MEMORY_DEFAULT;
119 sTheRecord->mStackSize = STACK_SIZE_DEFAULT;
120 sTheRecord->mIDToRollback = -1;
121 sTheRecord->currSnapShotID = 0;
127 void initSnapShotLibrary(unsigned int numbackingpages, unsigned int numsnapshots, unsigned int nummemoryregions, unsigned int numheappages, MyFuncPtr entryPoint){
128 #if USE_CHECKPOINTING
130 sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART;
131 sigemptyset( &sa.sa_mask );
132 sa.sa_sigaction = HandlePF;
133 if( sigaction( SIGSEGV, &sa, NULL ) == -1 ){
134 printf("SIGACTION CANNOT BE INSTALLED\n");
137 initSnapShotRecord(numbackingpages, numsnapshots, nummemoryregions);
138 mySpace = create_mspace( numheappages*PAGESIZE, 1 );
139 addMemoryRegionToSnapShot(mySpace, numheappages);
142 //add a signal to indicate that the process is going to terminate.
144 sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART;
145 sigemptyset( &sa.sa_mask );
146 sa.sa_sigaction = HandlePF;
147 if( sigaction( SIGUSR1, &sa, NULL ) == -1 ){
148 printf("SIGACTION CANNOT BE INSTALLED\n");
151 createSharedLibrary();
153 starttime = &(sTheRecord->startTimeGlobal);
154 gettimeofday( starttime, NULL );
156 //step 2 setup the stack context.
158 int alreadySwapped = 0;
159 getcontext( &savedSnapshotContext );
160 if( !alreadySwapped ){
162 ucontext_t currentContext, swappedContext, newContext;
163 getcontext( &newContext );
164 newContext.uc_stack.ss_sp = sTheRecord->mStackBase;
165 newContext.uc_stack.ss_size = STACK_SIZE_DEFAULT;
166 newContext.uc_link = ¤tContext;
167 makecontext( &newContext, entryPoint, 0 );
168 swapcontext( &swappedContext, &newContext );
171 //add the code to take a snapshot here...
172 //to return to user process, do a second swapcontext...
174 snapshotid = sTheRecord->currSnapShotID;
175 bool swapContext = false;
176 while( !sTheRecord->mbFinalize ){
177 sTheRecord->currSnapShotID=snapshotid+1;
180 ucontext_t currentContext;
186 swapcontext( ¤tContext, &( sTheRecord->mContextToRollback ) );
188 swapcontext( ¤tContext, &savedUserSnapshotContext );
194 char mesg[ 1024 ] = { 0 };
195 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 );
196 DumpIntoLog( "ModelSnapshot", mesg );
199 retVal=waitpid( forkedID, &status, 0 );
200 } while( -1 == retVal && errno == EINTR );
202 if( sTheRecord->mIDToRollback != snapshotid )
212 /* This function assumes that addr is page aligned */
213 void addMemoryRegionToSnapShot( void * addr, unsigned int numPages) {
214 #if USE_CHECKPOINTING
215 unsigned int memoryregion=snapshotrecord->lastRegion++;
216 if (memoryregion==snapshotrecord->maxRegions) {
217 printf("Exceeded supported number of memory regions!\n");
221 snapshotrecord->regionsToSnapShot[ memoryregion ].basePtr=addr;
222 snapshotrecord->regionsToSnapShot[ memoryregion ].sizeInPages=numPages;
223 #endif //NOT REQUIRED IN THE CASE OF FORK BASED SNAPSHOTS.
226 snapshot_id takeSnapshot( ){
227 #if USE_CHECKPOINTING
228 for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
229 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ ) == -1 ){
230 printf("Failed to mprotect inside of takeSnapShot\n");
234 unsigned int snapshot=snapshotrecord->lastSnapShot++;
235 if (snapshot==snapshotrecord->maxSnapShots) {
236 printf("Out of snapshots\n");
239 snapshotrecord->snapShots[snapshot].firstBackingPage=snapshotrecord->lastBackingPage;
243 swapcontext( &savedUserSnapshotContext, &savedSnapshotContext );
247 void rollBack( snapshot_id theID ){
248 #if USE_CHECKPOINTING
249 std::map< void *, bool, std::less< void * >, MyAlloc< std::pair< const void *, bool > > > duplicateMap;
250 for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
251 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE ) == -1 ){
252 printf("Failed to mprotect inside of takeSnapShot\n");
256 for(unsigned int page=snapshotrecord->snapShots[theID].firstBackingPage; page<snapshotrecord->lastBackingPage; page++) {
258 if( duplicateMap.find( snapshotrecord->backingRecords[page].basePtrOfPage ) != duplicateMap.end() ){
262 duplicateMap[ snapshotrecord->backingRecords[page].basePtrOfPage ] = true;
265 memcpy(snapshotrecord->backingRecords[page].basePtrOfPage, &snapshotrecord->backingStore[page], sizeof(struct SnapShotPage));
268 snapshotrecord->lastSnapShot=theID;
269 snapshotrecord->lastBackingPage=snapshotrecord->snapShots[theID].firstBackingPage;
270 takeSnapshot(); //Make sure current snapshot is still good...All later ones are cleared
272 sTheRecord->mIDToRollback = theID;
274 getcontext( &sTheRecord->mContextToRollback );
278 DumpIntoLog( "ModelSnapshot", "Invoked rollback" );
286 #if !USE_CHECKPOINTING
287 sTheRecord->mbFinalize = true;