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