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