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