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