3 #include "machinepile.h"
8 #include "threadnotify.h"
10 #include "addUdpEnhance.h"
11 #include "addPrefetchEnhance.h"
19 #include "abortreaders.h"
24 #define CONFIG_FILENAME "dstm.conf"
26 /* Thread transaction variables */
28 __thread objstr_t *t_cache;
29 __thread struct ___Object___ *revertlist;
32 __thread jmp_buf aborttrans;
36 /* Global Variables */
37 extern int classsize[];
38 pfcstats_t *evalPrefetch;
39 extern int numprefetchsites; //Global variable containing number of prefetch sites
40 extern pthread_mutex_t mainobjstore_mutex; // Mutex to lock main Object store
41 pthread_mutex_t prefetchcache_mutex; // Mutex to lock Prefetch Cache
42 pthread_mutexattr_t prefetchcache_mutex_attr; /* Attribute for lock to make it a recursive lock */
43 extern prehashtable_t pflookup; //Global Prefetch cache's lookup table
44 pthread_t wthreads[NUM_THREADS]; //Worker threads for working on the prefetch queue
45 pthread_t tPrefetch; /* Primary Prefetch thread that processes the prefetch queue */
46 extern objstr_t *mainobjstore;
47 unsigned int myIpAddr;
48 unsigned int *hostIpAddrs;
51 int myIndexInHostArray;
52 unsigned int oidsPerBlock;
56 sockPoolHashTable_t *transReadSockPool;
57 sockPoolHashTable_t *transPrefetchSockPool;
58 sockPoolHashTable_t *transRequestSockPool;
59 pthread_mutex_t notifymutex;
60 pthread_mutex_t atomicObjLock;
62 /***********************************
63 * Global Variables for statistics
64 **********************************/
65 int numTransCommit = 0;
66 int numTransAbort = 0;
69 int nprehashSearch = 0;
75 int sendRemoteReq = 0;
78 void printhex(unsigned char *, int);
79 plistnode_t *createPiles();
80 plistnode_t *sortPiles(plistnode_t *pileptr);
83 char bigarray[16*1024*1024];
85 #define LOGEVENT(x) { \
93 /*******************************
94 * Send and Recv function calls
95 *******************************/
96 void send_data(int fd, void *buf, int buflen) {
97 char *buffer = (char *)(buf);
101 numbytes = send(fd, buffer, size, MSG_NOSIGNAL);
102 bytesSent = bytesSent + numbytes;
103 if (numbytes == -1) {
112 void send_buf(int fd, struct writestruct * sendbuffer, void *buffer, int buflen) {
113 if (buflen+sendbuffer->offset>WMAXBUF) {
114 send_data(fd, sendbuffer->buf, sendbuffer->offset);
115 sendbuffer->offset=0;
116 send_data(fd, buffer, buflen);
119 memcpy(&sendbuffer->buf[sendbuffer->offset], buffer, buflen);
120 sendbuffer->offset+=buflen;
121 if (sendbuffer->offset>WTOP) {
122 send_data(fd, sendbuffer->buf, sendbuffer->offset);
123 sendbuffer->offset=0;
127 void forcesend_buf(int fd, struct writestruct * sendbuffer, void *buffer, int buflen) {
128 if (buflen+sendbuffer->offset>WMAXBUF) {
129 send_data(fd, sendbuffer->buf, sendbuffer->offset);
130 sendbuffer->offset=0;
131 send_data(fd, buffer, buflen);
134 memcpy(&sendbuffer->buf[sendbuffer->offset], buffer, buflen);
135 sendbuffer->offset+=buflen;
136 send_data(fd, sendbuffer->buf, sendbuffer->offset);
137 sendbuffer->offset=0;
140 int recvw(int fd, void *buf, int len, int flags) {
141 return recv(fd, buf, len, flags);
144 void recv_data_buf(int fd, struct readstruct * readbuffer, void *buffer, int buflen) {
145 char *buf=(char *)buffer;
146 int numbytes=readbuffer->head-readbuffer->tail;
150 memcpy(buf, &readbuffer->buf[readbuffer->tail], numbytes);
151 readbuffer->tail+=numbytes;
158 if (buflen>=MAXBUF) {
159 recv_data(fd, buf, buflen);
168 int numbytes = recvw(fd, &readbuffer->buf[readbuffer->head], maxbuf, 0);
169 if (numbytes == -1) {
174 readbuffer->head+=numbytes;
177 memcpy(buf,readbuffer->buf,obufflen);
178 readbuffer->tail=obufflen;
181 int recv_data_errorcode_buf(int fd, struct readstruct * readbuffer, void *buffer, int buflen) {
182 char *buf=(char *)buffer;
184 int numbytes=readbuffer->head-readbuffer->tail;
188 memcpy(buf, &readbuffer->buf[readbuffer->tail], numbytes);
189 readbuffer->tail+=numbytes;
196 if (buflen>=MAXBUF) {
197 return recv_data_errorcode(fd, buf, buflen);
205 int numbytes = recvw(fd, &readbuffer->buf[readbuffer->head], maxbuf, 0);
214 readbuffer->head+=numbytes;
217 memcpy(buf,readbuffer->buf,obufflen);
218 readbuffer->tail=obufflen;
223 void recv_data(int fd, void *buf, int buflen) {
224 char *buffer = (char *)(buf);
228 numbytes = recvw(fd, buffer, size, 0);
229 bytesRecv = bytesRecv + numbytes;
230 if (numbytes == -1) {
239 int recv_data_errorcode(int fd, void *buf, int buflen) {
240 char *buffer = (char *)(buf);
244 numbytes = recvw(fd, buffer, size, 0);
247 if (numbytes == -1) {
257 void printhex(unsigned char *ptr, int numBytes) {
259 for (i = 0; i < numBytes; i++) {
261 printf("0%x ", ptr[i]);
263 printf("%x ", ptr[i]);
269 inline int arrayLength(int *array) {
271 for(i=0 ; array[i] != -1; i++)
276 inline int findmax(int *array, int arraylength) {
279 for(i = 0; i < arraylength; i++) {
287 //#define INLINEPREFETCH
288 #define PREFTHRESHOLD 4
290 /* This function is a prefetch call generated by the compiler that
291 * populates the shared primary prefetch queue*/
292 void prefetch(int siteid, int ntuples, unsigned int *oids, unsigned short *endoffsets, short *arrayfields) {
293 /* Allocate for the queue node*/
294 int qnodesize = 2*sizeof(int) + ntuples * (sizeof(unsigned short) + sizeof(unsigned int)) + endoffsets[ntuples - 1] * sizeof(short);
296 #ifdef INLINEPREFETCH
300 node=getmemory(qnodesize);
301 if (node==NULL&&attempted)
305 char *node=getmemory(qnodesize);
307 int top=endoffsets[ntuples-1];
313 /* Set queue node values */
315 /* TODO: Remove this after testing */
316 evalPrefetch[siteid].callcount++;
318 *((int *)(node))=siteid;
319 *((int *)(node + sizeof(int))) = ntuples;
321 memcpy(node+len, oids, ntuples*sizeof(unsigned int));
322 memcpy(node+len+ntuples*sizeof(unsigned int), endoffsets, ntuples*sizeof(unsigned short));
323 memcpy(node+len+ntuples*(sizeof(unsigned int)+sizeof(short)), arrayfields, top*sizeof(short));
325 #ifdef INLINEPREFETCH
328 int numpref=numavailable();
331 if (node==NULL && numpref!=0 || numpref==PREFTHRESHOLD) {
333 prefetchpile_t *pilehead = foundLocal(node,numpref);
334 if (pilehead!=NULL) {
335 // Get sock from shared pool
337 /* Send Prefetch Request */
338 prefetchpile_t *ptr = pilehead;
340 int sd = getSock2(transPrefetchSockPool, ptr->mid);
341 sendPrefetchReq(ptr, sd);
348 }//end do prefetch if condition
351 /* Lock and insert into primary prefetch queue */
356 /* This function starts up the transaction runtime. */
357 int dstmStartup(const char * option) {
358 pthread_t thread_Listen, udp_thread_Listen;
360 int master=option!=NULL && strcmp(option, "master")==0;
364 if (processConfigFile() != 0)
365 return 0; //TODO: return error value, cause main program to exit
372 printf("Trans stats is on\n");
379 //Initialize socket pool
380 transReadSockPool = createSockPool(transReadSockPool, DEFAULTSOCKPOOLSIZE);
381 transPrefetchSockPool = createSockPool(transPrefetchSockPool, DEFAULTSOCKPOOLSIZE);
382 transRequestSockPool = createSockPool(transRequestSockPool, DEFAULTSOCKPOOLSIZE);
388 pthread_attr_init(&attr);
389 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
392 pthread_create(&udp_thread_Listen, &attr, udpListenBroadcast, (void*)udpfd);
395 pthread_create(&thread_Listen, &attr, dstmListen, (void*)fd);
398 dstmListen((void *)fd);
403 //TODO Use this later
404 void *pCacheAlloc(objstr_t *store, unsigned int size) {
410 while(ptr->next != NULL) {
411 /* check if store is empty */
412 if(((unsigned int)ptr->top - (unsigned int)ptr - sizeof(objstr_t) + size) <= ptr->size) {
427 /* This function initiates the prefetch thread A queue is shared
428 * between the main thread of execution and the prefetch thread to
429 * process the prefetch call Call from compiler populates the shared
430 * queue with prefetch requests while prefetch thread processes the
431 * prefetch requests */
434 //Create and initialize prefetch cache structure
437 if((evalPrefetch = initPrefetchStats()) == NULL) {
438 printf("%s() Error allocating memory at %s, %d\n", __func__, __FILE__, __LINE__);
443 /* Initialize attributes for mutex */
444 pthread_mutexattr_init(&prefetchcache_mutex_attr);
445 pthread_mutexattr_settype(&prefetchcache_mutex_attr, PTHREAD_MUTEX_RECURSIVE_NP);
447 pthread_mutex_init(&prefetchcache_mutex, &prefetchcache_mutex_attr);
448 pthread_mutex_init(¬ifymutex, NULL);
449 pthread_mutex_init(&atomicObjLock, NULL);
451 //Create prefetch cache lookup table
452 if(prehashCreate(PHASH_SIZE, PLOADFACTOR)) {
457 //Initialize primary shared queue
459 //Initialize machine pile w/prefetch oids and offsets shared queue
462 //Create the primary prefetch thread
466 retval=pthread_create(&tPrefetch, NULL, transPrefetchNew, NULL);
469 #ifndef INLINEPREFETCH
471 retval=pthread_create(&tPrefetch, NULL, transPrefetch, NULL);
475 #ifndef INLINEPREFETCH
476 pthread_detach(tPrefetch);
481 /* This function stops the threads spawned */
485 pthread_cancel(tPrefetch);
486 for(t = 0; t < NUM_THREADS; t++)
487 pthread_cancel(wthreads[t]);
493 /* This functions inserts randowm wait delays in the order of msec
494 * Mostly used when transaction commits retry*/
501 req.tv_nsec = (long)(1000 + (t%10000)); //1-11 microsec
502 nanosleep(&req, NULL);
506 /* This function initializes things required in the transaction start*/
508 t_cache = objstrCreate(1048576);
509 t_chashCreate(CHASH_SIZE, CLOADFACTOR);
516 // Search for an address for a given oid
517 /*#define INLINE inline __attribute__((always_inline))
519 INLINE void * chashSearchI(chashtable_t *table, unsigned int key) {
520 //REMOVE HASH FUNCTION CALL TO MAKE SURE IT IS INLINED HERE
521 chashlistnode_t *node = &table->table[(key & table->mask)>>1];
524 if(node->key == key) {
528 } while(node != NULL);
536 /* This function finds the location of the objects involved in a transaction
537 * and returns the pointer to the object if found in a remote location */
538 __attribute__((pure)) objheader_t *transRead(unsigned int oid) {
539 unsigned int machinenumber;
540 objheader_t *tmp, *objheader;
541 objheader_t *objcopy;
544 chashlistnode_t *node;
551 node= &c_table[(oid & c_mask)>>1];
553 if(node->key == oid) {
558 return &((objheader_t*)node->val)[1];
564 } while(node != NULL);
568 if((objheader = chashSearchI(record->lookupTable, oid)) != NULL) {
573 return &objheader[1];
582 //abort this transaction
583 //printf("ABORTING\n");
584 removetransactionhash();
585 objstrDelete(t_cache);
587 _longjmp(aborttrans,1);
592 if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
596 /* Look up in machine lookup table and copy into cache*/
597 GETSIZE(size, objheader);
598 size += sizeof(objheader_t);
599 objcopy = (objheader_t *) objstrAlloc(&t_cache, size);
600 memcpy(objcopy, objheader, size);
601 /* Insert into cache's lookup table */
603 t_chashInsert(OID(objheader), objcopy);
611 if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) {
615 /* Look up in prefetch cache */
617 size+=sizeof(objheader_t);
618 objcopy = (objheader_t *) objstrAlloc(&t_cache, size);
619 memcpy(objcopy, tmp, size);
620 /* Insert into cache's lookup table */
621 t_chashInsert(OID(tmp), objcopy);
629 /* Get the object from the remote location */
630 if((machinenumber = lhashSearch(oid)) == 0) {
631 printf("Error: %s() No machine found for oid =% %s,%dx\n",__func__, machinenumber, __FILE__, __LINE__);
634 objcopy = getRemoteObj(machinenumber, oid);
636 if(objcopy == NULL) {
637 printf("Error: Object not found in Remote location %s, %d\n", __FILE__, __LINE__);
653 /* This function finds the location of the objects involved in a transaction
654 * and returns the pointer to the object if found in a remote location */
655 __attribute__((pure)) objheader_t *transRead2(unsigned int oid) {
656 unsigned int machinenumber;
657 objheader_t *tmp, *objheader;
658 objheader_t *objcopy;
663 //abort this transaction
664 //printf("ABORTING\n");
665 removetransactionhash();
666 objstrDelete(t_cache);
668 _longjmp(aborttrans,1);
673 if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
677 /* Look up in machine lookup table and copy into cache*/
678 GETSIZE(size, objheader);
679 size += sizeof(objheader_t);
680 objcopy = (objheader_t *) objstrAlloc(&t_cache, size);
681 memcpy(objcopy, objheader, size);
682 /* Insert into cache's lookup table */
684 t_chashInsert(OID(objheader), objcopy);
692 if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) {
697 /* Look up in prefetch cache */
699 size+=sizeof(objheader_t);
700 objcopy = (objheader_t *) objstrAlloc(&t_cache, size);
701 memcpy(objcopy, tmp, size);
702 /* Insert into cache's lookup table */
703 t_chashInsert(OID(tmp), objcopy);
711 /* Get the object from the remote location */
712 if((machinenumber = lhashSearch(oid)) == 0) {
713 printf("Error: %s() No machine found for oid =% %s,%dx\n",__func__, machinenumber, __FILE__, __LINE__);
716 objcopy = getRemoteObj(machinenumber, oid);
718 if(objcopy == NULL) {
719 printf("Error: Object not found in Remote location %s, %d\n", __FILE__, __LINE__);
736 /* This function creates objects in the transaction record */
737 objheader_t *transCreateObj(unsigned int size) {
738 objheader_t *tmp = (objheader_t *) objstrAlloc(&t_cache, (sizeof(objheader_t) + size));
739 OID(tmp) = getNewOID();
743 t_chashInsert(OID(tmp), tmp);
746 return &tmp[1]; //want space after object header
753 /* This function creates machine piles based on all machines involved in a
754 * transaction commit request */
755 plistnode_t *createPiles() {
757 plistnode_t *pile = NULL;
758 unsigned int machinenum;
759 objheader_t *headeraddr;
760 chashlistnode_t * ptr = c_table;
761 /* Represents number of bins in the chash table */
762 unsigned int size = c_size;
764 for(i = 0; i < size ; i++) {
765 chashlistnode_t * curr = &ptr[i];
766 /* Inner loop to traverse the linked list of the cache lookupTable */
767 while(curr != NULL) {
768 //if the first bin in hash table is empty
771 headeraddr=(objheader_t *) curr->val;
773 //Get machine location for object id (and whether local or not)
774 if (STATUS(headeraddr) & NEW || (mhashSearch(curr->key) != NULL)) {
775 machinenum = myIpAddr;
776 } else if ((machinenum = lhashSearch(curr->key)) == 0) {
777 printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
781 //Make machine groups
782 pile = pInsert(pile, headeraddr, machinenum, c_numelements);
789 /* This function creates machine piles based on all machines involved in a
790 * transaction commit request */
791 plistnode_t *createPiles() {
793 plistnode_t *pile = NULL;
794 unsigned int machinenum;
795 objheader_t *headeraddr;
796 struct chashentry * ptr = c_table;
797 /* Represents number of bins in the chash table */
798 unsigned int size = c_size;
800 for(i = 0; i < size ; i++) {
801 struct chashentry * curr = & ptr[i];
802 /* Inner loop to traverse the linked list of the cache lookupTable */
803 //if the first bin in hash table is empty
806 headeraddr=(objheader_t *) curr->ptr;
808 //Get machine location for object id (and whether local or not)
809 if (STATUS(headeraddr) & NEW || (mhashSearch(curr->key) != NULL)) {
810 machinenum = myIpAddr;
811 } else if ((machinenum = lhashSearch(curr->key)) == 0) {
812 printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
816 //Make machine groups
817 pile = pInsert(pile, headeraddr, machinenum, c_numelements);
823 /* This function initiates the transaction commit process
824 * Spawns threads for each of the new connections with Participants
825 * and creates new piles by calling the createPiles(),
826 * Sends a transrequest() to each remote machines for objects found remotely
827 * and calls handleLocalReq() to process objects found locally */
829 unsigned int tot_bytes_mod, *listmid;
830 plistnode_t *pile, *pile_ptr;
831 char treplyretry; /* keeps track of the common response that needs to be sent */
833 trans_commit_data_t transinfo; /* keeps track of objs locked during transaction */
838 for(iii=0;iii<bigindex;iii++) {
839 printf("%c", bigarray[iii]);
845 //abort this transaction
847 * printf("ABORTING TRANSACTION AT COMMIT\n");
849 removetransactionhash();
850 objstrDelete(t_cache);
860 /* Look through all the objects in the transaction record and make piles
861 * for each machine involved in the transaction*/
863 pile_ptr = pile = createPiles();
864 pile_ptr = pile = sortPiles(pile);
869 /* Create the packet to be sent in TRANS_REQUEST */
871 /* Count the number of participants */
873 pilecount = pCount(pile);
875 /* Create a list of machine ids(Participants) involved in transaction */
876 listmid = calloc(pilecount, sizeof(unsigned int));
877 pListMid(pile, listmid);
879 /* Create a socket and getReplyCtrl array, initialize */
880 int socklist[pilecount];
882 for(loopcount = 0 ; loopcount < pilecount; loopcount++)
883 socklist[loopcount] = 0;
884 char getReplyCtrl[pilecount];
885 for(loopcount = 0 ; loopcount < pilecount; loopcount++)
886 getReplyCtrl[loopcount] = 0;
888 /* Process each machine pile */
890 trans_req_data_t *tosend;
891 tosend = calloc(pilecount, sizeof(trans_req_data_t));
892 while(pile != NULL) {
893 tosend[sockindex].f.control = TRANS_REQUEST;
894 tosend[sockindex].f.mcount = pilecount;
895 tosend[sockindex].f.numread = pile->numread;
896 tosend[sockindex].f.nummod = pile->nummod;
897 tosend[sockindex].f.numcreated = pile->numcreated;
898 tosend[sockindex].f.sum_bytes = pile->sum_bytes;
899 tosend[sockindex].listmid = listmid;
900 tosend[sockindex].objread = pile->objread;
901 tosend[sockindex].oidmod = pile->oidmod;
902 tosend[sockindex].oidcreated = pile->oidcreated;
904 if(pile->mid != myIpAddr) {
905 if((sd = getSock2WithLock(transRequestSockPool, pile->mid)) < 0) {
906 printf("transRequest(): socket create error\n");
911 socklist[sockindex] = sd;
912 /* Send bytes of data with TRANS_REQUEST control message */
913 send_data(sd, &(tosend[sockindex].f), sizeof(fixed_data_t));
915 /* Send list of machines involved in the transaction */
917 int size=sizeof(unsigned int)*(tosend[sockindex].f.mcount);
918 send_data(sd, tosend[sockindex].listmid, size);
921 /* Send oids and version number tuples for objects that are read */
923 int size=(sizeof(unsigned int)+sizeof(unsigned short))*(tosend[sockindex].f.numread);
924 send_data(sd, tosend[sockindex].objread, size);
927 /* Send objects that are modified */
929 if((modptr = calloc(1, tosend[sockindex].f.sum_bytes)) == NULL) {
930 printf("Calloc error for modified objects %s, %d\n", __FILE__, __LINE__);
937 for(i = 0; i < tosend[sockindex].f.nummod ; i++) {
939 objheader_t *headeraddr;
940 if((headeraddr = t_chashSearch(tosend[sockindex].oidmod[i])) == NULL) {
941 printf("%s() Error: No such oid %s, %d\n", __func__, __FILE__, __LINE__);
947 GETSIZE(size,headeraddr);
948 size+=sizeof(objheader_t);
949 memcpy(modptr+offset, headeraddr, size);
952 send_data(sd, modptr, tosend[sockindex].f.sum_bytes);
954 } else { //handle request locally
955 handleLocalReq(&tosend[sockindex], &transinfo, &getReplyCtrl[sockindex]);
959 } //end of pile processing
960 /* Recv Ctrl msgs from all machines */
962 for(i = 0; i < pilecount; i++) {
963 int sd = socklist[i];
966 recv_data(sd, &control, sizeof(char));
967 //Update common data structure with new ctrl msg
968 getReplyCtrl[i] = control;
969 /* Recv Objects if participant sends TRANS_DISAGREE */
971 if(control == TRANS_DISAGREE) {
973 recv_data(sd, &length, sizeof(int));
975 pthread_mutex_lock(&prefetchcache_mutex);
976 if ((newAddr = prefetchobjstrAlloc((unsigned int)length)) == NULL) {
977 printf("Error: %s() objstrAlloc error for copying into prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
980 pthread_mutex_unlock(&prefetchcache_mutex);
983 pthread_mutex_unlock(&prefetchcache_mutex);
984 recv_data(sd, newAddr, length);
987 unsigned int oidToPrefetch;
988 objheader_t * header;
989 header = (objheader_t *)(((char *)newAddr) + offset);
990 oidToPrefetch = OID(header);
993 GETSIZE(size, header);
994 size += sizeof(objheader_t);
995 //make an entry in prefetch hash table
997 if((oldptr = prehashSearch(oidToPrefetch)) != NULL) {
998 prehashRemove(oidToPrefetch);
999 prehashInsert(oidToPrefetch, header);
1001 prehashInsert(oidToPrefetch, header);
1003 length = length - size;
1006 } //end of receiving objs
1010 /* Decide the final response */
1011 if((finalResponse = decideResponse(getReplyCtrl, &treplyretry, pilecount)) == 0) {
1012 printf("Error: %s() in updating prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
1018 /* Send responses to all machines */
1019 for(i = 0; i < pilecount; i++) {
1020 int sd = socklist[i];
1023 if(finalResponse == TRANS_COMMIT) {
1025 /* Update prefetch cache */
1026 if((retval = updatePrefetchCache(&(tosend[i]))) != 0) {
1027 printf("Error: %s() in updating prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
1034 /* Invalidate objects in other machine cache */
1035 if(tosend[i].f.nummod > 0) {
1036 if((retval = invalidateObj(&(tosend[i]))) != 0) {
1037 printf("Error: %s() in invalidating Objects %s, %d\n", __func__, __FILE__, __LINE__);
1044 removetransaction(tosend[i].oidmod,tosend[i].f.nummod);
1045 removethisreadtransaction(tosend[i].objread, tosend[i].f.numread);
1049 else if (!treplyretry) {
1050 removethistransaction(tosend[i].oidmod,tosend[i].f.nummod);
1051 removethisreadtransaction(tosend[i].objread,tosend[i].f.numread);
1055 send_data(sd, &finalResponse, sizeof(char));
1057 /* Complete local processing */
1058 doLocalProcess(finalResponse, &(tosend[i]), &transinfo);
1060 if(finalResponse == TRANS_COMMIT) {
1061 removetransaction(tosend[i].oidmod,tosend[i].f.nummod);
1062 removethisreadtransaction(tosend[i].objread,tosend[i].f.numread);
1063 } else if (!treplyretry) {
1064 removethistransaction(tosend[i].oidmod,tosend[i].f.nummod);
1065 removethisreadtransaction(tosend[i].objread,tosend[i].f.numread);
1071 /* Free resources */
1076 /* wait a random amount of time before retrying to commit transaction*/
1083 /* Retry trans commit procedure during soft_abort case */
1084 } while (treplyretry);
1086 if(finalResponse == TRANS_ABORT) {
1087 //printf("Aborting trans\n");
1091 /* Free Resources */
1092 objstrDelete(t_cache);
1095 } else if(finalResponse == TRANS_COMMIT) {
1099 /* Free Resources */
1100 objstrDelete(t_cache);
1104 //TODO Add other cases
1105 printf("Error: in %s() THIS SHOULD NOT HAPPEN.....EXIT PROGRAM\n", __func__);
1111 /* This function handles the local objects involved in a transaction
1112 * commiting process. It also makes a decision if this local machine
1113 * sends AGREE or DISAGREE or SOFT_ABORT to coordinator */
1114 void handleLocalReq(trans_req_data_t *tdata, trans_commit_data_t *transinfo, char *getReplyCtrl) {
1115 unsigned int *oidnotfound = NULL, *oidlocked = NULL;
1116 int numoidnotfound = 0, numoidlocked = 0;
1117 int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
1120 unsigned short version;
1122 /* Counters and arrays to formulate decision on control message to be sent */
1123 oidnotfound = (unsigned int *) calloc((tdata->f.numread + tdata->f.nummod), sizeof(unsigned int));
1124 oidlocked = (unsigned int *) calloc((tdata->f.numread + tdata->f.nummod +1), sizeof(unsigned int)); // calloc additional 1 byte for
1125 //setting a divider between read and write locks
1126 numread = tdata->f.numread;
1127 /* Process each oid in the machine pile/ group per thread */
1128 for (i = 0; i < tdata->f.numread + tdata->f.nummod; i++) {
1129 if (i < tdata->f.numread) {
1130 int incr = sizeof(unsigned int) + sizeof(unsigned short); // Offset that points to next position in the objread array
1132 oid = *((unsigned int *)(((char *)tdata->objread) + incr));
1133 version = *((unsigned short *)(((char *)tdata->objread) + incr + sizeof(unsigned int)));
1134 commitCountForObjRead(getReplyCtrl, oidnotfound, oidlocked, &numoidnotfound, &numoidlocked, &v_nomatch, &v_matchlock, &v_matchnolock, oid, version);
1135 } else { // Objects Modified
1136 if(i == tdata->f.numread) {
1137 oidlocked[numoidlocked++] = -1;
1140 objheader_t *headptr;
1141 headptr = (objheader_t *) t_chashSearch(tdata->oidmod[i-numread]);
1142 if (headptr == NULL) {
1143 printf("Error: handleLocalReq() returning NULL, no such oid %s, %d\n", __FILE__, __LINE__);
1147 version = headptr->version;
1148 commitCountForObjMod(getReplyCtrl, oidnotfound, oidlocked, &numoidnotfound, &numoidlocked, &v_nomatch, &v_matchlock, &v_matchnolock, oid, version);
1152 /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
1153 * if Participant receives a TRANS_COMMIT */
1154 transinfo->objlocked = oidlocked;
1155 transinfo->objnotfound = oidnotfound;
1156 transinfo->modptr = NULL;
1157 transinfo->numlocked = numoidlocked;
1158 transinfo->numnotfound = numoidnotfound;
1160 /* Condition to send TRANS_AGREE */
1161 if(v_matchnolock == tdata->f.numread + tdata->f.nummod) {
1162 *getReplyCtrl = TRANS_AGREE;
1164 /* Condition to send TRANS_SOFT_ABORT */
1165 if((v_matchlock > 0 && v_nomatch == 0) || (numoidnotfound > 0 && v_nomatch == 0)) {
1166 *getReplyCtrl = TRANS_SOFT_ABORT;
1170 void doLocalProcess(char finalResponse, trans_req_data_t *tdata, trans_commit_data_t *transinfo) {
1171 if(finalResponse == TRANS_ABORT) {
1172 if(transAbortProcess(transinfo) != 0) {
1173 printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
1177 } else if(finalResponse == TRANS_COMMIT) {
1179 /* Invalidate objects in other machine cache */
1180 if(tdata->f.nummod > 0) {
1182 if((retval = invalidateObj(tdata)) != 0) {
1183 printf("Error: %s() in invalidating Objects %s, %d\n", __func__, __FILE__, __LINE__);
1188 if(transComProcess(tdata, transinfo) != 0) {
1189 printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
1194 printf("ERROR...No Decision\n");
1198 if (transinfo->objlocked != NULL) {
1199 free(transinfo->objlocked);
1201 if (transinfo->objnotfound != NULL) {
1202 free(transinfo->objnotfound);
1206 /* This function decides the reponse that needs to be sent to
1207 * all Participant machines after the TRANS_REQUEST protocol */
1208 char decideResponse(char *getReplyCtrl, char *treplyretry, int pilecount) {
1209 int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
1211 for (i = 0 ; i < pilecount; i++) {
1213 control = getReplyCtrl[i];
1216 printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
1218 /* treat as disagree, pass thru */
1219 case TRANS_DISAGREE:
1227 case TRANS_SOFT_ABORT:
1233 if(transdisagree > 0) {
1238 /* clear objects from prefetch cache */
1241 } else if(transagree == pilecount) {
1244 return TRANS_COMMIT;
1246 /* Send Abort in soft abort case followed by retry commiting transaction again*/
1253 /* This function opens a connection, places an object read request to
1254 * the remote machine, reads the control message and object if
1255 * available and copies the object and its header to the local
1258 void *getRemoteObj(unsigned int mnum, unsigned int oid) {
1260 struct sockaddr_in serv_addr;
1264 void *objcopy = NULL;
1266 int sd = getSock2(transReadSockPool, mnum);
1267 char readrequest[sizeof(char)+sizeof(unsigned int)];
1268 readrequest[0] = READ_REQUEST;
1269 *((unsigned int *)(&readrequest[1])) = oid;
1270 send_data(sd, readrequest, sizeof(readrequest));
1272 /* Read response from the Participant */
1273 recv_data(sd, &control, sizeof(char));
1275 if (control==OBJECT_NOT_FOUND) {
1278 /* Read object if found into local cache */
1279 recv_data(sd, &size, sizeof(int));
1280 objcopy = objstrAlloc(&t_cache, size);
1281 recv_data(sd, objcopy, size);
1283 /* Insert into cache's lookup table */
1284 t_chashInsert(oid, objcopy);
1286 totalObjSize += size;
1293 /* Commit info for objects modified */
1294 void commitCountForObjMod(char *getReplyCtrl, unsigned int *oidnotfound, unsigned int *oidlocked, int *numoidnotfound,
1295 int *numoidlocked, int *v_nomatch, int *v_matchlock, int *v_matchnolock, unsigned int oid, unsigned short version) {
1297 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
1298 /* Save the oids not found and number of oids not found for later use */
1299 if ((mobj = mhashSearch(oid)) == NULL) { /* Obj not found */
1300 /* Save the oids not found and number of oids not found for later use */
1301 oidnotfound[*numoidnotfound] = oid;
1302 (*numoidnotfound)++;
1303 } else { /* If Obj found in machine (i.e. has not moved) */
1304 /* Check if Obj is locked by any previous transaction */
1305 if (write_trylock(STATUSPTR(mobj))) { // Can acquire write lock
1306 if (version == ((objheader_t *)mobj)->version) { /* match versions */
1308 //Keep track of what is locked
1309 oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj));
1310 } else { /* If versions don't match ...HARD ABORT */
1312 /* Send TRANS_DISAGREE to Coordinator */
1313 *getReplyCtrl = TRANS_DISAGREE;
1315 //Keep track of what is locked
1316 oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj));
1317 //printf("%s() oid = %d, type = %d\t", __func__, OID(mobj), TYPE((objheader_t *)mobj));
1320 } else { //A lock is acquired some place else
1321 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
1323 } else { /* If versions don't match ...HARD ABORT */
1325 /* Send TRANS_DISAGREE to Coordinator */
1326 *getReplyCtrl = TRANS_DISAGREE;
1327 //printf("%s() oid = %d, type = %d\t", __func__, OID(mobj), TYPE((objheader_t *)mobj));
1334 /* Commit info for objects modified */
1335 void commitCountForObjRead(char *getReplyCtrl, unsigned int *oidnotfound, unsigned int *oidlocked, int *numoidnotfound,
1336 int *numoidlocked, int *v_nomatch, int *v_matchlock, int *v_matchnolock, unsigned int oid, unsigned short version) {
1338 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
1339 /* Save the oids not found and number of oids not found for later use */
1340 if ((mobj = mhashSearch(oid)) == NULL) { /* Obj not found */
1341 /* Save the oids not found and number of oids not found for later use */
1342 oidnotfound[*numoidnotfound] = oid;
1343 (*numoidnotfound)++;
1344 } else { /* If Obj found in machine (i.e. has not moved) */
1345 /* Check if Obj is locked by any previous transaction */
1346 if (read_trylock(STATUSPTR(mobj))) { // Can further acquire read locks
1347 if (version == ((objheader_t *)mobj)->version) { /* If locked then match versions */
1349 //Keep track of what is locked
1350 oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj));
1351 } else { /* If versions don't match ...HARD ABORT */
1353 /* Send TRANS_DISAGREE to Coordinator */
1354 *getReplyCtrl = TRANS_DISAGREE;
1355 //Keep track of what is locked
1356 oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj));
1357 //printf("%s() oid = %d, type = %d\t", __func__, OID(mobj), TYPE((objheader_t *)mobj));
1360 } else { //Has reached max number of readers or some other transaction
1361 //has acquired a lock on this object
1362 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
1364 } else { /* If versions don't match ...HARD ABORT */
1366 /* Send TRANS_DISAGREE to Coordinator */
1367 *getReplyCtrl = TRANS_DISAGREE;
1368 //printf("%s() oid = %d, type = %d\t", __func__, OID(mobj), TYPE((objheader_t *)mobj));
1375 /* This function completes the ABORT process if the transaction is aborting */
1376 int transAbortProcess(trans_commit_data_t *transinfo) {
1378 unsigned int *objlocked;
1381 numlocked = transinfo->numlocked;
1382 objlocked = transinfo->objlocked;
1384 int useWriteUnlock = 0;
1385 for (i = 0; i < numlocked; i++) {
1386 if(objlocked[i] == -1) {
1390 if((header = mhashSearch(objlocked[i])) == NULL) {
1391 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1394 if(!useWriteUnlock) {
1395 read_unlock(STATUSPTR(header));
1397 write_unlock(STATUSPTR(header));
1404 /*This function completes the COMMIT process if the transaction is commiting*/
1405 int transComProcess(trans_req_data_t *tdata, trans_commit_data_t *transinfo) {
1406 objheader_t *header, *tcptr;
1407 int i, nummod, tmpsize, numcreated, numlocked;
1408 unsigned int *oidmod, *oidcreated, *oidlocked;
1411 nummod = tdata->f.nummod;
1412 oidmod = tdata->oidmod;
1413 numcreated = tdata->f.numcreated;
1414 oidcreated = tdata->oidcreated;
1415 numlocked = transinfo->numlocked;
1416 oidlocked = transinfo->objlocked;
1418 for (i = 0; i < nummod; i++) {
1419 if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
1420 printf("Error: transComProcess() mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1423 /* Copy from transaction cache -> main object store */
1424 if ((tcptr = ((objheader_t *) t_chashSearch(oidmod[i]))) == NULL) {
1425 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1428 GETSIZE(tmpsize, header);
1429 char *tmptcptr = (char *) tcptr;
1431 struct ___Object___ *dst=(struct ___Object___*)((char*)header+sizeof(objheader_t));
1432 struct ___Object___ *src=(struct ___Object___*)((char*)tmptcptr+sizeof(objheader_t));
1433 dst->___cachedCode___=src->___cachedCode___;
1434 dst->___cachedHash___=src->___cachedHash___;
1436 memcpy(&dst[1], &src[1], tmpsize-sizeof(struct ___Object___));
1439 header->version += 1;
1440 if(header->notifylist != NULL) {
1441 notifyAll(&header->notifylist, OID(header), header->version);
1444 /* If object is newly created inside transaction then commit it */
1445 for (i = 0; i < numcreated; i++) {
1446 if ((header = ((objheader_t *) t_chashSearch(oidcreated[i]))) == NULL) {
1447 printf("Error: transComProcess() chashSearch returned NULL for oid = %x at %s, %d\n", oidcreated[i], __FILE__, __LINE__);
1450 GETSIZE(tmpsize, header);
1451 tmpsize += sizeof(objheader_t);
1452 pthread_mutex_lock(&mainobjstore_mutex);
1453 if ((ptrcreate = objstrAlloc(&mainobjstore, tmpsize)) == NULL) {
1454 printf("Error: transComProcess() failed objstrAlloc %s, %d\n", __FILE__, __LINE__);
1455 pthread_mutex_unlock(&mainobjstore_mutex);
1458 pthread_mutex_unlock(&mainobjstore_mutex);
1459 /* Initialize read and write locks */
1460 initdsmlocks(STATUSPTR(header));
1461 memcpy(ptrcreate, header, tmpsize);
1462 mhashInsert(oidcreated[i], ptrcreate);
1463 lhashInsert(oidcreated[i], myIpAddr);
1465 /* Unlock locked objects */
1466 int useWriteUnlock = 0;
1467 for(i = 0; i < numlocked; i++) {
1468 if(oidlocked[i] == -1) {
1472 if((header = (objheader_t *) mhashSearch(oidlocked[i])) == NULL) {
1473 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1476 if(!useWriteUnlock) {
1477 read_unlock(STATUSPTR(header));
1479 write_unlock(STATUSPTR(header));
1485 prefetchpile_t *foundLocal(char *ptr, int numprefetches) {
1488 prefetchpile_t * head=NULL;
1490 for(j=0;j<numprefetches;j++) {
1491 int siteid = *(GET_SITEID(ptr));
1492 int ntuples = *(GET_NTUPLES(ptr));
1493 unsigned int * oidarray = GET_PTR_OID(ptr);
1494 unsigned short * endoffsets = GET_PTR_EOFF(ptr, ntuples);
1495 short * arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1498 for(i=0; i<ntuples; i++) {
1499 unsigned short baseindex=(i==0) ? 0 : endoffsets[i-1];
1500 unsigned short endindex=endoffsets[i];
1501 unsigned int oid=oidarray[i];
1507 //Look up fields locally
1508 for(newbase=baseindex; newbase<endindex; newbase++) {
1509 if (!lookupObject(&oid, arryfields[newbase]))
1511 //Ended in a null pointer...
1515 //Entire prefetch is local
1516 if (newbase==endindex&&checkoid(oid)) {
1520 //Add to remote requests
1521 machinenum=lhashSearch(oid);
1522 insertPile(machinenum, oid, endindex-newbase, &arryfields[newbase], &head);
1527 /* handle dynamic prefetching */
1528 handleDynPrefetching(numLocal, ntuples, siteid);
1529 ptr=((char *)&arryfields[endoffsets[ntuples-1]])+sizeof(int);
1535 int checkoid(unsigned int oid) {
1536 objheader_t *header;
1537 if ((header=mhashSearch(oid))!=NULL) {
1540 } else if ((header=prehashSearch(oid))!=NULL) {
1548 int lookupObject(unsigned int * oid, short offset) {
1549 objheader_t *header;
1550 if ((header=mhashSearch(*oid))!=NULL) {
1553 } else if ((header=prehashSearch(*oid))!=NULL) {
1560 if(TYPE(header) >= NUMCLASSES) {
1561 int elementsize = classsize[TYPE(header)];
1562 struct ArrayObject *ao = (struct ArrayObject *) (((char *)header) + sizeof(objheader_t));
1563 int length = ao->___length___;
1564 /* Check if array out of bounds */
1565 if(offset < 0 || offset >= length) {
1566 //if yes treat the object as found
1570 (*oid) = *((unsigned int *)(((char *)ao) + sizeof(struct ArrayObject) + (elementsize*offset)));
1573 (*oid) = *((unsigned int *)(((char *)header) + sizeof(objheader_t) + offset));
1579 /* This function is called by the thread calling transPrefetch */
1580 void *transPrefetch(void *t) {
1582 /* read from prefetch queue */
1583 void *node=gettail();
1584 /* Check if the tuples are found locally, if yes then reduce them further*/
1585 /* and group requests by remote machine ids by calling the makePreGroups() */
1586 int count=numavailable();
1587 prefetchpile_t *pilehead = foundLocal(node, count);
1589 if (pilehead!=NULL) {
1590 // Get sock from shared pool
1592 /* Send Prefetch Request */
1593 prefetchpile_t *ptr = pilehead;
1594 while(ptr != NULL) {
1595 int sd = getSock2(transPrefetchSockPool, ptr->mid);
1596 sendPrefetchReq(ptr, sd);
1600 /* Release socket */
1601 // freeSock(transPrefetchSockPool, pilehead->mid, sd);
1603 /* Deallocated pilehead */
1604 mcdealloc(pilehead);
1606 // Deallocate the prefetch queue pile node
1611 void sendPrefetchReqnew(prefetchpile_t *mcpilenode, int sd) {
1614 int size=sizeof(char)+sizeof(int);
1615 for(tmp=mcpilenode->objpiles; tmp!=NULL; tmp=tmp->next) {
1616 size += sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1621 *buf=TRANS_PREFETCH;
1624 for(tmp=mcpilenode->objpiles; tmp!=NULL; tmp=tmp->next) {
1625 int len = sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1628 *((unsigned int *)buf)=tmp->oid;
1629 buf+=sizeof(unsigned int);
1630 *((unsigned int *)(buf)) = myIpAddr;
1631 buf+=sizeof(unsigned int);
1632 memcpy(buf, tmp->offset, tmp->numoffset*sizeof(short));
1633 buf+=tmp->numoffset*sizeof(short);
1636 send_data(sd, buft, size);
1640 void sendPrefetchReq(prefetchpile_t *mcpilenode, int sd) {
1644 struct writestruct writebuffer;
1645 writebuffer.offset=0;
1647 /* Send TRANS_PREFETCH control message */
1650 /* Send Oids and offsets in pairs */
1651 tmp = mcpilenode->objpiles;
1652 while(tmp != NULL) {
1653 len = sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1654 char oidnoffset[len+5];
1655 char *buf=oidnoffset;
1657 *buf=TRANS_PREFETCH;
1661 *((int*)buf) = tmp->numoffset;
1663 *((unsigned int *)buf) = tmp->oid;
1667 buf+=sizeof(unsigned int);
1668 *((unsigned int *)buf) = myIpAddr;
1669 buf += sizeof(unsigned int);
1670 memcpy(buf, tmp->offset, (tmp->numoffset)*sizeof(short));
1673 *((int *)(&oidnoffset[len]))=-1;
1677 send_buf(sd, & writebuffer, oidnoffset, len);
1679 forcesend_buf(sd, & writebuffer, oidnoffset, len);
1686 int getPrefetchResponse(int sd, struct readstruct *readbuffer) {
1687 int length = 0, size = 0;
1690 void *modptr, *oldptr;
1692 recv_data_buf(sd, readbuffer, &length, sizeof(int));
1693 size = length - sizeof(int);
1694 char recvbuffer[size];
1699 recv_data_buf(sd, readbuffer, recvbuffer, size);
1700 control = *((char *) recvbuffer);
1701 if(control == OBJECT_FOUND) {
1702 oid = *((unsigned int *)(recvbuffer + sizeof(char)));
1703 size = size - (sizeof(char) + sizeof(unsigned int));
1704 pthread_mutex_lock(&prefetchcache_mutex);
1705 if ((modptr = prefetchobjstrAlloc(size)) == NULL) {
1706 printf("Error: objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
1707 pthread_mutex_unlock(&prefetchcache_mutex);
1710 pthread_mutex_unlock(&prefetchcache_mutex);
1711 memcpy(modptr, recvbuffer + sizeof(char) + sizeof(unsigned int), size);
1714 /* Insert the oid and its address into the prefetch hash lookup table */
1715 /* Do a version comparison if the oid exists */
1716 if((oldptr = prehashSearch(oid)) != NULL) {
1717 /* If older version then update with new object ptr */
1718 if(((objheader_t *)oldptr)->version <= ((objheader_t *)modptr)->version) {
1720 prehashInsert(oid, modptr);
1722 } else { /* Else add the object ptr to hash table*/
1723 prehashInsert(oid, modptr);
1725 /* Lock the Prefetch Cache look up table*/
1726 pthread_mutex_lock(&pflookup.lock);
1727 /* Broadcast signal on prefetch cache condition variable */
1728 pthread_cond_broadcast(&pflookup.cond);
1729 /* Unlock the Prefetch Cache look up table*/
1730 pthread_mutex_unlock(&pflookup.lock);
1731 } else if(control == OBJECT_NOT_FOUND) {
1732 oid = *((unsigned int *)(recvbuffer + sizeof(char)));
1733 /* TODO: For each object not found query DHT for new location and retrieve the object */
1734 /* Throw an error */
1735 //printf("OBJECT %x NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n", oid);
1738 printf("Error: in decoding the control value %d, %s, %d\n",control, __FILE__, __LINE__);
1744 unsigned short getObjType(unsigned int oid) {
1745 objheader_t *objheader;
1746 unsigned short numoffset[] ={0};
1747 short fieldoffset[] ={};
1749 if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL) {
1751 if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL) {
1753 unsigned int mid = lhashSearch(oid);
1754 int sd = getSock2(transReadSockPool, mid);
1755 char remotereadrequest[sizeof(char)+sizeof(unsigned int)];
1756 remotereadrequest[0] = READ_REQUEST;
1757 *((unsigned int *)(&remotereadrequest[1])) = oid;
1758 send_data(sd, remotereadrequest, sizeof(remotereadrequest));
1760 /* Read response from the Participant */
1762 recv_data(sd, &control, sizeof(char));
1764 if (control==OBJECT_NOT_FOUND) {
1765 printf("Error: in %s() THIS SHOULD NOT HAPPEN.....EXIT PROGRAM\n", __func__);
1769 /* Read object if found into local cache */
1771 recv_data(sd, &size, sizeof(int));
1773 pthread_mutex_lock(&prefetchcache_mutex);
1774 if ((objheader = prefetchobjstrAlloc(size)) == NULL) {
1775 printf("Error: %s() objstrAlloc error for copying into prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
1778 pthread_mutex_unlock(&prefetchcache_mutex);
1779 recv_data(sd, objheader, size);
1780 prehashInsert(oid, objheader);
1781 return TYPE(objheader);
1784 if((buffer = calloc(1, size)) == NULL) {
1785 printf("%s() Calloc Error %s at line %d\n", __func__, __FILE__, __LINE__);
1789 recv_data(sd, buffer, size);
1790 objheader = (objheader_t *)buffer;
1791 unsigned short type = TYPE(objheader);
1800 return TYPE(objheader);
1803 int startRemoteThread(unsigned int oid, unsigned int mid) {
1805 struct sockaddr_in remoteAddr;
1806 char msg[1 + sizeof(unsigned int)];
1810 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
1811 perror("startRemoteThread():socket()");
1815 bzero(&remoteAddr, sizeof(remoteAddr));
1816 remoteAddr.sin_family = AF_INET;
1817 remoteAddr.sin_port = htons(LISTEN_PORT);
1818 remoteAddr.sin_addr.s_addr = htonl(mid);
1820 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0) {
1821 printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
1822 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1826 msg[0] = START_REMOTE_THREAD;
1827 *((unsigned int *) &msg[1]) = oid;
1828 send_data(sock, msg, 1 + sizeof(unsigned int));
1835 //TODO: when reusing oids, make sure they are not already in use!
1836 static unsigned int id = 0xFFFFFFFF;
1837 unsigned int getNewOID(void) {
1839 if (id > oidMax || id < oidMin) {
1845 int processConfigFile() {
1847 const int maxLineLength = 200;
1848 char lineBuffer[maxLineLength];
1850 const char *delimiters = " \t\n";
1854 configFile = fopen(CONFIG_FILENAME, "r");
1855 if (configFile == NULL) {
1856 printf("error opening %s:\n", CONFIG_FILENAME);
1861 numHostsInSystem = 0;
1862 sizeOfHostArray = 8;
1863 hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
1865 while(fgets(lineBuffer, maxLineLength, configFile) != NULL) {
1866 commentBegin = strchr(lineBuffer, '#');
1867 if (commentBegin != NULL)
1868 *commentBegin = '\0';
1869 token = strtok(lineBuffer, delimiters);
1870 while (token != NULL) {
1871 tmpAddr = inet_addr(token);
1872 if ((int)tmpAddr == -1) {
1873 printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
1877 addHost(htonl(tmpAddr));
1878 token = strtok(NULL, delimiters);
1884 if (numHostsInSystem < 1) {
1885 printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
1889 myIpAddr = getMyIpAddr("en1");
1891 myIpAddr = getMyIpAddr("eth0");
1893 myIndexInHostArray = findHost(myIpAddr);
1894 if (myIndexInHostArray == -1) {
1895 printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
1898 oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
1899 oidMin = oidsPerBlock * myIndexInHostArray;
1900 if (myIndexInHostArray == numHostsInSystem - 1)
1901 oidMax = 0xFFFFFFFF;
1903 oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
1908 void addHost(unsigned int hostIp) {
1909 unsigned int *tmpArray;
1911 if (findHost(hostIp) != -1)
1914 if (numHostsInSystem == sizeOfHostArray) {
1915 tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
1916 memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
1918 hostIpAddrs = tmpArray;
1921 hostIpAddrs[numHostsInSystem++] = hostIp;
1926 int findHost(unsigned int hostIp) {
1928 for (i = 0; i < numHostsInSystem; i++)
1929 if (hostIpAddrs[i] == hostIp)
1936 /* This function sends notification request per thread waiting on object(s) whose version
1938 int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int numoid) {
1940 objheader_t *objheader;
1941 struct sockaddr_in remoteAddr;
1942 char msg[1 + numoid * (sizeof(unsigned short) + sizeof(unsigned int)) + 3 * sizeof(unsigned int)];
1946 unsigned short version;
1947 unsigned int oid,mid;
1948 static unsigned int threadid = 0;
1949 pthread_mutex_t threadnotify = PTHREAD_MUTEX_INITIALIZER; //Lock and condition var for threadjoin and notification
1950 pthread_cond_t threadcond = PTHREAD_COND_INITIALIZER;
1951 notifydata_t *ndata;
1954 if((mid = lhashSearch(oid)) == 0) {
1955 printf("Error: %s() No such machine found for oid =%x\n",__func__, oid);
1959 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
1960 perror("reqNotify():socket()");
1964 bzero(&remoteAddr, sizeof(remoteAddr));
1965 remoteAddr.sin_family = AF_INET;
1966 remoteAddr.sin_port = htons(LISTEN_PORT);
1967 remoteAddr.sin_addr.s_addr = htonl(mid);
1969 /* Generate unique threadid */
1972 /* Save threadid, numoid, oidarray, versionarray, pthread_cond_variable for later processing */
1973 if((ndata = calloc(1, sizeof(notifydata_t))) == NULL) {
1974 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
1977 ndata->numoid = numoid;
1978 ndata->threadid = threadid;
1979 ndata->oidarry = oidarry;
1980 ndata->versionarry = versionarry;
1981 ndata->threadcond = threadcond;
1982 ndata->threadnotify = threadnotify;
1983 if((status = notifyhashInsert(threadid, ndata)) != 0) {
1984 printf("reqNotify(): Insert into notify hash table not successful %s, %d\n", __FILE__, __LINE__);
1989 /* Send number of oids, oidarry, version array, machine id and threadid */
1990 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0) {
1991 printf("reqNotify():error %d connecting to %s:%d\n", errno,
1992 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1996 msg[0] = THREAD_NOTIFY_REQUEST;
1997 *((unsigned int *)(&msg[1])) = numoid;
1998 /* Send array of oids */
1999 size = sizeof(unsigned int);
2001 for(i = 0;i < numoid; i++) {
2003 *((unsigned int *)(&msg[1] + size)) = oid;
2004 size += sizeof(unsigned int);
2007 /* Send array of version */
2008 for(i = 0;i < numoid; i++) {
2009 version = versionarry[i];
2010 *((unsigned short *)(&msg[1] + size)) = version;
2011 size += sizeof(unsigned short);
2014 *((unsigned int *)(&msg[1] + size)) = myIpAddr; size += sizeof(unsigned int);
2015 *((unsigned int *)(&msg[1] + size)) = threadid;
2016 pthread_mutex_lock(&(ndata->threadnotify));
2017 size = 1 + numoid * (sizeof(unsigned int) + sizeof(unsigned short)) + 3 * sizeof(unsigned int);
2018 send_data(sock, msg, size);
2019 pthread_cond_wait(&(ndata->threadcond), &(ndata->threadnotify));
2020 pthread_mutex_unlock(&(ndata->threadnotify));
2023 pthread_cond_destroy(&threadcond);
2024 pthread_mutex_destroy(&threadnotify);
2030 void threadNotify(unsigned int oid, unsigned short version, unsigned int tid) {
2031 notifydata_t *ndata;
2032 int i, objIsFound = 0, index;
2035 //Look up the tid and call the corresponding pthread_cond_signal
2036 if((ndata = notifyhashSearch(tid)) == NULL) {
2037 printf("threadnotify(): No such threadid is present %s, %d\n", __FILE__, __LINE__);
2040 for(i = 0; i < ndata->numoid; i++) {
2041 if(ndata->oidarry[i] == oid) {
2046 if(objIsFound == 0) {
2047 printf("threadNotify(): Oid not found %s, %d\n", __FILE__, __LINE__);
2050 if(version <= ndata->versionarry[index]) {
2051 printf("threadNotify(): New version %d has not changed since last version for oid = %d, %s, %d\n", version, oid, __FILE__, __LINE__);
2055 /* Clear from prefetch cache and free thread related data structure */
2056 if((ptr = prehashSearch(oid)) != NULL) {
2060 pthread_mutex_lock(&(ndata->threadnotify));
2061 pthread_cond_signal(&(ndata->threadcond));
2062 pthread_mutex_unlock(&(ndata->threadnotify));
2069 int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) {
2072 struct sockaddr_in remoteAddr;
2073 char msg[1 + sizeof(unsigned short) + 2*sizeof(unsigned int)];
2074 int sock, status, size, bytesSent;
2076 while(*head != NULL) {
2079 //create a socket connection to that machine
2080 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
2081 perror("notifyAll():socket()");
2085 bzero(&remoteAddr, sizeof(remoteAddr));
2086 remoteAddr.sin_family = AF_INET;
2087 remoteAddr.sin_port = htons(LISTEN_PORT);
2088 remoteAddr.sin_addr.s_addr = htonl(mid);
2089 //send Thread Notify response and threadid to that machine
2090 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0) {
2091 printf("notifyAll():error %d connecting to %s:%d\n", errno,
2092 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
2096 bzero(msg, (1+sizeof(unsigned short) + 2*sizeof(unsigned int)));
2097 msg[0] = THREAD_NOTIFY_RESPONSE;
2098 *((unsigned int *)&msg[1]) = oid;
2099 size = sizeof(unsigned int);
2100 *((unsigned short *)(&msg[1]+ size)) = version;
2101 size+= sizeof(unsigned short);
2102 *((unsigned int *)(&msg[1]+ size)) = ptr->threadid;
2104 size = 1 + 2*sizeof(unsigned int) + sizeof(unsigned short);
2105 send_data(sock, msg, size);
2118 removetransactionhash();
2120 objstrDelete(t_cache);
2124 /* This function inserts necessary information into
2125 * a machine pile data structure */
2126 plistnode_t *pInsert(plistnode_t *pile, objheader_t *headeraddr, unsigned int mid, int num_objs) {
2127 plistnode_t *ptr, *tmp;
2128 int found = 0, offset = 0;
2131 //Add oid into a machine that is already present in the pile linked list structure
2132 while(tmp != NULL) {
2133 if (tmp->mid == mid) {
2136 if (STATUS(headeraddr) & NEW) {
2137 tmp->oidcreated[tmp->numcreated] = OID(headeraddr);
2139 GETSIZE(tmpsize, headeraddr);
2140 tmp->sum_bytes += sizeof(objheader_t) + tmpsize;
2141 } else if (STATUS(headeraddr) & DIRTY) {
2142 tmp->oidmod[tmp->nummod] = OID(headeraddr);
2144 GETSIZE(tmpsize, headeraddr);
2145 tmp->sum_bytes += sizeof(objheader_t) + tmpsize;
2147 offset = (sizeof(unsigned int) + sizeof(short)) * tmp->numread;
2148 *((unsigned int *)(((char *)tmp->objread) + offset))=OID(headeraddr);
2149 offset += sizeof(unsigned int);
2150 *((short *)(((char *)tmp->objread) + offset)) = headeraddr->version;
2158 //Add oid for any new machine
2161 if((ptr = pCreate(num_objs)) == NULL) {
2165 if (STATUS(headeraddr) & NEW) {
2166 ptr->oidcreated[ptr->numcreated] = OID(headeraddr);
2168 GETSIZE(tmpsize, headeraddr);
2169 ptr->sum_bytes += sizeof(objheader_t) + tmpsize;
2170 } else if (STATUS(headeraddr) & DIRTY) {
2171 ptr->oidmod[ptr->nummod] = OID(headeraddr);
2173 GETSIZE(tmpsize, headeraddr);
2174 ptr->sum_bytes += sizeof(objheader_t) + tmpsize;
2176 *((unsigned int *)ptr->objread)=OID(headeraddr);
2177 offset = sizeof(unsigned int);
2178 *((short *)(((char *)ptr->objread) + offset)) = headeraddr->version;
2186 STATUS(headeraddr) =0;
2192 plistnode_t *sortPiles(plistnode_t *pileptr) {
2193 plistnode_t *head, *ptr, *tail;
2196 /* Get tail pointer */
2202 plistnode_t *prev = pileptr;
2203 /* Arrange local machine processing at the end of the pile list */
2204 while(ptr != NULL) {
2206 if(ptr->mid == myIpAddr && (prev != pileptr)) {
2207 prev->next = ptr->next;
2212 if((ptr->mid == myIpAddr) && (prev == pileptr)) {