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