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