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