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