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