changes
[IRC.git] / Robust / src / Runtime / DSTM / interface / trans.c
index 36fdcf1ecd20221b2c866b006ec3d73ce0baa39a..ec852ce3bde1b9d06e9ad856d81f3db32eec4d01 100644 (file)
@@ -1,30 +1,85 @@
 #include "dstm.h"
+#include "debugmacro.h"
 #include "ip.h"
 #include "machinepile.h"
-#include "mlookup.h"
+#include "altmlookup.h"
 #include "llookup.h"
 #include "plookup.h"
-#include "prelookup.h"
+#include "altprelookup.h"
 #include "threadnotify.h"
 #include "queue.h"
 #include "addUdpEnhance.h"
 #include "addPrefetchEnhance.h"
 #include "gCollect.h"
 #include "dsmlock.h"
+#include "prefetch.h"
 #ifdef COMPILER
 #include "thread.h"
 #endif
+#ifdef ABORTREADERS
+#include "abortreaders.h"
+#endif
+#include "trans.h"
 
 #define NUM_THREADS 1
-#define PREFETCH_CACHE_SIZE 1048576 //1MB
 #define CONFIG_FILENAME "dstm.conf"
 
+//#define LOGEVENTS //turn on Logging events
+#ifdef LOGEVENTS
+char bigarray[16*1024*1024];
+int bigindex=0;
+#define LOGEVENT(x) { \
+    int tmp=bigindex++;                                \
+    bigarray[tmp]=x;                           \
+  }
+#else
+#define LOGEVENT(x)
+#endif
+
+//#define LOGTIMES
+#ifdef LOGTIMES
+char bigarray1[6*1024*1024];
+unsigned int bigarray2[6*1024*1024];
+unsigned int bigarray3[6*1024*1024];
+long long bigarray4[6*1024*1024];
+int bigarray5[6*1024*1024];
+int bigindex1=0;
+#define LOGTIME(x,y,z,a,b) {\
+  int tmp=bigindex1; \
+  bigarray1[tmp]=x; \
+  bigarray2[tmp]=y; \
+  bigarray3[tmp]=z; \
+  bigarray4[tmp]=a; \
+  bigarray5[tmp]=b; \
+  bigindex1++; \
+}
+#else
+#define LOGTIME(x,y,z,a,b)
+#endif
+
+/* Thread transaction variables */
+__thread objstr_t *t_cache;
+__thread struct ___Object___ *revertlist;
+__thread struct timespec exponential_backoff;
+__thread int count_exponential_backoff;
+__thread const int max_exponential_backoff = 1000; // safety limit
+#ifdef SANDBOX
+__thread int trans_allocation_bytes;
+#endif
+
+
+#ifdef ABORTREADERS
+__thread int t_abort;
+__thread jmp_buf aborttrans;
+#endif
+
+int globalid=0; /* This variable is a unique global identifier for a sendPrefetch request */
+
 /* Global Variables */
 extern int classsize[];
 pfcstats_t *evalPrefetch;
 extern int numprefetchsites; //Global variable containing number of prefetch sites
 extern pthread_mutex_t mainobjstore_mutex; // Mutex to lock main Object store
-objstr_t *prefetchcache; //Global Prefetch cache
 pthread_mutex_t prefetchcache_mutex; // Mutex to lock Prefetch Cache
 pthread_mutexattr_t prefetchcache_mutex_attr; /* Attribute for lock to make it a recursive lock */
 extern prehashtable_t pflookup; //Global Prefetch cache's lookup table
@@ -39,7 +94,6 @@ int myIndexInHostArray;
 unsigned int oidsPerBlock;
 unsigned int oidMin;
 unsigned int oidMax;
-
 sockPoolHashTable_t *transReadSockPool;
 sockPoolHashTable_t *transPrefetchSockPool;
 sockPoolHashTable_t *transRequestSockPool;
@@ -54,11 +108,18 @@ int numTransAbort = 0;
 int nchashSearch = 0;
 int nmhashSearch = 0;
 int nprehashSearch = 0;
+int ndirtyCacheObj = 0;
 int nRemoteSend = 0;
 int nSoftAbort = 0;
+int bytesSent = 0;
+int bytesRecv = 0;
+int totalObjSize = 0;
+int sendRemoteReq = 0;
+int getResponse = 0;
 
 void printhex(unsigned char *, int);
-plistnode_t *createPiles(transrecord_t *);
+plistnode_t *createPiles();
+plistnode_t *sortPiles(plistnode_t *pileptr);
 
 /*******************************
 * Send and Recv function calls
@@ -69,6 +130,7 @@ void send_data(int fd, void *buf, int buflen) {
   int numbytes;
   while (size > 0) {
     numbytes = send(fd, buffer, size, MSG_NOSIGNAL);
+    bytesSent = bytesSent + numbytes;
     if (numbytes == -1) {
       perror("send");
       exit(0);
@@ -78,12 +140,126 @@ void send_data(int fd, void *buf, int buflen) {
   }
 }
 
+void send_buf(int fd, struct writestruct * sendbuffer, void *buffer, int buflen) {
+  if (buflen+sendbuffer->offset>WMAXBUF) {
+    send_data(fd, sendbuffer->buf, sendbuffer->offset);
+    sendbuffer->offset=0;
+    send_data(fd, buffer, buflen);
+    return;
+  }
+  memcpy(&sendbuffer->buf[sendbuffer->offset], buffer, buflen);
+  sendbuffer->offset+=buflen;
+  if (sendbuffer->offset>WTOP) {
+    send_data(fd, sendbuffer->buf, sendbuffer->offset);
+    sendbuffer->offset=0;
+  }
+}
+
+void forcesend_buf(int fd, struct writestruct * sendbuffer, void *buffer, int buflen) {
+  if (buflen+sendbuffer->offset>WMAXBUF) {
+    send_data(fd, sendbuffer->buf, sendbuffer->offset);
+    sendbuffer->offset=0;
+    send_data(fd, buffer, buflen);
+    return;
+  }
+  memcpy(&sendbuffer->buf[sendbuffer->offset], buffer, buflen);
+  sendbuffer->offset+=buflen;
+  send_data(fd, sendbuffer->buf, sendbuffer->offset);
+  sendbuffer->offset=0;
+}
+
+int recvw(int fd, void *buf, int len, int flags) {
+  return recv(fd, buf, len, flags);
+}
+void recv_data_buf(int fd, struct readstruct * readbuffer, void *buffer, int buflen) {
+  char *buf=(char *)buffer;
+  int numbytes=readbuffer->head-readbuffer->tail;
+  if (numbytes>buflen)
+    numbytes=buflen;
+  if (numbytes>0) {
+    memcpy(buf, &readbuffer->buf[readbuffer->tail], numbytes);
+    readbuffer->tail+=numbytes;
+    buflen-=numbytes;
+    buf+=numbytes;
+  }
+  if (buflen==0) {
+    return;
+  }
+  if (buflen>=MAXBUF) {
+    recv_data(fd, buf, buflen);
+    return;
+  }
+  
+  int maxbuf=MAXBUF;
+  int obufflen=buflen;
+  readbuffer->head=0;
+  
+  while (buflen > 0) {
+    int numbytes = recvw(fd, &readbuffer->buf[readbuffer->head], maxbuf, 0);
+    if (numbytes == -1) {
+      perror("recv");
+      exit(0);
+    }
+    bytesRecv+=numbytes;
+    buflen-=numbytes;
+    readbuffer->head+=numbytes;
+    maxbuf-=numbytes;
+  }
+  memcpy(buf,readbuffer->buf,obufflen);
+  readbuffer->tail=obufflen;
+}
+
+int recv_data_errorcode_buf(int fd, struct readstruct * readbuffer, void *buffer, int buflen) {
+  char *buf=(char *)buffer;
+  //now tail<=head
+  int numbytes=readbuffer->head-readbuffer->tail;
+  if (numbytes>buflen)
+    numbytes=buflen;
+  if (numbytes>0) {
+    memcpy(buf, &readbuffer->buf[readbuffer->tail], numbytes);
+    readbuffer->tail+=numbytes;
+    buflen-=numbytes;
+    buf+=numbytes;
+  }
+  if (buflen==0)
+    return 1;
+
+  if (buflen>=MAXBUF) {
+    return recv_data_errorcode(fd, buf, buflen);
+  }
+
+  int maxbuf=MAXBUF;
+  int obufflen=buflen;
+  readbuffer->head=0;
+  
+  while (buflen > 0) {
+    int numbytes = recvw(fd, &readbuffer->buf[readbuffer->head], maxbuf, 0);
+    if (numbytes ==0) {
+      return 0;
+    }
+    if (numbytes==-1) {
+      perror("recvbuf");
+      return -1;
+    }
+    bytesRecv+=numbytes;
+    buflen-=numbytes;
+    readbuffer->head+=numbytes;
+    maxbuf-=numbytes;
+  }
+  memcpy(buf,readbuffer->buf,obufflen);
+  readbuffer->tail=obufflen;
+  return 1;
+}
+
+
 void recv_data(int fd, void *buf, int buflen) {
   char *buffer = (char *)(buf);
   int size = buflen;
   int numbytes;
   while (size > 0) {
-    numbytes = recv(fd, buffer, size, 0);
+    numbytes = recvw(fd, buffer, size, 0);
+    bytesRecv = bytesRecv + numbytes;
     if (numbytes == -1) {
       perror("recv");
       exit(0);
@@ -98,13 +274,14 @@ int recv_data_errorcode(int fd, void *buf, int buflen) {
   int size = buflen;
   int numbytes;
   while (size > 0) {
-    numbytes = recv(fd, buffer, size, 0);
+    numbytes = recvw(fd, buffer, size, 0);
     if (numbytes==0)
       return 0;
     if (numbytes == -1) {
       perror("recv");
       return -1;
     }
+    bytesRecv+=numbytes;
     buffer += numbytes;
     size -= numbytes;
   }
@@ -141,17 +318,32 @@ inline int findmax(int *array, int arraylength) {
   return max;
 }
 
+#define INLINEPREFETCH
+#define PREFTHRESHOLD 0
+
 /* This function is a prefetch call generated by the compiler that
  * populates the shared primary prefetch queue*/
 void prefetch(int siteid, int ntuples, unsigned int *oids, unsigned short *endoffsets, short *arrayfields) {
   /* Allocate for the queue node*/
   int qnodesize = 2*sizeof(int) + ntuples * (sizeof(unsigned short) + sizeof(unsigned int)) + endoffsets[ntuples - 1] * sizeof(short);
   int len;
-  char * node= getmemory(qnodesize);
+#ifdef INLINEPREFETCH
+  int attempted=0;
+  char *node;
+  do {
+  node=getmemory(qnodesize);
+  if (node==NULL&&attempted)
+    break;
+  if (node!=NULL) {
+#else
+  char *node=getmemory(qnodesize);
+#endif
   int top=endoffsets[ntuples-1];
 
-  if (node==NULL)
+  if (node==NULL) {
+    LOGEVENT('D');
     return;
+  }
   /* Set queue node values */
 
   /* TODO: Remove this after testing */
@@ -164,8 +356,36 @@ void prefetch(int siteid, int ntuples, unsigned int *oids, unsigned short *endof
   memcpy(node+len+ntuples*sizeof(unsigned int), endoffsets, ntuples*sizeof(unsigned short));
   memcpy(node+len+ntuples*(sizeof(unsigned int)+sizeof(short)), arrayfields, top*sizeof(short));
 
+#ifdef INLINEPREFETCH
+  movehead(qnodesize);
+  }
+  int numpref=numavailable();
+  attempted=1;
+
+  if (node==NULL && numpref!=0 || numpref>=PREFTHRESHOLD) {
+    node=gettail();
+    prefetchpile_t *pilehead = foundLocal(node,numpref,siteid);
+    if (pilehead!=NULL) {
+      // Get sock from shared pool
+      
+      /* Send  Prefetch Request */
+      prefetchpile_t *ptr = pilehead;
+      while(ptr != NULL) {
+        globalid++;
+        int sd = getSock2(transPrefetchSockPool, ptr->mid);
+        sendPrefetchReq(ptr, sd, globalid);
+        ptr = ptr->next;
+      }
+      
+      mcdealloc(pilehead);
+    }
+    resetqueue();
+  }//end do prefetch if condition
+  } while(node==NULL);
+#else
   /* Lock and insert into primary prefetch queue */
   movehead(qnodesize);
+#endif
 }
 
 /* This function starts up the transaction runtime. */
@@ -187,6 +407,9 @@ int dstmStartup(const char * option) {
   printf("Trans stats is on\n");
   fflush(stdout);
 #endif
+#ifdef ABORTREADERS
+  initreaderlist();
+#endif
 
   //Initialize socket pool
   transReadSockPool = createSockPool(transReadSockPool, DEFAULTSOCKPOOLSIZE);
@@ -245,7 +468,6 @@ void *pCacheAlloc(objstr_t *store, unsigned int size) {
 void transInit() {
   //Create and initialize prefetch cache structure
 #ifdef CACHE
-  prefetchcache = objstrCreate(PREFETCH_CACHE_SIZE);
   initializePCache();
   if((evalPrefetch = initPrefetchStats()) == NULL) {
     printf("%s() Error allocating memory at %s, %d\n", __func__, __FILE__, __LINE__);
@@ -262,7 +484,7 @@ void transInit() {
   pthread_mutex_init(&atomicObjLock, NULL);
 #ifdef CACHE
   //Create prefetch cache lookup table
-  if(prehashCreate(HASH_SIZE, LOADFACTOR)) {
+  if(prehashCreate(PHASH_SIZE, PLOADFACTOR)) {
     printf("ERROR\n");
     return; //Failure
   }
@@ -274,11 +496,21 @@ void transInit() {
 
   //Create the primary prefetch thread
   int retval;
+#ifdef RANGEPREFETCH
+  do {
+    retval=pthread_create(&tPrefetch, NULL, transPrefetchNew, NULL);
+  } while(retval!=0);
+#else
+#ifndef INLINEPREFETCH
   do {
     retval=pthread_create(&tPrefetch, NULL, transPrefetch, NULL);
   } while(retval!=0);
+#endif
+#endif
+#ifndef INLINEPREFETCH
   pthread_detach(tPrefetch);
 #endif
+#endif
 }
 
 /* This function stops the threads spawned */
@@ -306,56 +538,117 @@ void randomdelay() {
   return;
 }
 
-/* This function initializes things required in the transaction start*/
-transrecord_t *transStart() {
-  transrecord_t *tmp;
-  if((tmp = calloc(1, sizeof(transrecord_t))) == NULL) {
-    printf("%s() Calloc error at line %d, %s\n", __func__, __LINE__, __FILE__);
-    return NULL;
+void exponentialdelay() {
+  exponential_backoff.tv_nsec = exponential_backoff.tv_nsec * 2;
+  nanosleep(&exponential_backoff, NULL);
+  ++count_exponential_backoff;
+  if (count_exponential_backoff >= max_exponential_backoff) {
+    printf(" reached max_exponential_backoff at %s, %s(), %d\n", __FILE__, __func__, __LINE__);
+    exit(-1);
   }
-  tmp->cache = objstrCreate(1048576);
-  tmp->lookupTable = chashCreate(CHASH_SIZE, CLOADFACTOR);
-#ifdef COMPILER
-  tmp->revertlist=NULL;
+  return;
+}
+
+/* This function initializes things required in the transaction start*/
+void transStart() {
+  t_cache = objstrCreate(1048576);
+  t_chashCreate(CHASH_SIZE, CLOADFACTOR);
+  revertlist=NULL;
+#ifdef SANDBOX
+  trans_allocation_bytes = 0;
+#endif
+#ifdef ABORTREADERS
+  t_abort=0;
 #endif
-  return tmp;
 }
 
+// Search for an address for a given oid                                                                               
+/*#define INLINE    inline __attribute__((always_inline))
+
+INLINE void * chashSearchI(chashtable_t *table, unsigned int key) {
+  //REMOVE HASH FUNCTION CALL TO MAKE SURE IT IS INLINED HERE                                                          
+  chashlistnode_t *node = &table->table[(key & table->mask)>>1];
+
+  do {
+    if(node->key == key) {
+      return node->val;
+    }
+    node = node->next;
+  } while(node != NULL);
+
+  return NULL;
+  }*/
+
+
+
+
 /* This function finds the location of the objects involved in a transaction
  * and returns the pointer to the object if found in a remote location */
-objheader_t *transRead(transrecord_t *record, unsigned int oid) {
+__attribute__((pure)) objheader_t *transRead(unsigned int oid) {
   unsigned int machinenumber;
   objheader_t *tmp, *objheader;
   objheader_t *objcopy;
   int size;
   void *buf;
+  chashlistnode_t *node;
 
   if(oid == 0) {
     return NULL;
   }
+  
 
-  if((objheader = chashSearch(record->lookupTable, oid)) != NULL) {
+  node= &c_table[(oid & c_mask)>>1];
+  do {
+    if(node->key == oid) {
+#ifdef TRANSSTATS
+    nchashSearch++;
+#endif
+#ifdef COMPILER
+    return &((objheader_t*)node->val)[1];
+#else
+    return node->val;
+#endif
+    }
+    node = node->next;
+  } while(node != NULL);
+  
+
+  /*  
+  if((objheader = chashSearchI(record->lookupTable, oid)) != NULL) {
 #ifdef TRANSSTATS
     nchashSearch++;
 #endif
-    /* Search local transaction cache */
 #ifdef COMPILER
     return &objheader[1];
 #else
     return objheader;
 #endif
-  } else if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
+  } else 
+  */
+
+#ifdef ABORTREADERS
+  if (t_abort) {
+    //abort this transaction
+    removetransactionhash();
+    objstrDelete(t_cache);
+    t_chashDelete();
+    _longjmp(aborttrans,1);
+  } else
+    addtransaction(oid);
+#endif
+
+  if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
 #ifdef TRANSSTATS
     nmhashSearch++;
 #endif
     /* Look up in machine lookup table  and copy  into cache*/
     GETSIZE(size, objheader);
     size += sizeof(objheader_t);
-    objcopy = (objheader_t *) objstrAlloc(record->cache, size);
+    objcopy = (objheader_t *) objstrAlloc(&t_cache, size);
     memcpy(objcopy, objheader, size);
     /* Insert into cache's lookup table */
     STATUS(objcopy)=0;
-    chashInsert(record->lookupTable, OID(objheader), objcopy);
+    t_chashInsert(OID(objheader), objcopy);
 #ifdef COMPILER
     return &objcopy[1];
 #else
@@ -364,29 +657,36 @@ objheader_t *transRead(transrecord_t *record, unsigned int oid) {
   } else {
 #ifdef CACHE
     if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) {
+      if(STATUS(tmp) & DIRTY) {
+#ifdef TRANSSTATS
+        ndirtyCacheObj++;
+#endif
+        goto remoteread;
+      }
 #ifdef TRANSSTATS
       nprehashSearch++;
 #endif
       /* Look up in prefetch cache */
       GETSIZE(size, tmp);
       size+=sizeof(objheader_t);
-      objcopy = (objheader_t *) objstrAlloc(record->cache, size);
+      objcopy = (objheader_t *) objstrAlloc(&t_cache, size);
       memcpy(objcopy, tmp, size);
       /* Insert into cache's lookup table */
-      chashInsert(record->lookupTable, OID(tmp), objcopy);
+      t_chashInsert(OID(tmp), objcopy);
 #ifdef COMPILER
       return &objcopy[1];
 #else
       return objcopy;
 #endif
     }
+remoteread:
 #endif
     /* Get the object from the remote location */
     if((machinenumber = lhashSearch(oid)) == 0) {
       printf("Error: %s() No machine found for oid =% %s,%dx\n",__func__, machinenumber, __FILE__, __LINE__);
       return NULL;
     }
-    objcopy = getRemoteObj(record, machinenumber, oid);
+    objcopy = getRemoteObj(machinenumber, oid);
 
     if(objcopy == NULL) {
       printf("Error: Object not found in Remote location %s, %d\n", __FILE__, __LINE__);
@@ -395,8 +695,136 @@ objheader_t *transRead(transrecord_t *record, unsigned int oid) {
 #ifdef TRANSSTATS
       nRemoteSend++;
 #endif
-      STATUS(objcopy)=0;
 #ifdef COMPILER
+#ifdef CACHE
+      //Copy object to prefetch cache
+      pthread_mutex_lock(&prefetchcache_mutex);
+      objheader_t *headerObj;
+      int size;
+      GETSIZE(size, objcopy);
+      if((headerObj = prefetchobjstrAlloc(size + sizeof(objheader_t))) == NULL) {
+        printf("%s(): Error in getting memory from prefetch cache at %s, %d\n", __func__,
+            __FILE__, __LINE__);
+        pthread_mutex_unlock(&prefetchcache_mutex);
+        return NULL;
+      }
+      pthread_mutex_unlock(&prefetchcache_mutex);
+      memcpy(headerObj, objcopy, size+sizeof(objheader_t));
+      //make an entry in prefetch lookup hashtable
+      prehashInsert(oid, headerObj);
+      LOGEVENT('B');
+#endif
+      return &objcopy[1];
+#else
+      return objcopy;
+#endif
+    }
+  }
+}
+
+
+/* This function finds the location of the objects involved in a transaction
+ * and returns the pointer to the object if found in a remote location */
+__attribute__((pure)) objheader_t *transRead2(unsigned int oid) {
+//DEBUG: __attribute__((pure)) objheader_t *transRead2(unsigned int oid, char tmpptr[]) {
+  unsigned int machinenumber;
+  objheader_t *tmp, *objheader;
+  objheader_t *objcopy;
+  int size;
+
+#ifdef ABORTREADERS
+  if (t_abort) {
+    //abort this transaction
+    removetransactionhash();
+    objstrDelete(t_cache);
+    t_chashDelete();
+    _longjmp(aborttrans,1);
+  } else
+    addtransaction(oid);
+#endif
+
+  if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
+#ifdef TRANSSTATS
+    nmhashSearch++;
+#endif
+    /* Look up in machine lookup table  and copy  into cache*/
+    GETSIZE(size, objheader);
+    size += sizeof(objheader_t);
+    objcopy = (objheader_t *) objstrAlloc(&t_cache, size);
+    memcpy(objcopy, objheader, size);
+    /* Insert into cache's lookup table */
+    STATUS(objcopy)=0;
+    t_chashInsert(OID(objheader), objcopy);
+#ifdef COMPILER
+    return &objcopy[1];
+#else
+    return objcopy;
+#endif
+  } else {
+#ifdef CACHE
+    if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) {
+      if(STATUS(tmp) & DIRTY) {
+#ifdef TRANSSTATS
+        ndirtyCacheObj++;
+#endif
+        goto remoteread;
+      }
+#ifdef TRANSSTATS
+      LOGEVENT('P')
+      nprehashSearch++;
+#endif
+      /* Look up in prefetch cache */
+      GETSIZE(size, tmp);
+      size+=sizeof(objheader_t);
+      objcopy = (objheader_t *) objstrAlloc(&t_cache, size);
+      memcpy(objcopy, tmp, size);
+      LOGOIDTYPE("P",oid, TYPE(objcopy), myrdtsc());
+      /* Insert into cache's lookup table */
+      t_chashInsert(OID(tmp), objcopy);
+#ifdef COMPILER
+      return &objcopy[1];
+#else
+      return objcopy;
+#endif
+    }
+remoteread:
+#endif
+    /* Get the object from the remote location */
+    if((machinenumber = lhashSearch(oid)) == 0) {
+      printf("Error: %s() No machine found for oid =% %s,%dx\n",__func__, machinenumber, __FILE__, __LINE__);
+      return NULL;
+    }
+    objcopy = getRemoteObj(machinenumber, oid);
+#ifdef TRANSSTATS
+      LOGEVENT('R');
+      nRemoteSend++;
+#endif
+
+    if(objcopy == NULL) {
+      printf("Error: Object %u not found in Remote location %s, %d\n", oid,__FILE__, __LINE__);
+      return NULL;
+    } else {
+#ifdef COMPILER
+#ifdef CACHE
+      LOGOIDTYPE("RR",oid, TYPE(objcopy),myrdtsc());
+      LOGTIME('r', oid, TYPE(objcopy),myrdtsc(),0);
+      //Copy object to prefetch cache
+      pthread_mutex_lock(&prefetchcache_mutex);
+      objheader_t *headerObj;
+      int size;
+      GETSIZE(size, objcopy);
+      if((headerObj = prefetchobjstrAlloc(size+sizeof(objheader_t))) == NULL) {
+        printf("%s(): Error in getting memory from prefetch cache at %s, %d\n", __func__,
+            __FILE__, __LINE__);
+        pthread_mutex_unlock(&prefetchcache_mutex);
+        return NULL;
+      }
+      pthread_mutex_unlock(&prefetchcache_mutex);
+      memcpy(headerObj, objcopy, size+sizeof(objheader_t));
+      //make an entry in prefetch lookup hashtable
+      prehashInsert(oid, headerObj);
+      LOGEVENT('B');
+#endif
       return &objcopy[1];
 #else
       return objcopy;
@@ -406,13 +834,20 @@ objheader_t *transRead(transrecord_t *record, unsigned int oid) {
 }
 
 /* This function creates objects in the transaction record */
-objheader_t *transCreateObj(transrecord_t *record, unsigned int size) {
-  objheader_t *tmp = (objheader_t *) objstrAlloc(record->cache, (sizeof(objheader_t) + size));
+objheader_t *transCreateObj(unsigned int size) {
+  objheader_t *tmp = (objheader_t *) objstrAlloc(&t_cache, (sizeof(objheader_t) + size));
   OID(tmp) = getNewOID();
   tmp->version = 1;
   tmp->rcount = 1;
   STATUS(tmp) = NEW;
-  chashInsert(record->lookupTable, OID(tmp), tmp);
+  t_chashInsert(OID(tmp), tmp);
+#ifdef SANDBOX
+  trans_allocation_bytes += size;
+  /* Validate the read set if allocation is exceeds threshold */
+  if(trans_allocation_bytes > MEM_ALLOC_THRESHOLD) {
+    check_mem_alloc();
+  }
+#endif
 
 #ifdef COMPILER
   return &tmp[1]; //want space after object header
@@ -421,16 +856,17 @@ objheader_t *transCreateObj(transrecord_t *record, unsigned int size) {
 #endif
 }
 
+#if 1
 /* This function creates machine piles based on all machines involved in a
  * transaction commit request */
-plistnode_t *createPiles(transrecord_t *record) {
+plistnode_t *createPiles() {
   int i;
   plistnode_t *pile = NULL;
   unsigned int machinenum;
   objheader_t *headeraddr;
-  chashlistnode_t * ptr = record->lookupTable->table;
+  chashlistnode_t * ptr = c_table;
   /* Represents number of bins in the chash table */
-  unsigned int size = record->lookupTable->size;
+  unsigned int size = c_size;
 
   for(i = 0; i < size ; i++) {
     chashlistnode_t * curr = &ptr[i];
@@ -439,11 +875,7 @@ plistnode_t *createPiles(transrecord_t *record) {
       //if the first bin in hash table is empty
       if(curr->key == 0)
        break;
-
-      if ((headeraddr = (objheader_t *) chashSearch(record->lookupTable, curr->key)) == NULL) {
-       printf("Error: No such oid %s, %d\n", __FILE__, __LINE__);
-       return NULL;
-      }
+      headeraddr=(objheader_t *) curr->val;
 
       //Get machine location for object id (and whether local or not)
       if (STATUS(headeraddr) & NEW || (mhashSearch(curr->key) != NULL)) {
@@ -454,205 +886,347 @@ plistnode_t *createPiles(transrecord_t *record) {
       }
 
       //Make machine groups
-      pile = pInsert(pile, headeraddr, machinenum, record->lookupTable->numelements);
+      pile = pInsert(pile, headeraddr, machinenum, c_numelements);
       curr = curr->next;
     }
   }
   return pile;
 }
+#else
+/* This function creates machine piles based on all machines involved in a
+ * transaction commit request */
+plistnode_t *createPiles() {
+  int i;
+  plistnode_t *pile = NULL;
+  unsigned int machinenum;
+  objheader_t *headeraddr;
+  struct chashentry * ptr = c_table;
+  /* Represents number of bins in the chash table */
+  unsigned int size = c_size;
+
+  for(i = 0; i < size ; i++) {
+    struct chashentry * curr = & ptr[i];
+    /* Inner loop to traverse the linked list of the cache lookupTable */
+    //if the first bin in hash table is empty
+    if(curr->key == 0)
+      continue;
+    headeraddr=(objheader_t *) curr->ptr;
+
+    //Get machine location for object id (and whether local or not)
+    if (STATUS(headeraddr) & NEW || (mhashSearch(curr->key) != NULL)) {
+      machinenum = myIpAddr;
+    } else if ((machinenum = lhashSearch(curr->key)) == 0) {
+      printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
+      return NULL;
+    }
+
+    //Make machine groups
+    pile = pInsert(pile, headeraddr, machinenum, c_numelements);
+  }
+  return pile;
+}
+#endif
 
 /* This function initiates the transaction commit process
  * Spawns threads for each of the new connections with Participants
  * and creates new piles by calling the createPiles(),
  * Sends a transrequest() to each remote machines for objects found remotely
  * and calls handleLocalReq() to process objects found locally */
-int transCommit(transrecord_t *record) {
+int transCommit() {
+  //char buffer[30];
   unsigned int tot_bytes_mod, *listmid;
   plistnode_t *pile, *pile_ptr;
-  int i, j, rc, val;
-  int pilecount, offset, threadnum, trecvcount;
-  char control;
-  char transid[TID_LEN];
-  trans_req_data_t *tosend;
-  trans_commit_data_t transinfo;
-  static int newtid = 0;
-  char treplyctrl, treplyretry; /* keeps track of the common response that needs to be sent */
-  thread_data_array_t *thread_data_array;
-  local_thread_data_array_t *ltdata;
+  char treplyretry; /* keeps track of the common response that needs to be sent */
   int firsttime=1;
+  trans_commit_data_t transinfo; /* keeps track of objs locked during transaction */
+  char finalResponse;
+#ifdef SANDBOX
+  abortenabled=0;
+#endif
+  struct writestruct writebuffer;
+  writebuffer.offset=0;
+
+#ifdef LOGEVENTS
+  int iii;
+  for(iii=0;iii<bigindex;iii++) {
+    printf("%c", bigarray[iii]);
+  }
+#endif
+
+#ifdef LOGTIMES
+  int jjj;
+  for(jjj=0; jjj<bigindex1; jjj++) {
+    printf("[%c %u %u %lld %d]\n", bigarray1[jjj], bigarray2[jjj], bigarray3[jjj], bigarray4[jjj], bigarray5[jjj]);
+  }
+#endif
 
+#ifdef ABORTREADERS
+  if (t_abort) {
+    //abort this transaction
+    removetransactionhash();
+    objstrDelete(t_cache);
+    t_chashDelete();
+    return 1;
+  }
+#endif
+
+
+  int treplyretryCount = 0;
+  /* Initialize timeout for exponential delay */
+  exponential_backoff.tv_sec = 0;
+  exponential_backoff.tv_nsec = (long)(10000);//10 microsec
+  count_exponential_backoff = 0;
   do {
-    treplyctrl=0;
-    trecvcount = 0;
-    threadnum = 0;
     treplyretry = 0;
-    thread_data_array = NULL;
-    ltdata = NULL;
 
     /* Look through all the objects in the transaction record and make piles
      * for each machine involved in the transaction*/
-    if (firsttime)
-      pile_ptr = pile = createPiles(record);
-    else
-      pile=pile_ptr;
-    firsttime=0;
-
+    if (firsttime) {
+      pile_ptr = pile = createPiles();
+      pile_ptr = pile = sortPiles(pile);
+    } else {
+      pile = pile_ptr;
+    }
+    firsttime = 0;
     /* Create the packet to be sent in TRANS_REQUEST */
 
     /* Count the number of participants */
+    int pilecount;
     pilecount = pCount(pile);
 
-    /* Create a list of machine ids(Participants) involved in transaction      */
+    /* Create a list of machine ids(Participants) involved in transaction   */
     listmid = calloc(pilecount, sizeof(unsigned int));
     pListMid(pile, listmid);
 
-
-    /* Initialize thread variables,
-     * Spawn a thread for each Participant involved in a transaction */
-    pthread_t thread[pilecount];
-    pthread_attr_t attr;
-    pthread_cond_t tcond;
-    pthread_mutex_t tlock;
-    pthread_mutex_t tlshrd;
-
-    thread_data_array = (thread_data_array_t *) calloc(pilecount, sizeof(thread_data_array_t));
-    ltdata = calloc(1, sizeof(local_thread_data_array_t));
-
-    thread_response_t rcvd_control_msg[pilecount];      /* Shared thread array that keeps track of responses of participants */
-
-    /* Initialize and set thread detach attribute */
-    pthread_attr_init(&attr);
-    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
-    pthread_mutex_init(&tlock, NULL);
-    pthread_cond_init(&tcond, NULL);
+    /* Create a socket and getReplyCtrl array, initialize */
+    int socklist[pilecount];
+    char getReplyCtrl[pilecount];
+    int loopcount;
+    for(loopcount = 0 ; loopcount < pilecount; loopcount++){
+      socklist[loopcount] = 0;
+      getReplyCtrl[loopcount] = 0;
+    }
 
     /* Process each machine pile */
+    int sockindex = 0;
+    trans_req_data_t *tosend;
+    tosend = calloc(pilecount, sizeof(trans_req_data_t));
     while(pile != NULL) {
-      //Create transaction id
-      newtid++;
-      tosend = calloc(1, sizeof(trans_req_data_t));
-      tosend->f.control = TRANS_REQUEST;
-      sprintf(tosend->f.trans_id, "%x_%d", pile->mid, newtid);
-      tosend->f.mcount = pilecount;
-      tosend->f.numread = pile->numread;
-      tosend->f.nummod = pile->nummod;
-      tosend->f.numcreated = pile->numcreated;
-      tosend->f.sum_bytes = pile->sum_bytes;
-      tosend->listmid = listmid;
-      tosend->objread = pile->objread;
-      tosend->oidmod = pile->oidmod;
-      tosend->oidcreated = pile->oidcreated;
-      thread_data_array[threadnum].thread_id = threadnum;
-      thread_data_array[threadnum].mid = pile->mid;
-      thread_data_array[threadnum].buffer = tosend;
-      thread_data_array[threadnum].recvmsg = rcvd_control_msg;
-      thread_data_array[threadnum].threshold = &tcond;
-      thread_data_array[threadnum].lock = &tlock;
-      thread_data_array[threadnum].count = &trecvcount;
-      thread_data_array[threadnum].replyctrl = &treplyctrl;
-      thread_data_array[threadnum].replyretry = &treplyretry;
-      thread_data_array[threadnum].rec = record;
-      /* If local do not create any extra connection */
-      if(pile->mid != myIpAddr) { /* Not local */
-       do {
-         rc = pthread_create(&thread[threadnum], &attr, transRequest, (void *) &thread_data_array[threadnum]);
-       } while(rc!=0);
-       if(rc) {
-         perror("Error in pthread create\n");
-         pthread_cond_destroy(&tcond);
-         pthread_mutex_destroy(&tlock);
-         pDelete(pile_ptr);
+      tosend[sockindex].f.control = TRANS_REQUEST;
+      tosend[sockindex].f.mcount = pilecount;
+      tosend[sockindex].f.numread = pile->numread;
+      tosend[sockindex].f.nummod = pile->nummod;
+      tosend[sockindex].f.numcreated = pile->numcreated;
+      tosend[sockindex].f.sum_bytes = pile->sum_bytes;
+      tosend[sockindex].listmid = listmid;
+      tosend[sockindex].objread = pile->objread;
+      tosend[sockindex].oidmod = pile->oidmod;
+      tosend[sockindex].oidcreated = pile->oidcreated;
+      int sd = 0;
+      if(pile->mid != myIpAddr) {
+       if((sd = getSock2WithLock(transRequestSockPool, pile->mid)) < 0) {
+         printf("transRequest(): socket create error\n");
          free(listmid);
-         for (i = 0; i < threadnum; i++)
-           free(thread_data_array[i].buffer);
-         free(thread_data_array);
-         free(ltdata);
+         free(tosend);
          return 1;
        }
-      } else { /*Local*/
-       ltdata->tdata = &thread_data_array[threadnum];
-       ltdata->transinfo = &transinfo;
-       do {
-         val = pthread_create(&thread[threadnum], &attr, handleLocalReq, (void *) ltdata);
-       } while(val!=0);
-       if(val) {
-         perror("Error in pthread create\n");
-         pthread_cond_destroy(&tcond);
-         pthread_mutex_destroy(&tlock);
-         pDelete(pile_ptr);
+       socklist[sockindex] = sd;
+       /* Send bytes of data with TRANS_REQUEST control message */
+       send_buf(sd, &writebuffer, &(tosend[sockindex].f), sizeof(fixed_data_t));
+
+       /* Send list of machines involved in the transaction */
+       {
+         int size=sizeof(unsigned int)*(tosend[sockindex].f.mcount);
+         send_buf(sd, &writebuffer, tosend[sockindex].listmid, size);
+       }
+
+       /* Send oids and version number tuples for objects that are read */
+       {
+         int size=(sizeof(unsigned int)+sizeof(unsigned short))*(tosend[sockindex].f.numread);
+         send_buf(sd, &writebuffer, tosend[sockindex].objread, size);
+       }
+
+       /* Send objects that are modified */
+       void *modptr;
+       if((modptr = calloc(1, tosend[sockindex].f.sum_bytes)) == NULL) {
+         printf("Calloc error for modified objects %s, %d\n", __FILE__, __LINE__);
          free(listmid);
-         for (i = 0; i < threadnum; i++)
-           free(thread_data_array[i].buffer);
-         free(thread_data_array);
-         free(ltdata);
+         free(tosend);
          return 1;
        }
+       int offset = 0;
+       int i;
+       for(i = 0; i < tosend[sockindex].f.nummod ; i++) {
+         int size;
+         objheader_t *headeraddr;
+         if((headeraddr = t_chashSearch(tosend[sockindex].oidmod[i])) == NULL) {
+           printf("%s() Error: No such oid %s, %d\n", __func__, __FILE__, __LINE__);
+           free(modptr);
+           free(listmid);
+           free(tosend);
+           return 1;
+         }
+         GETSIZE(size,headeraddr);
+         size+=sizeof(objheader_t);
+         memcpy(modptr+offset, headeraddr, size);
+         offset+=size;
+       }
+       forcesend_buf(sd, &writebuffer, modptr, tosend[sockindex].f.sum_bytes);
+       free(modptr);
+      } else { //handle request locally
+       handleLocalReq(&tosend[sockindex], &transinfo, &getReplyCtrl[sockindex]);
       }
-
-      threadnum++;
+      sockindex++;
       pile = pile->next;
+    } //end of pile processing
+
+      /* Recv Ctrl msgs from all machines */
+    int i;
+    for(i = 0; i < pilecount; i++) {
+      int sd = socklist[i];
+      if(sd != 0) {
+       char control;
+       recv_data(sd, &control, sizeof(char));
+       //Update common data structure with new ctrl msg
+       getReplyCtrl[i] = control;
+       /* Recv Objects if participant sends TRANS_DISAGREE */
+#ifdef CACHE
+       if(control == TRANS_DISAGREE) {
+         int length;
+         recv_data(sd, &length, sizeof(int));
+         void *newAddr;
+         pthread_mutex_lock(&prefetchcache_mutex);
+         if ((newAddr = prefetchobjstrAlloc((unsigned int)length)) == NULL) {
+           printf("Error: %s() objstrAlloc error for copying into prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
+           free(tosend);
+           free(listmid);
+           pthread_mutex_unlock(&prefetchcache_mutex);
+           return 1;
+         }
+         pthread_mutex_unlock(&prefetchcache_mutex);
+         recv_data(sd, newAddr, length);
+         int offset = 0;
+         while(length != 0) {
+           unsigned int oidToPrefetch;
+           objheader_t * header;
+           header = (objheader_t *)(((char *)newAddr) + offset);
+           oidToPrefetch = OID(header);
+           STATUS(header)=0;
+           int size = 0;
+           GETSIZE(size, header);
+           size += sizeof(objheader_t);
+           //make an entry in prefetch hash table
+        prehashInsert(oidToPrefetch, header);
+        LOGEVENT('E');
+           length = length - size;
+           offset += size;
+         }
+       } //end of receiving objs
+#endif
+      }
+    }
+
+    /* Decide the final response */
+    if((finalResponse = decideResponse(getReplyCtrl, &treplyretry, pilecount)) == 0) {
+      printf("Error: %s() in updating prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
+      free(tosend);
+      free(listmid);
+      return 1;
     }
-    /* Free attribute and wait for the other threads */
-    pthread_attr_destroy(&attr);
 
-    for (i = 0; i < threadnum; i++) {
-      rc = pthread_join(thread[i], NULL);
-      if(rc) {
-       printf("Error: return code from pthread_join() is %d\n", rc);
-       pthread_cond_destroy(&tcond);
-       pthread_mutex_destroy(&tlock);
-       pDelete(pile_ptr);
+#ifdef CACHE
+    if (finalResponse == TRANS_COMMIT) {
+      /* Invalidate objects in other machine cache */
+      int retval;
+      if((retval = invalidateObj(tosend, pilecount,finalResponse,socklist)) != 0) {
+       printf("Error: %s() in invalidating Objects %s, %d\n", __func__, __FILE__, __LINE__);
+       free(tosend);
        free(listmid);
-       for (j = i; j < threadnum; j++) {
-         free(thread_data_array[j].buffer);
-       }
        return 1;
       }
-      free(thread_data_array[i].buffer);
+    }
+#endif
+    /* Send responses to all machines */
+    for(i = 0; i < pilecount; i++) {
+      int sd = socklist[i];
+      if(sd != 0) {
+#ifdef CACHE
+       if(finalResponse == TRANS_COMMIT) {
+         int retval;
+         /* Update prefetch cache */
+         if((retval = updatePrefetchCache(&(tosend[i]))) != 0) {
+           printf("Error: %s() in updating prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
+           free(tosend);
+           free(listmid);
+           return 1;
+         }
+#ifdef ABORTREADERS
+         removetransaction(tosend[i].oidmod,tosend[i].f.nummod);
+         removethisreadtransaction(tosend[i].objread, tosend[i].f.numread);
+#endif
+       }
+#ifdef ABORTREADERS
+       else if (!treplyretry) {
+         removethistransaction(tosend[i].oidmod,tosend[i].f.nummod);
+         removethisreadtransaction(tosend[i].objread,tosend[i].f.numread);
+       }
+#endif
+#endif
+       send_data(sd, &finalResponse, sizeof(char));
+      } else {
+       /* Complete local processing */
+       doLocalProcess(finalResponse, &(tosend[i]), &transinfo);
+#ifdef ABORTREADERS
+       if(finalResponse == TRANS_COMMIT) {
+         removetransaction(tosend[i].oidmod,tosend[i].f.nummod);
+         removethisreadtransaction(tosend[i].objread,tosend[i].f.numread);
+       } else if (!treplyretry) {
+         removethistransaction(tosend[i].oidmod,tosend[i].f.nummod);
+         removethisreadtransaction(tosend[i].objread,tosend[i].f.numread);
+       }
+#endif
+      }
     }
 
     /* Free resources */
-    pthread_cond_destroy(&tcond);
-    pthread_mutex_destroy(&tlock);
+    free(tosend);
     free(listmid);
-
     if (!treplyretry)
       pDelete(pile_ptr);
-
     /* wait a random amount of time before retrying to commit transaction*/
     if(treplyretry) {
-      free(thread_data_array);
-      free(ltdata);
+      treplyretryCount++;
+     // if(treplyretryCount >= NUM_TRY_TO_COMMIT)
+     //   exponentialdelay();
+     // else 
       randomdelay();
 #ifdef TRANSSTATS
       nSoftAbort++;
 #endif
     }
-
     /* Retry trans commit procedure during soft_abort case */
   } while (treplyretry);
 
-  if(treplyctrl == TRANS_ABORT) {
+  if(finalResponse == TRANS_ABORT) {
 #ifdef TRANSSTATS
+    LOGEVENT('A');
     numTransAbort++;
 #endif
     /* Free Resources */
-    objstrDelete(record->cache);
-    chashDelete(record->lookupTable);
-    free(record);
-    free(thread_data_array);
-    free(ltdata);
+    objstrDelete(t_cache);
+    t_chashDelete();
+#ifdef SANDBOX
+      abortenabled=1;
+#endif
     return TRANS_ABORT;
-  } else if(treplyctrl == TRANS_COMMIT) {
+  } else if(finalResponse == TRANS_COMMIT) {
 #ifdef TRANSSTATS
+    LOGEVENT('C');
     numTransCommit++;
 #endif
     /* Free Resources */
-    objstrDelete(record->cache);
-    chashDelete(record->lookupTable);
-    free(record);
-    free(thread_data_array);
-    free(ltdata);
+    objstrDelete(t_cache);
+    t_chashDelete();
     return 0;
   } else {
     //TODO Add other cases
@@ -662,184 +1236,102 @@ int transCommit(transrecord_t *record) {
   return 0;
 }
 
-/* This function sends information involved in the transaction request
- * to participants and accepts a response from particpants.
- * It calls decideresponse() to decide on what control message
- * to send next to participants and sends the message using sendResponse()*/
-void *transRequest(void *threadarg) {
-  int sd, i, n;
-  struct sockaddr_in serv_addr;
-  thread_data_array_t *tdata;
-  objheader_t *headeraddr;
-  char control, recvcontrol;
-  char machineip[16], retval;
-
-  tdata = (thread_data_array_t *) threadarg;
-
-  if((sd = getSock2WithLock(transRequestSockPool, tdata->mid)) < 0) {
-    printf("transRequest(): socket create error\n");
-    pthread_exit(NULL);
-  }
-
-  /* Send bytes of data with TRANS_REQUEST control message */
-  send_data(sd, &(tdata->buffer->f), sizeof(fixed_data_t));
-
-  /* Send list of machines involved in the transaction */
-  {
-    int size=sizeof(unsigned int)*tdata->buffer->f.mcount;
-    send_data(sd, tdata->buffer->listmid, size);
-  }
-
-  /* Send oids and version number tuples for objects that are read */
-  {
-    int size=(sizeof(unsigned int)+sizeof(unsigned short))*tdata->buffer->f.numread;
-    send_data(sd, tdata->buffer->objread, size);
-  }
-
-  /* Send objects that are modified */
-  for(i = 0; i < tdata->buffer->f.nummod ; i++) {
-    int size;
-    if((headeraddr = chashSearch(tdata->rec->lookupTable, tdata->buffer->oidmod[i])) == NULL) {
-      printf("%s() Error: No such oid %s, %d\n", __func__, __FILE__, __LINE__);
-      pthread_exit(NULL);
-    }
-    GETSIZE(size,headeraddr);
-    size+=sizeof(objheader_t);
-    send_data(sd, headeraddr, size);
-  }
+/* This function handles the local objects involved in a transaction
+ * commiting process.  It also makes a decision if this local machine
+ * sends AGREE or DISAGREE or SOFT_ABORT to coordinator */
+void handleLocalReq(trans_req_data_t *tdata, trans_commit_data_t *transinfo, char *getReplyCtrl) {
+  unsigned int *oidnotfound = NULL, *oidlocked = NULL;
+  int numoidnotfound = 0, numoidlocked = 0;
+  int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
+  int numread, i;
+  unsigned int oid;
+  unsigned short version;
 
-  /* Read control message from Participant */
-  recv_data(sd, &control, sizeof(char));
-  /* Recv Objects if participant sends TRANS_DISAGREE */
-#ifdef CACHE
-  if(control == TRANS_DISAGREE) {
-    int length;
-    recv_data(sd, &length, sizeof(int));
-    void *newAddr;
-    pthread_mutex_lock(&prefetchcache_mutex);
-    if ((newAddr = prefetchobjstrAlloc((unsigned int)length)) == NULL) {
-      printf("Error: %s() objstrAlloc error for copying into prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
-      pthread_mutex_unlock(&prefetchcache_mutex);
-      pthread_exit(NULL);
-    }
-    pthread_mutex_unlock(&prefetchcache_mutex);
-    recv_data(sd, newAddr, length);
-    int offset = 0;
-    while(length != 0) {
-      unsigned int oidToPrefetch;
-      objheader_t * header;
-      header = (objheader_t *)(((char *)newAddr) + offset);
-      oidToPrefetch = OID(header);
-      int size = 0;
-      GETSIZE(size, header);
-      size += sizeof(objheader_t);
-      //make an entry in prefetch hash table
-      void *oldptr;
-      if((oldptr = prehashSearch(oidToPrefetch)) != NULL) {
-       prehashRemove(oidToPrefetch);
-       prehashInsert(oidToPrefetch, header);
-      } else {
-       prehashInsert(oidToPrefetch, header);
+  /* Counters and arrays to formulate decision on control message to be sent */
+  oidnotfound = (unsigned int *) calloc((tdata->f.numread + tdata->f.nummod), sizeof(unsigned int));
+  oidlocked = (unsigned int *) calloc((tdata->f.numread + tdata->f.nummod +1), sizeof(unsigned int)); // calloc additional 1 byte for
+  //setting a divider between read and write locks
+  numread = tdata->f.numread;
+  /* Process each oid in the machine pile/ group per thread */
+  for (i = 0; i < tdata->f.numread + tdata->f.nummod; i++) {
+    if (i < tdata->f.numread) {
+      int incr = sizeof(unsigned int) + sizeof(unsigned short); // Offset that points to next position in the objread array
+      incr *= i;
+      oid = *((unsigned int *)(((char *)tdata->objread) + incr));
+      version = *((unsigned short *)(((char *)tdata->objread) + incr + sizeof(unsigned int)));
+      commitCountForObjRead(getReplyCtrl, oidnotfound, oidlocked, &numoidnotfound, &numoidlocked, &v_nomatch, &v_matchlock, &v_matchnolock, oid, version);
+    } else { // Objects Modified
+      if(i == tdata->f.numread) {
+       oidlocked[numoidlocked++] = -1;
       }
-      length = length - size;
-      offset += size;
+      int tmpsize;
+      objheader_t *headptr;
+      headptr = (objheader_t *) t_chashSearch(tdata->oidmod[i-numread]);
+      if (headptr == NULL) {
+       printf("Error: handleLocalReq() returning NULL, no such oid %s, %d\n", __FILE__, __LINE__);
+       return;
+      }
+      oid = OID(headptr);
+      version = headptr->version;
+      commitCountForObjMod(getReplyCtrl, oidnotfound, oidlocked, &numoidnotfound, &numoidlocked, &v_nomatch, &v_matchlock, &v_matchnolock, oid, version);
     }
   }
-#endif
-
-  recvcontrol = control;
-  /* Update common data structure and increment count */
-  tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol;
-
-  /* Lock and update count */
-  /* Thread sleeps until all messages from pariticipants are received by coordinator */
-  pthread_mutex_lock(tdata->lock);
 
-  (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */
-
-  /* Wake up the threads and invoke decideResponse (once) */
-  if(*(tdata->count) == tdata->buffer->f.mcount) {
-    decideResponse(tdata);
-    pthread_cond_broadcast(tdata->threshold);
-  } else {
-    pthread_cond_wait(tdata->threshold, tdata->lock);
-  }
-  pthread_mutex_unlock(tdata->lock);
-
-  /* clear objects from prefetch cache */
-  /*
-     if(*(tdata->replyctrl) == TRANS_ABORT) {
-     int i;
-     for(i=0; i<tdata->buffer->f.nummod; i++) {
-      unsigned int oid = tdata->buffer->oidmod[i];
-      objheader_t *header;
-      if((header = prehashSearch(oid)) != NULL) {
-        prehashRemove(oid);
-      }
-     }
-     for(i=0; i<tdata->buffer->f.numread; i++) {
-      char *objread = tdata->buffer->objread;
-      unsigned int oid = *((unsigned int *)(objread+(sizeof(unsigned int) +
-                  sizeof(unsigned short))*i));
-      objheader_t *header;
-      if((header = prehashSearch(oid)) != NULL) {
-        prehashRemove(oid);
-      }
-     }
-     }
-   */
+/* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
+ * if Participant receives a TRANS_COMMIT */
+  transinfo->objlocked = oidlocked;
+  transinfo->objnotfound = oidnotfound;
+  transinfo->modptr = NULL;
+  transinfo->numlocked = numoidlocked;
+  transinfo->numnotfound = numoidnotfound;
+  
+  /* Condition to send TRANS_AGREE */
+  if(v_matchnolock == tdata->f.numread + tdata->f.nummod) {
+    *getReplyCtrl = TRANS_AGREE;
+  }
+  /* Condition to send TRANS_SOFT_ABORT */
+  if((v_matchlock > 0 && v_nomatch == 0) || (numoidnotfound > 0 && v_nomatch == 0)) {
+    *getReplyCtrl = TRANS_SOFT_ABORT;
+  }
+}
 
-#ifdef CACHE
-  if(*(tdata->replyctrl) == TRANS_COMMIT) {
-    int retval;
-    /* Update prefetch cache */
-    if((retval = updatePrefetchCache(tdata)) != 0) {
-      printf("Error: %s() in updating prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
+void doLocalProcess(char finalResponse, trans_req_data_t *tdata, trans_commit_data_t *transinfo) {
+  if(finalResponse == TRANS_ABORT) {
+    if(transAbortProcess(transinfo) != 0) {
+      printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
+      fflush(stdout);
       return;
     }
-
-    /* Invalidate objects in other machine cache */
-    if(tdata->buffer->f.nummod > 0) {
-      if((retval = invalidateObj(tdata)) != 0) {
-       printf("Error: %s() in invalidating Objects %s, %d\n", __func__, __FILE__, __LINE__);
-       return;
-      }
+  } else if(finalResponse == TRANS_COMMIT) {
+    if(transComProcess(tdata, transinfo) != 0) {
+      printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
+      fflush(stdout);
+      return;
     }
+  } else {
+    printf("ERROR...No Decision\n");
   }
-#endif
 
-  /* Send the final response such as TRANS_COMMIT or TRANS_ABORT
-   * to all participants in their respective socket */
-  if (sendResponse(tdata, sd) == 0) {
-    printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__);
-    pthread_exit(NULL);
+  /* Free memory */
+  if (transinfo->objlocked != NULL) {
+    free(transinfo->objlocked);
   }
-
-  recv_data((int)sd, &control, sizeof(char));
-
-  if(control == TRANS_UNSUCESSFUL) {
-    //printf("DEBUG-> TRANS_ABORTED\n");
-  } else if(control == TRANS_SUCESSFUL) {
-    //printf("DEBUG-> TRANS_SUCCESSFUL\n");
-  } else {
-    //printf("DEBUG-> Error: Incorrect Transaction End Message %d\n", control);
+  if (transinfo->objnotfound != NULL) {
+    free(transinfo->objnotfound);
   }
-  pthread_exit(NULL);
 }
 
 /* This function decides the reponse that needs to be sent to
  * all Participant machines after the TRANS_REQUEST protocol */
-void decideResponse(thread_data_array_t *tdata) {
-  char control;
+char decideResponse(char *getReplyCtrl, char *treplyretry, int pilecount) {
   int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
                                                                   message to send */
-
-  for (i = 0 ; i < tdata->buffer->f.mcount; i++) {
-    control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses
-                                              written onto the shared array */
+  for (i = 0 ; i < pilecount; i++) {
+    char control;
+    control = getReplyCtrl[i];
     switch(control) {
     default:
-      printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
+      printf("Participant sent unknown message %d in %s, %d\n", control, __FILE__, __LINE__);
 
       /* treat as disagree, pass thru */
     case TRANS_DISAGREE:
@@ -858,58 +1350,22 @@ void decideResponse(thread_data_array_t *tdata) {
 
   if(transdisagree > 0) {
     /* Send Abort */
-    *(tdata->replyctrl) = TRANS_ABORT;
-    *(tdata->replyretry) = 0;
+    *treplyretry = 0;
+    return TRANS_ABORT;
 #ifdef CACHE
     /* clear objects from prefetch cache */
-    cleanPCache(tdata);
+    //cleanPCache();
 #endif
-  } else if(transagree == tdata->buffer->f.mcount) {
+  } else if(transagree == pilecount) {
     /* Send Commit */
-    *(tdata->replyctrl) = TRANS_COMMIT;
-    *(tdata->replyretry) = 0;
-#ifdef CACHE
-#if 0
-    /* Turn prefetching on */
-    int i;
-    for (i=0; i<numprefetchsites; i++)
-      evalPrefetch[i].operMode = 1;
-#endif
-#endif
+    *treplyretry = 0;
+    return TRANS_COMMIT;
   } else {
     /* Send Abort in soft abort case followed by retry commiting transaction again*/
-    *(tdata->replyctrl) = TRANS_ABORT;
-    *(tdata->replyretry) = 1;
-  }
-  return;
-}
-
-/* This function sends the final response to remote machines per
- * thread in their respective socket id It returns a char that is only
- * needed to check the correctness of execution of this function
- * inside transRequest()*/
-
-char sendResponse(thread_data_array_t *tdata, int sd) {
-  int n, size, sum, oidcount = 0, control;
-  char *ptr, retval = 0;
-  unsigned int *oidnotfound;
-
-  control = *(tdata->replyctrl);
-  send_data(sd, &control, sizeof(char));
-
-  //TODO read missing objects during object migration
-  /* If response is a soft abort due to missing objects at the
-     Participant's side */
-
-  /* If the decided response is TRANS_ABORT */
-  if(*(tdata->replyctrl) == TRANS_ABORT) {
-    retval = TRANS_ABORT;
-  } else if(*(tdata->replyctrl) == TRANS_COMMIT) {
-    /* If the decided response is TRANS_COMMIT */
-    retval = TRANS_COMMIT;
+    *treplyretry = 1;
+    return TRANS_ABORT;
   }
-
-  return retval;
+  return 0;
 }
 
 /* This function opens a connection, places an object read request to
@@ -917,7 +1373,7 @@ char sendResponse(thread_data_array_t *tdata, int sd) {
  * available and copies the object and its header to the local
  * cache. */
 
-void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
+void *getRemoteObj(unsigned int mnum, unsigned int oid) {
   int size, val;
   struct sockaddr_in serv_addr;
   char machineip[16];
@@ -939,134 +1395,21 @@ void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
   } else {
     /* Read object if found into local cache */
     recv_data(sd, &size, sizeof(int));
-    objcopy = objstrAlloc(record->cache, size);
+    objcopy = objstrAlloc(&t_cache, size);
     recv_data(sd, objcopy, size);
+    STATUS(objcopy)=0;
     /* Insert into cache's lookup table */
-    chashInsert(record->lookupTable, oid, objcopy);
-  }
-
-  return objcopy;
-}
-
-/* This function handles the local objects involved in a transaction
- * commiting process.  It also makes a decision if this local machine
- * sends AGREE or DISAGREE or SOFT_ABORT to coordinator.  Note
- * Coordinator = local machine It wakes up the other threads from
- * remote participants that are waiting for the coordinator's decision
- * and based on common agreement it either commits or aborts the
- * transaction.  It also frees the memory resources */
-
-void *handleLocalReq(void *threadarg) {
-  unsigned int *oidnotfound = NULL, *oidlocked = NULL;
-  local_thread_data_array_t *localtdata;
-  int numoidnotfound = 0, numoidlocked = 0;
-  int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
-  int numread, i;
-  unsigned int oid;
-  unsigned short version;
-
-  localtdata = (local_thread_data_array_t *) threadarg;
-
-  /* Counters and arrays to formulate decision on control message to be sent */
-  oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
-  oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod +1), sizeof(unsigned int)); // calloc additional 1 byte for
-                                                                                                                                              //setting a divider of read locks
-                                                                                                                                              //and write locks
-
-  numread = localtdata->tdata->buffer->f.numread;
-  /* Process each oid in the machine pile/ group per thread */
-  for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) {
-    if (i < localtdata->tdata->buffer->f.numread) {
-      int incr = sizeof(unsigned int) + sizeof(unsigned short); // Offset that points to next position in the objread array
-      incr *= i;
-      oid = *((unsigned int *)(((char *)localtdata->tdata->buffer->objread) + incr));
-      version = *((unsigned short *)(((char *)localtdata->tdata->buffer->objread) + incr + sizeof(unsigned int)));
-      commitCountForObjRead(localtdata, oidnotfound, oidlocked, &numoidnotfound, &numoidlocked, &v_nomatch, &v_matchlock, &v_matchnolock, oid, version);
-    } else { // Objects Modified
-      if(i == localtdata->tdata->buffer->f.numread) {
-       oidlocked[numoidlocked] = -1;
-       numoidlocked++;
-      }
-      int tmpsize;
-      objheader_t *headptr;
-      headptr = (objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidmod[i-numread]);
-      if (headptr == NULL) {
-       printf("Error: handleLocalReq() returning NULL, no such oid %s, %d\n", __FILE__, __LINE__);
-       return NULL;
-      }
-      oid = OID(headptr);
-      version = headptr->version;
-      commitCountForObjMod(localtdata, oidnotfound, oidlocked, &numoidnotfound, &numoidlocked, &v_nomatch, &v_matchlock, &v_matchnolock, oid, version);
-    }
-  }
-
-  /* Condition to send TRANS_AGREE */
-  if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
-    localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
-  }
-  /* Condition to send TRANS_SOFT_ABORT */
-  if((v_matchlock > 0 && v_nomatch == 0) || (numoidnotfound > 0 && v_nomatch == 0)) {
-    localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
-  }
-
-  /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
-   * if Participant receives a TRANS_COMMIT */
-  localtdata->transinfo->objlocked = oidlocked;
-  localtdata->transinfo->objnotfound = oidnotfound;
-  localtdata->transinfo->modptr = NULL;
-  localtdata->transinfo->numlocked = numoidlocked;
-  localtdata->transinfo->numnotfound = numoidnotfound;
-
-  /* Lock and update count */
-  //Thread sleeps until all messages from pariticipants are received by coordinator
-  pthread_mutex_lock(localtdata->tdata->lock);
-  (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */
-
-  /* Wake up the threads and invoke decideResponse (once) */
-  if(*(localtdata->tdata->count) == localtdata->tdata->buffer->f.mcount) {
-    decideResponse(localtdata->tdata);
-    pthread_cond_broadcast(localtdata->tdata->threshold);
-  } else {
-    pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock);
-  }
-  pthread_mutex_unlock(localtdata->tdata->lock);
-
-  if(*(localtdata->tdata->replyctrl) == TRANS_ABORT) {
-    if(transAbortProcess(localtdata) != 0) {
-      printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
-      fflush(stdout);
-      pthread_exit(NULL);
-    }
-  } else if(*(localtdata->tdata->replyctrl) == TRANS_COMMIT) {
-#ifdef CACHE
-    /* Invalidate objects in other machine cache */
-    if(localtdata->tdata->buffer->f.nummod > 0) {
-      int retval;
-      if((retval = invalidateObj(localtdata->tdata)) != 0) {
-       printf("Error: %s() in invalidating Objects %s, %d\n", __func__, __FILE__, __LINE__);
-       return;
-      }
-    }
+    t_chashInsert(oid, objcopy);
+#ifdef TRANSSTATS
+    totalObjSize += size;
 #endif
-    if(transComProcess(localtdata) != 0) {
-      printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
-      fflush(stdout);
-      pthread_exit(NULL);
-    }
-  }
-  /* Free memory */
-  if (localtdata->transinfo->objlocked != NULL) {
-    free(localtdata->transinfo->objlocked);
   }
-  if (localtdata->transinfo->objnotfound != NULL) {
-    free(localtdata->transinfo->objnotfound);
-  }
-  pthread_exit(NULL);
 
+  return objcopy;
 }
 
 /*  Commit info for objects modified */
-void commitCountForObjMod(local_thread_data_array_t *localtdata, unsigned int *oidnotfound, unsigned int *oidlocked, int *numoidnotfound,
+void commitCountForObjMod(char *getReplyCtrl, unsigned int *oidnotfound, unsigned int *oidlocked, int *numoidnotfound,
                           int *numoidlocked, int *v_nomatch, int *v_matchlock, int *v_matchnolock, unsigned int oid, unsigned short version) {
   void *mobj;
   /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
@@ -1081,15 +1424,14 @@ void commitCountForObjMod(local_thread_data_array_t *localtdata, unsigned int *o
       if (version == ((objheader_t *)mobj)->version) {      /* match versions */
        (*v_matchnolock)++;
        //Keep track of what is locked
-       oidlocked[*numoidlocked] = OID(((objheader_t *)mobj));
-       (*numoidlocked)++;
+       oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj));
       } else { /* If versions don't match ...HARD ABORT */
        (*v_nomatch)++;
        /* Send TRANS_DISAGREE to Coordinator */
-       localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
+       *getReplyCtrl = TRANS_DISAGREE;
+
        //Keep track of what is locked
-       oidlocked[*numoidlocked] = OID(((objheader_t *)mobj));
-       (*numoidlocked)++;
+       oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj));
        return;
       }
     } else { //A lock is acquired some place else
@@ -1098,7 +1440,7 @@ void commitCountForObjMod(local_thread_data_array_t *localtdata, unsigned int *o
       } else { /* If versions don't match ...HARD ABORT */
        (*v_nomatch)++;
        /* Send TRANS_DISAGREE to Coordinator */
-       localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
+       *getReplyCtrl = TRANS_DISAGREE;
        return;
       }
     }
@@ -1106,7 +1448,7 @@ void commitCountForObjMod(local_thread_data_array_t *localtdata, unsigned int *o
 }
 
 /*  Commit info for objects modified */
-void commitCountForObjRead(local_thread_data_array_t *localtdata, unsigned int *oidnotfound, unsigned int *oidlocked, int *numoidnotfound,
+void commitCountForObjRead(char *getReplyCtrl, unsigned int *oidnotfound, unsigned int *oidlocked, int *numoidnotfound,
                            int *numoidlocked, int *v_nomatch, int *v_matchlock, int *v_matchnolock, unsigned int oid, unsigned short version) {
   void *mobj;
   /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
@@ -1121,15 +1463,13 @@ void commitCountForObjRead(local_thread_data_array_t *localtdata, unsigned int *
       if (version == ((objheader_t *)mobj)->version) {      /* If locked then match versions */
        (*v_matchnolock)++;
        //Keep track of what is locked
-       oidlocked[*numoidlocked] = OID(((objheader_t *)mobj));
-       (*numoidlocked)++;
+       oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj));
       } else { /* If versions don't match ...HARD ABORT */
        (*v_nomatch)++;
        /* Send TRANS_DISAGREE to Coordinator */
-       localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
+       *getReplyCtrl = TRANS_DISAGREE;
        //Keep track of what is locked
-       oidlocked[*numoidlocked] = OID(((objheader_t *)mobj));
-       (*numoidlocked)++;
+       oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj));
        return;
       }
     } else { //Has reached max number of readers or some other transaction
@@ -1139,7 +1479,7 @@ void commitCountForObjRead(local_thread_data_array_t *localtdata, unsigned int *
       } else { /* If versions don't match ...HARD ABORT */
        (*v_nomatch)++;
        /* Send TRANS_DISAGREE to Coordinator */
-       localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
+       *getReplyCtrl = TRANS_DISAGREE;
        return;
       }
     }
@@ -1147,13 +1487,13 @@ void commitCountForObjRead(local_thread_data_array_t *localtdata, unsigned int *
 }
 
 /* This function completes the ABORT process if the transaction is aborting */
-int transAbortProcess(local_thread_data_array_t  *localtdata) {
+int transAbortProcess(trans_commit_data_t *transinfo) {
   int i, numlocked;
   unsigned int *objlocked;
   void *header;
 
-  numlocked = localtdata->transinfo->numlocked;
-  objlocked = localtdata->transinfo->objlocked;
+  numlocked = transinfo->numlocked;
+  objlocked = transinfo->objlocked;
 
   int useWriteUnlock = 0;
   for (i = 0; i < numlocked; i++) {
@@ -1176,18 +1516,18 @@ int transAbortProcess(local_thread_data_array_t  *localtdata) {
 }
 
 /*This function completes the COMMIT process if the transaction is commiting*/
-int transComProcess(local_thread_data_array_t  *localtdata) {
+int transComProcess(trans_req_data_t *tdata, trans_commit_data_t *transinfo) {
   objheader_t *header, *tcptr;
   int i, nummod, tmpsize, numcreated, numlocked;
   unsigned int *oidmod, *oidcreated, *oidlocked;
   void *ptrcreate;
 
-  nummod = localtdata->tdata->buffer->f.nummod;
-  oidmod = localtdata->tdata->buffer->oidmod;
-  numcreated = localtdata->tdata->buffer->f.numcreated;
-  oidcreated = localtdata->tdata->buffer->oidcreated;
-  numlocked = localtdata->transinfo->numlocked;
-  oidlocked = localtdata->transinfo->objlocked;
+  nummod = tdata->f.nummod;
+  oidmod = tdata->oidmod;
+  numcreated = tdata->f.numcreated;
+  oidcreated = tdata->oidcreated;
+  numlocked = transinfo->numlocked;
+  oidlocked = transinfo->objlocked;
 
   for (i = 0; i < nummod; i++) {
     if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
@@ -1195,13 +1535,21 @@ int transComProcess(local_thread_data_array_t  *localtdata) {
       return 1;
     }
     /* Copy from transaction cache -> main object store */
-    if ((tcptr = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidmod[i]))) == NULL) {
+    if ((tcptr = ((objheader_t *) t_chashSearch(oidmod[i]))) == NULL) {
       printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
       return 1;
     }
     GETSIZE(tmpsize, header);
     char *tmptcptr = (char *) tcptr;
-    memcpy((char*)header+sizeof(objheader_t), (char *)tmptcptr+ sizeof(objheader_t), tmpsize);
+    {
+      struct ___Object___ *dst=(struct ___Object___*)((char*)header+sizeof(objheader_t));
+      struct ___Object___ *src=(struct ___Object___*)((char*)tmptcptr+sizeof(objheader_t));
+      dst->___cachedCode___=src->___cachedCode___;
+      dst->___cachedHash___=src->___cachedHash___;
+
+      memcpy(&dst[1], &src[1], tmpsize-sizeof(struct ___Object___));
+    }
+
     header->version += 1;
     if(header->notifylist != NULL) {
       notifyAll(&header->notifylist, OID(header), header->version);
@@ -1209,14 +1557,14 @@ int transComProcess(local_thread_data_array_t  *localtdata) {
   }
   /* If object is newly created inside transaction then commit it */
   for (i = 0; i < numcreated; i++) {
-    if ((header = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidcreated[i]))) == NULL) {
+    if ((header = ((objheader_t *) t_chashSearch(oidcreated[i]))) == NULL) {
       printf("Error: transComProcess() chashSearch returned NULL for oid = %x at %s, %d\n", oidcreated[i], __FILE__, __LINE__);
       return 1;
     }
     GETSIZE(tmpsize, header);
     tmpsize += sizeof(objheader_t);
     pthread_mutex_lock(&mainobjstore_mutex);
-    if ((ptrcreate = objstrAlloc(mainobjstore, tmpsize)) == NULL) {
+    if ((ptrcreate = objstrAlloc(&mainobjstore, tmpsize)) == NULL) {
       printf("Error: transComProcess() failed objstrAlloc %s, %d\n", __FILE__, __LINE__);
       pthread_mutex_unlock(&mainobjstore_mutex);
       return 1;
@@ -1248,55 +1596,79 @@ int transComProcess(local_thread_data_array_t  *localtdata) {
   return 0;
 }
 
-prefetchpile_t *foundLocal(char *ptr) {
-  int siteid = *(GET_SITEID(ptr));
-  int ntuples = *(GET_NTUPLES(ptr));
-  unsigned int * oidarray = GET_PTR_OID(ptr);
-  unsigned short * endoffsets = GET_PTR_EOFF(ptr, ntuples);
-  short * arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
+prefetchpile_t *foundLocal(char *ptr, int numprefetches, int mysiteid) {
+  int i;
+  int j;
   prefetchpile_t * head=NULL;
-  int numLocal = 0;
 
-  int i;
-  for(i=0; i<ntuples; i++) {
-    unsigned short baseindex=(i==0) ? 0 : endoffsets[i-1];
-    unsigned short endindex=endoffsets[i];
-    unsigned int oid=oidarray[i];
-    int newbase;
-    int machinenum;
-    if (oid==0)
-      continue;
-    //Look up fields locally
-    for(newbase=baseindex; newbase<endindex; newbase++) {
-      if (!lookupObject(&oid, arryfields[newbase]))
-       break;
-      //Ended in a null pointer...
-      if (oid==0)
+  for(j=0;j<numprefetches;j++) {
+    int siteid = *(GET_SITEID(ptr));
+    int ntuples = *(GET_NTUPLES(ptr));
+    unsigned int * oidarray = GET_PTR_OID(ptr);
+    unsigned short * endoffsets = GET_PTR_EOFF(ptr, ntuples);
+    short * arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
+    int numLocal = 0;
+    
+    for(i=0; i<ntuples; i++) {
+      unsigned short baseindex=(i==0) ? 0 : endoffsets[i-1];
+      unsigned short endindex=endoffsets[i];
+      unsigned int oid=oidarray[i];
+      int newbase;
+      int machinenum;
+      int countInvalidObj=0;
+
+      if (oid==0) {
+       numLocal++;
+       continue;
+      }
+      //Look up fields locally
+      int isLastOffset=0;
+      if(endindex==0)
+          isLastOffset=1;
+      for(newbase=baseindex; newbase<endindex; newbase++) {
+        if(newbase==(endindex-1))
+          isLastOffset=1;
+       if (!lookupObject(&oid,arryfields[newbase],&countInvalidObj)) {
+         break;
+       }
+       //Ended in a null pointer...
+       if (oid==0) {
+         numLocal++;
+         goto tuple;
+       }
+      }
+
+      //Entire prefetch is local
+      if (newbase==endindex&&checkoid(oid,isLastOffset)) {
+       numLocal++;
        goto tuple;
+      }
+
+      //Add to remote requests
+      machinenum=lhashSearch(oid);
+      insertPile(machinenum, oid, siteid,endindex-newbase, &arryfields[newbase], &head);
+    tuple:
+      ;
     }
-    //Entire prefetch is local
-    if (newbase==endindex&&checkoid(oid)) {
-      numLocal++;
-      goto tuple;
-    }
-    //Add to remote requests
-    machinenum=lhashSearch(oid);
-    insertPile(machinenum, oid, endindex-newbase, &arryfields[newbase], &head);
-tuple:
-    ;
+    
+    /* handle dynamic prefetching */
+    handleDynPrefetching(numLocal, ntuples, siteid);
+    ptr=((char *)&arryfields[endoffsets[ntuples-1]])+sizeof(int);
   }
 
-  /* handle dynamic prefetching */
-  handleDynPrefetching(numLocal, ntuples, siteid);
   return head;
 }
 
-int checkoid(unsigned int oid) {
+int checkoid(unsigned int oid, int isLastOffset) {
   objheader_t *header;
   if ((header=mhashSearch(oid))!=NULL) {
     //Found on machine
     return 1;
   } else if ((header=prehashSearch(oid))!=NULL) {
+    //if the last offset then prefetch object
+    if((STATUS(header) & DIRTY) && isLastOffset) {
+      return 0;
+    }
     //Found in cache
     return 1;
   } else {
@@ -1304,19 +1676,25 @@ int checkoid(unsigned int oid) {
   }
 }
 
-int lookupObject(unsigned int * oid, short offset) {
+int lookupObject(unsigned int * oid, short offset, int *countInvalidObj) {
   objheader_t *header;
   if ((header=mhashSearch(*oid))!=NULL) {
     //Found on machine
     ;
   } else if ((header=prehashSearch(*oid))!=NULL) {
     //Found in cache
-    ;
+    if(STATUS(header) & DIRTY) {//Read an oid that is an old entry in the cache;
+      //only once because later old entries may still cause unnecessary roundtrips during prefetching
+      (*countInvalidObj)+=1;
+      if(*countInvalidObj > 1) {
+        return 0;
+      }
+    }
   } else {
     return 0;
   }
 
-  if(TYPE(header) > NUMCLASSES) {
+  if(TYPE(header) >= NUMCLASSES) {
     int elementsize = classsize[TYPE(header)];
     struct ArrayObject *ao = (struct ArrayObject *) (((char *)header) + sizeof(objheader_t));
     int length = ao->___length___;
@@ -1338,21 +1716,23 @@ int lookupObject(unsigned int * oid, short offset) {
 /* This function is called by the thread calling transPrefetch */
 void *transPrefetch(void *t) {
   while(1) {
-    /* lock mutex of primary prefetch queue */
+    /* read from prefetch queue */
     void *node=gettail();
     /* Check if the tuples are found locally, if yes then reduce them further*/
     /* and group requests by remote machine ids by calling the makePreGroups() */
-    prefetchpile_t *pilehead = foundLocal(node);
+    int count=numavailable();
+    prefetchpile_t *pilehead = foundLocal(node, count, 0);
 
     if (pilehead!=NULL) {
       // Get sock from shared pool
-      int sd = getSock2(transPrefetchSockPool, pilehead->mid);
 
       /* Send  Prefetch Request */
       prefetchpile_t *ptr = pilehead;
       while(ptr != NULL) {
-       sendPrefetchReq(ptr, sd);
-       ptr = ptr->next;
+        globalid++;
+        int sd = getSock2(transPrefetchSockPool, ptr->mid);
+        sendPrefetchReq(ptr, sd,globalid);
+        ptr = ptr->next;
       }
 
       /* Release socket */
@@ -1362,7 +1742,7 @@ void *transPrefetch(void *t) {
       mcdealloc(pilehead);
     }
     // Deallocate the prefetch queue pile node
-    inctail();
+    incmulttail(count);
   }
 }
 
@@ -1395,54 +1775,83 @@ void sendPrefetchReqnew(prefetchpile_t *mcpilenode, int sd) {
   return;
 }
 
-void sendPrefetchReq(prefetchpile_t *mcpilenode, int sd) {
+/**
+ * parameters: mcpilenode -> pile node to traverse to assemble pref requests
+ * sd -> socket id
+ * gid -> global identifier for each prefetch request sent, starts with 0
+ **/
+void sendPrefetchReq(prefetchpile_t *mcpilenode, int sd, int gid) {
   int len, endpair;
   char control;
   objpile_t *tmp;
+  struct writestruct writebuffer;
+  writebuffer.offset=0;
+
 
   /* Send TRANS_PREFETCH control message */
-  control = TRANS_PREFETCH;
-  send_data(sd, &control, sizeof(char));
+  int first=1;
 
   /* Send Oids and offsets in pairs */
   tmp = mcpilenode->objpiles;
   while(tmp != NULL) {
-    len = sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
-    char oidnoffset[len];
+    len = sizeof(int)+sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
+    char oidnoffset[len+5];
     char *buf=oidnoffset;
+    if (first) {
+      *buf=TRANS_PREFETCH;
+      buf++;len++;
+      first=0;
+    }
     *((int*)buf) = tmp->numoffset;
     buf+=sizeof(int);
     *((unsigned int *)buf) = tmp->oid;
+    LOGOIDTYPE("S",tmp->oid,tmp->numoffset,myrdtsc());
+#ifdef TRANSSTATS
+    sendRemoteReq++;
+#endif
     buf+=sizeof(unsigned int);
     *((unsigned int *)buf) = myIpAddr;
-    buf += sizeof(unsigned int);
+    buf+= sizeof(unsigned int);
+    *((int*)buf) = gid;
+    buf+=sizeof(int);
     memcpy(buf, tmp->offset, (tmp->numoffset)*sizeof(short));
-    send_data(sd, oidnoffset, len);
     tmp = tmp->next;
+    if (tmp==NULL) {
+      *((int *)(&oidnoffset[len]))=-1;
+      len+=sizeof(int);
+    }
+    if (tmp!=NULL)
+      send_buf(sd, &writebuffer, oidnoffset, len);
+    else
+      forcesend_buf(sd, &writebuffer, oidnoffset, len);
   }
-
-  /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
-  endpair = -1;
-  send_data(sd, &endpair, sizeof(int));
-
+  LOGOIDTYPE("SREQ",0,0,myrdtsc());
+  LOGEVENT('S');
+  LOGTIME('S',0,0,myrdtsc(),gid); //after sending
   return;
 }
 
-int getPrefetchResponse(int sd) {
-  int length = 0, size = 0;
+int getPrefetchResponse(int sd, struct readstruct *readbuffer) {
+  int gid,length = 0, size = 0;
   char control;
   unsigned int oid;
   void *modptr, *oldptr;
 
-  recv_data((int)sd, &length, sizeof(int));
+  recv_data_buf(sd, readbuffer, &length, sizeof(int));
   size = length - sizeof(int);
   char recvbuffer[size];
-
-  recv_data((int)sd, recvbuffer, size);
+#ifdef TRANSSTATS
+  getResponse++;
+  LOGEVENT('Z');
+  LOGTIME('K',0,0, myrdtsc(),0); //log time after first recv
+#endif
+  recv_data_buf(sd, readbuffer, recvbuffer, size);
   control = *((char *) recvbuffer);
   if(control == OBJECT_FOUND) {
     oid = *((unsigned int *)(recvbuffer + sizeof(char)));
-    size = size - (sizeof(char) + sizeof(unsigned int));
+    gid = *((int *) (recvbuffer+sizeof(char)+sizeof(unsigned int)));
+    LOGTIME('G',oid,0, myrdtsc(),gid); //log time after first recv
+    size = size - (sizeof(char) + sizeof(unsigned int) + sizeof(int));
     pthread_mutex_lock(&prefetchcache_mutex);
     if ((modptr = prefetchobjstrAlloc(size)) == NULL) {
       printf("Error: objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
@@ -1450,28 +1859,27 @@ int getPrefetchResponse(int sd) {
       return -1;
     }
     pthread_mutex_unlock(&prefetchcache_mutex);
-    memcpy(modptr, recvbuffer + sizeof(char) + sizeof(unsigned int), size);
+    memcpy(modptr, recvbuffer + sizeof(char) + sizeof(unsigned int)+sizeof(int), size);
     STATUS(modptr)=0;
 
+
     /* Insert the oid and its address into the prefetch hash lookup table */
     /* Do a version comparison if the oid exists */
     if((oldptr = prehashSearch(oid)) != NULL) {
       /* If older version then update with new object ptr */
-      if(((objheader_t *)oldptr)->version <= ((objheader_t *)modptr)->version) {
-       prehashRemove(oid);
-       prehashInsert(oid, modptr);
+      if(((objheader_t *)oldptr)->version < ((objheader_t *)modptr)->version) {
+        prehashInsert(oid, modptr);
       }
     } else { /* Else add the object ptr to hash table*/
       prehashInsert(oid, modptr);
     }
-    /* Lock the Prefetch Cache look up table*/
-    pthread_mutex_lock(&pflookup.lock);
-    /* Broadcast signal on prefetch cache condition variable */
-    pthread_cond_broadcast(&pflookup.cond);
-    /* Unlock the Prefetch Cache look up table*/
-    pthread_mutex_unlock(&pflookup.lock);
+    LOGOIDTYPE("GR",oid, TYPE(modptr),myrdtsc());
+    LOGTIME('Z',oid, TYPE(modptr), myrdtsc(),gid); //log time after copying it into the prefetch cache
   } else if(control == OBJECT_NOT_FOUND) {
     oid = *((unsigned int *)(recvbuffer + sizeof(char)));
+    gid = *((int *) (recvbuffer+sizeof(char)+sizeof(unsigned int)));
+    LOGOIDTYPE("NF",oid,0,myrdtsc());
+    LOGTIME('F',oid, 0, myrdtsc(),gid); //log time after copying it into the prefetch cache
     /* TODO: For each object not found query DHT for new location and retrieve the object */
     /* Throw an error */
     //printf("OBJECT %x NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n", oid);
@@ -1546,7 +1954,7 @@ int startRemoteThread(unsigned int oid, unsigned int mid) {
   int sock;
   struct sockaddr_in remoteAddr;
   char msg[1 + sizeof(unsigned int)];
-  int bytesSent;
+  //int bytesSent;
   int status;
 
   if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
@@ -1683,7 +2091,7 @@ int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int n
   struct sockaddr_in remoteAddr;
   char msg[1 + numoid * (sizeof(unsigned short) + sizeof(unsigned int)) +  3 * sizeof(unsigned int)];
   char *ptr;
-  int bytesSent;
+  //int bytesSent;
   int status, size;
   unsigned short version;
   unsigned int oid,mid;
@@ -1739,29 +2147,21 @@ int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int n
     *((unsigned int *)(&msg[1])) = numoid;
     /* Send array of oids  */
     size = sizeof(unsigned int);
-    {
-      i = 0;
-      while(i < numoid) {
-       oid = oidarry[i];
-       *((unsigned int *)(&msg[1] + size)) = oid;
-       size += sizeof(unsigned int);
-       i++;
-      }
+
+    for(i = 0;i < numoid; i++) {
+      oid = oidarry[i];
+      *((unsigned int *)(&msg[1] + size)) = oid;
+      size += sizeof(unsigned int);
     }
 
     /* Send array of version  */
-    {
-      i = 0;
-      while(i < numoid) {
-       version = versionarry[i];
-       *((unsigned short *)(&msg[1] + size)) = version;
-       size += sizeof(unsigned short);
-       i++;
-      }
+    for(i = 0;i < numoid; i++) {
+      version = versionarry[i];
+      *((unsigned short *)(&msg[1] + size)) = version;
+      size += sizeof(unsigned short);
     }
 
-    *((unsigned int *)(&msg[1] + size)) = myIpAddr;
-    size += sizeof(unsigned int);
+    *((unsigned int *)(&msg[1] + size)) = myIpAddr; size += sizeof(unsigned int);
     *((unsigned int *)(&msg[1] + size)) = threadid;
     pthread_mutex_lock(&(ndata->threadnotify));
     size = 1 + numoid * (sizeof(unsigned int) + sizeof(unsigned short)) + 3 * sizeof(unsigned int);
@@ -1807,7 +2207,9 @@ void threadNotify(unsigned int oid, unsigned short version, unsigned int tid) {
          prehashRemove(oid);
        }
 #endif
+       pthread_mutex_lock(&(ndata->threadnotify));
        pthread_cond_signal(&(ndata->threadcond));
+       pthread_mutex_unlock(&(ndata->threadnotify));
       }
     }
   }
@@ -1819,7 +2221,8 @@ int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) {
   unsigned int mid;
   struct sockaddr_in remoteAddr;
   char msg[1 + sizeof(unsigned short) + 2*sizeof(unsigned int)];
-  int sock, status, size, bytesSent;
+  int sock, status, size;
+  //int bytesSent;
 
   while(*head != NULL) {
     ptr = *head;
@@ -1861,10 +2264,12 @@ int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) {
   return status;
 }
 
-void transAbort(transrecord_t *trans) {
-  objstrDelete(trans->cache);
-  chashDelete(trans->lookupTable);
-  free(trans);
+void transAbort() {
+#ifdef ABORTREADERS
+  removetransactionhash();
+#endif
+  objstrDelete(t_cache);
+  t_chashDelete();
 }
 
 /* This function inserts necessary information into
@@ -1934,3 +2339,36 @@ plistnode_t *pInsert(plistnode_t *pile, objheader_t *headeraddr, unsigned int mi
 
   return pile;
 }
+
+plistnode_t *sortPiles(plistnode_t *pileptr) {
+  plistnode_t *head, *ptr, *tail;
+  head = pileptr;
+  ptr = pileptr;
+  /* Get tail pointer */
+  while(ptr!= NULL) {
+    tail = ptr;
+    ptr = ptr->next;
+  }
+  ptr = pileptr;
+  plistnode_t *prev = pileptr;
+  /* Arrange local machine processing at the end of the pile list */
+  while(ptr != NULL) {
+    if(ptr != tail) {
+      if(ptr->mid == myIpAddr && (prev != pileptr)) {
+       prev->next = ptr->next;
+       ptr->next = NULL;
+       tail->next = ptr;
+       return pileptr;
+      }
+      if((ptr->mid == myIpAddr) && (prev == pileptr)) {
+       prev = ptr->next;
+       ptr->next = NULL;
+       tail->next = ptr;
+       return prev;
+      }
+      prev = ptr;
+    }
+    ptr = ptr->next;
+  }
+  return pileptr;
+}