04dc63cef4a2e44d4056acacf1880460a6909391
[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       exit(-1);
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       exit(-1);
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     headeraddr = chashSearch(tdata->rec->lookupTable, tdata->buffer->oidmod[i]);
697     GETSIZE(size,headeraddr);
698     size+=sizeof(objheader_t);
699     send_data(sd, headeraddr, size);
700   }
701   
702   /* Read control message from Participant */
703   recv_data(sd, &control, sizeof(char));
704   /* Recv Objects if participant sends TRANS_DISAGREE */
705   if(control == TRANS_DISAGREE) {
706     int length;
707     recv_data(sd, &length, sizeof(int));
708     void *newAddr;
709     pthread_mutex_lock(&prefetchcache_mutex);
710     if ((newAddr = prefetchobjstrAlloc((unsigned int)length)) == NULL) {
711       printf("Error: %s() objstrAlloc error for copying into prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
712       pthread_exit(NULL);
713     }
714     pthread_mutex_unlock(&prefetchcache_mutex);
715     recv_data(sd, newAddr, length);
716     int offset = 0;
717     while(length != 0) {
718       unsigned int oidToPrefetch;
719       objheader_t * header;
720       header = (objheader_t *) (((char *)newAddr) + offset);
721       oidToPrefetch = OID(header);
722 #ifdef CHECKTA
723       char a[] = "object type";
724       TABORT8(__func__, a, TYPE(header));
725 #endif
726       int size = 0;
727       GETSIZE(size, header);
728       size += sizeof(objheader_t);
729       //make an entry in prefetch hash table
730       void *oldptr;
731       if((oldptr = prehashSearch(oidToPrefetch)) != NULL) {
732         prehashRemove(oidToPrefetch);
733         prehashInsert(oidToPrefetch, header);
734       } else {
735         prehashInsert(oidToPrefetch, header);
736       }
737       length = length - size;
738       offset += size;
739     }
740   }
741
742   recvcontrol = control;
743 #ifdef CHECKTA
744   char a[] = "mid";
745   char c[] = "status";
746   TABORT5(__func__, a, c, tdata->mid, control);
747 #endif
748   /* Update common data structure and increment count */
749   tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol;
750   
751   /* Lock and update count */
752   /* Thread sleeps until all messages from pariticipants are received by coordinator */
753   pthread_mutex_lock(tdata->lock);
754   
755   (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */
756   
757   /* Wake up the threads and invoke decideResponse (once) */
758   if(*(tdata->count) == tdata->buffer->f.mcount) {
759     decideResponse(tdata); 
760     pthread_cond_broadcast(tdata->threshold);
761   } else {
762     pthread_cond_wait(tdata->threshold, tdata->lock);
763   }
764   pthread_mutex_unlock(tdata->lock);
765
766   if(*(tdata->replyctrl) == TRANS_COMMIT) {
767     int retval;
768      /* Update prefetch cache */
769     if((retval = updatePrefetchCache(tdata)) != 0) {
770       printf("Error: %s() in updating prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
771       return;
772     }
773
774     /* Invalidate objects in other machine cache */
775     if(tdata->buffer->f.nummod > 0) {
776       if((retval = invalidateObj(tdata)) != 0) {
777         printf("Error: %s() in invalidating Objects %s, %d\n", __func__, __FILE__, __LINE__);
778         return;
779       }
780     }
781   }
782   
783   /* Send the final response such as TRANS_COMMIT or TRANS_ABORT 
784    * to all participants in their respective socket */
785   if (sendResponse(tdata, sd) == 0) { 
786     printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__);
787     pthread_exit(NULL);
788   }
789   
790   recv_data((int)sd, &control, sizeof(char)); 
791   
792   if(control == TRANS_UNSUCESSFUL) {
793     //printf("DEBUG-> TRANS_ABORTED\n");
794   } else if(control == TRANS_SUCESSFUL) {
795     //printf("DEBUG-> TRANS_SUCCESSFUL\n");
796   } else {
797     //printf("DEBUG-> Error: Incorrect Transaction End Message %d\n", control);
798   }
799   pthread_exit(NULL);
800 }
801
802 /* This function decides the reponse that needs to be sent to 
803  * all Participant machines after the TRANS_REQUEST protocol */
804 void decideResponse(thread_data_array_t *tdata) {
805   char control;
806   int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
807                                                                    message to send */
808   
809   for (i = 0 ; i < tdata->buffer->f.mcount; i++) {
810     control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses
811                                                written onto the shared array */
812     switch(control) {
813     default:
814       printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
815       /* treat as disagree, pass thru */
816     case TRANS_DISAGREE:
817       transdisagree++;
818       break;
819       
820     case TRANS_AGREE:
821       transagree++;
822       break;
823       
824     case TRANS_SOFT_ABORT:
825       transsoftabort++;
826       break;
827     }
828   }
829   
830   if(transdisagree > 0) {
831     /* Send Abort */
832     *(tdata->replyctrl) = TRANS_ABORT;
833     *(tdata->replyretry) = 0;
834     /* clear objects from prefetch cache */
835     cleanPCache(tdata);
836   } else if(transagree == tdata->buffer->f.mcount){
837     /* Send Commit */
838     *(tdata->replyctrl) = TRANS_COMMIT;
839     *(tdata->replyretry) = 0;
840   } else { 
841     /* Send Abort in soft abort case followed by retry commiting transaction again*/
842     *(tdata->replyctrl) = TRANS_ABORT;
843     *(tdata->replyretry) = 1;
844   }
845   return;
846 }
847
848 /* This function sends the final response to remote machines per
849  * thread in their respective socket id It returns a char that is only
850  * needed to check the correctness of execution of this function
851  * inside transRequest()*/
852
853 char sendResponse(thread_data_array_t *tdata, int sd) {
854   int n, size, sum, oidcount = 0, control;
855   char *ptr, retval = 0;
856   unsigned int *oidnotfound;
857   
858   control = *(tdata->replyctrl);
859   send_data(sd, &control, sizeof(char));
860   
861   //TODO read missing objects during object migration
862   /* If response is a soft abort due to missing objects at the
863      Participant's side */
864   
865   /* If the decided response is TRANS_ABORT */
866   if(*(tdata->replyctrl) == TRANS_ABORT) {
867     retval = TRANS_ABORT;
868   } else if(*(tdata->replyctrl) == TRANS_COMMIT) { 
869     /* If the decided response is TRANS_COMMIT */ 
870     retval = TRANS_COMMIT;
871   }
872   
873   return retval;
874 }
875
876 /* This function opens a connection, places an object read request to
877  * the remote machine, reads the control message and object if
878  * available and copies the object and its header to the local
879  * cache. */ 
880
881 void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
882   int size, val;
883   struct sockaddr_in serv_addr;
884   char machineip[16];
885   char control;
886   objheader_t *h;
887   void *objcopy = NULL;
888   
889   int sd = getSock2(transReadSockPool, mnum);
890   char readrequest[sizeof(char)+sizeof(unsigned int)];
891   readrequest[0] = READ_REQUEST;
892   *((unsigned int *)(&readrequest[1])) = oid;
893   send_data(sd, readrequest, sizeof(readrequest));
894   
895   /* Read response from the Participant */
896   recv_data(sd, &control, sizeof(char));
897   
898   if (control==OBJECT_NOT_FOUND) {
899     objcopy = NULL;
900   } else {
901     /* Read object if found into local cache */
902     recv_data(sd, &size, sizeof(int));
903     objcopy = objstrAlloc(record->cache, size);
904     recv_data(sd, objcopy, size);
905     /* Insert into cache's lookup table */
906     chashInsert(record->lookupTable, oid, objcopy); 
907   }
908   
909   return objcopy;
910 }
911
912 /* This function handles the local objects involved in a transaction
913  * commiting process.  It also makes a decision if this local machine
914  * sends AGREE or DISAGREE or SOFT_ABORT to coordinator.  Note
915  * Coordinator = local machine It wakes up the other threads from
916  * remote participants that are waiting for the coordinator's decision
917  * and based on common agreement it either commits or aborts the
918  * transaction.  It also frees the memory resources */
919
920 void *handleLocalReq(void *threadarg) {
921   unsigned int *oidnotfound = NULL, *oidlocked = NULL;
922   local_thread_data_array_t *localtdata;
923   int numoidnotfound = 0, numoidlocked = 0;
924   int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
925   int numread, i;
926   unsigned int oid;
927   unsigned short version;
928   void *mobj;
929   objheader_t *headptr;
930
931   localtdata = (local_thread_data_array_t *) threadarg;
932   
933   /* Counters and arrays to formulate decision on control message to be sent */
934   oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
935   oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
936   
937   numread = localtdata->tdata->buffer->f.numread;
938   /* Process each oid in the machine pile/ group per thread */
939   for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) {
940     if (i < localtdata->tdata->buffer->f.numread) {
941       int incr = sizeof(unsigned int) + sizeof(unsigned short);// Offset that points to next position in the objread array
942       incr *= i;
943       oid = *((unsigned int *)(((char *)localtdata->tdata->buffer->objread) + incr));
944       version = *((unsigned short *)(((char *)localtdata->tdata->buffer->objread) + incr + sizeof(unsigned int)));
945     } else { // Objects Modified
946       int tmpsize;
947       headptr = (objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidmod[i-numread]);
948       if (headptr == NULL) {
949         printf("Error: handleLocalReq() returning NULL %s, %d\n", __FILE__, __LINE__);
950         return NULL;
951       }
952       oid = OID(headptr);
953       version = headptr->version;
954     }
955     /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
956     
957     /* Save the oids not found and number of oids not found for later use */
958     if ((mobj = mhashSearch(oid)) == NULL) { /* Obj not found */
959       /* Save the oids not found and number of oids not found for later use */
960       oidnotfound[numoidnotfound] = oid;
961       numoidnotfound++;
962     } else { /* If Obj found in machine (i.e. has not moved) */
963       /* Check if Obj is locked by any previous transaction */
964       if (test_and_set(STATUSPTR(mobj))) {
965         if (version == ((objheader_t *)mobj)->version) {      /* If locked then match versions */ 
966           v_matchlock++;
967         } else {/* If versions don't match ...HARD ABORT */
968           v_nomatch++;
969           /* Send TRANS_DISAGREE to Coordinator */
970           localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
971 #ifdef CHECKTA
972   char a[] = "mid";
973   char b[] = "version mismatch";
974   char c[] = "object type";
975   TABORT7(__func__, b, a, c, localtdata->tdata->mid, TYPE(mobj));
976 #endif
977           break;
978         }
979       } else {
980         //we're locked
981         /* Save all object oids that are locked on this machine during this transaction request call */
982         oidlocked[numoidlocked] = OID(((objheader_t *)mobj));
983         numoidlocked++;
984         if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
985           v_matchnolock++;
986         } else { /* If versions don't match ...HARD ABORT */
987           v_nomatch++;
988           /* Send TRANS_DISAGREE to Coordinator */
989           localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
990 #ifdef CHECKTA
991   char a[] = "mid";
992   char b[] = "version mismatch";
993   char c[] = "object type";
994   TABORT7(__func__, b, a, c, localtdata->tdata->mid, TYPE(mobj));
995 #endif
996           break;
997         }
998       }
999     }
1000   } // End for
1001   /* Condition to send TRANS_AGREE */
1002   if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
1003     localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
1004   }
1005   /* Condition to send TRANS_SOFT_ABORT */
1006   if((v_matchlock > 0 && v_nomatch == 0) || (numoidnotfound > 0 && v_nomatch == 0)) {
1007 #ifdef CHECKTA
1008   char a[] = "mid";
1009   char b[] = "version mismatch";
1010   char c[] = "object type";
1011   TABORT7(__func__, b, a, c, localtdata->tdata->mid, TYPE(mobj));
1012 #endif
1013     localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
1014   }
1015   
1016   /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
1017    * if Participant receives a TRANS_COMMIT */
1018   localtdata->transinfo->objlocked = oidlocked;
1019   localtdata->transinfo->objnotfound = oidnotfound;
1020   localtdata->transinfo->modptr = NULL;
1021   localtdata->transinfo->numlocked = numoidlocked;
1022   localtdata->transinfo->numnotfound = numoidnotfound;
1023   /* Lock and update count */
1024   //Thread sleeps until all messages from pariticipants are received by coordinator
1025   pthread_mutex_lock(localtdata->tdata->lock);
1026   (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */
1027   
1028   /* Wake up the threads and invoke decideResponse (once) */
1029   if(*(localtdata->tdata->count) == localtdata->tdata->buffer->f.mcount) {
1030     decideResponse(localtdata->tdata); 
1031     pthread_cond_broadcast(localtdata->tdata->threshold);
1032   } else {
1033     pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock);
1034   }
1035   pthread_mutex_unlock(localtdata->tdata->lock);
1036   if(*(localtdata->tdata->replyctrl) == TRANS_ABORT){
1037     if(transAbortProcess(localtdata) != 0) {
1038       printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
1039       fflush(stdout);
1040       pthread_exit(NULL);
1041     }
1042   } else if(*(localtdata->tdata->replyctrl) == TRANS_COMMIT) {
1043     if(transComProcess(localtdata) != 0) {
1044       printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
1045       fflush(stdout);
1046       pthread_exit(NULL);
1047     }
1048   }
1049   /* Free memory */
1050   if (localtdata->transinfo->objlocked != NULL) {
1051     free(localtdata->transinfo->objlocked);
1052   }
1053   if (localtdata->transinfo->objnotfound != NULL) {
1054     free(localtdata->transinfo->objnotfound);
1055   }
1056   pthread_exit(NULL);
1057 }
1058
1059 /* This function completes the ABORT process if the transaction is aborting */
1060 int transAbortProcess(local_thread_data_array_t  *localtdata) {
1061   int i, numlocked;
1062   unsigned int *objlocked;
1063   void *header;
1064   
1065   numlocked = localtdata->transinfo->numlocked;
1066   objlocked = localtdata->transinfo->objlocked;
1067   
1068   for (i = 0; i < numlocked; i++) {
1069     if((header = mhashSearch(objlocked[i])) == NULL) {
1070       printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1071       return 1;
1072     }
1073     UnLock(STATUSPTR(header));
1074   }
1075
1076   return 0;
1077 }
1078
1079 /*This function completes the COMMIT process if the transaction is commiting*/
1080 int transComProcess(local_thread_data_array_t  *localtdata) {
1081   objheader_t *header, *tcptr;
1082   int i, nummod, tmpsize, numcreated, numlocked;
1083   unsigned int *oidmod, *oidcreated, *oidlocked;
1084   void *ptrcreate;
1085   
1086   nummod = localtdata->tdata->buffer->f.nummod;
1087   oidmod = localtdata->tdata->buffer->oidmod;
1088   numcreated = localtdata->tdata->buffer->f.numcreated;
1089   oidcreated = localtdata->tdata->buffer->oidcreated;
1090   numlocked = localtdata->transinfo->numlocked;
1091   oidlocked = localtdata->transinfo->objlocked;
1092   
1093   for (i = 0; i < nummod; i++) {
1094     if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
1095       printf("Error: transComProcess() mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1096       return 1;
1097     }
1098     /* Copy from transaction cache -> main object store */
1099     if ((tcptr = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidmod[i]))) == NULL) {
1100       printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1101       return 1;
1102     }
1103     GETSIZE(tmpsize, header);
1104     char *tmptcptr = (char *) tcptr;
1105     memcpy((char*)header+sizeof(objheader_t), (char *)tmptcptr+ sizeof(objheader_t), tmpsize);
1106     header->version += 1;
1107     if(header->notifylist != NULL) {
1108       notifyAll(&header->notifylist, OID(header), header->version);
1109     }
1110   }
1111   /* If object is newly created inside transaction then commit it */
1112   for (i = 0; i < numcreated; i++) {
1113     if ((header = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidcreated[i]))) == NULL) {
1114       printf("Error: transComProcess() chashSearch returned NULL for oid = %x at %s, %d\n", oidcreated[i], __FILE__, __LINE__);
1115       return 1;
1116     }
1117     GETSIZE(tmpsize, header);
1118     tmpsize += sizeof(objheader_t);
1119     pthread_mutex_lock(&mainobjstore_mutex);
1120     if ((ptrcreate = objstrAlloc(mainobjstore, tmpsize)) == NULL) {
1121       printf("Error: transComProcess() failed objstrAlloc %s, %d\n", __FILE__, __LINE__);
1122       pthread_mutex_unlock(&mainobjstore_mutex);
1123       return 1;
1124     }
1125     pthread_mutex_unlock(&mainobjstore_mutex);
1126     memcpy(ptrcreate, header, tmpsize);
1127     mhashInsert(oidcreated[i], ptrcreate);
1128     lhashInsert(oidcreated[i], myIpAddr);
1129   }
1130   /* Unlock locked objects */
1131   for(i = 0; i < numlocked; i++) {
1132     if((header = (objheader_t *) mhashSearch(oidlocked[i])) == NULL) {
1133       printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1134       return 1;
1135     }
1136     UnLock(STATUSPTR(header));
1137   }
1138   
1139   return 0;
1140 }
1141
1142 prefetchpile_t *foundLocal(char *ptr) {
1143   int siteid = *(GET_SITEID(ptr));
1144   int ntuples = *(GET_NTUPLES(ptr));
1145   unsigned int * oidarray = GET_PTR_OID(ptr);
1146   unsigned short * endoffsets = GET_PTR_EOFF(ptr, ntuples); 
1147   short * arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1148   prefetchpile_t * head=NULL;
1149   int numLocal = 0;
1150   
1151   int i;
1152   for(i=0;i<ntuples; i++) {
1153     unsigned short baseindex=(i==0)?0:endoffsets[i-1];
1154     unsigned short endindex=endoffsets[i];
1155     unsigned int oid=oidarray[i];
1156     int newbase;
1157     int machinenum;
1158     if (oid==0)
1159       continue;
1160     //Look up fields locally
1161     for(newbase=baseindex;newbase<endindex;newbase++) {
1162       if (!lookupObject(&oid, arryfields[newbase]))
1163         break;
1164       //Ended in a null pointer...
1165       if (oid==0)
1166         goto tuple;
1167     }
1168     //Entire prefetch is local
1169     if (newbase==endindex&&checkoid(oid)){
1170       numLocal++;
1171       goto tuple;
1172     }
1173     //Add to remote requests
1174     machinenum=lhashSearch(oid);
1175     insertPile(machinenum, oid, endindex-newbase, &arryfields[newbase], &head);
1176   tuple:
1177     ;
1178   }
1179
1180   /* handle dynamic prefetching */
1181   handleDynPrefetching(numLocal, ntuples, siteid);
1182   return head;
1183 }
1184
1185 int checkoid(unsigned int oid) {
1186   objheader_t *header;
1187   if ((header=mhashSearch(oid))!=NULL) {
1188     //Found on machine
1189     return 1;
1190   } else if ((header=prehashSearch(oid))!=NULL) {
1191     //Found in cache
1192     return 1;
1193   } else {
1194     return 0;
1195   }
1196 }
1197
1198 int lookupObject(unsigned int * oid, short offset) {
1199   objheader_t *header;
1200   if ((header=mhashSearch(*oid))!=NULL) {
1201     //Found on machine
1202     ;
1203   } else if ((header=prehashSearch(*oid))!=NULL) {
1204     //Found in cache
1205     ;
1206   } else {
1207     return 0;
1208   }
1209
1210   if(TYPE(header) > NUMCLASSES) {
1211     int elementsize = classsize[TYPE(header)];
1212     struct ArrayObject *ao = (struct ArrayObject *) (((char *)header) + sizeof(objheader_t));
1213     int length = ao->___length___;
1214     /* Check if array out of bounds */
1215     if(offset < 0 || offset >= length) {
1216       //if yes treat the object as found
1217       (*oid)=0;
1218       return 1;
1219     }
1220     (*oid) = *((unsigned int *)(((char *)ao) + sizeof(struct ArrayObject) + (elementsize*offset)));
1221     return 1;
1222   } else {
1223     (*oid) = *((unsigned int *)(((char *)header) + sizeof(objheader_t) + offset));
1224     return 1;
1225   }
1226 }
1227
1228
1229 /* This function is called by the thread calling transPrefetch */
1230 void *transPrefetch(void *t) {
1231   while(1) {
1232     /* lock mutex of primary prefetch queue */
1233     void *node=gettail();
1234     /* Check if the tuples are found locally, if yes then reduce them further*/ 
1235     /* and group requests by remote machine ids by calling the makePreGroups() */
1236     prefetchpile_t *pilehead = foundLocal(node);
1237
1238     if (pilehead!=NULL) {
1239       // Get sock from shared pool 
1240       int sd = getSock2(transPrefetchSockPool, pilehead->mid);
1241       
1242       /* Send  Prefetch Request */
1243       prefetchpile_t *ptr = pilehead;
1244       while(ptr != NULL) {
1245         sendPrefetchReq(ptr, sd);
1246         ptr = ptr->next; 
1247       }
1248       
1249       /* Release socket */
1250       //        freeSock(transPrefetchSockPool, pilehead->mid, sd);
1251       
1252       /* Deallocated pilehead */
1253       mcdealloc(pilehead);
1254     }
1255     // Deallocate the prefetch queue pile node
1256     inctail();
1257   }
1258 }
1259
1260 void sendPrefetchReqnew(prefetchpile_t *mcpilenode, int sd) {
1261   objpile_t *tmp;
1262   
1263   int size=sizeof(char)+sizeof(int);
1264   for(tmp=mcpilenode->objpiles;tmp!=NULL;tmp=tmp->next) {
1265     size += sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1266   }
1267   
1268   char buft[size];
1269   char *buf=buft;
1270   *buf=TRANS_PREFETCH;
1271   buf+=sizeof(char);
1272   
1273   for(tmp=mcpilenode->objpiles;tmp!=NULL;tmp=tmp->next) {
1274     int len = sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1275     *((int*)buf)=len;
1276     buf+=sizeof(int);
1277     *((unsigned int *)buf)=tmp->oid;
1278     buf+=sizeof(unsigned int);
1279     *((unsigned int *)(buf)) = myIpAddr; 
1280     buf+=sizeof(unsigned int);
1281     memcpy(buf, tmp->offset, tmp->numoffset*sizeof(short));
1282     buf+=tmp->numoffset*sizeof(short);
1283   }
1284   *((int *)buf)=-1;
1285   send_data(sd, buft, size);
1286   return;
1287 }
1288
1289 void sendPrefetchReq(prefetchpile_t *mcpilenode, int sd) {
1290   int len, endpair;
1291   char control;
1292   objpile_t *tmp;
1293   
1294   /* Send TRANS_PREFETCH control message */
1295   control = TRANS_PREFETCH;
1296   send_data(sd, &control, sizeof(char));
1297   
1298   /* Send Oids and offsets in pairs */
1299   tmp = mcpilenode->objpiles;
1300   while(tmp != NULL) {
1301     len = sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1302     char oidnoffset[len];
1303     char *buf=oidnoffset;
1304     *((int*)buf) = tmp->numoffset;
1305     buf+=sizeof(int);
1306     *((unsigned int *)buf) = tmp->oid;
1307     buf+=sizeof(unsigned int);
1308     *((unsigned int *)buf) = myIpAddr; 
1309     buf += sizeof(unsigned int);
1310     memcpy(buf, tmp->offset, (tmp->numoffset)*sizeof(short));
1311     send_data(sd, oidnoffset, len);
1312     tmp = tmp->next;
1313   }
1314   
1315   /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
1316   endpair = -1;
1317   send_data(sd, &endpair, sizeof(int));
1318   
1319   return;
1320 }
1321
1322 int getPrefetchResponse(int sd) {
1323   int length = 0, size = 0;
1324   char control;
1325   unsigned int oid;
1326   void *modptr, *oldptr;
1327   
1328   recv_data((int)sd, &length, sizeof(int)); 
1329   size = length - sizeof(int);
1330   char recvbuffer[size];
1331
1332   recv_data((int)sd, recvbuffer, size);
1333   control = *((char *) recvbuffer);
1334   if(control == OBJECT_FOUND) {
1335     oid = *((unsigned int *)(recvbuffer + sizeof(char)));
1336     size = size - (sizeof(char) + sizeof(unsigned int));
1337     pthread_mutex_lock(&prefetchcache_mutex);
1338     if ((modptr = prefetchobjstrAlloc(size)) == NULL) {
1339       printf("Error: objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
1340       pthread_mutex_unlock(&prefetchcache_mutex);
1341       return -1;
1342     }
1343     pthread_mutex_unlock(&prefetchcache_mutex);
1344     memcpy(modptr, recvbuffer + sizeof(char) + sizeof(unsigned int), size);
1345     STATUS(modptr)=0;
1346
1347     /* Insert the oid and its address into the prefetch hash lookup table */
1348     /* Do a version comparison if the oid exists */
1349     if((oldptr = prehashSearch(oid)) != NULL) {
1350       /* If older version then update with new object ptr */
1351       if(((objheader_t *)oldptr)->version <= ((objheader_t *)modptr)->version) {
1352         prehashRemove(oid);
1353         prehashInsert(oid, modptr);
1354       }
1355     } else {/* Else add the object ptr to hash table*/
1356       prehashInsert(oid, modptr);
1357     }
1358     /* Lock the Prefetch Cache look up table*/
1359     pthread_mutex_lock(&pflookup.lock);
1360     /* Broadcast signal on prefetch cache condition variable */ 
1361     pthread_cond_broadcast(&pflookup.cond);
1362     /* Unlock the Prefetch Cache look up table*/
1363     pthread_mutex_unlock(&pflookup.lock);
1364   } else if(control == OBJECT_NOT_FOUND) {
1365     oid = *((unsigned int *)(recvbuffer + sizeof(char)));
1366     /* TODO: For each object not found query DHT for new location and retrieve the object */
1367     /* Throw an error */
1368     //printf("OBJECT %x NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n", oid);
1369     //    exit(-1);
1370   } else {
1371     printf("Error: in decoding the control value %d, %s, %d\n",control, __FILE__, __LINE__);
1372   }
1373   
1374   return 0;
1375 }
1376
1377 unsigned short getObjType(unsigned int oid) {
1378   objheader_t *objheader;
1379   unsigned short numoffset[] ={0};
1380   short fieldoffset[] ={};
1381   
1382   if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL) {
1383       if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL) {
1384         prefetch(0, 1, &oid, numoffset, fieldoffset);
1385         pthread_mutex_lock(&pflookup.lock);
1386         while ((objheader = (objheader_t *) prehashSearch(oid)) == NULL) {
1387           pthread_cond_wait(&pflookup.cond, &pflookup.lock);
1388         }
1389         pthread_mutex_unlock(&pflookup.lock);
1390       }
1391   }
1392   
1393   return TYPE(objheader);
1394 }
1395
1396 int startRemoteThread(unsigned int oid, unsigned int mid)
1397 {
1398         int sock;
1399         struct sockaddr_in remoteAddr;
1400         char msg[1 + sizeof(unsigned int)];
1401         int bytesSent;
1402         int status;
1403
1404         if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
1405         {
1406                 perror("startRemoteThread():socket()");
1407                 return -1;
1408         }
1409
1410         bzero(&remoteAddr, sizeof(remoteAddr));
1411         remoteAddr.sin_family = AF_INET;
1412         remoteAddr.sin_port = htons(LISTEN_PORT);
1413         remoteAddr.sin_addr.s_addr = htonl(mid);
1414         
1415         if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0)
1416         {
1417                 printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
1418                         inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1419                 status = -1;
1420         }
1421         else
1422         {
1423                 msg[0] = START_REMOTE_THREAD;
1424         *((unsigned int *) &msg[1]) = oid;
1425                 send_data(sock, msg, 1 + sizeof(unsigned int));
1426         }
1427
1428         close(sock);
1429         return status;
1430 }
1431
1432 //TODO: when reusing oids, make sure they are not already in use!
1433 static unsigned int id = 0xFFFFFFFF;
1434 unsigned int getNewOID(void) {
1435         id += 2;
1436         if (id > oidMax || id < oidMin)
1437         {
1438                 id = (oidMin | 1);
1439         }
1440         return id;
1441 }
1442
1443 int processConfigFile()
1444 {
1445         FILE *configFile;
1446         const int maxLineLength = 200;
1447         char lineBuffer[maxLineLength];
1448         char *token;
1449         const char *delimiters = " \t\n";
1450         char *commentBegin;
1451         in_addr_t tmpAddr;
1452         
1453         configFile = fopen(CONFIG_FILENAME, "r");
1454         if (configFile == NULL)
1455         {
1456                 printf("error opening %s:\n", CONFIG_FILENAME);
1457                 perror("");
1458                 return -1;
1459         }
1460
1461         numHostsInSystem = 0;
1462         sizeOfHostArray = 8;
1463         hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
1464         
1465         while(fgets(lineBuffer, maxLineLength, configFile) != NULL)
1466         {
1467                 commentBegin = strchr(lineBuffer, '#');
1468                 if (commentBegin != NULL)
1469                         *commentBegin = '\0';
1470                 token = strtok(lineBuffer, delimiters);
1471                 while (token != NULL)
1472                 {
1473                         tmpAddr = inet_addr(token);
1474                         if ((int)tmpAddr == -1)
1475                         {
1476                                 printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
1477                                 fclose(configFile);
1478                                 return -1;
1479                         }
1480                         else
1481                                 addHost(htonl(tmpAddr));
1482                         token = strtok(NULL, delimiters);
1483                 }
1484         }
1485
1486         fclose(configFile);
1487         
1488         if (numHostsInSystem < 1)
1489         {
1490                 printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
1491                 return -1;
1492         }
1493 #ifdef MAC
1494         myIpAddr = getMyIpAddr("en1");
1495 #else
1496         myIpAddr = getMyIpAddr("eth0");
1497 #endif
1498
1499 #ifdef CHECKTA
1500     printf("My ip address = %x", myIpAddr);
1501 #endif
1502         myIndexInHostArray = findHost(myIpAddr);
1503         if (myIndexInHostArray == -1)
1504         {
1505                 printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
1506                 return -1;
1507         }
1508         oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
1509         oidMin = oidsPerBlock * myIndexInHostArray;
1510         if (myIndexInHostArray == numHostsInSystem - 1)
1511                 oidMax = 0xFFFFFFFF;
1512         else
1513                 oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
1514
1515         return 0;
1516 }
1517
1518 void addHost(unsigned int hostIp)
1519 {
1520         unsigned int *tmpArray;
1521
1522         if (findHost(hostIp) != -1)
1523                 return;
1524
1525         if (numHostsInSystem == sizeOfHostArray)
1526         {
1527                 tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
1528                 memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
1529                 free(hostIpAddrs);
1530                 hostIpAddrs = tmpArray;
1531         }
1532
1533         hostIpAddrs[numHostsInSystem++] = hostIp;
1534
1535         return;
1536 }
1537
1538 int findHost(unsigned int hostIp)
1539 {
1540         int i;
1541         for (i = 0; i < numHostsInSystem; i++)
1542                 if (hostIpAddrs[i] == hostIp)
1543                         return i;
1544
1545         //not found
1546         return -1;
1547 }
1548
1549 /* This function sends notification request per thread waiting on object(s) whose version 
1550  * changes */
1551 int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int numoid) {
1552   int sock,i;
1553   objheader_t *objheader;
1554   struct sockaddr_in remoteAddr;
1555   char msg[1 + numoid * (sizeof(unsigned short) + sizeof(unsigned int)) +  3 * sizeof(unsigned int)];
1556   char *ptr;
1557   int bytesSent;
1558   int status, size;
1559   unsigned short version;
1560   unsigned int oid,mid;
1561   static unsigned int threadid = 0;
1562   pthread_mutex_t threadnotify = PTHREAD_MUTEX_INITIALIZER; //Lock and condition var for threadjoin and notification
1563   pthread_cond_t threadcond = PTHREAD_COND_INITIALIZER;
1564   notifydata_t *ndata;
1565   
1566   oid = oidarry[0];
1567   if((mid = lhashSearch(oid)) == 0) {
1568     printf("Error: %s() No such machine found for oid =%x\n",__func__, oid);
1569     return;
1570   }
1571   
1572   if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1573     perror("reqNotify():socket()");
1574     return -1;
1575   }
1576   
1577   bzero(&remoteAddr, sizeof(remoteAddr));
1578   remoteAddr.sin_family = AF_INET;
1579   remoteAddr.sin_port = htons(LISTEN_PORT);
1580   remoteAddr.sin_addr.s_addr = htonl(mid);
1581   
1582   /* Generate unique threadid */
1583   threadid++;
1584   
1585   /* Save threadid, numoid, oidarray, versionarray, pthread_cond_variable for later processing */
1586   if((ndata = calloc(1, sizeof(notifydata_t))) == NULL) {
1587     printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
1588     return -1;
1589   }
1590   ndata->numoid = numoid;
1591   ndata->threadid = threadid;
1592   ndata->oidarry = oidarry;
1593   ndata->versionarry = versionarry;
1594   ndata->threadcond = threadcond;
1595   ndata->threadnotify = threadnotify;
1596   if((status = notifyhashInsert(threadid, ndata)) != 0) {
1597     printf("reqNotify(): Insert into notify hash table not successful %s, %d\n", __FILE__, __LINE__);
1598     free(ndata);
1599     return -1; 
1600   }
1601   
1602   /* Send  number of oids, oidarry, version array, machine id and threadid */   
1603   if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1604     printf("reqNotify():error %d connecting to %s:%d\n", errno,
1605            inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1606     free(ndata);
1607     return -1;
1608   } else {
1609     msg[0] = THREAD_NOTIFY_REQUEST;
1610     *((unsigned int *)(&msg[1])) = numoid;
1611     /* Send array of oids  */
1612     size = sizeof(unsigned int);
1613     {
1614       i = 0;
1615       while(i < numoid) {
1616         oid = oidarry[i];
1617         *((unsigned int *)(&msg[1] + size)) = oid;
1618         size += sizeof(unsigned int);
1619         i++;
1620       }
1621     }
1622     
1623     /* Send array of version  */
1624     {
1625       i = 0;
1626       while(i < numoid) {
1627         version = versionarry[i];
1628         *((unsigned short *)(&msg[1] + size)) = version;
1629         size += sizeof(unsigned short);
1630         i++;
1631       }
1632     }
1633     
1634     *((unsigned int *)(&msg[1] + size)) = myIpAddr;
1635     size += sizeof(unsigned int);
1636     *((unsigned int *)(&msg[1] + size)) = threadid;
1637     pthread_mutex_lock(&(ndata->threadnotify));
1638     size = 1 + numoid * (sizeof(unsigned int) + sizeof(unsigned short)) + 3 * sizeof(unsigned int);
1639     send_data(sock, msg, size);
1640     pthread_cond_wait(&(ndata->threadcond), &(ndata->threadnotify));
1641     pthread_mutex_unlock(&(ndata->threadnotify));
1642   }
1643   
1644   pthread_cond_destroy(&threadcond);
1645   pthread_mutex_destroy(&threadnotify);
1646   free(ndata);
1647   close(sock);
1648   return status;
1649 }
1650
1651 void threadNotify(unsigned int oid, unsigned short version, unsigned int tid) {
1652         notifydata_t *ndata;
1653         int i, objIsFound = 0, index;
1654         void *ptr;
1655
1656         //Look up the tid and call the corresponding pthread_cond_signal
1657         if((ndata = notifyhashSearch(tid)) == NULL) {
1658                 printf("threadnotify(): No such threadid is present %s, %d\n", __FILE__, __LINE__);
1659                 return;
1660         } else  {
1661                 for(i = 0; i < ndata->numoid; i++) {
1662                         if(ndata->oidarry[i] == oid){
1663                                 objIsFound = 1;
1664                                 index = i;
1665                         }
1666                 }
1667                 if(objIsFound == 0){
1668                         printf("threadNotify(): Oid not found %s, %d\n", __FILE__, __LINE__);
1669                         return;
1670                 } else {
1671                         if(version <= ndata->versionarry[index]){
1672                                 printf("threadNotify(): New version %d has not changed since last version %s, %d\n", version, __FILE__, __LINE__);
1673                                 return;
1674                         } else {
1675                                 /* Clear from prefetch cache and free thread related data structure */
1676                                 if((ptr = prehashSearch(oid)) != NULL) {
1677                                         prehashRemove(oid);
1678                                 }
1679                                 pthread_cond_signal(&(ndata->threadcond));
1680                         }
1681                 }
1682         }
1683         return;
1684 }
1685
1686 int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) {
1687   threadlist_t *ptr;
1688   unsigned int mid;
1689   struct sockaddr_in remoteAddr;
1690   char msg[1 + sizeof(unsigned short) + 2*sizeof(unsigned int)];
1691   int sock, status, size, bytesSent;
1692   
1693   while(*head != NULL) {
1694     ptr = *head;
1695     mid = ptr->mid; 
1696     //create a socket connection to that machine
1697     if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1698       perror("notifyAll():socket()");
1699       return -1;
1700     }
1701     
1702     bzero(&remoteAddr, sizeof(remoteAddr));
1703     remoteAddr.sin_family = AF_INET;
1704     remoteAddr.sin_port = htons(LISTEN_PORT);
1705     remoteAddr.sin_addr.s_addr = htonl(mid);
1706     //send Thread Notify response and threadid to that machine
1707     if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1708       printf("notifyAll():error %d connecting to %s:%d\n", errno,
1709              inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1710       fflush(stdout);
1711       status = -1;
1712     } else {
1713       bzero(msg, (1+sizeof(unsigned short) + 2*sizeof(unsigned int)));
1714       msg[0] = THREAD_NOTIFY_RESPONSE;
1715       *((unsigned int *)&msg[1]) = oid;
1716       size = sizeof(unsigned int);
1717       *((unsigned short *)(&msg[1]+ size)) = version;
1718       size+= sizeof(unsigned short);
1719       *((unsigned int *)(&msg[1]+ size)) = ptr->threadid;
1720       
1721       size = 1 + 2*sizeof(unsigned int) + sizeof(unsigned short);
1722       send_data(sock, msg, size);
1723     }
1724     //close socket
1725     close(sock);
1726     // Update head
1727     *head = ptr->next;
1728     free(ptr);
1729   }
1730   return status;
1731 }
1732
1733 void transAbort(transrecord_t *trans) {
1734   objstrDelete(trans->cache);
1735   chashDelete(trans->lookupTable);
1736   free(trans);
1737 }
1738
1739 /* This function inserts necessary information into 
1740  * a machine pile data structure */
1741 plistnode_t *pInsert(plistnode_t *pile, objheader_t *headeraddr, unsigned int mid, int num_objs) {
1742   plistnode_t *ptr, *tmp;
1743   int found = 0, offset = 0;
1744   
1745   tmp = pile;
1746   //Add oid into a machine that is already present in the pile linked list structure
1747   while(tmp != NULL) {
1748     if (tmp->mid == mid) {
1749       int tmpsize;
1750       
1751       if (STATUS(headeraddr) & NEW) {
1752         tmp->oidcreated[tmp->numcreated] = OID(headeraddr);
1753         tmp->numcreated++;
1754         GETSIZE(tmpsize, headeraddr);
1755         tmp->sum_bytes += sizeof(objheader_t) + tmpsize;
1756       }else if (STATUS(headeraddr) & DIRTY) {
1757         tmp->oidmod[tmp->nummod] = OID(headeraddr);
1758         tmp->nummod++;
1759         GETSIZE(tmpsize, headeraddr);
1760         tmp->sum_bytes += sizeof(objheader_t) + tmpsize;
1761       } else {
1762         offset = (sizeof(unsigned int) + sizeof(short)) * tmp->numread;
1763         *((unsigned int *)(((char *)tmp->objread) + offset))=OID(headeraddr);
1764         offset += sizeof(unsigned int);
1765         *((short *)(((char *)tmp->objread) + offset)) = headeraddr->version;
1766         tmp->numread ++;
1767       }
1768       found = 1;
1769       break;
1770     }
1771     tmp = tmp->next;
1772   }
1773   //Add oid for any new machine 
1774   if (!found) {
1775     int tmpsize;
1776     if((ptr = pCreate(num_objs)) == NULL) {
1777       return NULL;
1778     }
1779     ptr->mid = mid;
1780     if (STATUS(headeraddr) & NEW) {
1781       ptr->oidcreated[ptr->numcreated] = OID(headeraddr);
1782       ptr->numcreated ++;
1783       GETSIZE(tmpsize, headeraddr);
1784       ptr->sum_bytes += sizeof(objheader_t) + tmpsize;
1785     } else if (STATUS(headeraddr) & DIRTY) {
1786       ptr->oidmod[ptr->nummod] = OID(headeraddr);
1787       ptr->nummod ++;
1788       GETSIZE(tmpsize, headeraddr);
1789       ptr->sum_bytes += sizeof(objheader_t) + tmpsize;
1790     } else {
1791       *((unsigned int *)ptr->objread)=OID(headeraddr);
1792       offset = sizeof(unsigned int);
1793       *((short *)(((char *)ptr->objread) + offset)) = headeraddr->version;
1794       ptr->numread ++;
1795     }
1796     ptr->next = pile;
1797     pile = ptr;
1798   }
1799   
1800   /* Clear Flags */
1801   STATUS(headeraddr) =0;
1802   
1803   return pile;
1804 }