modifies getTypeObj()
[IRC.git] / Robust / src / Runtime / DSTM / interface_recovery / trans.c
1 #include "dstm.h"
2 #include "ip.h"
3 #include "machinepile.h"
4 #include "mlookup.h"
5 #include "llookup.h"
6 #include "plookup.h"
7 #include "prelookup.h"
8 #include "threadnotify.h"
9 #include "queue.h"
10 #include "addUdpEnhance.h"
11 #include "addPrefetchEnhance.h"
12 #include "gCollect.h"
13 #include "dsmlock.h"
14 #include "prefetch.h"
15 #ifdef COMPILER
16 #include "thread.h"
17 #endif
18 #ifdef ABORTREADERS
19 #include "abortreaders.h"
20 #endif
21 #include "trans.h"
22
23 #ifdef RECOVERY
24 #include <unistd.h>
25 #include <signal.h>
26 #include <sys/select.h>
27 #include "tlookup.h"
28 #endif
29
30 #define NUM_THREADS 1
31 #define CONFIG_FILENAME "dstm.conf"
32
33 /* Thread transaction variables */
34
35 __thread objstr_t *t_cache;
36 __thread struct ___Object___ *revertlist;
37 #ifdef ABORTREADERS
38 __thread int t_abort;
39 __thread jmp_buf aborttrans;
40 #endif
41
42 /* Global Variables */
43 extern int classsize[];
44 pfcstats_t *evalPrefetch;
45 extern int numprefetchsites; //Global variable containing number of prefetch sites
46 extern pthread_mutex_t mainobjstore_mutex; // Mutex to lock main Object store
47 pthread_mutex_t prefetchcache_mutex; // Mutex to lock Prefetch Cache
48 pthread_mutexattr_t prefetchcache_mutex_attr; /* Attribute for lock to make it a recursive lock */
49 extern prehashtable_t pflookup; //Global Prefetch cache's lookup table
50 pthread_t wthreads[NUM_THREADS]; //Worker threads for working on the prefetch queue
51 pthread_t tPrefetch;            /* Primary Prefetch thread that processes the prefetch queue */
52 extern objstr_t *mainobjstore;
53 unsigned int myIpAddr;
54 unsigned int *hostIpAddrs;
55 int sizeOfHostArray;
56 int numHostsInSystem;
57 int myIndexInHostArray;
58 unsigned int oidsPerBlock;
59 unsigned int oidMin;
60 unsigned int oidMax;
61
62 sockPoolHashTable_t *transReadSockPool;
63 sockPoolHashTable_t *transPrefetchSockPool;
64 sockPoolHashTable_t *transRequestSockPool;
65 pthread_mutex_t notifymutex;
66 pthread_mutex_t atomicObjLock;
67
68 /***********************************
69  * Global Variables for statistics
70  **********************************/
71 int numTransCommit = 0;
72 int numTransAbort = 0;
73 int nchashSearch = 0;
74 int nmhashSearch = 0;
75 int nprehashSearch = 0;
76 int nRemoteSend = 0;
77 int nSoftAbort = 0;
78 int bytesSent = 0;
79 int bytesRecv = 0;
80 int totalObjSize = 0;
81 int sendRemoteReq = 0;
82 int getResponse = 0;
83
84 #ifdef RECOVERY
85 /***********************************
86  * Global variables for Duplication
87  ***********************************/
88 int *liveHosts;
89 int numLiveHostsInSystem;       
90 unsigned int *locateObjHosts;
91
92
93 /* variables to clear dead threads */
94 int waitThreadMid;            
95 unsigned int waitThreadID; 
96
97 int transRetryFlag;
98 unsigned int transIDMin;
99 unsigned int transIDMax;
100
101 char ip[16];      // for debugging purpose
102
103 /******************************
104  * Global variables for Paxos
105  ******************************/
106 int n_a;
107 unsigned int v_a;
108 int n_h;
109 int my_n;
110 unsigned int leader;
111 unsigned int origleader;
112 unsigned int temp_v_a;
113 int paxosRound;
114 #endif
115
116 void printhex(unsigned char *, int);
117 plistnode_t *createPiles();
118 plistnode_t *sortPiles(plistnode_t *pileptr);
119
120 #ifdef LOGEVENTS
121 char bigarray[16*1024*1024];
122 int bigindex=0;
123 #define LOGEVENT(x) { \
124     int tmp=bigindex++;         \
125     bigarray[tmp]=x;          \
126   }
127 #else
128 #define LOGEVENT(x)
129 #endif
130
131 /*******************************
132 * Send and Recv function calls
133 *******************************/
134 int send_data(int fd, void *buf, int buflen) {
135   char *buffer = (char *)(buf);
136   int size = buflen;
137   int numbytes;
138
139   while (size > 0) {
140 #ifdef GDBDEBUG
141 GDBSEND1:
142 #endif
143     numbytes = send(fd, buffer, size, 0);
144
145     if( numbytes > 0) {
146       bytesSent += numbytes;
147       size -= numbytes;
148     }
149 #ifdef RECOVERY
150     else if( numbytes < 0) {    
151       // Receive returned an error.
152       // Analyze underlying cause
153 #ifdef DEBUG
154       printf("%s -> fd : %d errno = %d %s\n",__func__, fd, errno,strerror(errno));
155       fflush(stdout);
156 #endif
157       if(errno == ECONNRESET || errno == EAGAIN || errno == EWOULDBLOCK) {
158         // machine has failed
159         //
160         // if we see EAGAIN w/o failures, we should record the time
161         // when we start send and finish send see if it is longer
162         // than our threshold
163         //
164 #ifdef DEBUG
165         printf("%s -> EAGAIN : %s\n",__func__,(errno == EAGAIN)?"TRUE":"FALSE");
166 #endif
167         return -1;
168       } else {
169 #ifdef GDBDEBUG
170         if(errno == 4)
171           goto GDBSEND1;    
172 #endif
173
174 #ifdef DEBUG
175         printf("%s -> Unexpected ERROR!\n",__func__);
176 #endif
177         return -2;
178       }
179     }
180     else{
181       // Case : numbytes == 0
182       // // machine has failed -- this case probably doesn't occur in reality
183 #ifdef DEBUG
184       printf("%s -> SHOULD NOT BE HERE\n",__func__);
185 #endif
186       return -1;
187     }
188 #else
189     if(numbytes == -1) {
190       perror("send");
191       exit(0);
192     }
193 #endif
194   } // close while loop
195 #ifdef DEBUG
196   printf("%s-> Exiting\n", __func__);
197 #endif
198   return 0; // completed sending data
199 }
200
201 //Returns negative value if receive cannot be completed because of
202 //timeout or machine failure
203
204 int recv_data(int fd, void *buf, int buflen) {
205   char *buffer = (char *)(buf);
206   int size = buflen;
207   int numbytes;
208   int trycounter = 0;
209   
210   while (size > 0) {
211 #ifdef GDBDEBUG
212 GDBRECV1:
213 #endif
214     numbytes = recv(fd, buffer, size, 0);
215     
216     if (numbytes>0) {
217       buffer += numbytes;
218       size -= numbytes;
219     }
220 #ifdef RECOVERY
221     else if (numbytes<0){ 
222       //Receive returned an error.
223       //Analyze underlying cause
224 #ifdef DEBUG
225       printf("%s-> fd : %d errno = %d %s\n", __func__, fd, errno, strerror(errno));     
226 #endif
227       if(errno == ECONNRESET || errno == EAGAIN || errno == EWOULDBLOCK) {
228         //machine has failed
229         //if we see EAGAIN w/o failures, we should record the time
230         //when we start read and finish read and see if it is longer
231         //than our threshold
232 #ifdef DEBUG
233         printf("%s -> EAGAIN : %s\n",__func__,(errno == EAGAIN)?"TRUE":"FALSE");
234 #endif
235         if(errno == EAGAIN) {
236           if(trycounter < 5) {
237 #ifndef DEBUG
238             printf("%s -> TRYcounter increases\n",__func__);
239 #endif
240             trycounter++;
241             continue;
242           }
243           else
244             return -1;
245         }
246         return -1;
247       } else {
248 #ifdef GDBDEBUG
249         if(errno == 4)
250           goto GDBRECV1;
251 #endif
252
253 #ifdef DEBUG
254         printf("%s -> Unexpected ERROR!\n",__func__);
255         printf("%s-> errno = %d %s\n", __func__, errno, strerror(errno));
256 #endif
257         return -2;
258       }
259     } else {
260       //Case: numbytes==0
261       //machine has failed -- this case probably doesn't occur in reality
262       //
263 #ifdef DEBUG
264       printf("%s -> SHOULD NOT BE HERE\n",__func__);
265 #endif
266       return -1;
267     }
268 #else
269     if( numbytes == -1) {
270       perror("recv");
271       exit(0);
272     }
273 #endif
274   } //close while loop
275 #ifdef DEBUG
276   printf("%s -> fd = %d Exiting\n",__func__,fd);
277 #endif
278   return 0; // got all the data
279 }
280
281 int recv_data_errorcode(int fd, void *buf, int buflen) {
282 #ifdef DEBUG
283   printf("%s-> Start; fd:%d, buflen:%d\n", __func__, fd, buflen);
284 #endif
285   char *buffer = (char *)(buf);
286   int size = buflen;
287   int numbytes;
288   while (size > 0) {
289     numbytes = recv(fd, buffer, size, 0);
290 #ifdef DEBUG
291     printf("%s-> numbytes: %d\n", __func__, numbytes);
292 #endif
293     if (numbytes==0)
294       return 0;
295     else if (numbytes == -1) {
296       printf("%s -> ERROR NUMBER = %d %s\n",__func__,errno,strerror(errno));
297       perror("recv_data_errorcode");
298       return -1;
299     }
300     buffer += numbytes;
301     size -= numbytes;
302   }
303 #ifdef DEBUG
304   printf("%s-> Exiting\n", __func__);
305 #endif
306   return 1;
307 }
308
309 void printhex(unsigned char *ptr, int numBytes) {
310   int i;
311   for (i = 0; i < numBytes; i++) {
312     if (ptr[i] < 16)
313       printf("0%x ", ptr[i]);
314     else
315       printf("%x ", ptr[i]);
316   }
317   printf("\n");
318   return;
319 }
320
321 inline int arrayLength(int *array) {
322   int i;
323   for(i=0 ; array[i] != -1; i++)
324     ;
325   return i;
326 }
327
328 inline int findmax(int *array, int arraylength) {
329   int max, i;
330   max = array[0];
331   for(i = 0; i < arraylength; i++) {
332     if(array[i] > max) {
333       max = array[i];
334     }
335   }
336   return max;
337 }
338
339 #ifdef RECOVERY
340 char* midtoIPString(unsigned int mid){
341                 midtoIP(mid, ip);
342                 return ip;
343 }
344 #endif
345 /* This function is a prefetch call generated by the compiler that
346  * populates the shared primary prefetch queue*/
347 void prefetch(int siteid, int ntuples, unsigned int *oids, unsigned short *endoffsets, short *arrayfields) {
348   /* Allocate for the queue node*/
349   int qnodesize = 2*sizeof(int) + ntuples * (sizeof(unsigned short) + sizeof(unsigned int)) + endoffsets[ntuples - 1] * sizeof(short);
350   int len;
351   char * node= getmemory(qnodesize);
352   int top=endoffsets[ntuples-1];
353
354   if (node==NULL)
355     return;
356   /* Set queue node values */
357
358   /* TODO: Remove this after testing */
359   evalPrefetch[siteid].callcount++;
360
361   *((int *)(node))=siteid;
362   *((int *)(node + sizeof(int))) = ntuples;
363   len = 2*sizeof(int);
364   memcpy(node+len, oids, ntuples*sizeof(unsigned int));
365   memcpy(node+len+ntuples*sizeof(unsigned int), endoffsets, ntuples*sizeof(unsigned short));
366   memcpy(node+len+ntuples*(sizeof(unsigned int)+sizeof(short)), arrayfields, top*sizeof(short));
367
368   /* Lock and insert into primary prefetch queue */
369   movehead(qnodesize);
370 }
371
372 /* This function starts up the transaction runtime. */
373 int dstmStartup(const char * option) {
374   pthread_t thread_Listen, udp_thread_Listen;
375   pthread_attr_t attr;
376   int master=option!=NULL && strcmp(option, "master")==0;
377   int fd;
378   int udpfd;
379
380   if (processConfigFile() != 0)
381     return 0; //TODO: return error value, cause main program to exit
382 #ifdef COMPILER
383   if (!master)
384     threadcount--;
385 #endif
386
387 #ifdef TRANSSTATS
388   printf("Trans stats is on\n");
389   fflush(stdout);
390 #endif
391 #ifdef ABORTREADERS
392   initreaderlist();
393 #endif
394
395   //Initialize socket pool
396   transReadSockPool = createSockPool(transReadSockPool, DEFAULTSOCKPOOLSIZE);
397   transPrefetchSockPool = createSockPool(transPrefetchSockPool, DEFAULTSOCKPOOLSIZE);
398   transRequestSockPool = createSockPool(transRequestSockPool, DEFAULTSOCKPOOLSIZE);
399
400   dstmInit();
401   transInit();
402
403   fd=startlistening();
404   pthread_attr_init(&attr);
405   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
406 #ifdef CACHE
407   udpfd = udpInit();
408   pthread_create(&udp_thread_Listen, &attr, udpListenBroadcast, (void*)udpfd);
409 #endif
410   if (master) {
411                 pthread_create(&thread_Listen, &attr, dstmListen, (void*)fd);
412 #ifdef RECOVERY
413                 updateLiveHosts();
414                 setLocateObjHosts();
415                 updateLiveHostsCommit();
416                 paxos();
417     printHostsStatus();
418                 if(!allHostsLive()) {
419                         printf("Not all hosts live. Exiting.\n");
420                         exit(-1);
421                 }
422 #endif
423                 return 1;
424         } else {
425                 dstmListen((void *)fd);
426                 return 0;
427   }
428 }
429
430 //TODO Use this later
431 void *pCacheAlloc(objstr_t *store, unsigned int size) {
432   void *tmp;
433   objstr_t *ptr;
434   ptr = store;
435   int success = 0;
436
437   while(ptr->next != NULL) {
438     /* check if store is empty */
439     if(((unsigned int)ptr->top - (unsigned int)ptr - sizeof(objstr_t) + size) <= ptr->size) {
440       tmp = ptr->top;
441       ptr->top += size;
442       success = 1;
443       return tmp;
444     } else {
445       ptr = ptr->next;
446     }
447   }
448
449   if(success == 0) {
450     return NULL;
451   }
452 }
453
454 /* This function initiates the prefetch thread A queue is shared
455  * between the main thread of execution and the prefetch thread to
456  * process the prefetch call Call from compiler populates the shared
457  * queue with prefetch requests while prefetch thread processes the
458  * prefetch requests */
459
460 void transInit() {
461   //Create and initialize prefetch cache structure
462 #ifdef CACHE
463   initializePCache();
464   if((evalPrefetch = initPrefetchStats()) == NULL) {
465     printf("%s() Error allocating memory at %s, %d\n", __func__, __FILE__, __LINE__);
466     exit(0);
467   }
468 #endif
469
470   /* Initialize attributes for mutex */
471   pthread_mutexattr_init(&prefetchcache_mutex_attr);
472   pthread_mutexattr_settype(&prefetchcache_mutex_attr, PTHREAD_MUTEX_RECURSIVE_NP);
473
474   pthread_mutex_init(&prefetchcache_mutex, &prefetchcache_mutex_attr);
475   pthread_mutex_init(&notifymutex, NULL);
476   pthread_mutex_init(&atomicObjLock, NULL);
477 #ifdef CACHE
478   //Create prefetch cache lookup table
479   if(prehashCreate(PHASH_SIZE, PLOADFACTOR)) {
480     printf("ERROR\n");
481     return; //Failure
482   }
483
484   //Initialize primary shared queue
485   queueInit();
486   //Initialize machine pile w/prefetch oids and offsets shared queue
487   mcpileqInit();
488
489   //Create the primary prefetch thread
490   int retval;
491 #ifdef RANGEPREFETCH
492   do {
493     retval=pthread_create(&tPrefetch, NULL, transPrefetchNew, NULL);
494   } while(retval!=0);
495 #else
496   do {
497     retval=pthread_create(&tPrefetch, NULL, transPrefetch, NULL);
498   } while(retval!=0);
499 #endif
500   pthread_detach(tPrefetch);
501 #endif
502 }
503
504 /* This function stops the threads spawned */
505 void transExit() {
506 #ifdef CACHE
507   int t;
508   pthread_cancel(tPrefetch);
509   for(t = 0; t < NUM_THREADS; t++)
510     pthread_cancel(wthreads[t]);
511 #endif
512
513   return;
514 }
515
516 /* This functions inserts randowm wait delays in the order of msec
517  * Mostly used when transaction commits retry*/
518 void randomdelay() {
519   struct timespec req;
520   time_t t;
521
522   t = time(NULL);
523   req.tv_sec = 0;
524   req.tv_nsec = (long)(1000 + (t%10000)); //1-11 microsec
525   nanosleep(&req, NULL);
526   return;
527 }
528
529 /* This function initializes things required in the transaction start*/
530 void transStart() {
531   t_cache = objstrCreate(1048576);
532   t_chashCreate(CHASH_SIZE, CLOADFACTOR);
533   revertlist=NULL;
534 #ifdef ABORTREADERS
535   t_abort=0;
536 #endif
537 }
538
539 /*#define INLINE    inline __attribute__((always_inline))
540
541 INLINE void * chashSearchI(chashtable_t *table, unsigned int key) {
542   //REMOVE HASH FUNCTION CALL TO MAKE SURE IT IS INLINED HERE                                                          
543   chashlistnode_t *node = &table->table[(key & table->mask)>>1];
544
545   do {
546     if(node->key == key) {
547       return node->val;
548     }
549     node = node->next;
550   } while(node != NULL);
551
552   return NULL;
553   }*/
554
555
556
557
558 /* This function finds the location of the objects involved in a transaction
559  * and returns the pointer to the object if found in a remote location */
560 __attribute__((pure)) objheader_t *transRead(unsigned int oid) {
561   unsigned int machinenumber;
562   objheader_t *tmp, *objheader;
563   objheader_t *objcopy;
564   int size;
565   void *buf;
566   chashlistnode_t *node;
567         
568         if(oid == 0) {
569     return NULL;
570   }
571
572   node= &c_table[(oid & c_mask)>>1];
573   do {
574     if(node->key == oid) {
575 #ifdef TRANSSTATS
576     nchashSearch++;
577 #endif
578 #ifdef COMPILER
579     return &((objheader_t*)node->val)[1];
580 #else
581     return node->val;
582 #endif
583     }
584     node = node->next;
585   } while(node != NULL);
586   
587
588   /*  
589   if((objheader = chashSearchI(record->lookupTable, oid)) != NULL) {
590 #ifdef TRANSSTATS
591     nchashSearch++;
592 #endif
593 #ifdef COMPILER
594     return &objheader[1];
595 #else
596     return objheader;
597 #endif
598   } else 
599   */
600
601 #ifdef ABORTREADERS
602   if (t_abort) {
603     //abort this transaction
604     //printf("ABORTING\n");
605     removetransactionhash();
606     objstrDelete(t_cache);
607     t_chashDelete();
608     _longjmp(aborttrans,1);
609   } else
610     addtransaction(oid);
611 #endif
612
613   if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
614 #ifdef TRANSSTATS
615     nmhashSearch++;
616 #endif
617     /* Look up in machine lookup table  and copy  into cache*/
618     GETSIZE(size, objheader);
619     size += sizeof(objheader_t);
620     objcopy = (objheader_t *) objstrAlloc(&t_cache, size);
621     memcpy(objcopy, objheader, size);
622     /* Insert into cache's lookup table */
623     STATUS(objcopy)=0;
624     t_chashInsert(OID(objheader), objcopy);
625 #ifdef COMPILER
626     return &objcopy[1];
627 #else
628     return objcopy;
629 #endif
630   } else {
631 #ifdef CACHE
632     if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) {
633 #ifdef TRANSSTATS
634       nprehashSearch++;
635 #endif
636       /* Look up in prefetch cache */
637       GETSIZE(size, tmp);
638       size+=sizeof(objheader_t);
639       objcopy = (objheader_t *) objstrAlloc(&t_cache, size);
640       memcpy(objcopy, tmp, size);
641       /* Insert into cache's lookup table */
642       t_chashInsert(OID(tmp), objcopy);
643 #ifdef COMPILER
644       return &objcopy[1];
645 #else
646       return objcopy;
647 #endif
648     }
649 #endif
650     /* Get the object from the remote location */
651     if((machinenumber = lhashSearch(oid)) == 0) {
652       printf("Error: %s() No machine found for oid =% %s,%dx\n",__func__, machinenumber, __FILE__, __LINE__);
653       return NULL;
654     }
655     objcopy = getRemoteObj(machinenumber, oid);
656
657     if(objcopy == NULL) {
658       printf("Error: Object not found in Remote location %s, %d\n", __FILE__, __LINE__);
659       return NULL;
660     } else {
661 #ifdef TRANSSTATS
662       nRemoteSend++;
663 #endif
664 #ifdef COMPILER
665       return &objcopy[1];
666 #else
667       return objcopy;
668 #endif
669     }
670   }
671 }
672
673
674 /* This function finds the location of the objects involved in a transaction
675  * and returns the pointer to the object if found in a remote location */
676 __attribute__((pure)) objheader_t *transRead2(unsigned int oid) {
677   unsigned int machinenumber;
678   objheader_t *tmp, *objheader;
679   objheader_t *objcopy;
680   int size;
681
682 #ifdef DEBUG
683         printf("%s-> Start, oid:%u\n", __func__, oid);
684 #endif
685
686 #ifdef ABORTREADERS
687   if (t_abort) {
688     //abort this transaction
689     //printf("ABORTING\n");
690     removetransactionhash();
691     objstrDelete(t_cache);
692     t_chashDelete();
693     _longjmp(aborttrans,1);
694   } else
695     addtransaction(oid);
696 #endif
697
698     if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
699 #ifdef DEBUG
700                   printf("%s-> Grab from this machine\n", __func__);
701 #endif
702 #ifdef TRANSSTATS
703       nmhashSearch++;
704 #endif
705       /* Look up in machine lookup table  and copy  into cache*/
706       GETSIZE(size, objheader);
707       size += sizeof(objheader_t);
708       objcopy = (objheader_t *) objstrAlloc(&t_cache, size);
709       memcpy(objcopy, objheader, size);
710       /* Insert into cache's lookup table */
711       STATUS(objcopy)=0;
712       t_chashInsert(OID(objheader), objcopy);
713 #ifdef DEBUG
714       printf("%s -> obj type = %d\n",__func__,getObjType(oid));
715       printf("%s -> obj grabbed\n",__func__);
716 #endif
717 #ifdef COMPILER
718       return &objcopy[1];
719 #else
720       return objcopy;
721 #endif
722     } else {
723 #ifdef CACHE
724       if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) {
725 #ifdef TRANSSTATS
726       LOGEVENT('P')
727       nprehashSearch++;
728 #endif
729       /* Look up in prefetch cache */
730       GETSIZE(size, tmp);
731       size+=sizeof(objheader_t);
732       objcopy = (objheader_t *) objstrAlloc(&t_cache, size);
733       memcpy(objcopy, tmp, size);
734       /* Insert into cache's lookup table */
735       t_chashInsert(OID(tmp), objcopy);
736 #ifdef COMPILER
737       return &objcopy[1];
738 #else
739                         return objcopy;
740 #endif
741         } 
742 #endif
743                 /* Get the object from the remote location */
744     if((machinenumber = lhashSearch(oid)) == 0) {
745       printf("Error: %s() No machine found for oid =% %s,%dx\n",__func__, machinenumber, __FILE__, __LINE__);
746             return NULL;
747         }
748 #ifdef DEBUG
749         printf("%s-> Grab from remote machine\n", __func__);
750 #endif
751 #ifdef RECOVERY
752     transRetryFlag = 0;
753
754     unsigned int machinenumber; 
755     static int flipBit = 0;        // Used to distribute requests between primary and backup evenly
756     // either primary or backup machine
757     machinenumber = (flipBit)?getPrimaryMachine(lhashSearch(oid)):getBackupMachine(lhashSearch(oid));
758     flipBit ^= 1;
759
760 #ifdef DEBUG
761     printf("mindex:%d, oid:%d, machinenumber:%s\n", mindex, oid, midtoIPString(machinenumber));
762 #endif
763 #endif
764
765           objcopy = getRemoteObj(machinenumber, oid);
766
767 #ifdef RECOVERY
768     if(transRetryFlag) {
769       restoreDuplicationState(machinenumber);
770 #ifdef DEBUG
771       printf("%s -> Recall transRead2\n",__func__);
772 #endif
773       return transRead2(oid);
774     }
775 #endif
776
777   if(objcopy == NULL) {
778           printf("Error: Object not found in Remote location %s, %d\n", __FILE__, __LINE__);
779                 return NULL;
780         } else {
781 #ifdef TRANSSTATS
782     LOGEVENT('R');
783           nRemoteSend++;
784 #endif
785 #ifdef COMPILER
786                 return &objcopy[1];
787 #else
788                 return objcopy;
789 #endif
790         }
791     }
792 #ifdef DEBUG
793   printf("%s -> Finished!!\n",__func__);
794 #endif
795     
796 }
797
798 /* This function creates objects in the transaction record */
799 objheader_t *transCreateObj(unsigned int size) {
800   objheader_t *tmp = (objheader_t *) objstrAlloc(&t_cache, (sizeof(objheader_t) + size));
801   OID(tmp) = getNewOID();
802   tmp->version = 1;
803   tmp->rcount = 1;
804         tmp->isBackup = 0;
805   STATUS(tmp) = NEW;
806   t_chashInsert(OID(tmp), tmp);
807
808 #ifdef COMPILER
809   return &tmp[1]; //want space after object header
810 #else
811   return tmp;
812 #endif
813 }
814
815
816 #if 1
817 /* This function creates machine piles based on all machines involved in a
818  * transaction commit request */
819 plistnode_t *createPiles() {
820
821 #ifdef DEBUG
822   printf("%s -> Entering\n",__func__);
823 #endif
824   int i;
825         unsigned int oid;
826   plistnode_t *pile = NULL;
827   unsigned int machinenum;
828         unsigned int destMachine[2];
829   objheader_t *headeraddr;
830   chashlistnode_t * ptr = c_table;
831   /* Represents number of bins in the chash table */
832   unsigned int size = c_size;
833
834         for(i = 0; i < size ; i++) {
835     chashlistnode_t * curr = &ptr[i];
836                 /* Inner loop to traverse the linked list of the cache lookupTable */
837     while(curr != NULL) {
838       //if the first bin in hash table is empty
839       if(curr->key == 0)
840         break;
841       headeraddr=(objheader_t *) curr->val;
842
843 #if RECOVERY
844       oid = OID(headeraddr);
845
846                           int makedirty = 0;
847         unsigned int mid;
848
849         mid = lhashSearch(oid);
850
851         // if the obj is dirty or new
852                         if(STATUS(headeraddr) & DIRTY || STATUS(headeraddr) & NEW) {
853           // set flag for backup machine
854                                 makedirty = 1;
855                     }
856
857         // if the obj is new or local, destination will be my Ip
858         if((mid = lhashSearch(oid)) == 0) {
859             mid = myIpAddr;
860         }
861  
862                     pile = pInsert(pile, headeraddr, getPrimaryMachine(mid), c_numelements);
863                         
864         if(makedirty) { 
865                                   STATUS(headeraddr) = DIRTY;
866                         }
867
868                           pile = pInsert(pile, headeraddr, getBackupMachine(mid), c_numelements);
869 #else
870                         // Get machine location for object id (and whether local or not)
871                         if (STATUS(headeraddr) & NEW || (mhashSearch(curr->key) != NULL)) {
872                                 machinenum = myIpAddr;
873                         } else if ((machinenum = lhashSearch(curr->key)) == 0) {
874         printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
875         return NULL;
876       }
877       //Make machine groups
878       pile = pInsert(pile, headeraddr, machinenum, c_numelements);
879 #endif
880       curr = curr->next;
881     }
882   }
883         return pile;
884 }
885 #else
886 /* This function creates machine piles based on all machines involved in a
887  * transaction commit request */
888 plistnode_t *createPiles() {
889   int i;
890   plistnode_t *pile = NULL;
891   unsigned int machinenum;
892         unsigned int destMachine[2];
893   objheader_t *headeraddr;
894   struct chashentry * ptr = c_table;
895   /* Represents number of bins in the chash table */
896   unsigned int size = c_size;
897
898   for(i = 0; i < size ; i++) {
899     struct chashentry * curr = & ptr[i];
900     /* Inner loop to traverse the linked list of the cache lookupTable */
901     // if the first bin in hash table is empty
902     if(curr->key == 0)
903       continue;
904     headeraddr=(objheader_t *) curr->ptr;
905
906     //Get machine location for object id (and whether local or not)
907     if (STATUS(headeraddr) & NEW || (mhashSearch(curr->key) != NULL)) {
908       machinenum = myIpAddr;
909     } else if ((machinenum = lhashSearch(curr->key)) == 0) {
910       printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
911       return NULL;
912     }
913
914     //Make machine groups
915     pile = pInsert(pile, headeraddr, machinenum, c_numelements);
916   }
917   return pile;
918 }
919 #endif
920
921 /* This function initiates the transaction commit process
922  * Spawns threads for each of the new connections with Participants
923  * and creates new piles by calling the createPiles(),
924  * Sends a transrequest() to each remote machines for objects found remotely
925  * and calls handleLocalReq() to process objects found locally */
926 int transCommit() {
927   unsigned int tot_bytes_mod, *listmid;
928   plistnode_t *pile, *pile_ptr;
929   char treplyretry; /* keeps track of the common response that needs to be sent */
930   int firsttime=1;
931   trans_commit_data_t transinfo; /* keeps track of objs locked during transaction */
932   char finalResponse;
933
934 #ifdef RECOVERY
935   int deadsd = -1;
936   int deadmid = -1;
937   unsigned int transID = getNewTransID();
938 #endif
939
940 #ifdef DEBUG
941   printf("%s -> Starts transCommit\n",__func__);
942 #endif
943
944 #ifdef ABORTREADERS
945   if (t_abort) {
946     //abort this transaction
947     /* Debug
948      * printf("ABORTING TRANSACTION AT COMMIT\n");
949      */
950     removetransactionhash();
951     objstrDelete(t_cache);
952     t_chashDelete();
953 #ifdef DEBUG
954           printf("%s-> End, line:%d\n\n", __func__, __LINE__);
955 #endif
956     return 1;
957   }
958 #endif
959
960   do {
961     treplyretry = 0;
962
963     /* Look through all the objects in the transaction record and make piles
964      * for each machine involved in the transaction*/
965     if (firsttime) {
966       pile_ptr = pile = createPiles();
967       pile_ptr = pile = sortPiles(pile);
968     } else {
969       pile = pile_ptr;
970     }
971     firsttime = 0;
972     /* Create the packet to be sent in TRANS_REQUEST */
973
974     /* Count the number of participants */
975     int pilecount;
976     pilecount = pCount(pile);
977
978     /* Create a list of machine ids(Participants) involved in transaction   */
979     listmid = calloc(pilecount, sizeof(unsigned int));
980     pListMid(pile, listmid);
981
982     /* Create a socket and getReplyCtrl array, initialize */
983     int socklist[pilecount];
984     int loopcount;
985     for(loopcount = 0 ; loopcount < pilecount; loopcount++)
986       socklist[loopcount] = 0;
987     char getReplyCtrl[pilecount];
988     for(loopcount = 0 ; loopcount < pilecount; loopcount++)
989       getReplyCtrl[loopcount] = 0;
990
991     /* Process each machine pile */
992     int sockindex = 0;
993                 int localReqsock = -1;
994     trans_req_data_t *tosend;
995     tosend = calloc(pilecount, sizeof(trans_req_data_t));
996     while(pile != NULL) {
997 #ifdef DEBUG
998                         printf("%s-> New pile:[%s],", __func__, midtoIPString(pile->mid));
999                         printf(" myIp:[%s]\n", midtoIPString(myIpAddr));
1000 #endif
1001       tosend[sockindex].f.control = TRANS_REQUEST;
1002                         tosend[sockindex].f.mcount = pilecount;
1003                         tosend[sockindex].f.numread = pile->numread;
1004                         tosend[sockindex].f.nummod = pile->nummod;
1005                         tosend[sockindex].f.numcreated = pile->numcreated;
1006                         tosend[sockindex].f.sum_bytes = pile->sum_bytes;
1007                         tosend[sockindex].listmid = listmid;
1008                         tosend[sockindex].objread = pile->objread;
1009                         tosend[sockindex].oidmod = pile->oidmod;
1010                         tosend[sockindex].oidcreated = pile->oidcreated;
1011
1012
1013       int sd = 0;
1014                         if(pile->mid != myIpAddr) {
1015                                 if((sd = getSockWithLock(transRequestSockPool, pile->mid)) < 0) {
1016                                         printf("\ntransRequest(): socket create error\n");
1017                                         free(listmid);
1018                                         free(tosend);
1019 #ifdef DEBUG
1020                                         printf("%s-> End, line:%d\n\n", __func__, __LINE__);
1021 #endif
1022                                         return 1;
1023                                 }
1024                                 socklist[sockindex] = sd;
1025                                 /* Send bytes of data with TRANS_REQUEST control message */
1026                                 send_data(sd, &(tosend[sockindex].f), sizeof(fixed_data_t));
1027
1028                                 /* Send list of machines involved in the transaction */
1029                                 {
1030                                         int size=sizeof(unsigned int)*(tosend[sockindex].f.mcount);
1031                                         send_data(sd, tosend[sockindex].listmid, size);
1032                                 }
1033
1034                                 /* Send oids and version number tuples for objects that are read */
1035                                 {
1036                                         int size=(sizeof(unsigned int)+sizeof(unsigned short))*(tosend[sockindex].f.numread);
1037                                         send_data(sd, tosend[sockindex].objread, size);
1038                                 }
1039
1040                                 /* Send objects that are modified */
1041                                 void *modptr;
1042                                 if((modptr = calloc(1, tosend[sockindex].f.sum_bytes)) == NULL) {
1043                                         printf("Calloc error for modified objects %s, %d\n", __FILE__, __LINE__);
1044                                         free(listmid);
1045                                         free(tosend);
1046                                         return 1;
1047                                 }
1048                                 int offset = 0;
1049                                 int i;
1050                                 for(i = 0; i < tosend[sockindex].f.nummod ; i++) {
1051                                         int size;
1052                                         objheader_t *headeraddr;
1053                                         if((headeraddr = t_chashSearch(tosend[sockindex].oidmod[i])) == NULL) {
1054                                                 printf("%s() Error: No such oid %s, %d\n", __func__, __FILE__, __LINE__);
1055                                                 free(modptr);
1056                                                 free(listmid);
1057                                                 free(tosend);
1058                                                 return 1;
1059                                         }
1060                                         GETSIZE(size,headeraddr);
1061                                         size+=sizeof(objheader_t);
1062                                         memcpy(modptr+offset, headeraddr, size);
1063                                         offset+=size;
1064                                 }
1065                                 send_data(sd, modptr, tosend[sockindex].f.sum_bytes);
1066
1067 #ifdef RECOVERY
1068         /* send transaction id, number of machine involved, machine ids */
1069         send_data(sd, &transID, sizeof(unsigned int));
1070 #endif
1071                                 free(modptr);
1072                         } else { //handle request locally
1073                                 handleLocalReq(&tosend[sockindex], &transinfo, &getReplyCtrl[sockindex]);
1074                         }
1075                         sockindex++;
1076                         pile = pile->next;
1077                 } //end of pile processing
1078
1079                 /* Recv Ctrl msgs from all machines */
1080 #ifdef DEBUG
1081                 printf("%s-> Finished sending transaction read/mod objects\n",__func__);
1082 #endif
1083                 int i;
1084
1085                 for(i = 0; i < pilecount; i++) {
1086                         int sd = socklist[i]; 
1087                         if(sd != 0) {
1088                                 char control;
1089         int timeout;            // a variable to check if the connection is still alive. if it is -1, then need to transcommit again
1090         timeout = recv_data(sd, &control, sizeof(char));
1091                                 //Update common data structure with new ctrl msg
1092                                 getReplyCtrl[i] = control;
1093                                 /* Recv Objects if participant sends TRANS_DISAGREE */
1094 #ifdef CACHE
1095                                 if(control == TRANS_DISAGREE) {
1096                                         int length;
1097                                         recv_data(sd, &length, sizeof(int));
1098                                         void *newAddr;
1099                                         pthread_mutex_lock(&prefetchcache_mutex);
1100                                         if ((newAddr = prefetchobjstrAlloc((unsigned int)length)) == NULL) {
1101                                                 printf("Error: %s() objstrAlloc error for copying into prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
1102                                                 free(tosend);
1103                                                 free(listmid);
1104                                                 pthread_mutex_unlock(&prefetchcache_mutex);
1105                                                 return 1;
1106                                         }
1107                                         pthread_mutex_unlock(&prefetchcache_mutex);
1108                                         recv_data(sd, newAddr, length);
1109                                         int offset = 0;
1110                                         while(length != 0) {
1111                                                 unsigned int oidToPrefetch;
1112                                                 objheader_t * header;
1113                                                 header = (objheader_t *)(((char *)newAddr) + offset);
1114                                                 oidToPrefetch = OID(header);
1115                                                 STATUS(header)=0;
1116                                                 int size = 0;
1117                                                 GETSIZE(size, header);
1118                                                 size += sizeof(objheader_t);
1119                                                 //make an entry in prefetch hash table
1120                                                 void *oldptr;
1121                                                 if((oldptr = prehashSearch(oidToPrefetch)) != NULL) {
1122                                                         prehashRemove(oidToPrefetch);
1123                                                         prehashInsert(oidToPrefetch, header);
1124                                                 } else {
1125                                                         prehashInsert(oidToPrefetch, header);
1126                                                 }
1127                                                 length = length - size;
1128                                                 offset += size;
1129                                         }
1130                                 } //end of receiving objs
1131 #endif
1132
1133 #ifdef RECOVERY
1134         if(timeout < 0) {
1135           deadmid = listmid[i];
1136           deadsd = sd;
1137 #ifdef DEBUG
1138           printf("%s -> Dead Machine ID : %s\n",__func__,midtoIPString(deadmid));  
1139           printf("%s -> Dead SD         : %d\n",__func__,sd);
1140 #endif
1141           getReplyCtrl[i] = TRANS_DISAGREE;
1142         }
1143 #endif
1144                         }
1145                 }
1146
1147 #ifdef DEBUG
1148                 printf("%s-> Decide final response now\n", __func__);
1149 #endif
1150                 /* Decide the final response */
1151                 if((finalResponse = decideResponse(getReplyCtrl, &treplyretry, pilecount)) == 0) {
1152                         printf("Error: %s() in updating prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
1153                         free(tosend);
1154                         free(listmid);
1155                         return 1;
1156                 }
1157 #ifdef DEBUG
1158     printf("%s-> Final Response: %d\n", __func__, (int)finalResponse);
1159 #endif
1160     
1161                 /* Send responses to all machines */
1162                 for(i = 0; i < pilecount; i++) {
1163                         int sd = socklist[i];
1164 #ifdef RECOVERY
1165       if(sd != deadsd) {
1166 #endif
1167                         if(sd != 0) {
1168 #ifdef CACHE
1169                                 if(finalResponse == TRANS_COMMIT) {
1170                                         int retval;
1171                                         /* Update prefetch cache */
1172                                         if((retval = updatePrefetchCache(&(tosend[i]))) != 0) {
1173                                                 printf("Error: %s() in updating prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
1174                                                   free(tosend);
1175                                                 free(listmid);
1176                                                 return 1;
1177                                         }
1178
1179                                         /* Invalidate objects in other machine cache */
1180                                         if(tosend[i].f.nummod > 0) {
1181                                                 if((retval = invalidateObj(&(tosend[i]))) != 0) {
1182                                                         printf("Error: %s() in invalidating Objects %s, %d\n", __func__, __FILE__, __LINE__);
1183                                                         free(tosend);
1184                                                         free(listmid);
1185                                                         return 1;
1186                                                 }
1187                                         }
1188 #ifdef ABORTREADERS
1189                                         removetransaction(tosend[i].oidmod,tosend[i].f.nummod);
1190                                         removethisreadtransaction(tosend[i].objread, tosend[i].f.numread);
1191 #endif
1192                                   }
1193 #ifdef ABORTREADERS
1194                                 else if (!treplyretry) {
1195                                         removethistransaction(tosend[i].oidmod,tosend[i].f.nummod);
1196                                         removethisreadtransaction(tosend[i].objread,tosend[i].f.numread);
1197                                 }
1198 #endif
1199 #endif
1200           send_data(sd,&finalResponse,sizeof(char));
1201 #ifdef DEBUG
1202           printf("%s -> Decision Sent to %s\n",__func__,midtoIPString(listmid[i]));
1203 #endif
1204
1205       } else {
1206                                 /* Complete local processing */
1207 #ifdef RECOVERY
1208           thashInsert(transID,finalResponse);
1209 #endif
1210           doLocalProcess(finalResponse, &(tosend[i]), &transinfo);
1211
1212 #ifdef ABORTREADERS
1213                                   if(finalResponse == TRANS_COMMIT) {
1214                                           removetransaction(tosend[i].oidmod,tosend[i].f.nummod);
1215                                         removethisreadtransaction(tosend[i].objread,tosend[i].f.numread);
1216                                 } else if (!treplyretry) {
1217                                         removethistransaction(tosend[i].oidmod,tosend[i].f.nummod);
1218                                         removethisreadtransaction(tosend[i].objread,tosend[i].f.numread);
1219                                   }
1220 #endif
1221                         }
1222 #ifdef RECOVERY
1223       } 
1224 #endif
1225     }
1226
1227
1228    for(i = 0; i< pilecount; i++) {
1229      if(socklist[i] > 0) {
1230        freeSockWithLock(transRequestSockPool,listmid[i], socklist[i]);
1231      }
1232    }
1233
1234                         /* Free resources */
1235     free(tosend);
1236     free(listmid);
1237     if (!treplyretry)
1238       pDelete(pile_ptr);
1239     /* wait a random amount of time before retrying to commit transaction*/
1240     if(treplyretry) {
1241       randomdelay();
1242 #ifdef TRANSSTATS
1243                         nSoftAbort++;
1244 #endif
1245                 }
1246     
1247
1248         } while (treplyretry && deadmid != -1);
1249
1250         if(finalResponse == TRANS_ABORT) {
1251 #ifdef TRANSSTATS
1252                 numTransAbort++;
1253 #endif
1254     /* Free Resources */
1255     objstrDelete(t_cache);
1256     t_chashDelete();
1257 #ifdef RECOVERY
1258     if(deadmid != -1) { /* if deadmid is greater than or equal to 0, 
1259                           then there is dead machine. */
1260 #ifdef DEBUG
1261       printf("%s -> Dead machine Detected : %s\n",__func__,midtoIPString(deadmid));
1262 #endif
1263       restoreDuplicationState(deadmid);
1264     }
1265 #endif
1266     return TRANS_ABORT;
1267   } else if(finalResponse == TRANS_COMMIT) {
1268 #ifdef TRANSSTATS
1269                 numTransCommit++;
1270 #endif
1271     /* Free Resources */
1272     objstrDelete(t_cache);
1273     t_chashDelete();
1274     return 0;
1275   } else {
1276     //TODO Add other cases
1277     printf("Error: in %s() THIS SHOULD NOT HAPPEN.....EXIT PROGRAM\n", __func__);
1278     exit(-1);
1279   }
1280 #ifndef DEBUG
1281         printf("%s-> End, line:%d\n\n", __func__, __LINE__);
1282 #endif
1283   return 0;
1284 }
1285
1286 /* This function handles the local objects involved in a transaction
1287  * commiting process.  It also makes a decision if this local machine
1288  * sends AGREE or DISAGREE or SOFT_ABORT to coordinator */
1289 void handleLocalReq(trans_req_data_t *tdata, trans_commit_data_t *transinfo, char *getReplyCtrl) {
1290   unsigned int *oidnotfound = NULL, *oidlocked = NULL;
1291   int numoidnotfound = 0, numoidlocked = 0;
1292   int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
1293   int numread, i;
1294   unsigned int oid;
1295   unsigned short version;
1296
1297   /* Counters and arrays to formulate decision on control message to be sent */
1298   oidnotfound = (unsigned int *) calloc((tdata->f.numread + tdata->f.nummod), sizeof(unsigned int));
1299         oidlocked = (unsigned int *) calloc((tdata->f.numread + tdata->f.nummod +1), sizeof(unsigned int)); // calloc additional 1 byte for
1300         //setting a divider between read and write locks
1301         numread = tdata->f.numread;
1302         /* Process each oid in the machine pile/ group per thread */
1303         for (i = 0; i < tdata->f.numread + tdata->f.nummod; i++) {
1304                 if (i < tdata->f.numread) {
1305                         int incr = sizeof(unsigned int) + sizeof(unsigned short); // Offset that points to next position in the objread array
1306                         incr *= i;
1307                         oid = *((unsigned int *)(((char *)tdata->objread) + incr));
1308                         version = *((unsigned short *)(((char *)tdata->objread) + incr + sizeof(unsigned int)));
1309                         commitCountForObjRead(getReplyCtrl, oidnotfound, oidlocked, &numoidnotfound, &numoidlocked, &v_nomatch, &v_matchlock, &v_matchnolock, oid, version);
1310                 } else { // Objects Modified
1311                         if(i == tdata->f.numread) {
1312                                 oidlocked[numoidlocked++] = -1;
1313                         }
1314                         int tmpsize;
1315                         objheader_t *headptr;
1316                         headptr = (objheader_t *) t_chashSearch(tdata->oidmod[i-numread]);
1317                         if (headptr == NULL) {
1318                                 printf("Error: handleLocalReq() returning NULL, no such oid %s, %d\n", __FILE__, __LINE__);
1319                                 return;
1320                         }
1321                         oid = OID(headptr);
1322                         version = headptr->version;
1323                         commitCountForObjMod(getReplyCtrl, oidnotfound, oidlocked, &numoidnotfound, &numoidlocked, &v_nomatch, &v_matchlock, &v_matchnolock, oid, version);
1324                 }
1325   }
1326
1327         /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
1328          * if Participant receives a TRANS_COMMIT */
1329         transinfo->objlocked = oidlocked;
1330         transinfo->objnotfound = oidnotfound;
1331         transinfo->modptr = NULL;
1332         transinfo->numlocked = numoidlocked;
1333         transinfo->numnotfound = numoidnotfound;
1334
1335   /* Condition to send TRANS_AGREE */
1336   if(v_matchnolock == tdata->f.numread + tdata->f.nummod) {
1337     *getReplyCtrl = TRANS_AGREE;
1338   }
1339   /* Condition to send TRANS_SOFT_ABORT */
1340   if((v_matchlock > 0 && v_nomatch == 0) || (numoidnotfound > 0 && v_nomatch == 0)) {
1341     *getReplyCtrl = TRANS_SOFT_ABORT;
1342   }
1343 }
1344
1345 void doLocalProcess(char finalResponse, trans_req_data_t *tdata, trans_commit_data_t *transinfo) {
1346
1347   if(finalResponse == TRANS_ABORT) {
1348     if(transAbortProcess(transinfo) != 0) {
1349       printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
1350       fflush(stdout);
1351       return;
1352     }
1353   } else if(finalResponse == TRANS_COMMIT) {
1354 #ifdef CACHE
1355     /* Invalidate objects in other machine cache */
1356     if(tdata->f.nummod > 0) {
1357       int retval;
1358       if((retval = invalidateObj(tdata)) != 0) {
1359         printf("Error: %s() in invalidating Objects %s, %d\n", __func__, __FILE__, __LINE__);
1360         return;
1361       }
1362     }
1363 #endif
1364     if(transComProcess(tdata, transinfo) != 0) {
1365       printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
1366       fflush(stdout);
1367       return;
1368     }
1369   } else {
1370     printf("ERROR...No Decision\n");
1371   }
1372
1373   /* Free memory */
1374   if (transinfo->objlocked != NULL) {
1375     free(transinfo->objlocked);
1376   }
1377   if (transinfo->objnotfound != NULL) {
1378     free(transinfo->objnotfound);
1379   }
1380 }
1381
1382 /* This function decides the reponse that needs to be sent to
1383  * all Participant machines after the TRANS_REQUEST protocol */
1384 char decideResponse(char *getReplyCtrl, char *treplyretry, int pilecount) {
1385   int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
1386                                                                    message to send */
1387   for (i = 0 ; i < pilecount; i++) {
1388     char control;
1389     control = getReplyCtrl[i];
1390     switch(control) {
1391     default:
1392 #ifdef DEBUG
1393       printf("%s-> Participant sent unknown message, i:%d, Control: %d\n", __func__, i, (int)control);
1394 #endif
1395
1396       /* treat as disagree, pass thru */
1397     case TRANS_DISAGREE:
1398       transdisagree++;
1399 #ifdef DEBUG
1400       printf("%s-> Participant sent TRANS_DISAGREE, i:%d, Control: %d\n", __func__, i, (int)control);
1401 #endif
1402       break;
1403
1404     case TRANS_AGREE:
1405       transagree++;
1406 #ifdef DEBUG
1407       printf("%s-> Participant sent TRANS_AGREE, i:%d, Control: %d\n", __func__, i, (int)control);
1408 #endif
1409       break;
1410
1411     case TRANS_SOFT_ABORT:
1412       transsoftabort++;
1413 #ifdef DEBUG
1414       printf("%s-> Participant sent TRANS_SOFT_ABORT, i:%d, Control: %d\n", __func__, i, (int)control);
1415 #endif
1416       break;
1417     }
1418   }
1419
1420   if(transdisagree > 0) {
1421     /* Send Abort */
1422     *treplyretry = 0;
1423     return TRANS_ABORT;
1424 #ifdef CACHE
1425     /* clear objects from prefetch cache */
1426     cleanPCache();
1427 #endif
1428   } else if(transagree == pilecount) {
1429     /* Send Commit */
1430     *treplyretry = 0;
1431     return TRANS_COMMIT;
1432   } else {
1433     /* Send Abort in soft abort case followed by retry commiting transaction again*/
1434     *treplyretry = 1;
1435     return TRANS_ABORT;
1436   }
1437   return 0;
1438 }
1439
1440 /* This function opens a connection, places an object read request to
1441  * the remote machine, reads the control message and object if
1442  * available and copies the object and its header to the local
1443  * cache. */
1444
1445 void *getRemoteObj(unsigned int mnum, unsigned int oid) {
1446 #ifdef DEBUG
1447   printf("%s -> entering\n",__func__);
1448 #endif
1449   int size, val;
1450   struct sockaddr_in serv_addr;
1451   char control = 0;
1452   objheader_t *h;
1453   void *objcopy = NULL;
1454
1455   int sd = getSock2(transRequestSockPool, mnum);
1456   char readrequest[sizeof(char)+sizeof(unsigned int)];
1457   readrequest[0] = READ_REQUEST;
1458   *((unsigned int *)(&readrequest[1])) = oid;
1459   send_data(sd, readrequest, sizeof(readrequest));
1460   
1461   /* Read response from the Participant */
1462   if(recv_data(sd, &control, sizeof(char)) < 0) {
1463     transRetryFlag = 1;
1464     return NULL;
1465   }
1466
1467   if (control==OBJECT_NOT_FOUND) {
1468     objcopy = NULL;
1469   } else if(control==OBJECT_FOUND) {
1470   
1471   /* Read object if found into local cache */
1472
1473   if(recv_data(sd, &size, sizeof(int)) < 0) {
1474     transRetryFlag = 1;
1475     return NULL;
1476   }
1477
1478   objcopy = objstrAlloc(&t_cache, size);
1479
1480   if(recv_data(sd, objcopy, size) < 0) {
1481     transRetryFlag = 1;
1482     return NULL;
1483   }
1484   STATUS(objcopy)=0;
1485   
1486   /* Insert into cache's lookup table */
1487   t_chashInsert(oid, objcopy);
1488 #ifdef TRANSSTATS
1489   totalObjSize += size;
1490 #endif
1491         }
1492         return objcopy;
1493 }
1494
1495 #ifdef RECOVERY
1496 /* ask machines if they received decision */
1497 char receiveDecisionFromBackup(unsigned int transID,int nummid,unsigned int *listmid)
1498 {
1499 #ifdef DEBUG
1500   printf("%s -> Entering\n",__func__);
1501 #endif
1502
1503   int sd; // socket id
1504   int i;
1505   char response;
1506   
1507   for(i = 0; i < nummid; i++) {
1508     if((sd = getSock(transPrefetchSockPool, listmid[i])) < 0) {
1509       printf("%s -> socket Error!!\n");
1510     }
1511     else {
1512       char control = ASK_COMMIT;
1513
1514       send_data(sd,&control, sizeof(char));
1515       send_data(sd,&transID, sizeof(unsigned int));
1516
1517       // return -1 if it didn't receive the response
1518       int timeout = recv_data(sd,&response, sizeof(char));
1519
1520
1521       if(timeout == 0 || response > 0)
1522         break;  // received response
1523
1524       // else check next machine
1525       freeSock(transPrefetchSockPool, listmid[i],sd);
1526      }
1527   }
1528 #ifdef DEBUG
1529   printf("%s -> response : %d\n",__func__,response);
1530 #endif
1531
1532   return (response==-1)?TRANS_ABORT:response;
1533 }
1534 #endif
1535
1536 #ifdef RECOVERY
1537 void restoreDuplicationState(unsigned int deadHost) {
1538         int sd;
1539         char ctrl;
1540
1541         if(!liveHosts[findHost(deadHost)]) {  // if it is already fixed
1542                 sleep(WAIT_TIME);
1543                 return;
1544         }
1545
1546         if(deadHost == leader)  // if leader is dead, then pick a new leader
1547                 paxos();
1548         
1549 #ifdef DEBUG
1550         printf("%s-> leader?:%s, me?:%s\n", __func__, midtoIPString(leader), (myIpAddr == leader)?"LEADER":"NOT LEADER");
1551 #endif
1552         
1553         if(leader == myIpAddr) {
1554                 pthread_mutex_lock(&leaderFixing_mutex);
1555                 if(!leaderFixing) {
1556                         leaderFixing = 1;
1557                         pthread_mutex_unlock(&leaderFixing_mutex);
1558
1559       if(!liveHosts[findHost(deadHost)]) {  // if it is already fixed
1560 #ifdef DEBUG
1561         printf("%s -> already fixed\n",__func__);
1562 #endif
1563         pthread_mutex_lock(&leaderFixing_mutex);
1564         leaderFixing =0;
1565         pthread_mutex_unlock(&leaderFixing_mutex);
1566       }
1567       else {                // if i am the leader
1568                         updateLiveHosts();
1569         duplicateLostObjects(deadHost);
1570                         
1571                     if(updateLiveHostsCommit() != 0) {
1572                                 printf("%s -> error updateLiveHostsCommit()\n",__func__);
1573                                   exit(1);
1574                         }
1575                 pthread_mutex_lock(&leaderFixing_mutex);
1576                         leaderFixing = 0;
1577                           pthread_mutex_unlock(&leaderFixing_mutex);
1578       }
1579                 }
1580                 else {
1581                         pthread_mutex_unlock(&leaderFixing_mutex);
1582 #ifdef DEBUG
1583       printf("%s (REMOTE_RESTORE_DUPLICATED_STATE -> LEADER is already fixing\n",__func__);
1584 #endif
1585                         sleep(WAIT_TIME);
1586                 }
1587         }
1588         else {    // request leader to fix the situation
1589                 if((sd = getSockWithLock(transPrefetchSockPool, leader)) < 0) {
1590                         printf("%s -> socket create error\n",__func__);
1591                         exit(-1);
1592                 }
1593                 ctrl = REMOTE_RESTORE_DUPLICATED_STATE;
1594                 send_data(sd, &ctrl, sizeof(char));
1595                 send_data(sd, &deadHost, sizeof(unsigned int));
1596     freeSockWithLock(transPrefetchSockPool,leader,sd);
1597           sleep(WAIT_TIME);
1598         }
1599
1600   printf("%s -> Finished!\n",__func__);
1601 }
1602 #endif
1603
1604
1605 /*  Commit info for objects modified */
1606 void commitCountForObjMod(char *getReplyCtrl, unsigned int *oidnotfound, unsigned int *oidlocked, int *numoidnotfound,
1607                           int *numoidlocked, int *v_nomatch, int *v_matchlock, int *v_matchnolock, unsigned int oid, unsigned short version) {
1608   void *mobj;
1609   /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
1610   /* Save the oids not found and number of oids not found for later use */
1611   if ((mobj = mhashSearch(oid)) == NULL) { /* Obj not found */
1612     /* Save the oids not found and number of oids not found for later use */
1613     oidnotfound[*numoidnotfound] = oid;
1614     (*numoidnotfound)++;
1615   } else { /* If Obj found in machine (i.e. has not moved) */
1616     /* Check if Obj is locked by any previous transaction */
1617     if (write_trylock(STATUSPTR(mobj))) { // Can acquire write lock
1618       if (version == ((objheader_t *)mobj)->version) {      /* match versions */
1619         (*v_matchnolock)++;
1620         //Keep track of what is locked
1621         oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj));
1622       } else { /* If versions don't match ...HARD ABORT */
1623         (*v_nomatch)++;
1624         /* Send TRANS_DISAGREE to Coordinator */
1625         *getReplyCtrl = TRANS_DISAGREE;
1626
1627         //Keep track of what is locked
1628         oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj));
1629         //printf("%s() oid = %d, type = %d\t", __func__, OID(mobj), TYPE((objheader_t *)mobj));
1630         return;
1631       }
1632     } else { //A lock is acquired some place else
1633                       if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
1634         (*v_matchlock)++;
1635       } else { /* If versions don't match ...HARD ABORT */
1636         (*v_nomatch)++;
1637         /* Send TRANS_DISAGREE to Coordinator */
1638         *getReplyCtrl = TRANS_DISAGREE;
1639         //printf("%s() oid = %d, type = %d\t", __func__, OID(mobj), TYPE((objheader_t *)mobj));
1640         return;
1641       }
1642     }
1643   }
1644 }
1645
1646 /*  Commit info for objects modified */
1647 void commitCountForObjRead(char *getReplyCtrl, unsigned int *oidnotfound, unsigned int *oidlocked, int *numoidnotfound,
1648                            int *numoidlocked, int *v_nomatch, int *v_matchlock, int *v_matchnolock, unsigned int oid, unsigned short version) {
1649   void *mobj;
1650   /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
1651   /* Save the oids not found and number of oids not found for later use */
1652   if ((mobj = mhashSearch(oid)) == NULL) { /* Obj not found */
1653                 /* Save the oids not found and number of oids not found for later use */
1654                 oidnotfound[*numoidnotfound] = oid;
1655                 (*numoidnotfound)++;
1656         } else { /* If Obj found in machine (i.e. has not moved) */
1657                 /* Check if Obj is locked by any previous transaction */
1658                 if (read_trylock(STATUSPTR(mobj))) { // Can further acquire read locks
1659                         if (version == ((objheader_t *)mobj)->version) {      /* If locked then match versions */
1660                                 (*v_matchnolock)++;
1661                                 //Keep track of what is locked
1662                                 oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj));
1663                         } else { /* If versions don't match ...HARD ABORT */
1664                                 (*v_nomatch)++;
1665                                 /* Send TRANS_DISAGREE to Coordinator */
1666                                 *getReplyCtrl = TRANS_DISAGREE;
1667                                 //Keep track of what is locked
1668                                 oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj));
1669                                 //printf("%s() oid = %d, type = %d\t", __func__, OID(mobj), TYPE((objheader_t *)mobj));
1670                                 return;
1671                         }
1672                 } else { //Has reached max number of readers or some other transaction
1673                         //has acquired a lock on this object
1674                         if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
1675                                 (*v_matchlock)++;
1676                         } else { /* If versions don't match ...HARD ABORT */
1677                                 (*v_nomatch)++;
1678                                 /* Send TRANS_DISAGREE to Coordinator */
1679                                 *getReplyCtrl = TRANS_DISAGREE;
1680                                 //printf("%s() oid = %d, type = %d\t", __func__, OID(mobj), TYPE((objheader_t *)mobj));
1681                                 return;
1682                         }
1683     }
1684   }
1685 }
1686
1687 /* This function completes the ABORT process if the transaction is aborting */
1688 int transAbortProcess(trans_commit_data_t *transinfo) {
1689   int i, numlocked;
1690   unsigned int *objlocked;
1691   void *header;
1692
1693   numlocked = transinfo->numlocked;
1694   objlocked = transinfo->objlocked;
1695
1696   int useWriteUnlock = 0;
1697   for (i = 0; i < numlocked; i++) {
1698     if(objlocked[i] == -1) {
1699       useWriteUnlock = 1;
1700       continue;
1701     }
1702     if((header = mhashSearch(objlocked[i])) == NULL) {
1703       printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1704       return 1;
1705     }
1706     if(!useWriteUnlock) {
1707       read_unlock(STATUSPTR(header));
1708     } else {
1709       write_unlock(STATUSPTR(header));
1710     }
1711   }
1712
1713   return 0;
1714 }
1715
1716 /*This function completes the COMMIT process if the transaction is commiting*/
1717 int transComProcess(trans_req_data_t *tdata, trans_commit_data_t *transinfo) {
1718   objheader_t *header, *tcptr;
1719   int i, nummod, tmpsize, numcreated, numlocked;
1720   unsigned int *oidmod, *oidcreated, *oidlocked;
1721   void *ptrcreate;
1722 #ifdef DEBUG
1723         printf("%s-> Entering transComProcess, trans.c\n", __func__);
1724 #endif
1725
1726   nummod = tdata->f.nummod;
1727   oidmod = tdata->oidmod;
1728   numcreated = tdata->f.numcreated;
1729   oidcreated = tdata->oidcreated;
1730   numlocked = transinfo->numlocked;
1731   oidlocked = transinfo->objlocked;
1732
1733   for (i = 0; i < nummod; i++) {
1734     if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
1735       printf("Error: transComProcess() mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1736       return 1;
1737     }
1738     /* Copy from transaction cache -> main object store */
1739     if ((tcptr = ((objheader_t *) t_chashSearch(oidmod[i]))) == NULL) {
1740       printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1741       return 1;
1742     }
1743     GETSIZE(tmpsize, header);
1744     char *tmptcptr = (char *) tcptr;
1745     {
1746       struct ___Object___ *dst=(struct ___Object___*)((char*)header+sizeof(objheader_t));
1747       struct ___Object___ *src=(struct ___Object___*)((char*)tmptcptr+sizeof(objheader_t));
1748       dst->___cachedCode___=src->___cachedCode___;
1749       dst->___cachedHash___=src->___cachedHash___;
1750
1751       memcpy(&dst[1], &src[1], tmpsize-sizeof(struct ___Object___));
1752     }
1753
1754     header->version += 1;
1755     //printf("oid: %u, new header version: %d\n", oidmod[i], header->version);
1756     if(header->notifylist != NULL) {
1757 #ifdef RECOVERY
1758       if(header->isBackup != 0)   // if it is primary obj, notify
1759         notifyAll(&header->notifylist, OID(header), header->version);
1760       else                        // if not, just clear the notification list
1761         clearNotifyList(OID(header));
1762 #else  
1763       notifyAll(&header->notifylist, OID(header), header->version);
1764 #endif
1765     }
1766   }
1767   /* If object is newly created inside transaction then commit it */
1768   for (i = 0; i < numcreated; i++) {
1769     if ((header = ((objheader_t *) t_chashSearch(oidcreated[i]))) == NULL) {
1770       printf("Error: transComProcess() chashSearch returned NULL for oid = %x at %s, %d\n", oidcreated[i], __FILE__, __LINE__);
1771       return 1;
1772     }
1773     header->version += 1;
1774     GETSIZE(tmpsize, header);
1775     tmpsize += sizeof(objheader_t);
1776     pthread_mutex_lock(&mainobjstore_mutex);
1777     if ((ptrcreate = objstrAlloc(&mainobjstore, tmpsize)) == NULL) {
1778       printf("Error: transComProcess() failed objstrAlloc %s, %d\n", __FILE__, __LINE__);
1779       pthread_mutex_unlock(&mainobjstore_mutex);
1780       return 1;
1781     }
1782     pthread_mutex_unlock(&mainobjstore_mutex);
1783     /* Initialize read and write locks */
1784     initdsmlocks(STATUSPTR(header));
1785     memcpy(ptrcreate, header, tmpsize);
1786     mhashInsert(oidcreated[i], ptrcreate);
1787     lhashInsert(oidcreated[i], myIpAddr);
1788 //    printf("oid created : %u\n",oidcreated[i]);
1789   }
1790   /* Unlock locked objects */
1791   int useWriteUnlock = 0;
1792   for(i = 0; i < numlocked; i++) {
1793     if(oidlocked[i] == -1) {
1794       useWriteUnlock = 1;
1795       continue;
1796     }
1797     if((header = (objheader_t *) mhashSearch(oidlocked[i])) == NULL) {
1798       printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1799       return 1;
1800     }
1801     if(!useWriteUnlock) {
1802       read_unlock(STATUSPTR(header));
1803     } else {
1804       write_unlock(STATUSPTR(header));
1805     }
1806   }
1807   return 0;
1808 }
1809
1810 prefetchpile_t *foundLocal(char *ptr) {
1811         int siteid = *(GET_SITEID(ptr));
1812         int ntuples = *(GET_NTUPLES(ptr));
1813         unsigned int * oidarray = GET_PTR_OID(ptr);
1814         unsigned short * endoffsets = GET_PTR_EOFF(ptr, ntuples);
1815         short * arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1816         prefetchpile_t * head=NULL;
1817         int numLocal = 0;
1818
1819         int i;
1820         for(i=0; i<ntuples; i++) {
1821                 unsigned short baseindex=(i==0) ? 0 : endoffsets[i-1];
1822                 unsigned short endindex=endoffsets[i];
1823                 unsigned int oid=oidarray[i];
1824                 int newbase;
1825                 int machinenum;
1826                 if (oid==0)
1827                         continue;
1828                 //Look up fields locally
1829                 for(newbase=baseindex; newbase<endindex; newbase++) {
1830                         if (!lookupObject(&oid, arryfields[newbase]))
1831                                 break;
1832                         //Ended in a null pointer...
1833                         if (oid==0)
1834                                 goto tuple;
1835                 }
1836                 //Entire prefetch is local
1837                 if (newbase==endindex&&checkoid(oid)) {
1838                         numLocal++;
1839                         goto tuple;
1840                 }
1841                 //Add to remote requests
1842                 machinenum=lhashSearch(oid);
1843                 insertPile(machinenum, oid, endindex-newbase, &arryfields[newbase], &head);
1844 tuple:
1845                 ;
1846         }
1847
1848         /* handle dynamic prefetching */
1849         handleDynPrefetching(numLocal, ntuples, siteid);
1850         return head;
1851 }
1852
1853 int checkoid(unsigned int oid) {
1854         objheader_t *header;
1855         if ((header=mhashSearch(oid))!=NULL) {
1856                 //Found on machine
1857                 return 1;
1858         } else if ((header=prehashSearch(oid))!=NULL) {
1859                 //Found in cache
1860                 return 1;
1861         } else {
1862                 return 0;
1863         }
1864 }
1865
1866 int lookupObject(unsigned int * oid, short offset) {
1867   objheader_t *header;
1868   if ((header=mhashSearch(*oid))!=NULL) {
1869     //Found on machine
1870     ;
1871   } else if ((header=prehashSearch(*oid))!=NULL) {
1872     //Found in cache
1873     ;
1874   } else {
1875     return 0;
1876   }
1877
1878   if(TYPE(header) >= NUMCLASSES) {
1879     int elementsize = classsize[TYPE(header)];
1880     struct ArrayObject *ao = (struct ArrayObject *) (((char *)header) + sizeof(objheader_t));
1881     int length = ao->___length___;
1882     /* Check if array out of bounds */
1883     if(offset < 0 || offset >= length) {
1884       //if yes treat the object as found
1885       (*oid)=0;
1886       return 1;
1887     }
1888     (*oid) = *((unsigned int *)(((char *)ao) + sizeof(struct ArrayObject) + (elementsize*offset)));
1889     return 1;
1890   } else {
1891     (*oid) = *((unsigned int *)(((char *)header) + sizeof(objheader_t) + offset));
1892     return 1;
1893   }
1894 }
1895
1896
1897 /* This function is called by the thread calling transPrefetch */
1898 void *transPrefetch(void *t) {
1899   while(1) {
1900     /* read from prefetch queue */
1901     void *node=gettail();
1902     /* Check if the tuples are found locally, if yes then reduce them further*/
1903     /* and group requests by remote machine ids by calling the makePreGroups() */
1904     prefetchpile_t *pilehead = foundLocal(node);
1905
1906     if (pilehead!=NULL) {
1907       // Get sock from shared pool
1908
1909       /* Send  Prefetch Request */
1910       prefetchpile_t *ptr = pilehead;
1911       while(ptr != NULL) {
1912         int sd = getSock2(transPrefetchSockPool, ptr->mid);
1913         sendPrefetchReq(ptr, sd);
1914         ptr = ptr->next;
1915       }
1916
1917       /* Release socket */
1918       //        freeSock(transPrefetchSockPool, pilehead->mid, sd);
1919
1920       /* Deallocated pilehead */
1921       mcdealloc(pilehead);
1922     }
1923     // Deallocate the prefetch queue pile node
1924     inctail();
1925   }
1926 }
1927
1928 void sendPrefetchReqnew(prefetchpile_t *mcpilenode, int sd) {
1929   objpile_t *tmp;
1930
1931   int size=sizeof(char)+sizeof(int);
1932   for(tmp=mcpilenode->objpiles; tmp!=NULL; tmp=tmp->next) {
1933     size += sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1934   }
1935
1936   char buft[size];
1937   char *buf=buft;
1938   *buf=TRANS_PREFETCH;
1939   buf+=sizeof(char);
1940
1941   for(tmp=mcpilenode->objpiles; tmp!=NULL; tmp=tmp->next) {
1942     int len = sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1943     *((int*)buf)=len;
1944     buf+=sizeof(int);
1945     *((unsigned int *)buf)=tmp->oid;
1946     buf+=sizeof(unsigned int);
1947     *((unsigned int *)(buf)) = myIpAddr;
1948     buf+=sizeof(unsigned int);
1949     memcpy(buf, tmp->offset, tmp->numoffset*sizeof(short));
1950     buf+=tmp->numoffset*sizeof(short);
1951   }
1952   *((int *)buf)=-1;
1953   send_data(sd, buft, size);
1954   return;
1955 }
1956
1957 void sendPrefetchReq(prefetchpile_t *mcpilenode, int sd) {
1958   int len, endpair;
1959   char control;
1960   objpile_t *tmp;
1961
1962   /* Send TRANS_PREFETCH control message */
1963   control = TRANS_PREFETCH;
1964   send_data(sd, &control, sizeof(char));
1965
1966   /* Send Oids and offsets in pairs */
1967   tmp = mcpilenode->objpiles;
1968   while(tmp != NULL) {
1969     len = sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1970     char oidnoffset[len];
1971     char *buf=oidnoffset;
1972     *((int*)buf) = tmp->numoffset;
1973     buf+=sizeof(int);
1974     *((unsigned int *)buf) = tmp->oid;
1975     buf+=sizeof(unsigned int);
1976     *((unsigned int *)buf) = myIpAddr;
1977     buf += sizeof(unsigned int);
1978     memcpy(buf, tmp->offset, (tmp->numoffset)*sizeof(short));
1979     send_data(sd, oidnoffset, len);
1980     tmp = tmp->next;
1981   }
1982
1983   /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
1984   endpair = -1;
1985   send_data(sd, &endpair, sizeof(int));
1986
1987   return;
1988 }
1989
1990 int getPrefetchResponse(int sd) {
1991   int length = 0, size = 0;
1992   char control;
1993   unsigned int oid;
1994   void *modptr, *oldptr;
1995
1996   recv_data((int)sd, &length, sizeof(int));
1997   size = length - sizeof(int);
1998   char recvbuffer[size];
1999
2000   recv_data((int)sd, recvbuffer, size);
2001   control = *((char *) recvbuffer);
2002   if(control == OBJECT_FOUND) {
2003     oid = *((unsigned int *)(recvbuffer + sizeof(char)));
2004     size = size - (sizeof(char) + sizeof(unsigned int));
2005     pthread_mutex_lock(&prefetchcache_mutex);
2006     if ((modptr = prefetchobjstrAlloc(size)) == NULL) {
2007       printf("Error: objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
2008       pthread_mutex_unlock(&prefetchcache_mutex);
2009       return -1;
2010     }
2011     pthread_mutex_unlock(&prefetchcache_mutex);
2012     memcpy(modptr, recvbuffer + sizeof(char) + sizeof(unsigned int), size);
2013     STATUS(modptr)=0;
2014
2015     /* Insert the oid and its address into the prefetch hash lookup table */
2016     /* Do a version comparison if the oid exists */
2017     if((oldptr = prehashSearch(oid)) != NULL) {
2018       /* If older version then update with new object ptr */
2019       if(((objheader_t *)oldptr)->version <= ((objheader_t *)modptr)->version) {
2020         prehashRemove(oid);
2021         prehashInsert(oid, modptr);
2022       }
2023     } else { /* Else add the object ptr to hash table*/
2024       prehashInsert(oid, modptr);
2025     }
2026     /* Lock the Prefetch Cache look up table*/
2027     pthread_mutex_lock(&pflookup.lock);
2028     /* Broadcast signal on prefetch cache condition variable */
2029     pthread_cond_broadcast(&pflookup.cond);
2030     /* Unlock the Prefetch Cache look up table*/
2031     pthread_mutex_unlock(&pflookup.lock);
2032   } else if(control == OBJECT_NOT_FOUND) {
2033     oid = *((unsigned int *)(recvbuffer + sizeof(char)));
2034     /* TODO: For each object not found query DHT for new location and retrieve the object */
2035     /* Throw an error */
2036     //printf("OBJECT %x NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n", oid);
2037     //    exit(-1);
2038   } else {
2039     printf("Error: in decoding the control value %d, %s, %d\n",control, __FILE__, __LINE__);
2040   }
2041
2042   return 0;
2043 }
2044
2045 unsigned short getObjType(unsigned int oid) {
2046   objheader_t *objheader;
2047   unsigned short numoffset[] ={0};
2048   short fieldoffset[] ={};
2049
2050   if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL) {
2051 #ifdef CACHE
2052     if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL) {
2053 #endif
2054
2055 #ifdef RECOVERY
2056     unsigned int mid = lhashSearch(oid);
2057     unsigned int machineID;
2058     static flipBit = 0;
2059     machineID = (flipBit)?(getPrimaryMachine(mid)):(getBackupMachine(mid));
2060     int sd = getSock2(transReadSockPool, machineID);
2061 #else
2062     unsigned int mid = lhashSearch(oid);
2063     int sd = getSock2(transReadSockPool, mid);
2064 #endif
2065     char remotereadrequest[sizeof(char)+sizeof(unsigned int)];
2066     remotereadrequest[0] = READ_REQUEST;
2067     *((unsigned int *)(&remotereadrequest[1])) = oid;
2068     send_data(sd, remotereadrequest, sizeof(remotereadrequest));
2069
2070     /* Read response from the Participant */
2071     char control;
2072     recv_data(sd, &control, sizeof(char));
2073
2074     if (control==OBJECT_NOT_FOUND) {
2075       printf("Error: in %s() THIS SHOULD NOT HAPPEN.....EXIT PROGRAM\n", __func__);
2076       fflush(stdout);
2077       exit(-1);
2078     } else {
2079       /* Read object if found into local cache */
2080       int size;
2081       recv_data(sd, &size, sizeof(int));
2082 #ifdef CACHE
2083       pthread_mutex_lock(&prefetchcache_mutex);
2084       if ((objheader = prefetchobjstrAlloc(size)) == NULL) {
2085         printf("Error: %s() objstrAlloc error for copying into prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
2086         pthread_exit(NULL);
2087       }
2088       pthread_mutex_unlock(&prefetchcache_mutex);
2089       recv_data(sd, objheader, size);
2090       prehashInsert(oid, objheader);
2091       return TYPE(objheader);
2092 #else
2093       char *buffer;
2094       if((buffer = calloc(1, size)) == NULL) {
2095         printf("%s() Calloc Error %s at line %d\n", __func__, __FILE__, __LINE__);
2096         fflush(stdout);
2097         return 0;
2098       }
2099       recv_data(sd, buffer, size);
2100       objheader = (objheader_t *)buffer;
2101       unsigned short type = TYPE(objheader);
2102       free(buffer);
2103       return type;
2104 #endif
2105     }
2106 #ifdef CACHE
2107   }
2108 #endif
2109   }
2110   return TYPE(objheader);
2111 }
2112
2113 int startRemoteThread(unsigned int oid, unsigned int mid) {
2114   int sock;
2115   struct sockaddr_in remoteAddr;
2116   char msg[1 + sizeof(unsigned int)];
2117   int bytesSent;
2118   int status;
2119
2120   if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
2121     perror("startRemoteThread():socket()");
2122     return -1;
2123   }
2124
2125   bzero(&remoteAddr, sizeof(remoteAddr));
2126   remoteAddr.sin_family = AF_INET;
2127   remoteAddr.sin_port = htons(LISTEN_PORT);
2128   remoteAddr.sin_addr.s_addr = htonl(mid);
2129
2130   if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0) {
2131     printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
2132            inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
2133     status = -1;
2134   } else
2135   {
2136     msg[0] = START_REMOTE_THREAD;
2137     *((unsigned int *) &msg[1]) = oid;
2138     send_data(sock, msg, 1 + sizeof(unsigned int));
2139   }
2140
2141   close(sock);
2142   return status;
2143 }
2144
2145 //TODO: when reusing oids, make sure they are not already in use!
2146 static unsigned int id = 0xFFFFFFFF;
2147 unsigned int getNewOID(void) {
2148   id += 2;
2149   if (id > oidMax || id < oidMin) {
2150     id = (oidMin | 1);
2151   }
2152   return id;
2153 }
2154
2155 #ifdef RECOVERY
2156 static unsigned int tid = 0xFFFFFFFF;
2157 unsigned int getNewTransID(void) {
2158   tid++;
2159   if (tid > transIDMax || tid < transIDMin) {
2160     tid = (transIDMin | 1);
2161   }
2162   return tid;
2163 }
2164 #endif
2165
2166 int processConfigFile() {
2167   FILE *configFile;
2168   const int maxLineLength = 200;
2169   char lineBuffer[maxLineLength];
2170   char *token;
2171   const char *delimiters = " \t\n";
2172   char *commentBegin;
2173   unsigned int i;
2174   in_addr_t tmpAddr;
2175
2176   configFile = fopen(CONFIG_FILENAME, "r");
2177   if (configFile == NULL) {
2178     printf("error opening %s:\n", CONFIG_FILENAME);
2179     perror("");
2180     return -1;
2181   }
2182
2183   numHostsInSystem = 0;
2184   sizeOfHostArray = 8;
2185   hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
2186 #ifdef RECOVERY 
2187         liveHosts = calloc(sizeOfHostArray, sizeof(unsigned int));
2188         locateObjHosts = calloc(sizeOfHostArray*2, sizeof(unsigned int));
2189 #endif
2190
2191         while(fgets(lineBuffer, maxLineLength, configFile) != NULL) {
2192                 commentBegin = strchr(lineBuffer, '#');
2193                 if (commentBegin != NULL)
2194                         *commentBegin = '\0';
2195                 token = strtok(lineBuffer, delimiters);
2196                 while (token != NULL) {
2197                         tmpAddr = inet_addr(token);
2198                         if ((int)tmpAddr == -1) {
2199                                 printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
2200                                 fclose(configFile);
2201                                 return -1;
2202                         } else
2203                                 addHost(htonl(tmpAddr));
2204                         token = strtok(NULL, delimiters);
2205                 }
2206         }
2207
2208         fclose(configFile);
2209
2210   if (numHostsInSystem < 1) {
2211     printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
2212     return -1;
2213   }
2214 #ifdef MAC
2215   myIpAddr = getMyIpAddr("en1");
2216 #else
2217   myIpAddr = getMyIpAddr("eth0");
2218 #endif
2219   myIndexInHostArray = findHost(myIpAddr);
2220 #ifdef RECOVERY
2221         liveHosts[myIndexInHostArray] = 1;
2222 #endif  
2223         if (myIndexInHostArray == -1) {
2224     printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
2225     return -1;
2226   }
2227   oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
2228   oidMin = oidsPerBlock * myIndexInHostArray;
2229   if (myIndexInHostArray == numHostsInSystem - 1)
2230     oidMax = 0xFFFFFFFF;
2231   else
2232     oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
2233
2234         transIDMin = oidMin;
2235         transIDMax = oidMax;
2236
2237   waitThreadID = -1;
2238   waitThreadMid = -1;
2239
2240   return 0;
2241 }
2242
2243 #ifdef RECOVERY
2244 unsigned int getDuplicatedPrimaryMachine(unsigned int mid) {
2245         int i;
2246         for(i = 0; i < numHostsInSystem; i++) {
2247                 if(mid == locateObjHosts[(i*2)+1]) {
2248                         return locateObjHosts[i*2];
2249                 }
2250         }
2251         return -1;
2252 }
2253
2254 unsigned int getPrimaryMachine(unsigned int mid) {
2255         unsigned int pmid;
2256         int pmidindex = 2*findHost(mid);
2257
2258   if(pmidindex < 0)
2259     printf("What!!!\n");
2260
2261         pthread_mutex_lock(&liveHosts_mutex);
2262         pmid = locateObjHosts[pmidindex];
2263         pthread_mutex_unlock(&liveHosts_mutex);
2264         return pmid;
2265 }
2266
2267 unsigned int getBackupMachine(unsigned int mid) {
2268         unsigned int bmid;
2269         int bmidindex = 2*findHost(mid)+1;
2270
2271   if(bmidindex < 0)
2272     printf("damn!!\n");
2273
2274         pthread_mutex_lock(&liveHosts_mutex);
2275         bmid = locateObjHosts[bmidindex];
2276         pthread_mutex_unlock(&liveHosts_mutex);
2277         return bmid;
2278 }
2279
2280 int getStatus(int mid) {
2281 #ifdef DEBUG
2282   printf("%s -> host %s : %s\n",__func__,midtoIPString(hostIpAddrs[mid]),(liveHosts[mid] == 1)?"LIVE":"DEAD");
2283 #endif
2284   return liveHosts[mid];
2285 }
2286 #endif
2287
2288 #ifdef RECOVERY
2289 // updates the leader's liveHostArray and locateObj
2290 unsigned int updateLiveHosts() {
2291 #ifdef DEBUG
2292     printf("%s-> Entering updateLiveHosts\n", __func__);        
2293 #endif
2294         // update everyone's list
2295         
2296   //foreach in hostipaddrs, ping -> update list of livemachines 
2297   //socket connection?
2298
2299   int deadhost = -1;
2300         //liveHosts lock here
2301         int sd = 0, i, j, tmpNumLiveHosts = 0;
2302         for(i = 0; i < numHostsInSystem; i++) {
2303     if(i == myIndexInHostArray) 
2304                 {
2305       liveHosts[i] = 1;
2306                         tmpNumLiveHosts++;
2307                         continue;
2308                 }
2309                 if((sd = getSockWithLock(transPrefetchSockPool, hostIpAddrs[i])) < 0) {
2310                         usleep(1000);
2311     
2312                 if(liveHosts[i]) {
2313         liveHosts[i] = 0;
2314         deadhost = i;
2315       }
2316       continue;
2317                 }
2318       
2319     char liverequest;
2320                 liverequest = RESPOND_LIVE;
2321         
2322                 send_data(sd, &liverequest, sizeof(char));
2323       
2324                 char response = 0;
2325                 int timeout = recv_data(sd, &response, sizeof(char));
2326                         
2327                 //try to send msg
2328                 //if timeout, dead host
2329                 if(response == LIVE) {
2330         liveHosts[i] = 1;
2331                 tmpNumLiveHosts++;
2332                 }
2333                 else {
2334       if(liveHosts[i]) {
2335         liveHosts[i] = 0;
2336         deadhost = i;
2337       }
2338                 }
2339     freeSockWithLock(transPrefetchSockPool,hostIpAddrs[i],sd);
2340         }
2341   
2342   numLiveHostsInSystem = tmpNumLiveHosts;
2343 #ifdef DEBUG
2344         printf("numLiveHostsInSystem:%d\n", numLiveHostsInSystem);
2345 #endif
2346         //have updated list of live machines
2347 #ifdef DEBUG    
2348         printHostsStatus();
2349   printf("%s-> Exiting updateLiveHosts\n", __func__);   
2350 #endif
2351
2352   return deadhost;
2353 }
2354
2355 int getNumLiveHostsInSystem() {
2356         int count = 0, i = 0;
2357         for(; i<numHostsInSystem; i++) {
2358                 if(liveHosts[i])
2359                         count++;
2360         }
2361         return count;
2362 }
2363
2364 int updateLiveHostsCommit() {
2365 #ifdef DEBUG      
2366   printf("%s -> Enter\n",__func__);
2367 #endif
2368         int sd = 0, i;
2369         
2370         char updaterequest[sizeof(char)+sizeof(int)*numHostsInSystem+sizeof(unsigned int)*(numHostsInSystem*2)];
2371
2372   updaterequest[0] = UPDATE_LIVE_HOSTS;
2373         for(i = 0; i < numHostsInSystem; i++) {
2374                 *((int *)(&updaterequest[i*4+1])) = liveHosts[i];  // clean this up later
2375         }
2376
2377         for(i = 0; i < numHostsInSystem*2; i++) {
2378                 *((unsigned int *)(&updaterequest[i*4+(numHostsInSystem*4)+1])) = locateObjHosts[i];    //ditto
2379         }
2380
2381         //for each machine send data
2382         for(i = 0; i < numHostsInSystem; i++) {         // hard define num of retries
2383                 if(i == myIndexInHostArray) 
2384                         continue;
2385                 if(liveHosts[i] == 1) {
2386                         if((sd = getSockWithLock(transPrefetchSockPool, hostIpAddrs[i])) < 0) {
2387                         printf("%s -> socket create error, attempt %d\n",__func__, i);
2388                                 return -1;
2389                         }
2390                         send_data(sd, updaterequest, sizeof(updaterequest));
2391       freeSockWithLock(transPrefetchSockPool,hostIpAddrs[i],sd);
2392                 }
2393         }
2394 #ifdef DEBUG
2395         printHostsStatus();
2396   printf("%s -> Finish\n",__func__);
2397 #endif
2398
2399         return 0;
2400 }
2401 #endif
2402
2403 #ifdef RECOVERY
2404 void setLocateObjHosts() {
2405         int i = 0, validIndex = 0;
2406
2407         //check num hosts even valid first
2408         
2409         for(i = 0;i < numHostsInSystem; i++) {
2410                 
2411                 while(liveHosts[(i+validIndex)%numHostsInSystem] == 0) {
2412                         validIndex++;
2413                 }
2414                 locateObjHosts[i*2] = hostIpAddrs[(i+validIndex)%numHostsInSystem];
2415 #ifdef DEBUG
2416                 printf("%s-> locateObjHosts[%d]:%s\n", __func__, i*2, midtoIPString(locateObjHosts[(i*2)]));
2417 #endif
2418
2419                 validIndex++;
2420                 while(liveHosts[(i+validIndex)%numHostsInSystem] == 0) {
2421                         validIndex++;
2422                 }
2423 #ifdef DEBUG
2424                 printf("%s-> validIndex:%d, this mid is: [%s]\n", __func__, validIndex, midtoIPString(hostIpAddrs[(i+validIndex)%numHostsInSystem]));
2425 #endif
2426                 locateObjHosts[(i*2)+1] = hostIpAddrs[(i+validIndex)%numHostsInSystem];
2427                 validIndex=0;
2428
2429 #ifdef DEBUG
2430                 printf("%s-> locateObjHosts[%d]:%s\n", __func__, i*2+1, midtoIPString(locateObjHosts[(i*2)+1]));
2431 #endif
2432         }
2433 }
2434
2435 void setReLocateObjHosts(int mid)
2436 {
2437   int mIndex = findHost(mid);
2438   int backupMachine = getBackupMachine(mid);
2439   int newPrimary = getDuplicatedPrimaryMachine(mid);
2440   int newPrimaryIndex = findHost(newPrimary);
2441   int i;
2442
2443   /* duplicateLostObject example
2444    * Before M24 die,
2445    * MID        21      24      26
2446    * Primary    21      24      26
2447    * Backup     26      21      24
2448    * After M24 die,
2449    * MID        21      26
2450    * Primary   21,24    26
2451    * Backup     26      21,24
2452    */
2453
2454   locateObjHosts[2*newPrimaryIndex+1] = backupMachine;
2455   locateObjHosts[2*mIndex] = newPrimary;
2456
2457 /* relocate the objects of the machines already dead */
2458   for(i=0; i<numHostsInSystem *2; i+=2) {
2459     if(locateObjHosts[i] == mid)
2460       locateObjHosts[i] = newPrimary;
2461     if(locateObjHosts[i+1] == mid)
2462       locateObjHosts[i+1] = backupMachine;
2463   }
2464 }
2465
2466
2467 //debug function
2468 void printHostsStatus() {
2469         int i;
2470         printf("%s-> *printing live machines and backups*\n", __func__);
2471         for(i = 0; i < numHostsInSystem; i++) {
2472                 if(liveHosts[i]) {
2473                         printf("%s-> [%s]: LIVE\n", __func__, midtoIPString(hostIpAddrs[i])); 
2474                 }
2475                 else {
2476                         printf("%s-> [%s]: DEAD\n", __func__, midtoIPString(hostIpAddrs[i]));
2477                 }
2478                         printf("%s-> original:\t[%s]\n", __func__, midtoIPString(locateObjHosts[i*2]));
2479                         printf("%s-> backup:\t[%s]\n", __func__, midtoIPString(locateObjHosts[i*2+1]));
2480         }
2481 }
2482
2483 int allHostsLive() {
2484         int i;
2485         for(i = 0; i < numHostsInSystem; i++) {
2486                 if(!liveHosts[i])
2487                         return 0;
2488         }
2489         return 1;
2490 }
2491 #endif
2492
2493 #ifdef RECOVERY
2494 void duplicateLostObjects(unsigned int mid){
2495
2496         printf("%s-> Start, mid: [%s]\n", __func__, midtoIPString(mid));  
2497         
2498         //this needs to be changed.
2499         unsigned int backupMid = getBackupMachine(mid); // get backup machine of dead machine
2500         unsigned int originalMid = getDuplicatedPrimaryMachine(mid); // get primary machine that used deadmachine as backup machine.
2501
2502 #ifdef DEBUG
2503         printf("%s-> backupMid: [%s], ", __func__, midtoIPString(backupMid));
2504         printf("originalMid: [%s]\n", midtoIPString(originalMid));
2505         printHostsStatus(); 
2506 #endif
2507
2508   setReLocateObjHosts(mid);
2509         
2510         //connect to these machines
2511         //go through their object store copying necessary (in a transaction)
2512         int sd = 0, i, j, tmpNumLiveHosts = 0;
2513
2514   /* duplicateLostObject example
2515    * Before M24 die,
2516    * MID        21      24      26
2517    * Primary    21      24      26
2518    * Backup     26      21      24
2519    * After M24 die,
2520    * MID        21      26
2521    * Primary   21,24    26
2522    * Backup     26      21,24
2523    */
2524
2525         if(originalMid == myIpAddr) {   // copy local machine's backup data, make it as primary data of backup machine.
2526                 duplicateLocalOriginalObjects(backupMid);       
2527         }
2528         else if((sd = getSockWithLock(transPrefetchSockPool, originalMid)) < 0) {
2529                 printf("%s -> socket create error, attempt %d\n", __func__,j);
2530     exit(0);
2531                 //usleep(1000);
2532         }
2533         else {      // if original is not local
2534                 char duperequest;
2535                 duperequest = DUPLICATE_ORIGINAL;
2536                 send_data(sd, &duperequest, sizeof(char));
2537 #ifdef DEBUG
2538           printf("%s-> SD : %d  Sent DUPLICATE_ORIGINAL request to %s\n", __func__,sd,midtoIPString(originalMid));      
2539 #endif
2540                 send_data(sd, &backupMid, sizeof(unsigned int));
2541
2542     char response;
2543                 recv_data(sd, &response, sizeof(char));
2544 #ifdef DEBUG
2545                 printf("%s (DUPLICATE_ORIGINAL) -> Received %s\n", __func__,(response==DUPLICATION_COMPLETE)?"DUPLICATION_COMPLETE":"DUPLICATION_FAIL");
2546 #endif
2547
2548     freeSockWithLock(transPrefetchSockPool, originalMid, sd);
2549         }
2550
2551         if(backupMid == myIpAddr) {   // copy local machine's primary data, and make it as backup data of original machine.
2552                 duplicateLocalBackupObjects(originalMid);       
2553         }
2554         else if((sd = getSockWithLock(transPrefetchSockPool, backupMid)) < 0) {
2555                 printf("updateLiveHosts(): socket create error, attempt %d\n", j);
2556                 exit(1);
2557         }
2558         else {
2559                 char duperequest;
2560                 duperequest = DUPLICATE_BACKUP;
2561                 send_data(sd, &duperequest, sizeof(char));
2562 #ifdef DEBUG
2563           printf("%s-> SD : %d  Sent DUPLICATE_BACKUP request to %s\n", __func__,sd,midtoIPString(backupMid));  
2564 #endif
2565                 send_data(sd, &originalMid, sizeof(unsigned int));
2566
2567                 char response;
2568                 recv_data(sd, &response, sizeof(char));
2569 #ifdef DEBUG
2570                 printf("%s (DUPLICATE_BACKUP) -> Received %s\n", __func__,(response==DUPLICATION_COMPLETE)?"DUPLICATION_COMPLETE":"DUPLICATION_FAIL");
2571 #endif
2572
2573     freeSockWithLock(transPrefetchSockPool, backupMid, sd);
2574         }
2575
2576 #ifndef DEBUG
2577         printf("%s-> End\n", __func__);  
2578 #endif
2579 }
2580
2581 void duplicateLocalBackupObjects(unsigned int mid) {
2582         int tempsize, sd;
2583   int i;
2584         char *dupeptr, ctrl, response;
2585 #ifndef DEBUG
2586         printf("%s-> Start; backup mid:%s\n", __func__, midtoIPString(mid));  
2587 #endif
2588
2589         //copy code from dstmserver here
2590         tempsize = mhashGetDuplicate((void**)&dupeptr, 1);
2591
2592 #ifdef DEBUG
2593         printf("tempsize:%d, dupeptrfirstvalue:%d\n", tempsize, *((unsigned int *)(dupeptr)));
2594 #endif
2595         //send control and dupes after
2596         ctrl = RECEIVE_DUPES;
2597         if((sd = getSockWithLock(transPrefetchSockPool, mid)) < 0) {
2598                 printf("duplicatelocalbackup: socket create error\n");
2599                 //usleep(1000);
2600         }
2601 #ifdef DEBUG
2602         printf("%s -> sd:%d, tempsize:%d, dupeptrfirstvalue:%d\n", __func__,sd, tempsize, *((unsigned int *)(dupeptr)));
2603 #endif
2604         send_data(sd, &ctrl, sizeof(char));
2605         send_data(sd, dupeptr, tempsize);
2606         
2607   recv_data(sd, &response, sizeof(char));
2608   freeSockWithLock(transPrefetchSockPool,mid,sd);
2609
2610 #ifdef DEBUG
2611   printf("%s ->response : %d  -  %d\n",__func__,response,DUPLICATION_COMPLETE);
2612 #endif
2613
2614         if(response != DUPLICATION_COMPLETE) {
2615 #ifndef DEBUG
2616     printf("%s -> DUPLICATION_FAIL\n",__func__);
2617 #endif
2618     exit(-1);
2619         }
2620   free(dupeptr);
2621
2622 #ifndef DEBUG
2623         printf("%s-> End\n", __func__);  
2624 #endif
2625
2626 }
2627
2628 void duplicateLocalOriginalObjects(unsigned int mid) {
2629         int tempsize, sd;
2630         char *dupeptr, ctrl, response;
2631
2632 #ifndef DEBUG
2633         printf("%s-> Start\n", __func__);  
2634 #endif
2635         //copy code fom dstmserver here
2636
2637         tempsize = mhashGetDuplicate((void**)&dupeptr, 0);
2638
2639         //send control and dupes after
2640         ctrl = RECEIVE_DUPES;
2641
2642         if((sd = getSockWithLock(transPrefetchSockPool, mid)) < 0) {
2643                 printf("DUPLICATE_ORIGINAL: socket create error\n");
2644                 //usleep(1000);
2645         }
2646 #ifdef DEBUG
2647         printf("sd:%d, tempsize:%d, dupeptrfirstvalue:%d\n", sd, tempsize, *((unsigned int *)(dupeptr)));
2648 #endif
2649
2650         send_data(sd, &ctrl, sizeof(char));
2651         send_data(sd, dupeptr, tempsize);
2652
2653         recv_data(sd, &response, sizeof(char));
2654   freeSockWithLock(transPrefetchSockPool,mid,sd);
2655
2656 #ifdef DEBUG
2657   printf("%s ->response : %d  -  %d\n",__func__,response,DUPLICATION_COMPLETE);
2658 #endif
2659
2660         if(response != DUPLICATION_COMPLETE) {
2661                 //fail message
2662 #ifndef DEBUG
2663     printf("%s -> DUPLICATION_FAIL\n",__func__);
2664 #endif
2665     exit(0);
2666         }
2667   
2668   free(dupeptr);
2669
2670 #ifndef DEBUG
2671         printf("%s-> End\n", __func__);  
2672 #endif
2673
2674 }
2675
2676 #endif
2677
2678 void addHost(unsigned int hostIp) {
2679   unsigned int *tmpArray;
2680   int *tmpliveHostsArray;       
2681         unsigned int *tmplocateObjHostsArray;
2682
2683   if (findHost(hostIp) != -1)
2684     return;
2685
2686   if (numHostsInSystem == sizeOfHostArray) {
2687     tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
2688     memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
2689     free(hostIpAddrs);
2690     hostIpAddrs = tmpArray;
2691
2692 #ifdef RECOVERY
2693                 tmpliveHostsArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
2694                 memcpy(tmpliveHostsArray, liveHosts, sizeof(unsigned int) * numHostsInSystem);
2695     free(liveHosts);
2696     liveHosts = tmpliveHostsArray;
2697                 
2698                 tmplocateObjHostsArray = calloc(sizeOfHostArray * 2 * 2, sizeof(unsigned int));
2699                 memcpy(tmplocateObjHostsArray, locateObjHosts, sizeof(unsigned int) * numHostsInSystem);
2700     free(locateObjHosts);
2701     locateObjHosts = tmplocateObjHostsArray;
2702 #endif
2703                 sizeOfHostArray *= 2;
2704   }
2705
2706   hostIpAddrs[numHostsInSystem] = hostIp;
2707
2708 #ifdef RECOVERY
2709   liveHosts[numHostsInSystem] = 0;
2710   locateObjHosts[numHostsInSystem*2] = hostIp;
2711 #endif
2712
2713         numHostsInSystem++;
2714   return;
2715 }
2716
2717 int findHost(unsigned int hostIp) {
2718   int i;
2719   for (i = 0; i < numHostsInSystem; i++)
2720     if (hostIpAddrs[i] == hostIp)
2721       return i;
2722
2723   //not found
2724   return -1;
2725 }
2726
2727 /* This function sends notification request per thread waiting on object(s) whose version
2728  * changes */
2729 #ifdef RECOVERY
2730 int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int numoid, int waitmid) {
2731 #else
2732 int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int numoid) {
2733 #endif
2734   int psock,i;
2735   objheader_t *objheader;
2736   struct sockaddr_in premoteAddr;
2737   char msg[1 + numoid * (sizeof(unsigned short) + sizeof(unsigned int)) +  3 * sizeof(unsigned int)];
2738   char *ptr;
2739   int status, size;
2740   unsigned short version;
2741   unsigned int oid,mid;
2742   static unsigned int threadid = 0;
2743   pthread_mutex_t threadnotify = PTHREAD_MUTEX_INITIALIZER; //Lock and condition var for threadjoin and notification
2744   pthread_cond_t threadcond = PTHREAD_COND_INITIALIZER;
2745   notifydata_t *ndata;
2746
2747 #ifdef RECOVERY
2748   int bsock;
2749   struct sockaddr_in bremoteAddr;
2750 #endif
2751
2752   oid = oidarry[0];
2753
2754   if((mid = lhashSearch(oid)) == 0) {
2755     printf("Error: %s() No such machine found for oid =%x\n",__func__, oid);
2756     return;
2757   }
2758 #ifdef RECOVERY
2759   int pmid = getPrimaryMachine(mid);
2760   int bmid = getBackupMachine(mid);
2761 #else
2762   int pmid = mid;
2763 #endif
2764
2765 #ifdef RECOVERY
2766   if ((psock = socket(AF_INET, SOCK_STREAM, 0)) < 0 ||
2767       (bsock = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
2768 #else
2769   if ((psock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
2770 #endif
2771     perror("reqNotify():socket()");
2772     return -1;
2773   }
2774
2775   /* for primary machine */
2776   bzero(&premoteAddr, sizeof(premoteAddr));
2777   premoteAddr.sin_family = AF_INET;
2778   premoteAddr.sin_port = htons(LISTEN_PORT);
2779   premoteAddr.sin_addr.s_addr = htonl(pmid);
2780
2781 #ifdef RECOVERY
2782   /* for backup machine */
2783   bzero(&bremoteAddr, sizeof(bremoteAddr));
2784   bremoteAddr.sin_family = AF_INET;
2785   bremoteAddr.sin_port = htons(LISTEN_PORT);
2786   bremoteAddr.sin_addr.s_addr = htonl(bmid);
2787 #endif
2788   /* Generate unique threadid */
2789   threadid++;
2790   
2791   /* Save threadid, numoid, oidarray, versionarray, pthread_cond_variable for later processing */
2792   if((ndata = calloc(1, sizeof(notifydata_t))) == NULL) {
2793     printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
2794     return -1;
2795   }
2796   ndata->numoid = numoid;
2797   ndata->threadid = threadid;
2798   ndata->oidarry = oidarry;
2799   ndata->versionarry = versionarry;
2800   ndata->threadcond = threadcond;
2801   ndata->threadnotify = threadnotify;
2802   if((status = notifyhashInsert(threadid, ndata)) != 0) {
2803     printf("reqNotify(): Insert into notify hash table not successful %s, %d\n", __FILE__, __LINE__);
2804     free(ndata);
2805     return -1;
2806   }
2807
2808   /* Send  number of oids, oidarry, version array, machine id and threadid */
2809 #ifdef RECOVERY
2810   if ((connect(psock, (struct sockaddr *)&premoteAddr, sizeof(premoteAddr))< 0) || 
2811       (connect(bsock, (struct sockaddr *)&bremoteAddr, sizeof(bremoteAddr))< 0)) {
2812 #else
2813   if ((connect(psock, (struct sockaddr *)&premoteAddr, sizeof(premoteAddr))< 0)) {
2814 #endif
2815     printf("reqNotify():error %d connecting to %s:%d\n", errno,
2816     inet_ntoa(premoteAddr.sin_addr), LISTEN_PORT);
2817     free(ndata);
2818     return -1;
2819   } else {
2820
2821 #ifdef DEBUG
2822     printf("%s -> Pmid = %s\n",__func__,midtoIPString(pmid));
2823 #ifdef RECOVERY
2824     printf("%s -> Bmid = %s\n",__func__,midtoIPString(bmid));
2825 #endif
2826 #endif
2827
2828     msg[0] = THREAD_NOTIFY_REQUEST;
2829
2830     *((unsigned int *)(&msg[1])) = numoid;
2831     /* Send array of oids  */
2832     size = sizeof(unsigned int);
2833
2834     for(i = 0;i < numoid; i++) {
2835       oid = oidarry[i];
2836 #ifdef DEBUG
2837       printf("%s -> oid[%d] = %d\n",__func__,i,oidarry[i]);
2838 #endif
2839       *((unsigned int *)(&msg[1] + size)) = oid;
2840       size += sizeof(unsigned int);
2841     }
2842
2843     /* Send array of version  */
2844     for(i = 0;i < numoid; i++) {
2845       version = versionarry[i];
2846       *((unsigned short *)(&msg[1] + size)) = version;
2847       size += sizeof(unsigned short);
2848     }
2849
2850     *((unsigned int *)(&msg[1] + size)) = myIpAddr; 
2851     size += sizeof(unsigned int);
2852     *((unsigned int *)(&msg[1] + size)) = threadid;
2853 #ifdef RECOVERY
2854     waitThreadMid = waitmid;
2855     waitThreadID = threadid;
2856 #ifdef DEBUG
2857     printf("%s -> This Thread is waiting for %s\n",__func__,midtoIPString(waitmid));
2858 #endif
2859 #endif
2860
2861     size = 1 + numoid * (sizeof(unsigned int) + sizeof(unsigned short)) + 3 * sizeof(unsigned int);
2862     pthread_mutex_lock(&(ndata->threadnotify));
2863     send_data(psock, msg, size);
2864 #ifdef RECOVERY
2865     send_data(bsock, msg, size);
2866 #endif
2867     pthread_cond_wait(&(ndata->threadcond), &(ndata->threadnotify));
2868     pthread_mutex_unlock(&(ndata->threadnotify));
2869   }
2870
2871   pthread_cond_destroy(&threadcond);
2872   pthread_mutex_destroy(&threadnotify);
2873   free(ndata);
2874   close(psock);
2875
2876 #ifdef RECOVERY
2877   close(bsock);
2878 #endif
2879
2880   return status;
2881 }
2882
2883 void threadNotify(unsigned int oid, unsigned short version, unsigned int tid) {
2884   notifydata_t *ndata;
2885   int i, objIsFound = 0, index = -1;
2886   void *ptr;
2887 #ifdef DEBUG
2888   printf("%s -> oid = %d   vesion = %d    tid = %d\n",__func__,oid,version,tid);
2889 #endif
2890
2891   //Look up the tid and call the corresponding pthread_cond_signal
2892   if((ndata = notifyhashSearch(tid)) == NULL) {
2893     printf("threadnotify(): No such threadid is present %s, %d\n", __FILE__, __LINE__);
2894     return;
2895   } else  {
2896     for(i = 0; i < ndata->numoid; i++) {
2897       if(ndata->oidarry[i] == oid) {
2898         objIsFound = 1;
2899         index = i;
2900
2901       }
2902     }
2903     if(objIsFound == 0) {
2904       printf("threadNotify(): Oid not found %s, %d\n", __FILE__, __LINE__);
2905       return;
2906     } 
2907     else {
2908       if(version <= ndata->versionarry[index] && version >= 0) {
2909               printf("threadNotify(): New version %d has not changed since last version for oid = %d, %s, %d\n", version, oid, __FILE__, __LINE__);
2910         return;
2911       } else {
2912 #ifdef CACHE
2913         /* Clear from prefetch cache and free thread related data structure */
2914         if((ptr = prehashSearch(oid)) != NULL) {
2915           prehashRemove(oid);
2916         }
2917 #endif
2918         pthread_mutex_lock(&(ndata->threadnotify));
2919         pthread_cond_signal(&(ndata->threadcond));
2920         pthread_mutex_unlock(&(ndata->threadnotify));
2921       }
2922     }
2923   }
2924
2925 #ifdef DEBUG
2926   printf("%s -> Finished\n",__func__);
2927 #endif
2928   return;
2929 }
2930
2931 int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) {
2932   threadlist_t *ptr;
2933   unsigned int mid;
2934   struct sockaddr_in remoteAddr;
2935   char msg[1 + sizeof(unsigned short) + 2*sizeof(unsigned int)];
2936   int sock, status, size, bytesSent;
2937 #ifdef DEBUG
2938   printf("%s -> Entering \n",__func__);
2939 #endif
2940
2941   while(*head != NULL) {
2942     ptr = *head;
2943     mid = ptr->mid;
2944
2945     //create a socket connection to that machine
2946     if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
2947       perror("notifyAll():socket()");
2948       return -1;
2949     }
2950
2951     bzero(&remoteAddr, sizeof(remoteAddr));
2952     remoteAddr.sin_family = AF_INET;
2953     remoteAddr.sin_port = htons(LISTEN_PORT);
2954     remoteAddr.sin_addr.s_addr = htonl(mid);
2955     //send Thread Notify response and threadid to that machine
2956     if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0) {
2957       printf("notifyAll():error %d connecting to %s:%d\n", errno,
2958              inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
2959       fflush(stdout);
2960       status = -1;
2961     } else {
2962       bzero(msg, (1+sizeof(unsigned short) + 2*sizeof(unsigned int)));
2963       msg[0] = THREAD_NOTIFY_RESPONSE;
2964       *((unsigned int *)&msg[1]) = oid;
2965       size = sizeof(unsigned int);
2966       *((unsigned short *)(&msg[1]+ size)) = version;
2967       size+= sizeof(unsigned short);
2968       *((unsigned int *)(&msg[1]+ size)) = ptr->threadid;
2969
2970       size = 1 + 2*sizeof(unsigned int) + sizeof(unsigned short);
2971       send_data(sock, msg, size);
2972     }
2973     //close socket
2974     close(sock);
2975     // Update head
2976     *head = ptr->next;
2977     free(ptr);
2978   }
2979   return status;
2980 }
2981
2982
2983 void transAbort() {
2984 #ifdef ABORTREADERS
2985   removetransactionhash();
2986 #endif
2987   objstrDelete(t_cache);
2988   t_chashDelete();
2989 }
2990
2991 /* This function inserts necessary information into
2992  * a machine pile data structure */
2993 plistnode_t *pInsert(plistnode_t *pile, objheader_t *headeraddr, unsigned int mid, int num_objs) {
2994   plistnode_t *ptr, *tmp;
2995   int found = 0, offset = 0;
2996   tmp = pile;
2997
2998   //Add oid into a machine that is already present in the pile linked list structure
2999   while(tmp != NULL) {
3000     if (tmp->mid == mid) {
3001       int tmpsize;
3002
3003                         if (STATUS(headeraddr) & NEW) {
3004                                 tmp->oidcreated[tmp->numcreated] = OID(headeraddr);
3005                                 tmp->numcreated++;
3006                                 GETSIZE(tmpsize, headeraddr);
3007                                 tmp->sum_bytes += sizeof(objheader_t) + tmpsize;
3008                         } else if (STATUS(headeraddr) & DIRTY) {
3009                                 tmp->oidmod[tmp->nummod] = OID(headeraddr);
3010                                 tmp->nummod++;
3011                                 GETSIZE(tmpsize, headeraddr);
3012                                 tmp->sum_bytes += sizeof(objheader_t) + tmpsize;
3013                                 /*      midtoIP(tmp->mid, ip);
3014                                         printf("pp; Redo? pile->mid: %s, oid: %d, header version: %d\n", ip, OID(headeraddr), headeraddr->version);*/
3015                         } else {
3016                                 offset = (sizeof(unsigned int) + sizeof(short)) * tmp->numread;
3017                                 *((unsigned int *)(((char *)tmp->objread) + offset))=OID(headeraddr);
3018                                 offset += sizeof(unsigned int);
3019                                 *((short *)(((char *)tmp->objread) + offset)) = headeraddr->version;
3020                                 tmp->numread++;
3021       }
3022       found = 1;
3023       break;
3024     }
3025     tmp = tmp->next;
3026   }
3027   //Add oid for any new machine
3028   if (!found) {
3029     int tmpsize;
3030     if((ptr = pCreate(num_objs)) == NULL) {
3031       printf("pCreate Error\n");
3032       return NULL;
3033     }
3034
3035     ptr->mid = mid;
3036     if (STATUS(headeraddr) & NEW) {
3037       ptr->oidcreated[ptr->numcreated] = OID(headeraddr);
3038       ptr->numcreated++;
3039       GETSIZE(tmpsize, headeraddr);
3040       ptr->sum_bytes += sizeof(objheader_t) + tmpsize;
3041           } else if (STATUS(headeraddr) & DIRTY) {
3042       ptr->oidmod[ptr->nummod] = OID(headeraddr);
3043       ptr->nummod++;
3044       GETSIZE(tmpsize, headeraddr);
3045       ptr->sum_bytes += sizeof(objheader_t) + tmpsize;
3046     } else {
3047       *((unsigned int *)ptr->objread)=OID(headeraddr);
3048       offset = sizeof(unsigned int);
3049       *((short *)(((char *)ptr->objread) + offset)) = headeraddr->version;
3050       ptr->numread++;
3051     }
3052
3053     ptr->next = pile;
3054     pile = ptr;
3055   }
3056
3057   /* Clear Flags */
3058   STATUS(headeraddr) = 0;
3059
3060   return pile;
3061 }
3062
3063 plistnode_t *sortPiles(plistnode_t *pileptr) {
3064         plistnode_t *head, *ptr, *tail;
3065         head = pileptr;
3066         ptr = pileptr;
3067         /* Get tail pointer */
3068         while(ptr!= NULL) {
3069                 tail = ptr;
3070                 ptr = ptr->next;
3071         }
3072         ptr = pileptr;
3073         plistnode_t *prev = pileptr;
3074         /* Arrange local machine processing at the end of the pile list */
3075         while(ptr != NULL) {
3076                 if(ptr != tail) {
3077       /*
3078                         if(ptr->mid == myIpAddr && (prev != pileptr)) {
3079                                 prev->next = ptr->next;
3080                                 ptr->next = NULL;
3081                                 tail->next = ptr;
3082                                 return pileptr;
3083                         }
3084                         if((ptr->mid == myIpAddr) && (prev == pileptr)) {
3085         prev->next = ptr->next;
3086         ptr->next = NULL;
3087         tail->next = ptr;
3088                                 return pileptr;
3089                         }
3090       */
3091
3092       if((ptr->mid == myIpAddr))
3093       {
3094         tail->next = pileptr;
3095         pileptr = ptr->next;
3096         ptr->next = NULL;
3097         return pileptr;
3098       }
3099                         prev = ptr;
3100                 }
3101                 ptr = ptr->next;
3102         }
3103         return pileptr;
3104 }
3105
3106 #ifdef RECOVERY
3107 /* Paxo Algorithm: 
3108  * Executes when the known leader has failed.  
3109  * Guarantees consensus on next leader among all live hosts.  */
3110 int paxos()
3111 {
3112         int origRound = paxosRound;
3113         origleader = leader;
3114         int ret = -1;
3115 #ifdef DEBUG
3116         printf(">> Debug : Starting paxos..\n");
3117 #endif
3118
3119         do {
3120                 ret = paxosPrepare();           // phase 1
3121                 if (ret == 1) {
3122                         ret = paxosAccept();    // phase 2
3123                         if (ret == 1) {
3124                                 paxosLearn();                           // phase 3
3125                                 break;
3126                         }
3127                 }
3128                 // Paxos not successful; wait and retry if new leader is not yet slected
3129                 sleep(WAIT_TIME);               
3130                 if(paxosRound != origRound)
3131                         break;
3132         } while (ret == -1);
3133
3134 #ifdef DEBUG
3135         printf("\n>> Debug : Leader : [%s]\t[%u]\n", midtoIPString(leader),leader);
3136 #endif
3137
3138         return ret;
3139 }
3140
3141 int paxosPrepare()
3142 {
3143         char control;
3144         //int origleader = leader;
3145         int remote_n;
3146         int remote_v;
3147         int tmp_n = -1;
3148         int cnt = 0;
3149         int sd;
3150         int i;
3151         temp_v_a = v_a;
3152         my_n = n_h + 1;
3153
3154 #ifdef DEBUG
3155         printf("[Prepare]...\n");
3156 #endif
3157
3158         temp_v_a = myIpAddr;    // if no other value is proposed, make this machine the new leader
3159
3160         for (i = 0; i < numHostsInSystem; ++i) {
3161                 control = PAXOS_PREPARE;
3162                 if(!liveHosts[i]) 
3163                         continue;
3164
3165                 if ((sd = getSockWithLock(transPrefetchSockPool, hostIpAddrs[i])) < 0) {
3166                         printf("paxosPrepare(): socket create error\n");
3167                         continue;
3168                 }
3169 #ifdef DEBUG
3170                 printf("%s-> Send PAXOS_PREPARE to mid [%s] with my_n=%d\n", __func__, midtoIPString(hostIpAddrs[i]), my_n);
3171 #endif
3172                 send_data(sd, &control, sizeof(char));  
3173                 send_data(sd, &my_n, sizeof(int));
3174                 int timeout = recv_data(sd, &control, sizeof(char));
3175                 if ((sd == -1) || (timeout < 0)) {
3176 #ifdef DEBUG
3177                         printf("%s-> timeout to machine [%s]\n", __func__, midtoIPString(hostIpAddrs[i]));
3178 #endif
3179                         continue;
3180                 }
3181
3182                 switch (control) {
3183                         case PAXOS_PREPARE_OK:
3184                                 cnt++;
3185                                 recv_data(sd, &remote_n, sizeof(int));
3186                                 recv_data(sd, &remote_v, sizeof(int));
3187 #ifdef DEBUG
3188                                 printf("%s-> Received PAXOS_PREPARE_OK from mindex [%d] with remote_v=%s\n", __func__, i, midtoIPString(remote_v));
3189 #endif
3190                                 if(remote_v != origleader) {
3191                                         if (remote_n > tmp_n) {
3192                                                 tmp_n = remote_n;
3193                                                 temp_v_a = remote_v;
3194                                         }
3195                                 }
3196                                 break;
3197                         case PAXOS_PREPARE_REJECT:
3198                                 break;
3199                 }
3200     
3201     freeSockWithLock(transPrefetchSockPool,hostIpAddrs[i],sd);
3202         }
3203
3204 #ifdef DEBUG
3205         printf("%s-> cnt:%d, numLiveHostsInSystem:%d\n", __func__, cnt, numLiveHostsInSystem);
3206 #endif
3207
3208         if (cnt >= (numLiveHostsInSystem / 2)) {                // majority of OK replies
3209                 return 1;
3210                 }
3211                 else {
3212                         return -1;
3213                 }
3214 }
3215
3216 int paxosAccept()
3217 {
3218         char control;
3219         int i;
3220         int cnt = 0;
3221         int sd;
3222         int remote_v = temp_v_a;
3223
3224 #ifdef DEBUG
3225         printf("[Accept]...\n");
3226 #endif
3227         for (i = 0; i < numHostsInSystem; ++i) {
3228                 control = PAXOS_ACCEPT;
3229           
3230     if(!liveHosts[i]) 
3231                         continue;
3232
3233         if ((sd = getSockWithLock(transPrefetchSockPool, hostIpAddrs[i])) < 0) {
3234                         printf("paxosAccept(): socket create error\n");
3235                         continue;
3236                 }
3237
3238                 send_data(sd, &control, sizeof(char));
3239                 send_data(sd, &my_n, sizeof(int));
3240                 send_data(sd, &remote_v, sizeof(int));
3241
3242                 int timeout = recv_data(sd, &control, sizeof(char));
3243                 if ((sd == -1) || (timeout < 0)) {
3244 #ifdef DEBUG
3245                         printf("%s-> timeout to machine [%s]\n", __func__, midtoIPString(hostIpAddrs[i]));
3246 #endif
3247                         continue;  
3248                 }
3249
3250                 switch (control) {
3251                         case PAXOS_ACCEPT_OK:
3252                                 cnt++;
3253                                 break;
3254                         case PAXOS_ACCEPT_REJECT:
3255                                 break;
3256                 }
3257 #ifdef DEBUG
3258                 printf(">> Debug : Accept - n_h [%d], n_a [%d], v_a [%s]\n", n_h, n_a, midtoIPString(v_a));
3259 #endif
3260     freeSockWithLock(transPrefetchSockPool,hostIpAddrs[i],sd);
3261         }
3262
3263         if (cnt >= (numLiveHostsInSystem / 2)) {
3264                 return 1;
3265         }
3266         else {
3267                 return -1;
3268         }
3269 }
3270
3271 void paxosLearn()
3272 {
3273         char control;
3274         int sd;
3275         int i;
3276
3277 #ifdef DEBUG
3278         printf("[Learn]...\n");
3279 #endif
3280
3281         control = PAXOS_LEARN;
3282
3283         for (i = 0; i < numHostsInSystem; ++i) {
3284                 if(!liveHosts[i]) 
3285                         continue;
3286                 if(hostIpAddrs[i] == myIpAddr)
3287                 {
3288                         leader = v_a;
3289                         paxosRound++;
3290 #ifdef DEBUG
3291                         printf("This is my leader!!!: [%s]\n", midtoIPString(leader));
3292 #endif
3293                         continue;
3294                 }
3295                 if ((sd = getSockWithLock(transPrefetchSockPool, hostIpAddrs[i])) < 0) {
3296                         continue;
3297                         //                      printf("paxosLearn(): socket create error, attemp\n");
3298                 }
3299
3300                 send_data(sd, &control, sizeof(char));
3301                 send_data(sd, &v_a, sizeof(int));
3302
3303     freeSockWithLock(transPrefetchSockPool,hostIpAddrs[i],sd);
3304
3305         }
3306         //return v_a;
3307 }
3308 #endif
3309
3310 #ifdef RECOVERY
3311 void clearDeadThreadsNotification() 
3312 {
3313
3314 #ifdef DEBUG
3315   printf("%s -> Entered\n",__func__);
3316 #endif
3317 // clear all the threadnotify request first
3318   
3319   if(waitThreadID != -1) {
3320 #ifdef DEBUG
3321     printf("%s -> I was waitng for %s\n",__func__,midtoIPString(waitThreadMid));
3322 #endif
3323     int waitThreadIndex = findHost(waitThreadMid);
3324     int i;
3325     notifydata_t *ndata;
3326
3327     if(liveHosts[waitThreadIndex] == 0) // the thread waiting for is dead
3328     {
3329       if((ndata = (notifydata_t*)notifyhashSearch(waitThreadID)) == NULL) {
3330         return;
3331       }
3332    
3333       for(i =0 ; i < ndata->numoid; i++) {
3334         clearNotifyList(ndata->oidarry[i]);  // clear thread object's notifylist
3335       }
3336
3337       pthread_mutex_lock(&(ndata->threadnotify));
3338       pthread_cond_signal(&(ndata->threadcond));
3339       pthread_mutex_unlock(&(ndata->threadnotify));
3340
3341       waitThreadMid = -1;
3342       waitThreadID = -1;
3343     }
3344   }
3345
3346 #ifdef DEBUG
3347   printf("%s -> Finished\n",__func__);
3348 #endif
3349 }
3350
3351 /* request the primary and the backup machines to clear
3352    thread obj's notify list */
3353 void reqClearNotifyList(unsigned int oid)
3354 {
3355   int psock,bsock,i;
3356   int mid,pmid,bmid;
3357   objheader_t *objheader;
3358   struct sockaddr_in premoteAddr, bremoteAddr;
3359   char msg[1 + sizeof(unsigned int)];
3360
3361   if((mid = lhashSearch(oid)) == 0) {
3362     printf("%s -> No such machine found for oid %x\n",__func__,oid);
3363     return;
3364   }
3365
3366   pmid = getPrimaryMachine(mid);
3367   bmid = getBackupMachine(mid);
3368
3369   if((psock = socket(AF_INET, SOCK_STREAM, 0)) < 0 ||
3370      (bsock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
3371         perror("clearNotifyList() : socket()");
3372     return ;
3373   }
3374
3375   /* for primary machine */
3376   bzero(&premoteAddr, sizeof(premoteAddr));
3377   premoteAddr.sin_family = AF_INET;
3378   premoteAddr.sin_port = htons(LISTEN_PORT);
3379   premoteAddr.sin_addr.s_addr = htonl(pmid);
3380
3381   /* for backup machine */
3382   bzero(&bremoteAddr, sizeof(bremoteAddr));
3383   bremoteAddr.sin_family = AF_INET;
3384   bremoteAddr.sin_port = htons(LISTEN_PORT);
3385   bremoteAddr.sin_addr.s_addr = htonl(bmid);
3386
3387   /* send message to both the primary and the backup */
3388   if((connect(psock, (struct sockaddr *)&premoteAddr, sizeof(premoteAddr)) < 0) ||
3389      (connect(bsock, (struct sockaddr *)&bremoteAddr, sizeof(bremoteAddr)) < 0)) {
3390       printf("%s -> error in connecting\n",__func__);
3391       return;
3392   }
3393   else {
3394     printf("%s -> Pmid = %s\n",__func__,midtoIPString(pmid));
3395     printf("%s -> Bmid = %s\n",__func__,midtoIPString(bmid));
3396     
3397     msg[0] = CLEAR_NOTIFY_LIST;
3398     *((unsigned int *)(&msg[1])) = oid;
3399     
3400     send_data(psock, &msg, sizeof(char) + sizeof(unsigned int));
3401     send_data(bsock, &msg, sizeof(char) + sizeof(unsigned int)); 
3402   }
3403   
3404   close(psock);
3405   close(bsock);
3406   
3407 }
3408    
3409
3410 int checkiftheMachineDead(unsigned int mid) {
3411   int mIndex = findHost(mid);
3412   return getStatus(mIndex);
3413 }
3414
3415 #endif