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