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