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