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