changes
[IRC.git] / Robust / src / Runtime / DSTM / interface / trans.c
index 51d143587a82e53b1499b009e98771dce0f979bf..ec852ce3bde1b9d06e9ad856d81f3db32eec4d01 100644 (file)
@@ -1,10 +1,11 @@
 #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"
 #define NUM_THREADS 1
 #define CONFIG_FILENAME "dstm.conf"
 
-/* Thread transaction variables */
+//#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[];
@@ -52,7 +94,6 @@ int myIndexInHostArray;
 unsigned int oidsPerBlock;
 unsigned int oidMin;
 unsigned int oidMax;
-
 sockPoolHashTable_t *transReadSockPool;
 sockPoolHashTable_t *transPrefetchSockPool;
 sockPoolHashTable_t *transRequestSockPool;
@@ -67,6 +108,7 @@ int numTransAbort = 0;
 int nchashSearch = 0;
 int nmhashSearch = 0;
 int nprehashSearch = 0;
+int ndirtyCacheObj = 0;
 int nRemoteSend = 0;
 int nSoftAbort = 0;
 int bytesSent = 0;
@@ -79,17 +121,6 @@ void printhex(unsigned char *, int);
 plistnode_t *createPiles();
 plistnode_t *sortPiles(plistnode_t *pileptr);
 
-#ifdef LOGEVENTS
-char bigarray[16*1024*1024];
-int bigindex=0;
-#define LOGEVENT(x) { \
-    int tmp=bigindex++;                                \
-    bigarray[tmp]=x;                           \
-  }
-#else
-#define LOGEVENT(x)
-#endif
-
 /*******************************
 * Send and Recv function calls
 *******************************/
@@ -170,6 +201,7 @@ void recv_data_buf(int fd, struct readstruct * readbuffer, void *buffer, int buf
       perror("recv");
       exit(0);
     }
+    bytesRecv+=numbytes;
     buflen-=numbytes;
     readbuffer->head+=numbytes;
     maxbuf-=numbytes;
@@ -210,6 +242,7 @@ int recv_data_errorcode_buf(int fd, struct readstruct * readbuffer, void *buffer
       perror("recvbuf");
       return -1;
     }
+    bytesRecv+=numbytes;
     buflen-=numbytes;
     readbuffer->head+=numbytes;
     maxbuf-=numbytes;
@@ -248,6 +281,7 @@ int recv_data_errorcode(int fd, void *buf, int buflen) {
       perror("recv");
       return -1;
     }
+    bytesRecv+=numbytes;
     buffer += numbytes;
     size -= numbytes;
   }
@@ -284,7 +318,8 @@ inline int findmax(int *array, int arraylength) {
   return max;
 }
 
-#define INLINEPREFETCH 1
+#define INLINEPREFETCH
+#define PREFTHRESHOLD 0
 
 /* This function is a prefetch call generated by the compiler that
  * populates the shared primary prefetch queue*/
@@ -293,7 +328,13 @@ void prefetch(int siteid, int ntuples, unsigned int *oids, unsigned short *endof
   int qnodesize = 2*sizeof(int) + ntuples * (sizeof(unsigned short) + sizeof(unsigned int)) + endoffsets[ntuples - 1] * sizeof(short);
   int len;
 #ifdef INLINEPREFETCH
-  char node[qnodesize];
+  int attempted=0;
+  char *node;
+  do {
+  node=getmemory(qnodesize);
+  if (node==NULL&&attempted)
+    break;
+  if (node!=NULL) {
 #else
   char *node=getmemory(qnodesize);
 #endif
@@ -316,25 +357,31 @@ void prefetch(int siteid, int ntuples, unsigned int *oids, unsigned short *endof
   memcpy(node+len+ntuples*(sizeof(unsigned int)+sizeof(short)), arrayfields, top*sizeof(short));
 
 #ifdef INLINEPREFETCH
-  prefetchpile_t *pilehead = foundLocal(node);
+  movehead(qnodesize);
+  }
+  int numpref=numavailable();
+  attempted=1;
 
-  if (pilehead!=NULL) {
-    // Get sock from shared pool
-    
-    /* Send  Prefetch Request */
-    prefetchpile_t *ptr = pilehead;
-    while(ptr != NULL) {
-      int sd = getSock2(transPrefetchSockPool, ptr->mid);
-      sendPrefetchReq(ptr, sd);
-      ptr = ptr->next;
+  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);
     }
-    
-    /* Release socket */
-    // freeSock(transPrefetchSockPool, pilehead->mid, sd);
-    
-    /* Deallocated pilehead */
-    mcdealloc(pilehead);
-  }
+    resetqueue();
+  }//end do prefetch if condition
+  } while(node==NULL);
 #else
   /* Lock and insert into primary prefetch queue */
   movehead(qnodesize);
@@ -491,11 +538,25 @@ void randomdelay() {
   return;
 }
 
+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);
+  }
+  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
@@ -568,7 +629,6 @@ __attribute__((pure)) objheader_t *transRead(unsigned int oid) {
 #ifdef ABORTREADERS
   if (t_abort) {
     //abort this transaction
-    //printf("ABORTING\n");
     removetransactionhash();
     objstrDelete(t_cache);
     t_chashDelete();
@@ -597,6 +657,12 @@ __attribute__((pure)) objheader_t *transRead(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
@@ -613,6 +679,7 @@ __attribute__((pure)) objheader_t *transRead(unsigned int oid) {
       return objcopy;
 #endif
     }
+remoteread:
 #endif
     /* Get the object from the remote location */
     if((machinenumber = lhashSearch(oid)) == 0) {
@@ -629,6 +696,24 @@ __attribute__((pure)) objheader_t *transRead(unsigned int oid) {
       nRemoteSend++;
 #endif
 #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;
@@ -641,6 +726,7 @@ __attribute__((pure)) objheader_t *transRead(unsigned int oid) {
 /* 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;
@@ -649,7 +735,6 @@ __attribute__((pure)) objheader_t *transRead2(unsigned int oid) {
 #ifdef ABORTREADERS
   if (t_abort) {
     //abort this transaction
-    //printf("ABORTING\n");
     removetransactionhash();
     objstrDelete(t_cache);
     t_chashDelete();
@@ -678,6 +763,12 @@ __attribute__((pure)) objheader_t *transRead2(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
       LOGEVENT('P')
       nprehashSearch++;
@@ -687,6 +778,7 @@ __attribute__((pure)) objheader_t *transRead2(unsigned int oid) {
       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
@@ -695,6 +787,7 @@ __attribute__((pure)) objheader_t *transRead2(unsigned int oid) {
       return objcopy;
 #endif
     }
+remoteread:
 #endif
     /* Get the object from the remote location */
     if((machinenumber = lhashSearch(oid)) == 0) {
@@ -702,17 +795,36 @@ __attribute__((pure)) objheader_t *transRead2(unsigned int oid) {
       return NULL;
     }
     objcopy = getRemoteObj(machinenumber, oid);
-
-    if(objcopy == NULL) {
-      printf("Error: Object not found in Remote location %s, %d\n", __FILE__, __LINE__);
-      return NULL;
-    } else {
 #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;
@@ -729,6 +841,13 @@ objheader_t *transCreateObj(unsigned int size) {
   tmp->rcount = 1;
   STATUS(tmp) = NEW;
   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
@@ -814,12 +933,18 @@ plistnode_t *createPiles() {
  * Sends a transrequest() to each remote machines for objects found remotely
  * and calls handleLocalReq() to process objects found locally */
 int transCommit() {
+  //char buffer[30];
   unsigned int tot_bytes_mod, *listmid;
   plistnode_t *pile, *pile_ptr;
   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;
@@ -828,12 +953,16 @@ int transCommit() {
   }
 #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
-    /* Debug
-     * printf("ABORTING TRANSACTION AT COMMIT\n");
-     */
     removetransactionhash();
     objstrDelete(t_cache);
     t_chashDelete();
@@ -842,6 +971,11 @@ int transCommit() {
 #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 {
     treplyretry = 0;
 
@@ -866,12 +1000,12 @@ int transCommit() {
 
     /* Create a socket and getReplyCtrl array, initialize */
     int socklist[pilecount];
+    char getReplyCtrl[pilecount];
     int loopcount;
-    for(loopcount = 0 ; loopcount < pilecount; loopcount++)
+    for(loopcount = 0 ; loopcount < pilecount; loopcount++){
       socklist[loopcount] = 0;
-    char getReplyCtrl[pilecount];
-    for(loopcount = 0 ; loopcount < pilecount; loopcount++)
       getReplyCtrl[loopcount] = 0;
+    }
 
     /* Process each machine pile */
     int sockindex = 0;
@@ -898,18 +1032,18 @@ int transCommit() {
        }
        socklist[sockindex] = sd;
        /* Send bytes of data with TRANS_REQUEST control message */
-       send_data(sd, &(tosend[sockindex].f), sizeof(fixed_data_t));
+       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_data(sd, tosend[sockindex].listmid, size);
+         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_data(sd, tosend[sockindex].objread, size);
+         send_buf(sd, &writebuffer, tosend[sockindex].objread, size);
        }
 
        /* Send objects that are modified */
@@ -937,7 +1071,7 @@ int transCommit() {
          memcpy(modptr+offset, headeraddr, size);
          offset+=size;
        }
-       send_data(sd, modptr, tosend[sockindex].f.sum_bytes);
+       forcesend_buf(sd, &writebuffer, modptr, tosend[sockindex].f.sum_bytes);
        free(modptr);
       } else { //handle request locally
        handleLocalReq(&tosend[sockindex], &transinfo, &getReplyCtrl[sockindex]);
@@ -945,6 +1079,7 @@ int transCommit() {
       sockindex++;
       pile = pile->next;
     } //end of pile processing
+
       /* Recv Ctrl msgs from all machines */
     int i;
     for(i = 0; i < pilecount; i++) {
@@ -981,13 +1116,8 @@ int transCommit() {
            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);
-           }
+        prehashInsert(oidToPrefetch, header);
+        LOGEVENT('E');
            length = length - size;
            offset += size;
          }
@@ -995,6 +1125,7 @@ int transCommit() {
 #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__);
@@ -1003,6 +1134,18 @@ int transCommit() {
       return 1;
     }
 
+#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);
+       return 1;
+      }
+    }
+#endif
     /* Send responses to all machines */
     for(i = 0; i < pilecount; i++) {
       int sd = socklist[i];
@@ -1017,17 +1160,6 @@ int transCommit() {
            free(listmid);
            return 1;
          }
-
-
-         /* Invalidate objects in other machine cache */
-         if(tosend[i].f.nummod > 0) {
-           if((retval = invalidateObj(&(tosend[i]))) != 0) {
-             printf("Error: %s() in invalidating Objects %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);
@@ -1063,6 +1195,10 @@ int transCommit() {
       pDelete(pile_ptr);
     /* wait a random amount of time before retrying to commit transaction*/
     if(treplyretry) {
+      treplyretryCount++;
+     // if(treplyretryCount >= NUM_TRY_TO_COMMIT)
+     //   exponentialdelay();
+     // else 
       randomdelay();
 #ifdef TRANSSTATS
       nSoftAbort++;
@@ -1072,16 +1208,20 @@ int transCommit() {
   } while (treplyretry);
 
   if(finalResponse == TRANS_ABORT) {
-    //printf("Aborting trans\n");
 #ifdef TRANSSTATS
+    LOGEVENT('A');
     numTransAbort++;
 #endif
     /* Free Resources */
     objstrDelete(t_cache);
     t_chashDelete();
+#ifdef SANDBOX
+      abortenabled=1;
+#endif
     return TRANS_ABORT;
   } else if(finalResponse == TRANS_COMMIT) {
 #ifdef TRANSSTATS
+    LOGEVENT('C');
     numTransCommit++;
 #endif
     /* Free Resources */
@@ -1144,7 +1284,7 @@ void handleLocalReq(trans_req_data_t *tdata, trans_commit_data_t *transinfo, cha
   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;
@@ -1163,16 +1303,6 @@ void doLocalProcess(char finalResponse, trans_req_data_t *tdata, trans_commit_da
       return;
     }
   } else if(finalResponse == TRANS_COMMIT) {
-#ifdef CACHE
-    /* Invalidate objects in other machine cache */
-    if(tdata->f.nummod > 0) {
-      int retval;
-      if((retval = invalidateObj(tdata)) != 0) {
-       printf("Error: %s() in invalidating Objects %s, %d\n", __func__, __FILE__, __LINE__);
-       return;
-      }
-    }
-#endif
     if(transComProcess(tdata, transinfo) != 0) {
       printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
       fflush(stdout);
@@ -1201,7 +1331,7 @@ char decideResponse(char *getReplyCtrl, char *treplyretry, int pilecount) {
     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:
@@ -1224,7 +1354,7 @@ char decideResponse(char *getReplyCtrl, char *treplyretry, int pilecount) {
     return TRANS_ABORT;
 #ifdef CACHE
     /* clear objects from prefetch cache */
-    cleanPCache();
+    //cleanPCache();
 #endif
   } else if(transagree == pilecount) {
     /* Send Commit */
@@ -1302,7 +1432,6 @@ void commitCountForObjMod(char *getReplyCtrl, unsigned int *oidnotfound, unsigne
 
        //Keep track of what is locked
        oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj));
-       //printf("%s() oid = %d, type = %d\t", __func__, OID(mobj), TYPE((objheader_t *)mobj));
        return;
       }
     } else { //A lock is acquired some place else
@@ -1312,7 +1441,6 @@ void commitCountForObjMod(char *getReplyCtrl, unsigned int *oidnotfound, unsigne
        (*v_nomatch)++;
        /* Send TRANS_DISAGREE to Coordinator */
        *getReplyCtrl = TRANS_DISAGREE;
-       //printf("%s() oid = %d, type = %d\t", __func__, OID(mobj), TYPE((objheader_t *)mobj));
        return;
       }
     }
@@ -1342,7 +1470,6 @@ void commitCountForObjRead(char *getReplyCtrl, unsigned int *oidnotfound, unsign
        *getReplyCtrl = TRANS_DISAGREE;
        //Keep track of what is locked
        oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj));
-       //printf("%s() oid = %d, type = %d\t", __func__, OID(mobj), TYPE((objheader_t *)mobj));
        return;
       }
     } else { //Has reached max number of readers or some other transaction
@@ -1353,7 +1480,6 @@ void commitCountForObjRead(char *getReplyCtrl, unsigned int *oidnotfound, unsign
        (*v_nomatch)++;
        /* Send TRANS_DISAGREE to Coordinator */
        *getReplyCtrl = TRANS_DISAGREE;
-       //printf("%s() oid = %d, type = %d\t", __func__, OID(mobj), TYPE((objheader_t *)mobj));
        return;
       }
     }
@@ -1470,56 +1596,79 @@ int transComProcess(trans_req_data_t *tdata, trans_commit_data_t *transinfo) {
   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 {
@@ -1527,14 +1676,20 @@ 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;
   }
@@ -1565,7 +1720,8 @@ void *transPrefetch(void *t) {
     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
@@ -1573,9 +1729,10 @@ void *transPrefetch(void *t) {
       /* Send  Prefetch Request */
       prefetchpile_t *ptr = pilehead;
       while(ptr != NULL) {
-       int sd = getSock2(transPrefetchSockPool, ptr->mid);
-       sendPrefetchReq(ptr, sd);
-       ptr = ptr->next;
+        globalid++;
+        int sd = getSock2(transPrefetchSockPool, ptr->mid);
+        sendPrefetchReq(ptr, sd,globalid);
+        ptr = ptr->next;
       }
 
       /* Release socket */
@@ -1585,7 +1742,7 @@ void *transPrefetch(void *t) {
       mcdealloc(pilehead);
     }
     // Deallocate the prefetch queue pile node
-    inctail();
+    incmulttail(count);
   }
 }
 
@@ -1618,10 +1775,18 @@ 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 */
   int first=1;
@@ -1629,7 +1794,7 @@ void sendPrefetchReq(prefetchpile_t *mcpilenode, int sd) {
   /* 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));
+    len = sizeof(int)+sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
     char oidnoffset[len+5];
     char *buf=oidnoffset;
     if (first) {
@@ -1640,27 +1805,34 @@ void sendPrefetchReq(prefetchpile_t *mcpilenode, int sd) {
     *((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));
     tmp = tmp->next;
     if (tmp==NULL) {
       *((int *)(&oidnoffset[len]))=-1;
       len+=sizeof(int);
     }
-    send_data(sd, oidnoffset, len);
+    if (tmp!=NULL)
+      send_buf(sd, &writebuffer, oidnoffset, len);
+    else
+      forcesend_buf(sd, &writebuffer, oidnoffset, len);
   }
-
+  LOGOIDTYPE("SREQ",0,0,myrdtsc());
   LOGEVENT('S');
+  LOGTIME('S',0,0,myrdtsc(),gid); //after sending
   return;
 }
 
 int getPrefetchResponse(int sd, struct readstruct *readbuffer) {
-  int length = 0, size = 0;
+  int gid,length = 0, size = 0;
   char control;
   unsigned int oid;
   void *modptr, *oldptr;
@@ -1669,14 +1841,17 @@ int getPrefetchResponse(int sd, struct readstruct *readbuffer) {
   size = length - sizeof(int);
   char recvbuffer[size];
 #ifdef TRANSSTATS
-    getResponse++;
-    LOGEVENT('Z');
+  getResponse++;
+  LOGEVENT('Z');
+  LOGTIME('K',0,0, myrdtsc(),0); //log time after first recv
 #endif
-    recv_data_buf(sd, readbuffer, recvbuffer, size);
+  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__);
@@ -1684,28 +1859,27 @@ int getPrefetchResponse(int sd, struct readstruct *readbuffer) {
       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);
@@ -1780,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) {
@@ -1917,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;
@@ -2047,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;