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