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