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