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