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