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