changes and bug fixes
[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
42 void printhex(unsigned char *, int);
43 plistnode_t *createPiles(transrecord_t *);
44
45 /*******************************
46  * Send and Recv function calls 
47  *******************************/
48 void send_data(int fd , void *buf, int buflen) {
49   char *buffer = (char *)(buf); 
50   int size = buflen;
51   int numbytes; 
52   while (size > 0) {
53     numbytes = send(fd, buffer, size, MSG_NOSIGNAL);
54     if (numbytes == -1) {
55       perror("send");
56       exit(-1);
57     }
58     buffer += numbytes;
59     size -= numbytes;
60   }
61 }
62
63 void recv_data(int fd , void *buf, int buflen) {
64   char *buffer = (char *)(buf); 
65   int size = buflen;
66   int numbytes; 
67   while (size > 0) {
68     numbytes = recv(fd, buffer, size, 0);
69     if (numbytes == -1) {
70       perror("recv");
71       exit(-1);
72     }
73     buffer += numbytes;
74     size -= numbytes;
75   }
76 }
77
78 int recv_data_errorcode(int fd , void *buf, int buflen) {
79   char *buffer = (char *)(buf); 
80   int size = buflen;
81   int numbytes; 
82   while (size > 0) {
83     numbytes = recv(fd, buffer, size, 0);
84     if (numbytes == -1) {
85       return -1;
86     }
87     buffer += numbytes;
88     size -= numbytes;
89   }
90   return 0;
91 }
92
93 void printhex(unsigned char *ptr, int numBytes) {
94   int i;
95   for (i = 0; i < numBytes; i++) {
96     if (ptr[i] < 16)
97       printf("0%x ", ptr[i]);
98     else
99       printf("%x ", ptr[i]);
100   }
101   printf("\n");
102   return;
103 }
104
105 inline int arrayLength(int *array) {
106   int i;
107   for(i=0 ;array[i] != -1; i++)
108     ;
109   return i;
110 }
111
112 inline int findmax(int *array, int arraylength) {
113   int max, i;
114   max = array[0];
115   for(i = 0; i < arraylength; i++){
116     if(array[i] > max) {
117       max = array[i];
118     }
119   }
120   return max;
121 }
122
123 /* This function is a prefetch call generated by the compiler that
124  * populates the shared primary prefetch queue*/
125 void prefetch(int ntuples, unsigned int *oids, unsigned short *endoffsets, short *arrayfields) {
126   /* Allocate for the queue node*/
127   int qnodesize = sizeof(prefetchqelem_t) + sizeof(int) + ntuples * (sizeof(unsigned short) + sizeof(unsigned int)) + endoffsets[ntuples - 1] * sizeof(short);
128   char * node= malloc(qnodesize);
129   /* Set queue node values */
130   int len = sizeof(prefetchqelem_t);
131   int top=endoffsets[ntuples-1];
132   *((int *)(node+len))=ntuples;
133   len += sizeof(int);
134   /*  int i;
135   for(i=0;i<ntuples;i++) {
136     if (oids[i]%2==0&&(oids[i]!=0)) {
137       printf("Bad oid %ld\n",oids[i]);
138     }
139     }*/
140
141   memcpy(node+len, oids, ntuples*sizeof(unsigned int));
142   memcpy(node+len+ntuples*sizeof(unsigned int), endoffsets, ntuples*sizeof(unsigned short));
143   memcpy(node+len+ntuples*(sizeof(unsigned int)+sizeof(short)), arrayfields, top*sizeof(short));
144
145   /* Lock and insert into primary prefetch queue */
146   pthread_mutex_lock(&pqueue.qlock);
147   pre_enqueue((prefetchqelem_t *)node);
148   pthread_cond_signal(&pqueue.qcond);
149   pthread_mutex_unlock(&pqueue.qlock);
150 }
151
152 /* This function starts up the transaction runtime. */
153 int dstmStartup(const char * option) {
154   pthread_t thread_Listen;
155   pthread_attr_t attr;
156   int master=option!=NULL && strcmp(option, "master")==0;
157   
158   if (processConfigFile() != 0)
159     return 0; //TODO: return error value, cause main program to exit
160 #ifdef COMPILER
161   if (!master)
162     threadcount--;
163 #endif
164   
165   //Initialize socket pool
166   transReadSockPool = createSockPool(transReadSockPool, 2*numHostsInSystem+1);
167   transPrefetchSockPool = createSockPool(transPrefetchSockPool, 2*numHostsInSystem+1);
168   
169   dstmInit();
170   transInit();
171   
172   if (master) {
173     pthread_attr_init(&attr);
174     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
175     pthread_create(&thread_Listen, &attr, dstmListen, NULL);
176     return 1;
177   } else {
178     dstmListen();
179     return 0;
180   }
181 }
182
183 //TODO Use this later
184 void *pCacheAlloc(objstr_t *store, unsigned int size) {
185   void *tmp;
186   objstr_t *ptr;
187   ptr = store;
188   int success = 0;
189   
190   while(ptr->next != NULL) {
191     /* check if store is empty */
192     if(((unsigned int)ptr->top - (unsigned int)ptr - sizeof(objstr_t) + size) <= ptr->size) {
193       tmp = ptr->top;
194       ptr->top += size;
195       success = 1;
196       return tmp;
197     } else {
198       ptr = ptr-> next;
199     }
200   }
201   
202   if(success == 0) {
203     return NULL;
204   }
205 }
206
207 /* This function initiates the prefetch thread A queue is shared
208  * between the main thread of execution and the prefetch thread to
209  * process the prefetch call Call from compiler populates the shared
210  * queue with prefetch requests while prefetch thread processes the
211  * prefetch requests */
212
213 void transInit() {
214   int t, rc;
215   int retval;
216   //Create and initialize prefetch cache structure
217   prefetchcache = objstrCreate(PREFETCH_CACHE_SIZE);
218   
219   /* Initialize attributes for mutex */
220   pthread_mutexattr_init(&prefetchcache_mutex_attr);
221   pthread_mutexattr_settype(&prefetchcache_mutex_attr, PTHREAD_MUTEX_RECURSIVE_NP);
222   
223   pthread_mutex_init(&prefetchcache_mutex, &prefetchcache_mutex_attr);
224   
225   //Create prefetch cache lookup table
226   if(prehashCreate(HASH_SIZE, LOADFACTOR)) {
227     printf("ERROR\n");
228     return; //Failure
229   }
230   
231   //Initialize primary shared queue
232   queueInit();
233   //Initialize machine pile w/prefetch oids and offsets shared queue
234   mcpileqInit();
235   
236   //Create the primary prefetch thread 
237   do {
238     retval=pthread_create(&tPrefetch, NULL, transPrefetch, NULL);
239   } while(retval!=0);
240   pthread_detach(tPrefetch);
241 }
242
243 /* This function stops the threads spawned */
244 void transExit() {
245   int t;
246   pthread_cancel(tPrefetch);
247   for(t = 0; t < NUM_THREADS; t++)
248     pthread_cancel(wthreads[t]);
249   
250   return;
251 }
252
253 /* This functions inserts randowm wait delays in the order of msec
254  * Mostly used when transaction commits retry*/
255 void randomdelay() {
256   struct timespec req;
257   time_t t;
258   
259   t = time(NULL);
260   req.tv_sec = 0;
261   req.tv_nsec = (long)(1000000 + (t%10000000)); //1-11 msec
262   nanosleep(&req, NULL);
263   return;
264 }
265
266 /* This function initializes things required in the transaction start*/
267 transrecord_t *transStart() {
268   transrecord_t *tmp = calloc(1, sizeof(transrecord_t));
269   tmp->cache = objstrCreate(1048576);
270   tmp->lookupTable = chashCreate(HASH_SIZE, LOADFACTOR);
271 #ifdef COMPILER
272   tmp->revertlist=NULL;
273 #endif
274   return tmp;
275 }
276
277 /* This function finds the location of the objects involved in a transaction
278  * and returns the pointer to the object if found in a remote location */
279 objheader_t *transRead(transrecord_t *record, unsigned int oid) {
280   unsigned int machinenumber;
281   objheader_t *tmp, *objheader;
282   objheader_t *objcopy;
283   int size, found = 0;
284   void *buf;
285   
286   if(oid == 0) {
287     return NULL;
288   }
289   
290   if((objheader = (objheader_t *)chashSearch(record->lookupTable, oid)) != NULL){
291     /* Search local transaction cache */
292 #ifdef COMPILER
293     return &objheader[1];
294 #else
295     return objheader;
296 #endif
297   } else if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
298     /* Look up in machine lookup table  and copy  into cache*/
299     GETSIZE(size, objheader);
300     size += sizeof(objheader_t);
301     objcopy = (objheader_t *) objstrAlloc(record->cache, size);
302     memcpy(objcopy, objheader, size);
303     /* Insert into cache's lookup table */
304     chashInsert(record->lookupTable, OID(objheader), objcopy); 
305 #ifdef COMPILER
306     return &objcopy[1];
307 #else
308     return objcopy;
309 #endif
310   } else if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) { 
311     /* Look up in prefetch cache */
312     GETSIZE(size, tmp);
313     size+=sizeof(objheader_t);
314     objcopy = (objheader_t *) objstrAlloc(record->cache, size);
315     memcpy(objcopy, tmp, size);
316     /* Insert into cache's lookup table */
317     chashInsert(record->lookupTable, OID(tmp), objcopy); 
318 #ifdef COMPILER
319     return &objcopy[1];
320 #else
321     return objcopy;
322 #endif
323   } else {
324     /* Get the object from the remote location */
325     if((machinenumber = lhashSearch(oid)) == 0) {
326       printf("Error: %s() No machine found for oid =% %s,%dx\n",__func__, machinenumber, __FILE__, __LINE__);
327       return NULL;
328     }
329     objcopy = getRemoteObj(record, machinenumber, oid);
330     
331     if(objcopy == NULL) {
332       printf("Error: Object not found in Remote location %s, %d\n", __FILE__, __LINE__);
333       return NULL;
334     } else {
335       
336 #ifdef COMPILER
337       return &objcopy[1];
338 #else
339       return objcopy;
340 #endif
341     }
342   }
343 }
344
345 /* This function creates objects in the transaction record */
346 objheader_t *transCreateObj(transrecord_t *record, unsigned int size) {
347   objheader_t *tmp = (objheader_t *) objstrAlloc(record->cache, (sizeof(objheader_t) + size));
348   tmp->notifylist = NULL;
349   OID(tmp) = getNewOID();
350   tmp->version = 1;
351   tmp->rcount = 1;
352   STATUS(tmp) = NEW;
353   chashInsert(record->lookupTable, OID(tmp), tmp);
354   
355 #ifdef COMPILER
356   return &tmp[1]; //want space after object header
357 #else
358   return tmp;
359 #endif
360 }
361
362 /* This function creates machine piles based on all machines involved in a
363  * transaction commit request */
364 plistnode_t *createPiles(transrecord_t *record) {
365   int i;
366   plistnode_t *pile = NULL;
367   unsigned int machinenum;
368   objheader_t *headeraddr;
369   chashlistnode_t * ptr = record->lookupTable->table;
370   /* Represents number of bins in the chash table */
371   unsigned int size = record->lookupTable->size;
372   
373   for(i = 0; i < size ; i++) {
374     chashlistnode_t * curr = &ptr[i];
375     /* Inner loop to traverse the linked list of the cache lookupTable */
376     while(curr != NULL) {
377       //if the first bin in hash table is empty
378       if(curr->key == 0)
379         break;
380       
381       if ((headeraddr = chashSearch(record->lookupTable, curr->key)) == NULL) {
382         printf("Error: No such oid %s, %d\n", __FILE__, __LINE__);
383         return NULL;
384       }
385       
386       //Get machine location for object id (and whether local or not)
387       if (STATUS(headeraddr) & NEW || (mhashSearch(curr->key) != NULL)) {
388         machinenum = myIpAddr;
389       } else if ((machinenum = lhashSearch(curr->key)) == 0) {
390         printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
391         return NULL;
392       }
393       
394       //Make machine groups
395       pile = pInsert(pile, headeraddr, machinenum, record->lookupTable->numelements);
396       curr = curr->next;
397     }
398   }
399   return pile; 
400 }
401
402 /* This function initiates the transaction commit process
403  * Spawns threads for each of the new connections with Participants 
404  * and creates new piles by calling the createPiles(), 
405  * Sends a transrequest() to each remote machines for objects found remotely 
406  * and calls handleLocalReq() to process objects found locally */
407 int transCommit(transrecord_t *record) {        
408   unsigned int tot_bytes_mod, *listmid;
409   plistnode_t *pile, *pile_ptr;
410   int i, j, rc, val;
411   int pilecount, offset, threadnum = 0, trecvcount = 0;
412   char control;
413   char transid[TID_LEN];
414   trans_req_data_t *tosend;
415   trans_commit_data_t transinfo;
416   static int newtid = 0;
417   char treplyctrl = 0, treplyretry = 0; /* keeps track of the common response that needs to be sent */
418   char localstat = 0;
419   thread_data_array_t *thread_data_array;
420   local_thread_data_array_t *ltdata;
421   
422   do { 
423     trecvcount = 0; 
424     threadnum = 0; 
425     treplyretry = 0;
426     thread_data_array = NULL;
427     ltdata = NULL;
428     
429     /* Look through all the objects in the transaction record and make piles 
430      * for each machine involved in the transaction*/
431     pile_ptr = pile = createPiles(record);
432     
433     /* Create the packet to be sent in TRANS_REQUEST */
434     
435     /* Count the number of participants */
436     pilecount = pCount(pile);
437     
438     /* Create a list of machine ids(Participants) involved in transaction       */
439     listmid = calloc(pilecount, sizeof(unsigned int));
440     pListMid(pile, listmid);
441     
442     
443     /* Initialize thread variables,
444      * Spawn a thread for each Participant involved in a transaction */
445     pthread_t thread[pilecount];
446     pthread_attr_t attr;                        
447     pthread_cond_t tcond;
448     pthread_mutex_t tlock;
449     pthread_mutex_t tlshrd;
450     
451     thread_data_array = (thread_data_array_t *) calloc(pilecount, sizeof(thread_data_array_t));
452     
453     ltdata = calloc(1, sizeof(local_thread_data_array_t));
454     
455     thread_response_t rcvd_control_msg[pilecount];      /* Shared thread array that keeps track of responses of participants */
456     
457     /* Initialize and set thread detach attribute */
458     pthread_attr_init(&attr);
459     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
460     pthread_mutex_init(&tlock, NULL);
461     pthread_cond_init(&tcond, NULL);
462     
463     /* Process each machine pile */
464     while(pile != NULL) {
465       //Create transaction id
466       newtid++;
467       tosend = calloc(1, sizeof(trans_req_data_t));
468       tosend->f.control = TRANS_REQUEST;
469       sprintf(tosend->f.trans_id, "%x_%d", pile->mid, newtid);
470       tosend->f.mcount = pilecount;
471       tosend->f.numread = pile->numread;
472       tosend->f.nummod = pile->nummod;
473       tosend->f.numcreated = pile->numcreated;
474       tosend->f.sum_bytes = pile->sum_bytes;
475       tosend->listmid = listmid;
476       tosend->objread = pile->objread;
477       tosend->oidmod = pile->oidmod;
478       tosend->oidcreated = pile->oidcreated;
479       thread_data_array[threadnum].thread_id = threadnum;
480       thread_data_array[threadnum].mid = pile->mid;
481       thread_data_array[threadnum].buffer = tosend;
482       thread_data_array[threadnum].recvmsg = rcvd_control_msg;
483       thread_data_array[threadnum].threshold = &tcond;
484       thread_data_array[threadnum].lock = &tlock;
485       thread_data_array[threadnum].count = &trecvcount;
486       thread_data_array[threadnum].replyctrl = &treplyctrl;
487       thread_data_array[threadnum].replyretry = &treplyretry;
488       thread_data_array[threadnum].rec = record;
489       /* If local do not create any extra connection */
490       if(pile->mid != myIpAddr) { /* Not local */
491         do {
492           rc = pthread_create(&thread[threadnum], &attr, transRequest, (void *) &thread_data_array[threadnum]);  
493         } while(rc!=0);
494         if(rc) {
495           perror("Error in pthread create\n");
496           pthread_cond_destroy(&tcond);
497           pthread_mutex_destroy(&tlock);
498           pDelete(pile_ptr);
499           free(listmid);
500           for (i = 0; i < threadnum; i++)
501             free(thread_data_array[i].buffer);
502           free(thread_data_array);
503           free(ltdata);
504           return 1;
505         }
506       } else { /*Local*/
507         ltdata->tdata = &thread_data_array[threadnum];
508         ltdata->transinfo = &transinfo;
509         do {
510           val = pthread_create(&thread[threadnum], &attr, handleLocalReq, (void *) ltdata);
511         } while(val!=0);
512         if(val) {
513           perror("Error in pthread create\n");
514           pthread_cond_destroy(&tcond);
515           pthread_mutex_destroy(&tlock);
516           pDelete(pile_ptr);
517           free(listmid);
518           for (i = 0; i < threadnum; i++)
519             free(thread_data_array[i].buffer);
520           free(thread_data_array);
521           free(ltdata);
522           return 1;
523         }
524       }
525       
526       threadnum++;              
527       pile = pile->next;
528     }
529     /* Free attribute and wait for the other threads */
530     pthread_attr_destroy(&attr);
531     
532     for (i = 0; i < threadnum; i++) {
533       rc = pthread_join(thread[i], NULL);
534       if(rc)
535         {
536           printf("Error: return code from pthread_join() is %d\n", rc);
537           pthread_cond_destroy(&tcond);
538           pthread_mutex_destroy(&tlock);
539           pDelete(pile_ptr);
540           free(listmid);
541           for (j = i; j < threadnum; j++) {
542             free(thread_data_array[j].buffer);
543           }
544           return 1;
545         }
546       free(thread_data_array[i].buffer);
547     }
548     
549     /* Free resources */        
550     pthread_cond_destroy(&tcond);
551     pthread_mutex_destroy(&tlock);
552     free(listmid);
553     pDelete(pile_ptr);
554     
555     /* wait a random amount of time before retrying to commit transaction*/
556     if(treplyretry) {
557       free(thread_data_array);
558       free(ltdata);
559       randomdelay();
560     }
561     
562     /* Retry trans commit procedure during soft_abort case */
563   } while (treplyretry);
564   
565   
566   if(treplyctrl == TRANS_ABORT) {
567     /* Free Resources */
568     objstrDelete(record->cache);
569     chashDelete(record->lookupTable);
570     free(record);
571     free(thread_data_array);
572     free(ltdata);
573     return TRANS_ABORT;
574   } else if(treplyctrl == TRANS_COMMIT) {
575     /* Free Resources */
576     objstrDelete(record->cache);
577     chashDelete(record->lookupTable);
578     free(record);
579     free(thread_data_array);
580     free(ltdata);
581     return 0;
582   } else {
583     //TODO Add other cases
584     printf("Error: in %s() THIS SHOULD NOT HAPPEN.....EXIT PROGRAM\n", __func__);
585     exit(-1);
586   }
587   return 0;
588 }
589
590 /* This function sends information involved in the transaction request 
591  * to participants and accepts a response from particpants.
592  * It calls decideresponse() to decide on what control message 
593  * to send next to participants and sends the message using sendResponse()*/
594 void *transRequest(void *threadarg) {
595   int sd, i, n;
596   struct sockaddr_in serv_addr;
597   thread_data_array_t *tdata;
598   objheader_t *headeraddr;
599   char control, recvcontrol;
600   char machineip[16], retval;
601   
602   tdata = (thread_data_array_t *) threadarg;
603   
604   /* Send Trans Request */
605   if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
606     perror("Error in socket for TRANS_REQUEST\n");
607     pthread_exit(NULL);
608   }
609   bzero((char*) &serv_addr, sizeof(serv_addr));
610   serv_addr.sin_family = AF_INET;
611   serv_addr.sin_port = htons(LISTEN_PORT);
612   midtoIP(tdata->mid,machineip);
613   machineip[15] = '\0';
614   serv_addr.sin_addr.s_addr = inet_addr(machineip);
615   /* Open Connection */
616   if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
617     perror("Error in connect for TRANS_REQUEST\n");
618     close(sd);
619     pthread_exit(NULL);
620   }
621   
622   /* Send bytes of data with TRANS_REQUEST control message */
623   send_data(sd, &(tdata->buffer->f), sizeof(fixed_data_t));
624   
625   /* Send list of machines involved in the transaction */
626   {
627     int size=sizeof(unsigned int)*tdata->buffer->f.mcount;
628     send_data(sd, tdata->buffer->listmid, size);
629   }
630   
631   /* Send oids and version number tuples for objects that are read */
632   {
633     int size=(sizeof(unsigned int)+sizeof(unsigned short))*tdata->buffer->f.numread;
634     send_data(sd, tdata->buffer->objread, size);
635   }
636   
637   /* Send objects that are modified */
638   for(i = 0; i < tdata->buffer->f.nummod ; i++) {
639     int size;
640     headeraddr = chashSearch(tdata->rec->lookupTable, tdata->buffer->oidmod[i]);
641     GETSIZE(size,headeraddr);
642     size+=sizeof(objheader_t);
643     send_data(sd, headeraddr, size);
644   }
645   
646   /* Read control message from Participant */
647   recv_data(sd, &control, sizeof(char));
648   recvcontrol = control;
649   
650   /* Update common data structure and increment count */
651   tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol;
652   
653   /* Lock and update count */
654   /* Thread sleeps until all messages from pariticipants are received by coordinator */
655   pthread_mutex_lock(tdata->lock);
656   
657   (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */
658   
659   /* Wake up the threads and invoke decideResponse (once) */
660   if(*(tdata->count) == tdata->buffer->f.mcount) {
661     decideResponse(tdata); 
662     pthread_cond_broadcast(tdata->threshold);
663   } else {
664     pthread_cond_wait(tdata->threshold, tdata->lock);
665   }
666   pthread_mutex_unlock(tdata->lock);
667   
668   /* Send the final response such as TRANS_COMMIT or TRANS_ABORT t
669    * to all participants in their respective socket */
670   if (sendResponse(tdata, sd) == 0) { 
671     printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__);
672     close(sd);
673     pthread_exit(NULL);
674   }
675   
676   recv_data((int)sd, &control, sizeof(char)); 
677   
678   if(control == TRANS_UNSUCESSFUL) {
679     //printf("DEBUG-> TRANS_ABORTED\n");
680   } else if(control == TRANS_SUCESSFUL) {
681     //printf("DEBUG-> TRANS_SUCCESSFUL\n");
682   } else {
683     //printf("DEBUG-> Error: Incorrect Transaction End Message %d\n", control);
684   }
685   
686   /* Close connection */
687   close(sd);
688   pthread_exit(NULL);
689 }
690
691 /* This function decides the reponse that needs to be sent to 
692  * all Participant machines after the TRANS_REQUEST protocol */
693 void decideResponse(thread_data_array_t *tdata) {
694   char control;
695   int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
696                                                                    message to send */
697   
698   for (i = 0 ; i < tdata->buffer->f.mcount; i++) {
699     control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses
700                                                written onto the shared array */
701     switch(control) {
702     default:
703       printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
704       /* treat as disagree, pass thru */
705     case TRANS_DISAGREE:
706       transdisagree++;
707       break;
708       
709     case TRANS_AGREE:
710       transagree++;
711       break;
712       
713     case TRANS_SOFT_ABORT:
714       transsoftabort++;
715       break;
716     }
717   }
718   
719   if(transdisagree > 0) {
720     /* Send Abort */
721     *(tdata->replyctrl) = TRANS_ABORT;
722     *(tdata->replyretry) = 0;
723     /* clear objects from prefetch cache */
724     for (i = 0; i < tdata->buffer->f.numread; i++)
725       prehashRemove(*((unsigned int *)(((char *)tdata->buffer->objread) + (sizeof(unsigned int) + sizeof(unsigned short))*i)));
726     for (i = 0; i < tdata->buffer->f.nummod; i++)
727       prehashRemove(tdata->buffer->oidmod[i]);
728   } else if(transagree == tdata->buffer->f.mcount){
729     /* Send Commit */
730     *(tdata->replyctrl) = TRANS_COMMIT;
731     *(tdata->replyretry) = 0;
732   } else { 
733     /* Send Abort in soft abort case followed by retry commiting transaction again*/
734     *(tdata->replyctrl) = TRANS_ABORT;
735     *(tdata->replyretry) = 1;
736   }
737   
738   return;
739 }
740
741 /* This function sends the final response to remote machines per
742  * thread in their respective socket id It returns a char that is only
743  * needed to check the correctness of execution of this function
744  * inside transRequest()*/
745
746 char sendResponse(thread_data_array_t *tdata, int sd) {
747   int n, size, sum, oidcount = 0, control;
748   char *ptr, retval = 0;
749   unsigned int *oidnotfound;
750   
751   control = *(tdata->replyctrl);
752   send_data(sd, &control, sizeof(char));
753   
754   //TODO read missing objects during object migration
755   /* If response is a soft abort due to missing objects at the
756      Participant's side */
757   
758   /* If the decided response is TRANS_ABORT */
759   if(*(tdata->replyctrl) == TRANS_ABORT) {
760     retval = TRANS_ABORT;
761   } else if(*(tdata->replyctrl) == TRANS_COMMIT) { 
762     /* If the decided response is TRANS_COMMIT */ 
763     retval = TRANS_COMMIT;
764   }
765   
766   return retval;
767 }
768
769 /* This function opens a connection, places an object read request to
770  * the remote machine, reads the control message and object if
771  * available and copies the object and its header to the local
772  * cache. */ 
773
774 void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
775   int size, val;
776   struct sockaddr_in serv_addr;
777   char machineip[16];
778   char control;
779   objheader_t *h;
780   void *objcopy = NULL;
781   
782   int sd = getSock2(transReadSockPool, mnum);
783   char readrequest[sizeof(char)+sizeof(unsigned int)];
784   readrequest[0] = READ_REQUEST;
785   *((unsigned int *)(&readrequest[1])) = oid;
786   send_data(sd, readrequest, sizeof(readrequest));
787   
788   /* Read response from the Participant */
789   recv_data(sd, &control, sizeof(char));
790   
791   if (control==OBJECT_NOT_FOUND) {
792     objcopy = NULL;
793   } else {
794     /* Read object if found into local cache */
795     recv_data(sd, &size, sizeof(int));
796     objcopy = objstrAlloc(record->cache, size);
797     recv_data(sd, objcopy, size);
798     
799     /* Insert into cache's lookup table */
800     chashInsert(record->lookupTable, oid, objcopy); 
801   }
802   
803   //    freeSock(transReadSockPool, mnum, sd);
804   
805   return objcopy;
806 }
807
808 /* This function handles the local objects involved in a transaction
809  * commiting process.  It also makes a decision if this local machine
810  * sends AGREE or DISAGREE or SOFT_ABORT to coordinator.  Note
811  * Coordinator = local machine It wakes up the other threads from
812  * remote participants that are waiting for the coordinator's decision
813  * and based on common agreement it either commits or aborts the
814  * transaction.  It also frees the memory resources */
815
816 void *handleLocalReq(void *threadarg) {
817   unsigned int *oidnotfound = NULL, *oidlocked = NULL;
818   local_thread_data_array_t *localtdata;
819   int objnotfound = 0, objlocked = 0; 
820   int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
821   int numread, i;
822   unsigned int oid;
823   unsigned short version;
824   void *mobj;
825   objheader_t *headptr;
826   
827   localtdata = (local_thread_data_array_t *) threadarg;
828   
829   /* Counters and arrays to formulate decision on control message to be sent */
830   oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
831   oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
832   
833   numread = localtdata->tdata->buffer->f.numread;
834   /* Process each oid in the machine pile/ group per thread */
835   for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) {
836     if (i < localtdata->tdata->buffer->f.numread) {
837       int incr = sizeof(unsigned int) + sizeof(unsigned short);// Offset that points to next position in the objread array
838       incr *= i;
839       oid = *((unsigned int *)(((char *)localtdata->tdata->buffer->objread) + incr));
840       version = *((unsigned short *)(((char *)localtdata->tdata->buffer->objread) + incr + sizeof(unsigned int)));
841     } else { // Objects Modified
842       int tmpsize;
843       headptr = (objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidmod[i-numread]);
844       if (headptr == NULL) {
845         printf("Error: handleLocalReq() returning NULL %s, %d\n", __FILE__, __LINE__);
846         return NULL;
847       }
848       oid = OID(headptr);
849       version = headptr->version;
850     }
851     /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
852     
853     /* Save the oids not found and number of oids not found for later use */
854     if ((mobj = mhashSearch(oid)) == NULL) { /* Obj not found */
855       /* Save the oids not found and number of oids not found for later use */
856       oidnotfound[objnotfound] = oid;
857       objnotfound++;
858     } else { /* If Obj found in machine (i.e. has not moved) */
859       /* Check if Obj is locked by any previous transaction */
860       if ((STATUS((objheader_t *)mobj) & LOCK) == LOCK) {
861         if (version == ((objheader_t *)mobj)->version) {      /* If locked then match versions */ 
862           v_matchlock++;
863         } else {/* If versions don't match ...HARD ABORT */
864           v_nomatch++;
865           /* Send TRANS_DISAGREE to Coordinator */
866           localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
867         }
868       } else {/* If Obj is not locked then lock object */
869         STATUS(((objheader_t *)mobj)) |= LOCK;
870         /* Save all object oids that are locked on this machine during this transaction request call */
871         oidlocked[objlocked] = OID(((objheader_t *)mobj));
872         objlocked++;
873         if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
874           v_matchnolock++;
875         } else { /* If versions don't match ...HARD ABORT */
876           v_nomatch++;
877           /* Send TRANS_DISAGREE to Coordinator */
878           localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
879         }
880       }
881     }
882   } // End for
883   /* Condition to send TRANS_AGREE */
884   if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
885     localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
886   }
887   /* Condition to send TRANS_SOFT_ABORT */
888   if((v_matchlock > 0 && v_nomatch == 0) || (objnotfound > 0 && v_nomatch == 0)) {
889     localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
890   }
891   
892   /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
893    * if Participant receives a TRANS_COMMIT */
894   localtdata->transinfo->objlocked = oidlocked;
895   localtdata->transinfo->objnotfound = oidnotfound;
896   localtdata->transinfo->modptr = NULL;
897   localtdata->transinfo->numlocked = objlocked;
898   localtdata->transinfo->numnotfound = objnotfound;
899   /* Lock and update count */
900   //Thread sleeps until all messages from pariticipants are received by coordinator
901   pthread_mutex_lock(localtdata->tdata->lock);
902   (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */
903   
904   /* Wake up the threads and invoke decideResponse (once) */
905   if(*(localtdata->tdata->count) == localtdata->tdata->buffer->f.mcount) {
906     decideResponse(localtdata->tdata); 
907     pthread_cond_broadcast(localtdata->tdata->threshold);
908   } else {
909     pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock);
910   }
911   pthread_mutex_unlock(localtdata->tdata->lock);
912   if(*(localtdata->tdata->replyctrl) == TRANS_ABORT){
913     if(transAbortProcess(localtdata) != 0) {
914       printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
915       pthread_exit(NULL);
916     }
917   } else if(*(localtdata->tdata->replyctrl) == TRANS_COMMIT) {
918     if(transComProcess(localtdata) != 0) {
919       printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
920       pthread_exit(NULL);
921     }
922   }
923   /* Free memory */
924   if (localtdata->transinfo->objlocked != NULL) {
925     free(localtdata->transinfo->objlocked);
926   }
927   if (localtdata->transinfo->objnotfound != NULL) {
928     free(localtdata->transinfo->objnotfound);
929   }
930   
931   pthread_exit(NULL);
932 }
933
934 /* This function completes the ABORT process if the transaction is aborting */
935 int transAbortProcess(local_thread_data_array_t  *localtdata) {
936   int i, numlocked;
937   unsigned int *objlocked;
938   void *header;
939   
940   numlocked = localtdata->transinfo->numlocked;
941   objlocked = localtdata->transinfo->objlocked;
942   
943   for (i = 0; i < numlocked; i++) {
944     if((header = mhashSearch(objlocked[i])) == NULL) {
945       printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
946       return 1;
947     }
948     STATUS(((objheader_t *)header)) &= ~(LOCK);
949   }
950   
951   return 0;
952 }
953
954 /*This function completes the COMMIT process is the transaction is commiting*/
955 int transComProcess(local_thread_data_array_t  *localtdata) {
956         objheader_t *header, *tcptr;
957         int i, nummod, tmpsize, numcreated, numlocked;
958         unsigned int *oidmod, *oidcreated, *oidlocked;
959         void *ptrcreate;
960
961         nummod = localtdata->tdata->buffer->f.nummod;
962         oidmod = localtdata->tdata->buffer->oidmod;
963         numcreated = localtdata->tdata->buffer->f.numcreated;
964         oidcreated = localtdata->tdata->buffer->oidcreated;
965         numlocked = localtdata->transinfo->numlocked;
966         oidlocked = localtdata->transinfo->objlocked;
967
968         for (i = 0; i < nummod; i++) {
969                 if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
970                         printf("Error: transComProcess() mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
971                         return 1;
972                 }
973                 /* Copy from transaction cache -> main object store */
974                 if ((tcptr = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidmod[i]))) == NULL) {
975                         printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
976                         return 1;
977                 }
978                 GETSIZE(tmpsize, header);
979                 pthread_mutex_lock(&mainobjstore_mutex);
980                 memcpy((char*)header+sizeof(objheader_t), (char *)tcptr+ sizeof(objheader_t), tmpsize);
981                 header->version += 1;
982                 if(header->notifylist != NULL) {
983                         notifyAll(&header->notifylist, OID(header), header->version);
984                 }
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 at %s, %d\n", __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         //FIXME currently all oids belong to one machine
1442         oid = oidarry[0];
1443         if((mid = lhashSearch(oid)) == 0) {
1444                 printf("Error: %s() No such machine found for oid =%x\n",__func__, oid);
1445                 return;
1446         }
1447
1448         if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1449                 perror("reqNotify():socket()");
1450                 return -1;
1451         }
1452
1453         bzero(&remoteAddr, sizeof(remoteAddr));
1454         remoteAddr.sin_family = AF_INET;
1455         remoteAddr.sin_port = htons(LISTEN_PORT);
1456         remoteAddr.sin_addr.s_addr = htonl(mid);
1457
1458         /* Generate unique threadid */
1459         threadid++;
1460
1461         /* Save threadid, numoid, oidarray, versionarray, pthread_cond_variable for later processing */
1462         if((ndata = calloc(1, sizeof(notifydata_t))) == NULL) {
1463                 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
1464                 return -1;
1465         }
1466         ndata->numoid = numoid;
1467         ndata->threadid = threadid;
1468         ndata->oidarry = oidarry;
1469         ndata->versionarry = versionarry;
1470         ndata->threadcond = threadcond;
1471         ndata->threadnotify = threadnotify;
1472         if((status = notifyhashInsert(threadid, ndata)) != 0) {
1473                 printf("reqNotify(): Insert into notify hash table not successful %s, %d\n", __FILE__, __LINE__);
1474                 free(ndata);
1475                 return -1; 
1476         }
1477         
1478         /* Send  number of oids, oidarry, version array, machine id and threadid */     
1479         if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1480                 printf("reqNotify():error %d connecting to %s:%d\n", errno,
1481                                 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1482                 free(ndata);
1483                 return -1;
1484         } else {
1485                 msg[0] = THREAD_NOTIFY_REQUEST;
1486                 *((unsigned int *)(&msg[1])) = numoid;
1487                 /* Send array of oids  */
1488                 size = sizeof(unsigned int);
1489                 {
1490                         i = 0;
1491                         while(i < numoid) {
1492                                 oid = oidarry[i];
1493                                 *((unsigned int *)(&msg[1] + size)) = oid;
1494                                 size += sizeof(unsigned int);
1495                                 i++;
1496                         }
1497                 }
1498
1499                 /* Send array of version  */
1500                 {
1501                         i = 0;
1502                         while(i < numoid) {
1503                                 version = versionarry[i];
1504                                 *((unsigned short *)(&msg[1] + size)) = version;
1505                                 size += sizeof(unsigned short);
1506                                 i++;
1507                         }
1508                 }
1509
1510                 *((unsigned int *)(&msg[1] + size)) = myIpAddr;
1511                 size += sizeof(unsigned int);
1512                 *((unsigned int *)(&msg[1] + size)) = threadid;
1513
1514                 pthread_mutex_lock(&(ndata->threadnotify));
1515                 size = 1 + numoid * (sizeof(unsigned int) + sizeof(unsigned short)) + 3 * sizeof(unsigned int);
1516                 send_data(sock, msg, size);
1517                 pthread_cond_wait(&(ndata->threadcond), &(ndata->threadnotify));
1518                 pthread_mutex_unlock(&(ndata->threadnotify));
1519         }
1520
1521         pthread_cond_destroy(&threadcond);
1522         pthread_mutex_destroy(&threadnotify);
1523         free(ndata);
1524         close(sock);
1525         return status;
1526 }
1527
1528 void threadNotify(unsigned int oid, unsigned short version, unsigned int tid) {
1529         notifydata_t *ndata;
1530         int i, objIsFound = 0, index;
1531         void *ptr;
1532
1533         //Look up the tid and call the corresponding pthread_cond_signal
1534         if((ndata = notifyhashSearch(tid)) == NULL) {
1535                 printf("threadnotify(): No such threadid is present %s, %d\n", __FILE__, __LINE__);
1536                 return;
1537         } else  {
1538                 for(i = 0; i < ndata->numoid; i++) {
1539                         if(ndata->oidarry[i] == oid){
1540                                 objIsFound = 1;
1541                                 index = i;
1542                         }
1543                 }
1544                 if(objIsFound == 0){
1545                         printf("threadNotify(): Oid not found %s, %d\n", __FILE__, __LINE__);
1546                         return;
1547                 } else {
1548                         if(version <= ndata->versionarry[index]){
1549                                 printf("threadNotify(): New version %d has not changed since last version %s, %d\n", version, __FILE__, __LINE__);
1550                                 return;
1551                         } else {
1552                                 /* Clear from prefetch cache and free thread related data structure */
1553                                 if((ptr = prehashSearch(oid)) != NULL) {
1554                                         prehashRemove(oid);
1555                                 }
1556                                 pthread_cond_signal(&(ndata->threadcond));
1557                         }
1558                 }
1559         }
1560         return;
1561 }
1562
1563 int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) {
1564         threadlist_t *ptr;
1565         unsigned int mid;
1566         struct sockaddr_in remoteAddr;
1567         char msg[1 + sizeof(unsigned short) + 2*sizeof(unsigned int)];
1568         int sock, status, size, bytesSent;
1569
1570         while(*head != NULL) {
1571                 ptr = *head;
1572                 mid = ptr->mid; 
1573                 //create a socket connection to that machine
1574                 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1575                         perror("notifyAll():socket()");
1576                         return -1;
1577                 }
1578
1579                 bzero(&remoteAddr, sizeof(remoteAddr));
1580                 remoteAddr.sin_family = AF_INET;
1581                 remoteAddr.sin_port = htons(LISTEN_PORT);
1582                 remoteAddr.sin_addr.s_addr = htonl(mid);
1583                 //send Thread Notify response and threadid to that machine
1584                 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1585                         printf("notifyAll():error %d connecting to %s:%d\n", errno,
1586                                         inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1587                         status = -1;
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 }