changes
[IRC.git] / Robust / src / Runtime / DSTM / interface / trans.c
index 81cd2081cbd95bbafb5a6bb20e2250255f0bc799..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
 *******************************/
@@ -287,8 +318,8 @@ inline int findmax(int *array, int arraylength) {
   return max;
 }
 
-//#define INLINEPREFETCH
-#define PREFTHRESHOLD 4
+#define INLINEPREFETCH
+#define PREFTHRESHOLD 0
 
 /* This function is a prefetch call generated by the compiler that
  * populates the shared primary prefetch queue*/
@@ -331,23 +362,24 @@ void prefetch(int siteid, int ntuples, unsigned int *oids, unsigned short *endof
   int numpref=numavailable();
   attempted=1;
 
-  if (node==NULL && numpref!=0 || numpref==PREFTHRESHOLD) {
+  if (node==NULL && numpref!=0 || numpref>=PREFTHRESHOLD) {
     node=gettail();
-    prefetchpile_t *pilehead = foundLocal(node,numpref);
+    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) {
-       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;
       }
       
       mcdealloc(pilehead);
-      resetqueue();
     }
+    resetqueue();
   }//end do prefetch if condition
   } while(node==NULL);
 #else
@@ -506,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
@@ -583,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();
@@ -612,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
@@ -628,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) {
@@ -659,13 +711,8 @@ __attribute__((pure)) objheader_t *transRead(unsigned int oid) {
       pthread_mutex_unlock(&prefetchcache_mutex);
       memcpy(headerObj, objcopy, size+sizeof(objheader_t));
       //make an entry in prefetch lookup hashtable
-      void *oldptr;
-      if((oldptr = prehashSearch(oid)) != NULL) {
-        prehashRemove(oid);
-        prehashInsert(oid, headerObj);
-      } else {
-        prehashInsert(oid, headerObj);
-      }
+      prehashInsert(oid, headerObj);
+      LOGEVENT('B');
 #endif
       return &objcopy[1];
 #else
@@ -679,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;
@@ -687,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();
@@ -716,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++;
@@ -725,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
@@ -733,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) {
@@ -740,18 +795,19 @@ __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;
@@ -766,13 +822,8 @@ __attribute__((pure)) objheader_t *transRead2(unsigned int oid) {
       pthread_mutex_unlock(&prefetchcache_mutex);
       memcpy(headerObj, objcopy, size+sizeof(objheader_t));
       //make an entry in prefetch lookup hashtable
-      void *oldptr;
-      if((oldptr = prehashSearch(oid)) != NULL) {
-        prehashRemove(oid);
-        prehashInsert(oid, headerObj);
-      } else {
-        prehashInsert(oid, headerObj);
-      }
+      prehashInsert(oid, headerObj);
+      LOGEVENT('B');
 #endif
       return &objcopy[1];
 #else
@@ -790,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
@@ -875,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;
@@ -889,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();
@@ -903,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;
 
@@ -927,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;
@@ -959,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 */
@@ -998,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]);
@@ -1006,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++) {
@@ -1042,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;
          }
@@ -1056,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__);
@@ -1064,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];
@@ -1078,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);
@@ -1124,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++;
@@ -1133,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 */
@@ -1205,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;
@@ -1224,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);
@@ -1262,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:
@@ -1285,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 */
@@ -1363,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
@@ -1373,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;
       }
     }
@@ -1403,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
@@ -1414,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;
       }
     }
@@ -1531,7 +1596,7 @@ int transComProcess(trans_req_data_t *tdata, trans_commit_data_t *transinfo) {
   return 0;
 }
 
-prefetchpile_t *foundLocal(char *ptr, int numprefetches) {
+prefetchpile_t *foundLocal(char *ptr, int numprefetches, int mysiteid) {
   int i;
   int j;
   prefetchpile_t * head=NULL;
@@ -1550,25 +1615,38 @@ prefetchpile_t *foundLocal(char *ptr, int numprefetches) {
       unsigned int oid=oidarray[i];
       int newbase;
       int machinenum;
-      
-      if (oid==0)
+      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 (!lookupObject(&oid, arryfields[newbase]))
+        if(newbase==(endindex-1))
+          isLastOffset=1;
+       if (!lookupObject(&oid,arryfields[newbase],&countInvalidObj)) {
          break;
+       }
        //Ended in a null pointer...
-       if (oid==0)
+       if (oid==0) {
+         numLocal++;
          goto tuple;
+       }
       }
+
       //Entire prefetch is local
-      if (newbase==endindex&&checkoid(oid)) {
+      if (newbase==endindex&&checkoid(oid,isLastOffset)) {
        numLocal++;
        goto tuple;
       }
+
       //Add to remote requests
       machinenum=lhashSearch(oid);
-      insertPile(machinenum, oid, endindex-newbase, &arryfields[newbase], &head);
+      insertPile(machinenum, oid, siteid,endindex-newbase, &arryfields[newbase], &head);
     tuple:
       ;
     }
@@ -1581,12 +1659,16 @@ prefetchpile_t *foundLocal(char *ptr, int numprefetches) {
   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 {
@@ -1594,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;
   }
@@ -1633,7 +1721,7 @@ void *transPrefetch(void *t) {
     /* Check if the tuples are found locally, if yes then reduce them further*/
     /* and group requests by remote machine ids by calling the makePreGroups() */
     int count=numavailable();
-    prefetchpile_t *pilehead = foundLocal(node, count);
+    prefetchpile_t *pilehead = foundLocal(node, count, 0);
 
     if (pilehead!=NULL) {
       // Get sock from shared pool
@@ -1641,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 */
@@ -1686,20 +1775,26 @@ 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;
 
   /* 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) {
@@ -1710,12 +1805,15 @@ 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) {
@@ -1723,17 +1821,18 @@ void sendPrefetchReq(prefetchpile_t *mcpilenode, int sd) {
       len+=sizeof(int);
     }
     if (tmp!=NULL)
-      send_buf(sd, & writebuffer, oidnoffset, len);
+      send_buf(sd, &writebuffer, oidnoffset, len);
     else
-      forcesend_buf(sd, & writebuffer, oidnoffset, len);
+      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;
@@ -1742,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__);
@@ -1757,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);
@@ -1853,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) {
@@ -1990,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;
@@ -2120,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;