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