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