Changes to increase garbage collector heap
[IRC.git] / Robust / src / Runtime / DSTM / interface / trans.c
1 #include "dstm.h"
2 #include "ip.h"
3 #include "machinepile.h"
4 #include "mlookup.h"
5 #include "llookup.h"
6 #include "plookup.h"
7 #include "prelookup.h"
8 #include "threadnotify.h"
9 #include "queue.h"
10 #include "addUdpEnhance.h"
11 #include "addPrefetchEnhance.h"
12 #include "gCollect.h"
13 #include "dsmlock.h"
14 #ifdef COMPILER
15 #include "thread.h"
16 #endif
17
18 #define NUM_THREADS 1
19 #define PREFETCH_CACHE_SIZE 1048576 //1MB
20 #define CONFIG_FILENAME "dstm.conf"
21
22
23 /* Global Variables */
24 extern int classsize[];
25 pfcstats_t *evalPrefetch;
26 extern int numprefetchsites; //Global variable containing number of prefetch sites
27 extern pthread_mutex_t mainobjstore_mutex; // Mutex to lock main Object store
28 objstr_t *prefetchcache; //Global Prefetch cache
29 pthread_mutex_t prefetchcache_mutex; // Mutex to lock Prefetch Cache
30 pthread_mutexattr_t prefetchcache_mutex_attr; /* Attribute for lock to make it a recursive lock */
31 extern prehashtable_t pflookup; //Global Prefetch cache's lookup table
32 pthread_t wthreads[NUM_THREADS]; //Worker threads for working on the prefetch queue
33 pthread_t tPrefetch;            /* Primary Prefetch thread that processes the prefetch queue */
34 extern objstr_t *mainobjstore;
35 unsigned int myIpAddr;
36 unsigned int *hostIpAddrs;
37 int sizeOfHostArray;
38 int numHostsInSystem;
39 int myIndexInHostArray;
40 unsigned int oidsPerBlock;
41 unsigned int oidMin;
42 unsigned int oidMax;
43
44 sockPoolHashTable_t *transReadSockPool;
45 sockPoolHashTable_t *transPrefetchSockPool;
46 sockPoolHashTable_t *transRequestSockPool;
47 pthread_mutex_t notifymutex;
48 pthread_mutex_t atomicObjLock;
49
50 /***********************************
51  * Global Variables for statistics
52  **********************************/
53 int numTransCommit = 0;
54 int numTransAbort = 0;
55 int nchashSearch = 0;
56 int nmhashSearch = 0;
57 int nprehashSearch = 0;
58 int nRemoteSend = 0;
59 int nSoftAbort = 0;
60
61 void printhex(unsigned char *, int);
62 plistnode_t *createPiles(transrecord_t *);
63 plistnode_t *sortPiles(plistnode_t *pileptr);
64
65 /*******************************
66 * Send and Recv function calls
67 *******************************/
68 void send_data(int fd, void *buf, int buflen) {
69   char *buffer = (char *)(buf);
70   int size = buflen;
71   int numbytes;
72   while (size > 0) {
73     numbytes = send(fd, buffer, size, MSG_NOSIGNAL);
74     if (numbytes == -1) {
75       perror("send");
76       exit(0);
77     }
78     buffer += numbytes;
79     size -= numbytes;
80   }
81 }
82
83 void recv_data(int fd, void *buf, int buflen) {
84   char *buffer = (char *)(buf);
85   int size = buflen;
86   int numbytes;
87   while (size > 0) {
88     numbytes = recv(fd, buffer, size, 0);
89     if (numbytes == -1) {
90       perror("recv");
91       exit(0);
92     }
93     buffer += numbytes;
94     size -= numbytes;
95   }
96 }
97
98 int recv_data_errorcode(int fd, void *buf, int buflen) {
99   char *buffer = (char *)(buf);
100   int size = buflen;
101   int numbytes;
102   while (size > 0) {
103     numbytes = recv(fd, buffer, size, 0);
104     if (numbytes==0)
105       return 0;
106     if (numbytes == -1) {
107       perror("recv");
108       return -1;
109     }
110     buffer += numbytes;
111     size -= numbytes;
112   }
113   return 1;
114 }
115
116 void printhex(unsigned char *ptr, int numBytes) {
117   int i;
118   for (i = 0; i < numBytes; i++) {
119     if (ptr[i] < 16)
120       printf("0%x ", ptr[i]);
121     else
122       printf("%x ", ptr[i]);
123   }
124   printf("\n");
125   return;
126 }
127
128 inline int arrayLength(int *array) {
129   int i;
130   for(i=0 ; array[i] != -1; i++)
131     ;
132   return i;
133 }
134
135 inline int findmax(int *array, int arraylength) {
136   int max, i;
137   max = array[0];
138   for(i = 0; i < arraylength; i++) {
139     if(array[i] > max) {
140       max = array[i];
141     }
142   }
143   return max;
144 }
145
146 /* This function is a prefetch call generated by the compiler that
147  * populates the shared primary prefetch queue*/
148 void prefetch(int siteid, int ntuples, unsigned int *oids, unsigned short *endoffsets, short *arrayfields) {
149   /* Allocate for the queue node*/
150   int qnodesize = 2*sizeof(int) + ntuples * (sizeof(unsigned short) + sizeof(unsigned int)) + endoffsets[ntuples - 1] * sizeof(short);
151   int len;
152   char * node= getmemory(qnodesize);
153   int top=endoffsets[ntuples-1];
154
155   if (node==NULL)
156     return;
157   /* Set queue node values */
158
159   /* TODO: Remove this after testing */
160   evalPrefetch[siteid].callcount++;
161
162   *((int *)(node))=siteid;
163   *((int *)(node + sizeof(int))) = ntuples;
164   len = 2*sizeof(int);
165   memcpy(node+len, oids, ntuples*sizeof(unsigned int));
166   memcpy(node+len+ntuples*sizeof(unsigned int), endoffsets, ntuples*sizeof(unsigned short));
167   memcpy(node+len+ntuples*(sizeof(unsigned int)+sizeof(short)), arrayfields, top*sizeof(short));
168
169   /* Lock and insert into primary prefetch queue */
170   movehead(qnodesize);
171 }
172
173 /* This function starts up the transaction runtime. */
174 int dstmStartup(const char * option) {
175   pthread_t thread_Listen, udp_thread_Listen;
176   pthread_attr_t attr;
177   int master=option!=NULL && strcmp(option, "master")==0;
178   int fd;
179   int udpfd;
180
181   if (processConfigFile() != 0)
182     return 0; //TODO: return error value, cause main program to exit
183 #ifdef COMPILER
184   if (!master)
185     threadcount--;
186 #endif
187
188 #ifdef TRANSSTATS
189   printf("Trans stats is on\n");
190   fflush(stdout);
191 #endif
192
193   //Initialize socket pool
194   transReadSockPool = createSockPool(transReadSockPool, DEFAULTSOCKPOOLSIZE);
195   transPrefetchSockPool = createSockPool(transPrefetchSockPool, DEFAULTSOCKPOOLSIZE);
196   transRequestSockPool = createSockPool(transRequestSockPool, DEFAULTSOCKPOOLSIZE);
197
198   dstmInit();
199   transInit();
200
201   fd=startlistening();
202   pthread_attr_init(&attr);
203   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
204 #ifdef CACHE
205   udpfd = udpInit();
206   pthread_create(&udp_thread_Listen, &attr, udpListenBroadcast, (void*)udpfd);
207 #endif
208   if (master) {
209     pthread_create(&thread_Listen, &attr, dstmListen, (void*)fd);
210     return 1;
211   } else {
212     dstmListen((void *)fd);
213     return 0;
214   }
215 }
216
217 //TODO Use this later
218 void *pCacheAlloc(objstr_t *store, unsigned int size) {
219   void *tmp;
220   objstr_t *ptr;
221   ptr = store;
222   int success = 0;
223
224   while(ptr->next != NULL) {
225     /* check if store is empty */
226     if(((unsigned int)ptr->top - (unsigned int)ptr - sizeof(objstr_t) + size) <= ptr->size) {
227       tmp = ptr->top;
228       ptr->top += size;
229       success = 1;
230       return tmp;
231     } else {
232       ptr = ptr->next;
233     }
234   }
235
236   if(success == 0) {
237     return NULL;
238   }
239 }
240
241 /* This function initiates the prefetch thread A queue is shared
242  * between the main thread of execution and the prefetch thread to
243  * process the prefetch call Call from compiler populates the shared
244  * queue with prefetch requests while prefetch thread processes the
245  * prefetch requests */
246
247 void transInit() {
248   //Create and initialize prefetch cache structure
249 #ifdef CACHE
250   prefetchcache = objstrCreate(PREFETCH_CACHE_SIZE);
251   initializePCache();
252   if((evalPrefetch = initPrefetchStats()) == NULL) {
253     printf("%s() Error allocating memory at %s, %d\n", __func__, __FILE__, __LINE__);
254     exit(0);
255   }
256 #endif
257
258   /* Initialize attributes for mutex */
259   pthread_mutexattr_init(&prefetchcache_mutex_attr);
260   pthread_mutexattr_settype(&prefetchcache_mutex_attr, PTHREAD_MUTEX_RECURSIVE_NP);
261
262   pthread_mutex_init(&prefetchcache_mutex, &prefetchcache_mutex_attr);
263   pthread_mutex_init(&notifymutex, NULL);
264   pthread_mutex_init(&atomicObjLock, NULL);
265 #ifdef CACHE
266   //Create prefetch cache lookup table
267   if(prehashCreate(HASH_SIZE, LOADFACTOR)) {
268     printf("ERROR\n");
269     return; //Failure
270   }
271
272   //Initialize primary shared queue
273   queueInit();
274   //Initialize machine pile w/prefetch oids and offsets shared queue
275   mcpileqInit();
276
277   //Create the primary prefetch thread
278   int retval;
279   do {
280     retval=pthread_create(&tPrefetch, NULL, transPrefetch, NULL);
281   } while(retval!=0);
282   pthread_detach(tPrefetch);
283 #endif
284 }
285
286 /* This function stops the threads spawned */
287 void transExit() {
288 #ifdef CACHE
289   int t;
290   pthread_cancel(tPrefetch);
291   for(t = 0; t < NUM_THREADS; t++)
292     pthread_cancel(wthreads[t]);
293 #endif
294
295   return;
296 }
297
298 /* This functions inserts randowm wait delays in the order of msec
299  * Mostly used when transaction commits retry*/
300 void randomdelay() {
301   struct timespec req;
302   time_t t;
303
304   t = time(NULL);
305   req.tv_sec = 0;
306   req.tv_nsec = (long)(1000 + (t%10000)); //1-11 microsec
307   nanosleep(&req, NULL);
308   return;
309 }
310
311 /* This function initializes things required in the transaction start*/
312 transrecord_t *transStart() {
313   transrecord_t *tmp;
314   if((tmp = calloc(1, sizeof(transrecord_t))) == NULL) {
315     printf("%s() Calloc error at line %d, %s\n", __func__, __LINE__, __FILE__);
316     return NULL;
317   }
318   tmp->cache = objstrCreate(1048576);
319   tmp->lookupTable = chashCreate(CHASH_SIZE, CLOADFACTOR);
320 #ifdef COMPILER
321   tmp->revertlist=NULL;
322 #endif
323   return tmp;
324 }
325
326 /* This function finds the location of the objects involved in a transaction
327  * and returns the pointer to the object if found in a remote location */
328 objheader_t *transRead(transrecord_t *record, unsigned int oid) {
329   unsigned int machinenumber;
330   objheader_t *tmp, *objheader;
331   objheader_t *objcopy;
332   int size;
333   void *buf;
334
335   if(oid == 0) {
336     return NULL;
337   }
338
339   if((objheader = chashSearch(record->lookupTable, oid)) != NULL) {
340 #ifdef TRANSSTATS
341     nchashSearch++;
342 #endif
343     /* Search local transaction cache */
344 #ifdef COMPILER
345     return &objheader[1];
346 #else
347     return objheader;
348 #endif
349   } else if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
350 #ifdef TRANSSTATS
351     nmhashSearch++;
352 #endif
353     /* Look up in machine lookup table  and copy  into cache*/
354     GETSIZE(size, objheader);
355     size += sizeof(objheader_t);
356     objcopy = (objheader_t *) objstrAlloc(record->cache, size);
357     memcpy(objcopy, objheader, size);
358     /* Insert into cache's lookup table */
359     STATUS(objcopy)=0;
360     chashInsert(record->lookupTable, OID(objheader), objcopy);
361 #ifdef COMPILER
362     return &objcopy[1];
363 #else
364     return objcopy;
365 #endif
366   } else {
367 #ifdef CACHE
368     if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) {
369 #ifdef TRANSSTATS
370       nprehashSearch++;
371 #endif
372       /* Look up in prefetch cache */
373       GETSIZE(size, tmp);
374       size+=sizeof(objheader_t);
375       objcopy = (objheader_t *) objstrAlloc(record->cache, size);
376       memcpy(objcopy, tmp, size);
377       /* Insert into cache's lookup table */
378       chashInsert(record->lookupTable, OID(tmp), objcopy);
379 #ifdef COMPILER
380       return &objcopy[1];
381 #else
382       return objcopy;
383 #endif
384     }
385 #endif
386     /* Get the object from the remote location */
387     if((machinenumber = lhashSearch(oid)) == 0) {
388       printf("Error: %s() No machine found for oid =% %s,%dx\n",__func__, machinenumber, __FILE__, __LINE__);
389       return NULL;
390     }
391     objcopy = getRemoteObj(record, machinenumber, oid);
392
393     if(objcopy == NULL) {
394       printf("Error: Object not found in Remote location %s, %d\n", __FILE__, __LINE__);
395       return NULL;
396     } else {
397 #ifdef TRANSSTATS
398       nRemoteSend++;
399 #endif
400       STATUS(objcopy)=0;
401 #ifdef COMPILER
402       return &objcopy[1];
403 #else
404       return objcopy;
405 #endif
406     }
407   }
408 }
409
410 /* This function creates objects in the transaction record */
411 objheader_t *transCreateObj(transrecord_t *record, unsigned int size) {
412   objheader_t *tmp = (objheader_t *) objstrAlloc(record->cache, (sizeof(objheader_t) + size));
413   OID(tmp) = getNewOID();
414   tmp->version = 1;
415   tmp->rcount = 1;
416   STATUS(tmp) = NEW;
417   chashInsert(record->lookupTable, OID(tmp), tmp);
418
419 #ifdef COMPILER
420   return &tmp[1]; //want space after object header
421 #else
422   return tmp;
423 #endif
424 }
425
426 /* This function creates machine piles based on all machines involved in a
427  * transaction commit request */
428 plistnode_t *createPiles(transrecord_t *record) {
429   int i;
430   plistnode_t *pile = NULL;
431   unsigned int machinenum;
432   objheader_t *headeraddr;
433   chashlistnode_t * ptr = record->lookupTable->table;
434   /* Represents number of bins in the chash table */
435   unsigned int size = record->lookupTable->size;
436
437   for(i = 0; i < size ; i++) {
438     chashlistnode_t * curr = &ptr[i];
439     /* Inner loop to traverse the linked list of the cache lookupTable */
440     while(curr != NULL) {
441       //if the first bin in hash table is empty
442       if(curr->key == 0)
443         break;
444
445       if ((headeraddr = (objheader_t *) chashSearch(record->lookupTable, curr->key)) == NULL) {
446         printf("Error: No such oid %s, %d\n", __FILE__, __LINE__);
447         return NULL;
448       }
449
450       //Get machine location for object id (and whether local or not)
451       if (STATUS(headeraddr) & NEW || (mhashSearch(curr->key) != NULL)) {
452         machinenum = myIpAddr;
453       } else if ((machinenum = lhashSearch(curr->key)) == 0) {
454         printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
455         return NULL;
456       }
457
458       //Make machine groups
459       pile = pInsert(pile, headeraddr, machinenum, record->lookupTable->numelements);
460       curr = curr->next;
461     }
462   }
463   return pile;
464 }
465
466 /* This function initiates the transaction commit process
467  * Spawns threads for each of the new connections with Participants
468  * and creates new piles by calling the createPiles(),
469  * Sends a transrequest() to each remote machines for objects found remotely
470  * and calls handleLocalReq() to process objects found locally */
471 int transCommit(transrecord_t *record) {
472   unsigned int tot_bytes_mod, *listmid;
473   plistnode_t *pile, *pile_ptr;
474   int trecvcount;
475   char treplyretry; /* keeps track of the common response that needs to be sent */
476   int firsttime=1;
477   trans_commit_data_t transinfo; /* keeps track of objs locked during transaction */
478   char finalResponse;
479
480   do {
481     trecvcount = 0;
482     treplyretry = 0;
483
484     /* Look through all the objects in the transaction record and make piles
485      * for each machine involved in the transaction*/
486     if (firsttime) {
487       pile_ptr = pile = createPiles(record);
488       pile_ptr = pile = sortPiles(pile);
489     } else {
490       pile = pile_ptr;
491     }
492     firsttime = 0;
493     /* Create the packet to be sent in TRANS_REQUEST */
494
495     /* Count the number of participants */
496     int pilecount;
497     pilecount = pCount(pile);
498
499     /* Create a list of machine ids(Participants) involved in transaction   */
500     listmid = calloc(pilecount, sizeof(unsigned int));
501     pListMid(pile, listmid);
502
503     /* Create a socket and getReplyCtrl array, initialize */
504     int socklist[pilecount];
505     int loopcount;
506     for(loopcount = 0 ; loopcount < pilecount; loopcount++)
507       socklist[loopcount] = 0;
508     char getReplyCtrl[pilecount];
509     for(loopcount = 0 ; loopcount < pilecount; loopcount++)
510       getReplyCtrl[loopcount] = 0;
511
512     /* Process each machine pile */
513     int sockindex = 0;
514     trans_req_data_t *tosend;
515     tosend = calloc(pilecount, sizeof(trans_req_data_t));
516     while(pile != NULL) {
517       tosend[sockindex].f.control = TRANS_REQUEST;
518       tosend[sockindex].f.mcount = pilecount;
519       tosend[sockindex].f.numread = pile->numread;
520       tosend[sockindex].f.nummod = pile->nummod;
521       tosend[sockindex].f.numcreated = pile->numcreated;
522       tosend[sockindex].f.sum_bytes = pile->sum_bytes;
523       tosend[sockindex].listmid = listmid;
524       tosend[sockindex].objread = pile->objread;
525       tosend[sockindex].oidmod = pile->oidmod;
526       tosend[sockindex].oidcreated = pile->oidcreated;
527       int sd = 0;
528       if(pile->mid != myIpAddr) {
529         if((sd = getSock2WithLock(transRequestSockPool, pile->mid)) < 0) {
530           printf("transRequest(): socket create error\n");
531           free(listmid);
532           free(tosend);
533           return 1;
534         }
535         socklist[sockindex] = sd;
536         /* Send bytes of data with TRANS_REQUEST control message */
537         send_data(sd, &(tosend[sockindex].f), sizeof(fixed_data_t));
538
539         /* Send list of machines involved in the transaction */
540         {
541           int size=sizeof(unsigned int)*(tosend[sockindex].f.mcount);
542           send_data(sd, tosend[sockindex].listmid, size);
543         }
544
545         /* Send oids and version number tuples for objects that are read */
546         {
547           int size=(sizeof(unsigned int)+sizeof(unsigned short))*(tosend[sockindex].f.numread);
548           send_data(sd, tosend[sockindex].objread, size);
549         }
550
551         /* Send objects that are modified */
552         void *modptr;
553         if((modptr = calloc(1, tosend[sockindex].f.sum_bytes)) == NULL) {
554           printf("Calloc error for modified objects %s, %d\n", __FILE__, __LINE__);
555           free(listmid);
556           free(tosend);
557           return 1;
558         }
559         int offset = 0;
560         int i;
561         for(i = 0; i < tosend[sockindex].f.nummod ; i++) {
562           int size;
563           objheader_t *headeraddr;
564           if((headeraddr = chashSearch(record->lookupTable, tosend[sockindex].oidmod[i])) == NULL) {
565             printf("%s() Error: No such oid %s, %d\n", __func__, __FILE__, __LINE__);
566             free(modptr);
567             free(listmid);
568             free(tosend);
569             return 1;
570           }
571           GETSIZE(size,headeraddr);
572           size+=sizeof(objheader_t);
573           memcpy(modptr+offset, headeraddr, size);
574           offset+=size;
575         }
576         send_data(sd, modptr, tosend[sockindex].f.sum_bytes);
577         free(modptr);
578       } else { //handle request locally
579         handleLocalReq(&tosend[sockindex], &transinfo, record, &getReplyCtrl[sockindex]);
580       }
581       sockindex++;
582       pile = pile->next;
583     } //end of pile processing
584       /* Recv Ctrl msgs from all machines */
585     int i;
586     for(i = 0; i < pilecount; i++) {
587       int sd = socklist[i];
588       if(sd != 0) {
589         char control;
590         recv_data(sd, &control, sizeof(char));
591         //Update common data structure with new ctrl msg
592         getReplyCtrl[i] = control;
593         /* Recv Objects if participant sends TRANS_DISAGREE */
594 #ifdef CACHE
595         if(control == TRANS_DISAGREE) {
596           int length;
597           recv_data(sd, &length, sizeof(int));
598           void *newAddr;
599           pthread_mutex_lock(&prefetchcache_mutex);
600           if ((newAddr = prefetchobjstrAlloc((unsigned int)length)) == NULL) {
601             printf("Error: %s() objstrAlloc error for copying into prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
602             free(tosend);
603             free(listmid);
604             pthread_mutex_unlock(&prefetchcache_mutex);
605             return 1;
606           }
607           pthread_mutex_unlock(&prefetchcache_mutex);
608           recv_data(sd, newAddr, length);
609           int offset = 0;
610           while(length != 0) {
611             unsigned int oidToPrefetch;
612             objheader_t * header;
613             header = (objheader_t *)(((char *)newAddr) + offset);
614             oidToPrefetch = OID(header);
615             int size = 0;
616             GETSIZE(size, header);
617             size += sizeof(objheader_t);
618             //make an entry in prefetch hash table
619             void *oldptr;
620             if((oldptr = prehashSearch(oidToPrefetch)) != NULL) {
621               prehashRemove(oidToPrefetch);
622               prehashInsert(oidToPrefetch, header);
623             } else {
624               prehashInsert(oidToPrefetch, header);
625             }
626             length = length - size;
627             offset += size;
628           }
629         } //end of receiving objs
630 #endif
631       }
632     }
633     /* Decide the final response */
634     if((finalResponse = decideResponse(getReplyCtrl, &treplyretry, record, pilecount)) == 0) {
635       printf("Error: %s() in updating prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
636       free(tosend);
637       free(listmid);
638       return 1;
639     }
640
641     /* Send responses to all machines */
642     for(i = 0; i < pilecount; i++) {
643       int sd = socklist[i];
644       if(sd != 0) {
645 #ifdef CACHE
646         if(finalResponse == TRANS_COMMIT) {
647           int retval;
648           /* Update prefetch cache */
649           if((retval = updatePrefetchCache(&(tosend[i]), record)) != 0) {
650             printf("Error: %s() in updating prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
651             free(tosend);
652             free(listmid);
653             return 1;
654           }
655           /* Invalidate objects in other machine cache */
656           if(tosend[i].f.nummod > 0) {
657             if((retval = invalidateObj(&(tosend[i]))) != 0) {
658               printf("Error: %s() in invalidating Objects %s, %d\n", __func__, __FILE__, __LINE__);
659               free(tosend);
660               free(listmid);
661               return 1;
662             }
663           }
664         }
665 #endif
666         send_data(sd, &finalResponse, sizeof(char));
667       } else {
668         /* Complete local processing */
669         doLocalProcess(finalResponse, &(tosend[i]), &transinfo, record);
670       }
671     }
672
673     /* Free resources */
674     free(tosend);
675     free(listmid);
676     if (!treplyretry)
677       pDelete(pile_ptr);
678     /* wait a random amount of time before retrying to commit transaction*/
679     if(treplyretry) {
680       randomdelay();
681 #ifdef TRANSSTATS
682       nSoftAbort++;
683 #endif
684     }
685     /* Retry trans commit procedure during soft_abort case */
686   } while (treplyretry);
687
688   if(finalResponse == TRANS_ABORT) {
689     //printf("Aborting trans\n");
690 #ifdef TRANSSTATS
691     numTransAbort++;
692 #endif
693     /* Free Resources */
694     objstrDelete(record->cache);
695     chashDelete(record->lookupTable);
696     free(record);
697     return TRANS_ABORT;
698   } else if(finalResponse == TRANS_COMMIT) {
699 #ifdef TRANSSTATS
700     numTransCommit++;
701 #endif
702     /* Free Resources */
703     objstrDelete(record->cache);
704     chashDelete(record->lookupTable);
705     free(record);
706     return 0;
707   } else {
708     //TODO Add other cases
709     printf("Error: in %s() THIS SHOULD NOT HAPPEN.....EXIT PROGRAM\n", __func__);
710     exit(-1);
711   }
712   return 0;
713 }
714
715 /* This function handles the local objects involved in a transaction
716  * commiting process.  It also makes a decision if this local machine
717  * sends AGREE or DISAGREE or SOFT_ABORT to coordinator */
718 void handleLocalReq(trans_req_data_t *tdata, trans_commit_data_t *transinfo, transrecord_t *rec, char *getReplyCtrl) {
719   unsigned int *oidnotfound = NULL, *oidlocked = NULL;
720   int numoidnotfound = 0, numoidlocked = 0;
721   int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
722   int numread, i;
723   unsigned int oid;
724   unsigned short version;
725
726   /* Counters and arrays to formulate decision on control message to be sent */
727   oidnotfound = (unsigned int *) calloc((tdata->f.numread + tdata->f.nummod), sizeof(unsigned int));
728   oidlocked = (unsigned int *) calloc((tdata->f.numread + tdata->f.nummod +1), sizeof(unsigned int)); // calloc additional 1 byte for
729   //setting a divider between read and write locks
730   numread = tdata->f.numread;
731   /* Process each oid in the machine pile/ group per thread */
732   for (i = 0; i < tdata->f.numread + tdata->f.nummod; i++) {
733     if (i < tdata->f.numread) {
734       int incr = sizeof(unsigned int) + sizeof(unsigned short); // Offset that points to next position in the objread array
735       incr *= i;
736       oid = *((unsigned int *)(((char *)tdata->objread) + incr));
737       version = *((unsigned short *)(((char *)tdata->objread) + incr + sizeof(unsigned int)));
738       commitCountForObjRead(getReplyCtrl, oidnotfound, oidlocked, &numoidnotfound, &numoidlocked, &v_nomatch, &v_matchlock, &v_matchnolock, oid, version);
739     } else { // Objects Modified
740       if(i == tdata->f.numread) {
741         oidlocked[numoidlocked] = -1;
742         numoidlocked++;
743       }
744       int tmpsize;
745       objheader_t *headptr;
746       headptr = (objheader_t *) chashSearch(rec->lookupTable, tdata->oidmod[i-numread]);
747       if (headptr == NULL) {
748         printf("Error: handleLocalReq() returning NULL, no such oid %s, %d\n", __FILE__, __LINE__);
749         return;
750       }
751       oid = OID(headptr);
752       version = headptr->version;
753       commitCountForObjMod(getReplyCtrl, oidnotfound, oidlocked, &numoidnotfound, &numoidlocked, &v_nomatch, &v_matchlock, &v_matchnolock, oid, version);
754     }
755   }
756
757 /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
758  * if Participant receives a TRANS_COMMIT */
759   transinfo->objlocked = oidlocked;
760   transinfo->objnotfound = oidnotfound;
761   transinfo->modptr = NULL;
762   transinfo->numlocked = numoidlocked;
763   transinfo->numnotfound = numoidnotfound;
764
765   /* Condition to send TRANS_AGREE */
766   if(v_matchnolock == tdata->f.numread + tdata->f.nummod) {
767     *getReplyCtrl = TRANS_AGREE;
768   }
769   /* Condition to send TRANS_SOFT_ABORT */
770   if((v_matchlock > 0 && v_nomatch == 0) || (numoidnotfound > 0 && v_nomatch == 0)) {
771     *getReplyCtrl = TRANS_SOFT_ABORT;
772   }
773 }
774
775 void doLocalProcess(char finalResponse, trans_req_data_t *tdata, trans_commit_data_t *transinfo, transrecord_t *record) {
776   if(finalResponse == TRANS_ABORT) {
777     if(transAbortProcess(transinfo) != 0) {
778       printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
779       fflush(stdout);
780       return;
781     }
782   } else if(finalResponse == TRANS_COMMIT) {
783 #ifdef CACHE
784     /* Invalidate objects in other machine cache */
785     if(tdata->f.nummod > 0) {
786       int retval;
787       if((retval = invalidateObj(tdata)) != 0) {
788         printf("Error: %s() in invalidating Objects %s, %d\n", __func__, __FILE__, __LINE__);
789         return;
790       }
791     }
792 #endif
793     if(transComProcess(tdata, transinfo, record) != 0) {
794       printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
795       fflush(stdout);
796       return;
797     }
798   }
799
800   /* Free memory */
801   if (transinfo->objlocked != NULL) {
802     free(transinfo->objlocked);
803   }
804   if (transinfo->objnotfound != NULL) {
805     free(transinfo->objnotfound);
806   }
807 }
808
809 /* This function decides the reponse that needs to be sent to
810  * all Participant machines after the TRANS_REQUEST protocol */
811 char decideResponse(char *getReplyCtrl, char *treplyretry, transrecord_t *record, int pilecount) {
812   int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
813                                                                    message to send */
814   for (i = 0 ; i < pilecount; i++) {
815     char control;
816     control = getReplyCtrl[i];
817     switch(control) {
818     default:
819       printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
820
821       /* treat as disagree, pass thru */
822     case TRANS_DISAGREE:
823       transdisagree++;
824       break;
825
826     case TRANS_AGREE:
827       transagree++;
828       break;
829
830     case TRANS_SOFT_ABORT:
831       transsoftabort++;
832       break;
833     }
834   }
835
836   if(transdisagree > 0) {
837     /* Send Abort */
838     *treplyretry = 0;
839     return TRANS_ABORT;
840 #ifdef CACHE
841     /* clear objects from prefetch cache */
842     cleanPCache(record);
843 #endif
844   } else if(transagree == pilecount) {
845     /* Send Commit */
846     *treplyretry = 0;
847     return TRANS_COMMIT;
848   } else {
849     /* Send Abort in soft abort case followed by retry commiting transaction again*/
850     *treplyretry = 1;
851     return TRANS_ABORT;
852   }
853   return 0;
854 }
855
856 /* This function opens a connection, places an object read request to
857  * the remote machine, reads the control message and object if
858  * available and copies the object and its header to the local
859  * cache. */
860
861 void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
862   int size, val;
863   struct sockaddr_in serv_addr;
864   char machineip[16];
865   char control;
866   objheader_t *h;
867   void *objcopy = NULL;
868
869   int sd = getSock2(transReadSockPool, mnum);
870   char readrequest[sizeof(char)+sizeof(unsigned int)];
871   readrequest[0] = READ_REQUEST;
872   *((unsigned int *)(&readrequest[1])) = oid;
873   send_data(sd, readrequest, sizeof(readrequest));
874
875   /* Read response from the Participant */
876   recv_data(sd, &control, sizeof(char));
877
878   if (control==OBJECT_NOT_FOUND) {
879     objcopy = NULL;
880   } else {
881     /* Read object if found into local cache */
882     recv_data(sd, &size, sizeof(int));
883     objcopy = objstrAlloc(record->cache, size);
884     recv_data(sd, objcopy, size);
885     /* Insert into cache's lookup table */
886     chashInsert(record->lookupTable, oid, objcopy);
887   }
888
889   return objcopy;
890 }
891
892 /*  Commit info for objects modified */
893 void commitCountForObjMod(char *getReplyCtrl, unsigned int *oidnotfound, unsigned int *oidlocked, int *numoidnotfound,
894                           int *numoidlocked, int *v_nomatch, int *v_matchlock, int *v_matchnolock, unsigned int oid, unsigned short version) {
895   void *mobj;
896   /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
897   /* Save the oids not found and number of oids not found for later use */
898   if ((mobj = mhashSearch(oid)) == NULL) { /* Obj not found */
899     /* Save the oids not found and number of oids not found for later use */
900     oidnotfound[*numoidnotfound] = oid;
901     (*numoidnotfound)++;
902   } else { /* If Obj found in machine (i.e. has not moved) */
903     /* Check if Obj is locked by any previous transaction */
904     if (write_trylock(STATUSPTR(mobj))) { // Can acquire write lock
905       if (version == ((objheader_t *)mobj)->version) {      /* match versions */
906         (*v_matchnolock)++;
907         //Keep track of what is locked
908         oidlocked[*numoidlocked] = OID(((objheader_t *)mobj));
909         (*numoidlocked)++;
910       } else { /* If versions don't match ...HARD ABORT */
911         (*v_nomatch)++;
912         /* Send TRANS_DISAGREE to Coordinator */
913         *getReplyCtrl = TRANS_DISAGREE;
914
915         //Keep track of what is locked
916         oidlocked[*numoidlocked] = OID(((objheader_t *)mobj));
917         (*numoidlocked)++;
918         //printf("%s() oid = %d, type = %d\t", __func__, OID(mobj), TYPE((objheader_t *)mobj));
919         return;
920       }
921     } else { //A lock is acquired some place else
922       if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
923         (*v_matchlock)++;
924       } else { /* If versions don't match ...HARD ABORT */
925         (*v_nomatch)++;
926         /* Send TRANS_DISAGREE to Coordinator */
927         *getReplyCtrl = TRANS_DISAGREE;
928         //printf("%s() oid = %d, type = %d\t", __func__, OID(mobj), TYPE((objheader_t *)mobj));
929         return;
930       }
931     }
932   }
933 }
934
935 /*  Commit info for objects modified */
936 void commitCountForObjRead(char *getReplyCtrl, unsigned int *oidnotfound, unsigned int *oidlocked, int *numoidnotfound,
937                            int *numoidlocked, int *v_nomatch, int *v_matchlock, int *v_matchnolock, unsigned int oid, unsigned short version) {
938   void *mobj;
939   /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
940   /* Save the oids not found and number of oids not found for later use */
941   if ((mobj = mhashSearch(oid)) == NULL) { /* Obj not found */
942     /* Save the oids not found and number of oids not found for later use */
943     oidnotfound[*numoidnotfound] = oid;
944     (*numoidnotfound)++;
945   } else { /* If Obj found in machine (i.e. has not moved) */
946     /* Check if Obj is locked by any previous transaction */
947     if (read_trylock(STATUSPTR(mobj))) { // Can further acquire read locks
948       if (version == ((objheader_t *)mobj)->version) {      /* If locked then match versions */
949         (*v_matchnolock)++;
950         //Keep track of what is locked
951         oidlocked[*numoidlocked] = OID(((objheader_t *)mobj));
952         (*numoidlocked)++;
953       } else { /* If versions don't match ...HARD ABORT */
954         (*v_nomatch)++;
955         /* Send TRANS_DISAGREE to Coordinator */
956         *getReplyCtrl = TRANS_DISAGREE;
957         //Keep track of what is locked
958         oidlocked[*numoidlocked] = OID(((objheader_t *)mobj));
959         (*numoidlocked)++;
960         //printf("%s() oid = %d, type = %d\t", __func__, OID(mobj), TYPE((objheader_t *)mobj));
961         return;
962       }
963     } else { //Has reached max number of readers or some other transaction
964       //has acquired a lock on this object
965       if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
966         (*v_matchlock)++;
967       } else { /* If versions don't match ...HARD ABORT */
968         (*v_nomatch)++;
969         /* Send TRANS_DISAGREE to Coordinator */
970         *getReplyCtrl = TRANS_DISAGREE;
971         //printf("%s() oid = %d, type = %d\t", __func__, OID(mobj), TYPE((objheader_t *)mobj));
972         return;
973       }
974     }
975   }
976 }
977
978 /* This function completes the ABORT process if the transaction is aborting */
979 int transAbortProcess(trans_commit_data_t *transinfo) {
980   int i, numlocked;
981   unsigned int *objlocked;
982   void *header;
983
984   numlocked = transinfo->numlocked;
985   objlocked = transinfo->objlocked;
986
987   int useWriteUnlock = 0;
988   for (i = 0; i < numlocked; i++) {
989     if(objlocked[i] == -1) {
990       useWriteUnlock = 1;
991       continue;
992     }
993     if((header = mhashSearch(objlocked[i])) == NULL) {
994       printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
995       return 1;
996     }
997     if(!useWriteUnlock) {
998       read_unlock(STATUSPTR(header));
999     } else {
1000       write_unlock(STATUSPTR(header));
1001     }
1002   }
1003
1004   return 0;
1005 }
1006
1007 /*This function completes the COMMIT process if the transaction is commiting*/
1008 int transComProcess(trans_req_data_t *tdata, trans_commit_data_t *transinfo, transrecord_t *rec) {
1009   objheader_t *header, *tcptr;
1010   int i, nummod, tmpsize, numcreated, numlocked;
1011   unsigned int *oidmod, *oidcreated, *oidlocked;
1012   void *ptrcreate;
1013
1014   nummod = tdata->f.nummod;
1015   oidmod = tdata->oidmod;
1016   numcreated = tdata->f.numcreated;
1017   oidcreated = tdata->oidcreated;
1018   numlocked = transinfo->numlocked;
1019   oidlocked = transinfo->objlocked;
1020
1021   for (i = 0; i < nummod; i++) {
1022     if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
1023       printf("Error: transComProcess() mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1024       return 1;
1025     }
1026     /* Copy from transaction cache -> main object store */
1027     if ((tcptr = ((objheader_t *) chashSearch(rec->lookupTable, oidmod[i]))) == NULL) {
1028       printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1029       return 1;
1030     }
1031     GETSIZE(tmpsize, header);
1032     char *tmptcptr = (char *) tcptr;
1033     memcpy((char*)header+sizeof(objheader_t), (char *)tmptcptr+ sizeof(objheader_t), tmpsize);
1034     header->version += 1;
1035     if(header->notifylist != NULL) {
1036       notifyAll(&header->notifylist, OID(header), header->version);
1037     }
1038   }
1039   /* If object is newly created inside transaction then commit it */
1040   for (i = 0; i < numcreated; i++) {
1041     if ((header = ((objheader_t *) chashSearch(rec->lookupTable, oidcreated[i]))) == NULL) {
1042       printf("Error: transComProcess() chashSearch returned NULL for oid = %x at %s, %d\n", oidcreated[i], __FILE__, __LINE__);
1043       return 1;
1044     }
1045     GETSIZE(tmpsize, header);
1046     tmpsize += sizeof(objheader_t);
1047     pthread_mutex_lock(&mainobjstore_mutex);
1048     if ((ptrcreate = objstrAlloc(mainobjstore, tmpsize)) == NULL) {
1049       printf("Error: transComProcess() failed objstrAlloc %s, %d\n", __FILE__, __LINE__);
1050       pthread_mutex_unlock(&mainobjstore_mutex);
1051       return 1;
1052     }
1053     pthread_mutex_unlock(&mainobjstore_mutex);
1054     /* Initialize read and write locks */
1055     initdsmlocks(STATUSPTR(header));
1056     memcpy(ptrcreate, header, tmpsize);
1057     mhashInsert(oidcreated[i], ptrcreate);
1058     lhashInsert(oidcreated[i], myIpAddr);
1059   }
1060   /* Unlock locked objects */
1061   int useWriteUnlock = 0;
1062   for(i = 0; i < numlocked; i++) {
1063     if(oidlocked[i] == -1) {
1064       useWriteUnlock = 1;
1065       continue;
1066     }
1067     if((header = (objheader_t *) mhashSearch(oidlocked[i])) == NULL) {
1068       printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1069       return 1;
1070     }
1071     if(!useWriteUnlock) {
1072       read_unlock(STATUSPTR(header));
1073     } else {
1074       write_unlock(STATUSPTR(header));
1075     }
1076   }
1077   return 0;
1078 }
1079
1080 prefetchpile_t *foundLocal(char *ptr) {
1081   int siteid = *(GET_SITEID(ptr));
1082   int ntuples = *(GET_NTUPLES(ptr));
1083   unsigned int * oidarray = GET_PTR_OID(ptr);
1084   unsigned short * endoffsets = GET_PTR_EOFF(ptr, ntuples);
1085   short * arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1086   prefetchpile_t * head=NULL;
1087   int numLocal = 0;
1088
1089   int i;
1090   for(i=0; i<ntuples; i++) {
1091     unsigned short baseindex=(i==0) ? 0 : endoffsets[i-1];
1092     unsigned short endindex=endoffsets[i];
1093     unsigned int oid=oidarray[i];
1094     int newbase;
1095     int machinenum;
1096     if (oid==0)
1097       continue;
1098     //Look up fields locally
1099     for(newbase=baseindex; newbase<endindex; newbase++) {
1100       if (!lookupObject(&oid, arryfields[newbase]))
1101         break;
1102       //Ended in a null pointer...
1103       if (oid==0)
1104         goto tuple;
1105     }
1106     //Entire prefetch is local
1107     if (newbase==endindex&&checkoid(oid)) {
1108       numLocal++;
1109       goto tuple;
1110     }
1111     //Add to remote requests
1112     machinenum=lhashSearch(oid);
1113     insertPile(machinenum, oid, endindex-newbase, &arryfields[newbase], &head);
1114 tuple:
1115     ;
1116   }
1117
1118   /* handle dynamic prefetching */
1119   handleDynPrefetching(numLocal, ntuples, siteid);
1120   return head;
1121 }
1122
1123 int checkoid(unsigned int oid) {
1124   objheader_t *header;
1125   if ((header=mhashSearch(oid))!=NULL) {
1126     //Found on machine
1127     return 1;
1128   } else if ((header=prehashSearch(oid))!=NULL) {
1129     //Found in cache
1130     return 1;
1131   } else {
1132     return 0;
1133   }
1134 }
1135
1136 int lookupObject(unsigned int * oid, short offset) {
1137   objheader_t *header;
1138   if ((header=mhashSearch(*oid))!=NULL) {
1139     //Found on machine
1140     ;
1141   } else if ((header=prehashSearch(*oid))!=NULL) {
1142     //Found in cache
1143     ;
1144   } else {
1145     return 0;
1146   }
1147
1148   if(TYPE(header) > NUMCLASSES) {
1149     int elementsize = classsize[TYPE(header)];
1150     struct ArrayObject *ao = (struct ArrayObject *) (((char *)header) + sizeof(objheader_t));
1151     int length = ao->___length___;
1152     /* Check if array out of bounds */
1153     if(offset < 0 || offset >= length) {
1154       //if yes treat the object as found
1155       (*oid)=0;
1156       return 1;
1157     }
1158     (*oid) = *((unsigned int *)(((char *)ao) + sizeof(struct ArrayObject) + (elementsize*offset)));
1159     return 1;
1160   } else {
1161     (*oid) = *((unsigned int *)(((char *)header) + sizeof(objheader_t) + offset));
1162     return 1;
1163   }
1164 }
1165
1166
1167 /* This function is called by the thread calling transPrefetch */
1168 void *transPrefetch(void *t) {
1169   while(1) {
1170     /* read from prefetch queue */
1171     void *node=gettail();
1172     /* Check if the tuples are found locally, if yes then reduce them further*/
1173     /* and group requests by remote machine ids by calling the makePreGroups() */
1174     prefetchpile_t *pilehead = foundLocal(node);
1175
1176     if (pilehead!=NULL) {
1177       // Get sock from shared pool
1178       int sd = getSock2(transPrefetchSockPool, pilehead->mid);
1179
1180       /* Send  Prefetch Request */
1181       prefetchpile_t *ptr = pilehead;
1182       while(ptr != NULL) {
1183         sendPrefetchReq(ptr, sd);
1184         ptr = ptr->next;
1185       }
1186
1187       /* Release socket */
1188       //        freeSock(transPrefetchSockPool, pilehead->mid, sd);
1189
1190       /* Deallocated pilehead */
1191       mcdealloc(pilehead);
1192     }
1193     // Deallocate the prefetch queue pile node
1194     inctail();
1195   }
1196 }
1197
1198 void sendPrefetchReqnew(prefetchpile_t *mcpilenode, int sd) {
1199   objpile_t *tmp;
1200
1201   int size=sizeof(char)+sizeof(int);
1202   for(tmp=mcpilenode->objpiles; tmp!=NULL; tmp=tmp->next) {
1203     size += sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1204   }
1205
1206   char buft[size];
1207   char *buf=buft;
1208   *buf=TRANS_PREFETCH;
1209   buf+=sizeof(char);
1210
1211   for(tmp=mcpilenode->objpiles; tmp!=NULL; tmp=tmp->next) {
1212     int len = sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1213     *((int*)buf)=len;
1214     buf+=sizeof(int);
1215     *((unsigned int *)buf)=tmp->oid;
1216     buf+=sizeof(unsigned int);
1217     *((unsigned int *)(buf)) = myIpAddr;
1218     buf+=sizeof(unsigned int);
1219     memcpy(buf, tmp->offset, tmp->numoffset*sizeof(short));
1220     buf+=tmp->numoffset*sizeof(short);
1221   }
1222   *((int *)buf)=-1;
1223   send_data(sd, buft, size);
1224   return;
1225 }
1226
1227 void sendPrefetchReq(prefetchpile_t *mcpilenode, int sd) {
1228   int len, endpair;
1229   char control;
1230   objpile_t *tmp;
1231
1232   /* Send TRANS_PREFETCH control message */
1233   control = TRANS_PREFETCH;
1234   send_data(sd, &control, sizeof(char));
1235
1236   /* Send Oids and offsets in pairs */
1237   tmp = mcpilenode->objpiles;
1238   while(tmp != NULL) {
1239     len = sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1240     char oidnoffset[len];
1241     char *buf=oidnoffset;
1242     *((int*)buf) = tmp->numoffset;
1243     buf+=sizeof(int);
1244     *((unsigned int *)buf) = tmp->oid;
1245     buf+=sizeof(unsigned int);
1246     *((unsigned int *)buf) = myIpAddr;
1247     buf += sizeof(unsigned int);
1248     memcpy(buf, tmp->offset, (tmp->numoffset)*sizeof(short));
1249     send_data(sd, oidnoffset, len);
1250     tmp = tmp->next;
1251   }
1252
1253   /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
1254   endpair = -1;
1255   send_data(sd, &endpair, sizeof(int));
1256
1257   return;
1258 }
1259
1260 int getPrefetchResponse(int sd) {
1261   int length = 0, size = 0;
1262   char control;
1263   unsigned int oid;
1264   void *modptr, *oldptr;
1265
1266   recv_data((int)sd, &length, sizeof(int));
1267   size = length - sizeof(int);
1268   char recvbuffer[size];
1269
1270   recv_data((int)sd, recvbuffer, size);
1271   control = *((char *) recvbuffer);
1272   if(control == OBJECT_FOUND) {
1273     oid = *((unsigned int *)(recvbuffer + sizeof(char)));
1274     size = size - (sizeof(char) + sizeof(unsigned int));
1275     pthread_mutex_lock(&prefetchcache_mutex);
1276     if ((modptr = prefetchobjstrAlloc(size)) == NULL) {
1277       printf("Error: objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
1278       pthread_mutex_unlock(&prefetchcache_mutex);
1279       return -1;
1280     }
1281     pthread_mutex_unlock(&prefetchcache_mutex);
1282     memcpy(modptr, recvbuffer + sizeof(char) + sizeof(unsigned int), size);
1283     STATUS(modptr)=0;
1284
1285     /* Insert the oid and its address into the prefetch hash lookup table */
1286     /* Do a version comparison if the oid exists */
1287     if((oldptr = prehashSearch(oid)) != NULL) {
1288       /* If older version then update with new object ptr */
1289       if(((objheader_t *)oldptr)->version <= ((objheader_t *)modptr)->version) {
1290         prehashRemove(oid);
1291         prehashInsert(oid, modptr);
1292       }
1293     } else { /* Else add the object ptr to hash table*/
1294       prehashInsert(oid, modptr);
1295     }
1296     /* Lock the Prefetch Cache look up table*/
1297     pthread_mutex_lock(&pflookup.lock);
1298     /* Broadcast signal on prefetch cache condition variable */
1299     pthread_cond_broadcast(&pflookup.cond);
1300     /* Unlock the Prefetch Cache look up table*/
1301     pthread_mutex_unlock(&pflookup.lock);
1302   } else if(control == OBJECT_NOT_FOUND) {
1303     oid = *((unsigned int *)(recvbuffer + sizeof(char)));
1304     /* TODO: For each object not found query DHT for new location and retrieve the object */
1305     /* Throw an error */
1306     //printf("OBJECT %x NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n", oid);
1307     //    exit(-1);
1308   } else {
1309     printf("Error: in decoding the control value %d, %s, %d\n",control, __FILE__, __LINE__);
1310   }
1311
1312   return 0;
1313 }
1314
1315 unsigned short getObjType(unsigned int oid) {
1316   objheader_t *objheader;
1317   unsigned short numoffset[] ={0};
1318   short fieldoffset[] ={};
1319
1320   if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL) {
1321 #ifdef CACHE
1322     if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL) {
1323 #endif
1324     unsigned int mid = lhashSearch(oid);
1325     int sd = getSock2(transReadSockPool, mid);
1326     char remotereadrequest[sizeof(char)+sizeof(unsigned int)];
1327     remotereadrequest[0] = READ_REQUEST;
1328     *((unsigned int *)(&remotereadrequest[1])) = oid;
1329     send_data(sd, remotereadrequest, sizeof(remotereadrequest));
1330
1331     /* Read response from the Participant */
1332     char control;
1333     recv_data(sd, &control, sizeof(char));
1334
1335     if (control==OBJECT_NOT_FOUND) {
1336       printf("Error: in %s() THIS SHOULD NOT HAPPEN.....EXIT PROGRAM\n", __func__);
1337       fflush(stdout);
1338       exit(-1);
1339     } else {
1340       /* Read object if found into local cache */
1341       int size;
1342       recv_data(sd, &size, sizeof(int));
1343 #ifdef CACHE
1344       pthread_mutex_lock(&prefetchcache_mutex);
1345       if ((objheader = prefetchobjstrAlloc(size)) == NULL) {
1346         printf("Error: %s() objstrAlloc error for copying into prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
1347         pthread_exit(NULL);
1348       }
1349       pthread_mutex_unlock(&prefetchcache_mutex);
1350       recv_data(sd, objheader, size);
1351       prehashInsert(oid, objheader);
1352       return TYPE(objheader);
1353 #else
1354       char *buffer;
1355       if((buffer = calloc(1, size)) == NULL) {
1356         printf("%s() Calloc Error %s at line %d\n", __func__, __FILE__, __LINE__);
1357         fflush(stdout);
1358         return 0;
1359       }
1360       recv_data(sd, buffer, size);
1361       objheader = (objheader_t *)buffer;
1362       unsigned short type = TYPE(objheader);
1363       free(buffer);
1364       return type;
1365 #endif
1366     }
1367 #ifdef CACHE
1368   }
1369 #endif
1370   }
1371   return TYPE(objheader);
1372 }
1373
1374 int startRemoteThread(unsigned int oid, unsigned int mid) {
1375   int sock;
1376   struct sockaddr_in remoteAddr;
1377   char msg[1 + sizeof(unsigned int)];
1378   int bytesSent;
1379   int status;
1380
1381   if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
1382     perror("startRemoteThread():socket()");
1383     return -1;
1384   }
1385
1386   bzero(&remoteAddr, sizeof(remoteAddr));
1387   remoteAddr.sin_family = AF_INET;
1388   remoteAddr.sin_port = htons(LISTEN_PORT);
1389   remoteAddr.sin_addr.s_addr = htonl(mid);
1390
1391   if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0) {
1392     printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
1393            inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1394     status = -1;
1395   } else
1396   {
1397     msg[0] = START_REMOTE_THREAD;
1398     *((unsigned int *) &msg[1]) = oid;
1399     send_data(sock, msg, 1 + sizeof(unsigned int));
1400   }
1401
1402   close(sock);
1403   return status;
1404 }
1405
1406 //TODO: when reusing oids, make sure they are not already in use!
1407 static unsigned int id = 0xFFFFFFFF;
1408 unsigned int getNewOID(void) {
1409   id += 2;
1410   if (id > oidMax || id < oidMin) {
1411     id = (oidMin | 1);
1412   }
1413   return id;
1414 }
1415
1416 int processConfigFile() {
1417   FILE *configFile;
1418   const int maxLineLength = 200;
1419   char lineBuffer[maxLineLength];
1420   char *token;
1421   const char *delimiters = " \t\n";
1422   char *commentBegin;
1423   in_addr_t tmpAddr;
1424
1425   configFile = fopen(CONFIG_FILENAME, "r");
1426   if (configFile == NULL) {
1427     printf("error opening %s:\n", CONFIG_FILENAME);
1428     perror("");
1429     return -1;
1430   }
1431
1432   numHostsInSystem = 0;
1433   sizeOfHostArray = 8;
1434   hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
1435
1436   while(fgets(lineBuffer, maxLineLength, configFile) != NULL) {
1437     commentBegin = strchr(lineBuffer, '#');
1438     if (commentBegin != NULL)
1439       *commentBegin = '\0';
1440     token = strtok(lineBuffer, delimiters);
1441     while (token != NULL) {
1442       tmpAddr = inet_addr(token);
1443       if ((int)tmpAddr == -1) {
1444         printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
1445         fclose(configFile);
1446         return -1;
1447       } else
1448         addHost(htonl(tmpAddr));
1449       token = strtok(NULL, delimiters);
1450     }
1451   }
1452
1453   fclose(configFile);
1454
1455   if (numHostsInSystem < 1) {
1456     printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
1457     return -1;
1458   }
1459 #ifdef MAC
1460   myIpAddr = getMyIpAddr("en1");
1461 #else
1462   myIpAddr = getMyIpAddr("eth0");
1463 #endif
1464   myIndexInHostArray = findHost(myIpAddr);
1465   if (myIndexInHostArray == -1) {
1466     printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
1467     return -1;
1468   }
1469   oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
1470   oidMin = oidsPerBlock * myIndexInHostArray;
1471   if (myIndexInHostArray == numHostsInSystem - 1)
1472     oidMax = 0xFFFFFFFF;
1473   else
1474     oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
1475
1476   return 0;
1477 }
1478
1479 void addHost(unsigned int hostIp) {
1480   unsigned int *tmpArray;
1481
1482   if (findHost(hostIp) != -1)
1483     return;
1484
1485   if (numHostsInSystem == sizeOfHostArray) {
1486     tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
1487     memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
1488     free(hostIpAddrs);
1489     hostIpAddrs = tmpArray;
1490   }
1491
1492   hostIpAddrs[numHostsInSystem++] = hostIp;
1493
1494   return;
1495 }
1496
1497 int findHost(unsigned int hostIp) {
1498   int i;
1499   for (i = 0; i < numHostsInSystem; i++)
1500     if (hostIpAddrs[i] == hostIp)
1501       return i;
1502
1503   //not found
1504   return -1;
1505 }
1506
1507 /* This function sends notification request per thread waiting on object(s) whose version
1508  * changes */
1509 int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int numoid) {
1510   int sock,i;
1511   objheader_t *objheader;
1512   struct sockaddr_in remoteAddr;
1513   char msg[1 + numoid * (sizeof(unsigned short) + sizeof(unsigned int)) +  3 * sizeof(unsigned int)];
1514   char *ptr;
1515   int bytesSent;
1516   int status, size;
1517   unsigned short version;
1518   unsigned int oid,mid;
1519   static unsigned int threadid = 0;
1520   pthread_mutex_t threadnotify = PTHREAD_MUTEX_INITIALIZER; //Lock and condition var for threadjoin and notification
1521   pthread_cond_t threadcond = PTHREAD_COND_INITIALIZER;
1522   notifydata_t *ndata;
1523
1524   oid = oidarry[0];
1525   if((mid = lhashSearch(oid)) == 0) {
1526     printf("Error: %s() No such machine found for oid =%x\n",__func__, oid);
1527     return;
1528   }
1529
1530   if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
1531     perror("reqNotify():socket()");
1532     return -1;
1533   }
1534
1535   bzero(&remoteAddr, sizeof(remoteAddr));
1536   remoteAddr.sin_family = AF_INET;
1537   remoteAddr.sin_port = htons(LISTEN_PORT);
1538   remoteAddr.sin_addr.s_addr = htonl(mid);
1539
1540   /* Generate unique threadid */
1541   threadid++;
1542
1543   /* Save threadid, numoid, oidarray, versionarray, pthread_cond_variable for later processing */
1544   if((ndata = calloc(1, sizeof(notifydata_t))) == NULL) {
1545     printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
1546     return -1;
1547   }
1548   ndata->numoid = numoid;
1549   ndata->threadid = threadid;
1550   ndata->oidarry = oidarry;
1551   ndata->versionarry = versionarry;
1552   ndata->threadcond = threadcond;
1553   ndata->threadnotify = threadnotify;
1554   if((status = notifyhashInsert(threadid, ndata)) != 0) {
1555     printf("reqNotify(): Insert into notify hash table not successful %s, %d\n", __FILE__, __LINE__);
1556     free(ndata);
1557     return -1;
1558   }
1559
1560   /* Send  number of oids, oidarry, version array, machine id and threadid */
1561   if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0) {
1562     printf("reqNotify():error %d connecting to %s:%d\n", errno,
1563            inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1564     free(ndata);
1565     return -1;
1566   } else {
1567     msg[0] = THREAD_NOTIFY_REQUEST;
1568     *((unsigned int *)(&msg[1])) = numoid;
1569     /* Send array of oids  */
1570     size = sizeof(unsigned int);
1571     {
1572       i = 0;
1573       while(i < numoid) {
1574         oid = oidarry[i];
1575         *((unsigned int *)(&msg[1] + size)) = oid;
1576         size += sizeof(unsigned int);
1577         i++;
1578       }
1579     }
1580
1581     /* Send array of version  */
1582     {
1583       i = 0;
1584       while(i < numoid) {
1585         version = versionarry[i];
1586         *((unsigned short *)(&msg[1] + size)) = version;
1587         size += sizeof(unsigned short);
1588         i++;
1589       }
1590     }
1591
1592     *((unsigned int *)(&msg[1] + size)) = myIpAddr;
1593     size += sizeof(unsigned int);
1594     *((unsigned int *)(&msg[1] + size)) = threadid;
1595     pthread_mutex_lock(&(ndata->threadnotify));
1596     size = 1 + numoid * (sizeof(unsigned int) + sizeof(unsigned short)) + 3 * sizeof(unsigned int);
1597     send_data(sock, msg, size);
1598     pthread_cond_wait(&(ndata->threadcond), &(ndata->threadnotify));
1599     pthread_mutex_unlock(&(ndata->threadnotify));
1600   }
1601
1602   pthread_cond_destroy(&threadcond);
1603   pthread_mutex_destroy(&threadnotify);
1604   free(ndata);
1605   close(sock);
1606   return status;
1607 }
1608
1609 void threadNotify(unsigned int oid, unsigned short version, unsigned int tid) {
1610   notifydata_t *ndata;
1611   int i, objIsFound = 0, index;
1612   void *ptr;
1613
1614   //Look up the tid and call the corresponding pthread_cond_signal
1615   if((ndata = notifyhashSearch(tid)) == NULL) {
1616     printf("threadnotify(): No such threadid is present %s, %d\n", __FILE__, __LINE__);
1617     return;
1618   } else  {
1619     for(i = 0; i < ndata->numoid; i++) {
1620       if(ndata->oidarry[i] == oid) {
1621         objIsFound = 1;
1622         index = i;
1623       }
1624     }
1625     if(objIsFound == 0) {
1626       printf("threadNotify(): Oid not found %s, %d\n", __FILE__, __LINE__);
1627       return;
1628     } else {
1629       if(version <= ndata->versionarry[index]) {
1630         printf("threadNotify(): New version %d has not changed since last version for oid = %d, %s, %d\n", version, oid, __FILE__, __LINE__);
1631         return;
1632       } else {
1633 #ifdef CACHE
1634         /* Clear from prefetch cache and free thread related data structure */
1635         if((ptr = prehashSearch(oid)) != NULL) {
1636           prehashRemove(oid);
1637         }
1638 #endif
1639         pthread_cond_signal(&(ndata->threadcond));
1640       }
1641     }
1642   }
1643   return;
1644 }
1645
1646 int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) {
1647   threadlist_t *ptr;
1648   unsigned int mid;
1649   struct sockaddr_in remoteAddr;
1650   char msg[1 + sizeof(unsigned short) + 2*sizeof(unsigned int)];
1651   int sock, status, size, bytesSent;
1652
1653   while(*head != NULL) {
1654     ptr = *head;
1655     mid = ptr->mid;
1656     //create a socket connection to that machine
1657     if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
1658       perror("notifyAll():socket()");
1659       return -1;
1660     }
1661
1662     bzero(&remoteAddr, sizeof(remoteAddr));
1663     remoteAddr.sin_family = AF_INET;
1664     remoteAddr.sin_port = htons(LISTEN_PORT);
1665     remoteAddr.sin_addr.s_addr = htonl(mid);
1666     //send Thread Notify response and threadid to that machine
1667     if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0) {
1668       printf("notifyAll():error %d connecting to %s:%d\n", errno,
1669              inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1670       fflush(stdout);
1671       status = -1;
1672     } else {
1673       bzero(msg, (1+sizeof(unsigned short) + 2*sizeof(unsigned int)));
1674       msg[0] = THREAD_NOTIFY_RESPONSE;
1675       *((unsigned int *)&msg[1]) = oid;
1676       size = sizeof(unsigned int);
1677       *((unsigned short *)(&msg[1]+ size)) = version;
1678       size+= sizeof(unsigned short);
1679       *((unsigned int *)(&msg[1]+ size)) = ptr->threadid;
1680
1681       size = 1 + 2*sizeof(unsigned int) + sizeof(unsigned short);
1682       send_data(sock, msg, size);
1683     }
1684     //close socket
1685     close(sock);
1686     // Update head
1687     *head = ptr->next;
1688     free(ptr);
1689   }
1690   return status;
1691 }
1692
1693 void transAbort(transrecord_t *trans) {
1694   objstrDelete(trans->cache);
1695   chashDelete(trans->lookupTable);
1696   free(trans);
1697 }
1698
1699 /* This function inserts necessary information into
1700  * a machine pile data structure */
1701 plistnode_t *pInsert(plistnode_t *pile, objheader_t *headeraddr, unsigned int mid, int num_objs) {
1702   plistnode_t *ptr, *tmp;
1703   int found = 0, offset = 0;
1704
1705   tmp = pile;
1706   //Add oid into a machine that is already present in the pile linked list structure
1707   while(tmp != NULL) {
1708     if (tmp->mid == mid) {
1709       int tmpsize;
1710
1711       if (STATUS(headeraddr) & NEW) {
1712         tmp->oidcreated[tmp->numcreated] = OID(headeraddr);
1713         tmp->numcreated++;
1714         GETSIZE(tmpsize, headeraddr);
1715         tmp->sum_bytes += sizeof(objheader_t) + tmpsize;
1716       } else if (STATUS(headeraddr) & DIRTY) {
1717         tmp->oidmod[tmp->nummod] = OID(headeraddr);
1718         tmp->nummod++;
1719         GETSIZE(tmpsize, headeraddr);
1720         tmp->sum_bytes += sizeof(objheader_t) + tmpsize;
1721       } else {
1722         offset = (sizeof(unsigned int) + sizeof(short)) * tmp->numread;
1723         *((unsigned int *)(((char *)tmp->objread) + offset))=OID(headeraddr);
1724         offset += sizeof(unsigned int);
1725         *((short *)(((char *)tmp->objread) + offset)) = headeraddr->version;
1726         tmp->numread++;
1727       }
1728       found = 1;
1729       break;
1730     }
1731     tmp = tmp->next;
1732   }
1733   //Add oid for any new machine
1734   if (!found) {
1735     int tmpsize;
1736     if((ptr = pCreate(num_objs)) == NULL) {
1737       return NULL;
1738     }
1739     ptr->mid = mid;
1740     if (STATUS(headeraddr) & NEW) {
1741       ptr->oidcreated[ptr->numcreated] = OID(headeraddr);
1742       ptr->numcreated++;
1743       GETSIZE(tmpsize, headeraddr);
1744       ptr->sum_bytes += sizeof(objheader_t) + tmpsize;
1745     } else if (STATUS(headeraddr) & DIRTY) {
1746       ptr->oidmod[ptr->nummod] = OID(headeraddr);
1747       ptr->nummod++;
1748       GETSIZE(tmpsize, headeraddr);
1749       ptr->sum_bytes += sizeof(objheader_t) + tmpsize;
1750     } else {
1751       *((unsigned int *)ptr->objread)=OID(headeraddr);
1752       offset = sizeof(unsigned int);
1753       *((short *)(((char *)ptr->objread) + offset)) = headeraddr->version;
1754       ptr->numread++;
1755     }
1756     ptr->next = pile;
1757     pile = ptr;
1758   }
1759
1760   /* Clear Flags */
1761   STATUS(headeraddr) =0;
1762
1763
1764   return pile;
1765 }
1766
1767 plistnode_t *sortPiles(plistnode_t *pileptr) {
1768   plistnode_t *head, *ptr, *tail;
1769   head = pileptr;
1770   ptr = pileptr;
1771   /* Get tail pointer */
1772   while(ptr!= NULL) {
1773     tail = ptr;
1774     ptr = ptr->next;
1775   }
1776   ptr = pileptr;
1777   plistnode_t *prev = pileptr;
1778   /* Arrange local machine processing at the end of the pile list */
1779   while(ptr != NULL) {
1780     if(ptr != tail) {
1781       if(ptr->mid == myIpAddr && (prev != pileptr)) {
1782         prev->next = ptr->next;
1783         ptr->next = NULL;
1784         tail->next = ptr;
1785         return pileptr;
1786       }
1787       if((ptr->mid == myIpAddr) && (prev == pileptr)) {
1788         prev = ptr->next;
1789         ptr->next = NULL;
1790         tail->next = ptr;
1791         return prev;
1792       }
1793       prev = ptr;
1794     }
1795     ptr = ptr->next;
1796   }
1797   return pileptr;
1798 }