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