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