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