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