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