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