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