11 #include "snapshotimp.h"
16 #include <semaphore.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 ); }
24 struct SnapShot * snapshotrecord = NULL;
25 struct Snapshot_t * sTheRecord = NULL;
27 struct Snapshot_t * sTheRecord = NULL;
29 void BeginOperation( struct timeval * theStartTime ){
31 gettimeofday( theStartTime, NULL );
35 struct timeval *starttime = NULL;
37 void DumpIntoLog( const char * filename, const char * message ){
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 );
52 #if !USE_CHECKPOINTING
53 static ucontext_t savedSnapshotContext;
54 static ucontext_t savedUserSnapshotContext;
55 static int snapshotid = 0;
57 /* Initialize snapshot data structure */
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 * )PageAlignAddressUpward(snapshotrecord->backingStoreBasePtr);
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;
74 #endif //nothing to initialize for the fork based snapshotting.
76 void HandlePF( int sig, siginfo_t *si, void * unused){
78 if( si->si_code == SEGV_MAPERR ){
79 printf("Real Fault at %p\n", si->si_addr);
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 %p\n", si->si_addr);
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 if (mprotect( addr, sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE )) {
96 // Handle error by quitting?
98 #endif //nothing to handle for non snapshotting case.
101 //Return a page aligned address for the address being added
102 //as a side effect the numBytes are also changed.
103 void * ReturnPageAlignedAddress(void * addr) {
104 return (void *)(((uintptr_t)addr)&~(PAGESIZE-1));
107 //Return a page aligned address for the address being added
108 //as a side effect the numBytes are also changed.
109 void * PageAlignAddressUpward(void * addr) {
110 return (void *)((((uintptr_t)addr)+PAGESIZE-1)&~(PAGESIZE-1));
115 void createSharedLibrary(){
116 #if !USE_CHECKPOINTING
117 //step 1. create shared memory.
118 if( sTheRecord ) return;
119 int fd = shm_open( "/ModelChecker-Snapshotter", O_RDWR | O_CREAT, 0777 ); //universal permissions.
120 if( -1 == fd ) FAILURE("shm_open");
121 if( -1 == ftruncate( fd, ( size_t )SHARED_MEMORY_DEFAULT + ( size_t )STACK_SIZE_DEFAULT ) ) FAILURE( "ftruncate" );
122 char * memMapBase = ( char * ) mmap( 0, ( size_t )SHARED_MEMORY_DEFAULT + ( size_t )STACK_SIZE_DEFAULT, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 );
123 if( MAP_FAILED == memMapBase ) FAILURE("mmap");
124 sTheRecord = ( struct Snapshot_t * )memMapBase;
125 sTheRecord->mSharedMemoryBase = memMapBase + sizeof( struct Snapshot_t );
126 sTheRecord->mStackBase = ( char * )memMapBase + ( size_t )SHARED_MEMORY_DEFAULT;
127 sTheRecord->mStackSize = STACK_SIZE_DEFAULT;
128 sTheRecord->mIDToRollback = -1;
129 sTheRecord->currSnapShotID = 0;
135 void initSnapShotLibrary(unsigned int numbackingpages, unsigned int numsnapshots, unsigned int nummemoryregions, unsigned int numheappages, MyFuncPtr entryPoint){
136 #if USE_CHECKPOINTING
137 /* Setup a stack for our signal handler.... */
139 ss.ss_sp = MYMALLOC(SIGSTACKSIZE);
140 ss.ss_size = SIGSTACKSIZE;
142 sigaltstack(&ss, NULL);
145 sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK;
146 sigemptyset( &sa.sa_mask );
147 sa.sa_sigaction = HandlePF;
148 if( sigaction( SIGSEGV, &sa, NULL ) == -1 ){
149 printf("SIGACTION CANNOT BE INSTALLED\n");
152 initSnapShotRecord(numbackingpages, numsnapshots, nummemoryregions);
154 basemySpace=MYMALLOC((numheappages+1)*PAGESIZE);
155 void * pagealignedbase=PageAlignAddressUpward(basemySpace);
156 mySpace = create_mspace_with_base(pagealignedbase, numheappages*PAGESIZE, 1 );
157 addMemoryRegionToSnapShot(pagealignedbase, numheappages);
160 //add a signal to indicate that the process is going to terminate.
162 sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART;
163 sigemptyset( &sa.sa_mask );
164 sa.sa_sigaction = HandlePF;
165 if( sigaction( SIGUSR1, &sa, NULL ) == -1 ){
166 printf("SIGACTION CANNOT BE INSTALLED\n");
169 createSharedLibrary();
171 starttime = &(sTheRecord->startTimeGlobal);
172 gettimeofday( starttime, NULL );
174 //step 2 setup the stack context.
176 int alreadySwapped = 0;
177 getcontext( &savedSnapshotContext );
178 if( !alreadySwapped ){
180 ucontext_t currentContext, swappedContext, newContext;
181 getcontext( &newContext );
182 newContext.uc_stack.ss_sp = sTheRecord->mStackBase;
183 newContext.uc_stack.ss_size = STACK_SIZE_DEFAULT;
184 newContext.uc_link = ¤tContext;
185 makecontext( &newContext, entryPoint, 0 );
186 swapcontext( &swappedContext, &newContext );
189 //add the code to take a snapshot here...
190 //to return to user process, do a second swapcontext...
192 snapshotid = sTheRecord->currSnapShotID;
193 bool swapContext = false;
194 while( !sTheRecord->mbFinalize ){
195 sTheRecord->currSnapShotID=snapshotid+1;
198 ucontext_t currentContext;
204 swapcontext( ¤tContext, &( sTheRecord->mContextToRollback ) );
206 swapcontext( ¤tContext, &savedUserSnapshotContext );
212 char mesg[ 1024 ] = { 0 };
213 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 );
214 DumpIntoLog( "ModelSnapshot", mesg );
217 retVal=waitpid( forkedID, &status, 0 );
218 } while( -1 == retVal && errno == EINTR );
220 if( sTheRecord->mIDToRollback != snapshotid )
230 /* This function assumes that addr is page aligned */
231 void addMemoryRegionToSnapShot( void * addr, unsigned int numPages) {
232 #if USE_CHECKPOINTING
233 unsigned int memoryregion=snapshotrecord->lastRegion++;
234 if (memoryregion==snapshotrecord->maxRegions) {
235 printf("Exceeded supported number of memory regions!\n");
239 snapshotrecord->regionsToSnapShot[ memoryregion ].basePtr=addr;
240 snapshotrecord->regionsToSnapShot[ memoryregion ].sizeInPages=numPages;
241 #endif //NOT REQUIRED IN THE CASE OF FORK BASED SNAPSHOTS.
244 snapshot_id takeSnapshot( ){
245 #if USE_CHECKPOINTING
246 for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
247 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ ) == -1 ){
249 printf("Failed to mprotect inside of takeSnapShot\n");
253 unsigned int snapshot=snapshotrecord->lastSnapShot++;
254 if (snapshot==snapshotrecord->maxSnapShots) {
255 printf("Out of snapshots\n");
258 snapshotrecord->snapShots[snapshot].firstBackingPage=snapshotrecord->lastBackingPage;
262 swapcontext( &savedUserSnapshotContext, &savedSnapshotContext );
266 void rollBack( snapshot_id theID ){
267 #if USE_CHECKPOINTING
268 std::map< void *, bool, std::less< void * >, MyAlloc< std::pair< const void *, bool > > > duplicateMap;
269 for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
270 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE ) == -1 ){
272 printf("Failed to mprotect inside of takeSnapShot\n");
276 for(unsigned int page=snapshotrecord->snapShots[theID].firstBackingPage; page<snapshotrecord->lastBackingPage; page++) {
278 if( duplicateMap.find( snapshotrecord->backingRecords[page].basePtrOfPage ) != duplicateMap.end() ){
282 duplicateMap[ snapshotrecord->backingRecords[page].basePtrOfPage ] = true;
285 memcpy(snapshotrecord->backingRecords[page].basePtrOfPage, &snapshotrecord->backingStore[page], sizeof(struct SnapShotPage));
288 snapshotrecord->lastSnapShot=theID;
289 snapshotrecord->lastBackingPage=snapshotrecord->snapShots[theID].firstBackingPage;
290 takeSnapshot(); //Make sure current snapshot is still good...All later ones are cleared
292 sTheRecord->mIDToRollback = theID;
294 getcontext( &sTheRecord->mContextToRollback );
298 DumpIntoLog( "ModelSnapshot", "Invoked rollback" );
306 #if !USE_CHECKPOINTING
307 sTheRecord->mbFinalize = true;