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