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