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