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