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