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