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