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