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