3 #include "machinepile.h"
8 #include "threadnotify.h"
10 #include "addUdpEnhance.h"
11 #include "addPrefetchEnhance.h"
18 #define PREFETCH_CACHE_SIZE 1048576 //1MB
19 #define CONFIG_FILENAME "dstm.conf"
21 /* Global Variables */
22 extern int classsize[];
23 pfcstats_t *evalPrefetch;
24 extern pthread_mutex_t mainobjstore_mutex;// Mutex to lock main Object store
25 objstr_t *prefetchcache; //Global Prefetch cache
26 pthread_mutex_t prefetchcache_mutex;// Mutex to lock Prefetch Cache
27 pthread_mutexattr_t prefetchcache_mutex_attr; /* Attribute for lock to make it a recursive lock */
28 extern prehashtable_t pflookup; //Global Prefetch cache's lookup table
29 pthread_t wthreads[NUM_THREADS]; //Worker threads for working on the prefetch queue
30 pthread_t tPrefetch; /* Primary Prefetch thread that processes the prefetch queue */
31 extern objstr_t *mainobjstore;
32 unsigned int myIpAddr;
33 unsigned int *hostIpAddrs;
36 int myIndexInHostArray;
37 unsigned int oidsPerBlock;
41 sockPoolHashTable_t *transReadSockPool;
42 sockPoolHashTable_t *transPrefetchSockPool;
43 sockPoolHashTable_t *transRequestSockPool;
44 pthread_mutex_t notifymutex;
45 pthread_mutex_t atomicObjLock;
47 /***********************************
48 * Global Variables for statistics
49 **********************************/
50 int numTransCommit = 0;
51 int numTransAbort = 0;
54 int nprehashSearch = 0;
57 void printhex(unsigned char *, int);
58 plistnode_t *createPiles(transrecord_t *);
60 /*******************************
61 * Send and Recv function calls
62 *******************************/
63 void send_data(int fd , void *buf, int buflen) {
64 char *buffer = (char *)(buf);
68 numbytes = send(fd, buffer, size, MSG_NOSIGNAL);
78 void recv_data(int fd , void *buf, int buflen) {
79 char *buffer = (char *)(buf);
83 numbytes = recv(fd, buffer, size, 0);
93 int recv_data_errorcode(int fd , void *buf, int buflen) {
94 char *buffer = (char *)(buf);
98 numbytes = recv(fd, buffer, size, 0);
101 if (numbytes == -1) {
111 void printhex(unsigned char *ptr, int numBytes) {
113 for (i = 0; i < numBytes; i++) {
115 printf("0%x ", ptr[i]);
117 printf("%x ", ptr[i]);
123 inline int arrayLength(int *array) {
125 for(i=0 ;array[i] != -1; i++)
130 inline int findmax(int *array, int arraylength) {
133 for(i = 0; i < arraylength; i++){
141 /* This function is a prefetch call generated by the compiler that
142 * populates the shared primary prefetch queue*/
143 void prefetch(int siteid, int ntuples, unsigned int *oids, unsigned short *endoffsets, short *arrayfields) {
144 /* Allocate for the queue node*/
145 int qnodesize = 2*sizeof(int) + ntuples * (sizeof(unsigned short) + sizeof(unsigned int)) + endoffsets[ntuples - 1] * sizeof(short);
147 char * node= getmemory(qnodesize);
148 int top=endoffsets[ntuples-1];
152 /* Set queue node values */
154 /* TODO: Remove this after testing */
155 evalPrefetch[siteid].callcount++;
157 *((int *)(node))=siteid;
158 *((int *)(node + sizeof(int))) = ntuples;
160 memcpy(node+len, oids, ntuples*sizeof(unsigned int));
161 memcpy(node+len+ntuples*sizeof(unsigned int), endoffsets, ntuples*sizeof(unsigned short));
162 memcpy(node+len+ntuples*(sizeof(unsigned int)+sizeof(short)), arrayfields, top*sizeof(short));
164 /* Lock and insert into primary prefetch queue */
168 /* This function starts up the transaction runtime. */
169 int dstmStartup(const char * option) {
170 pthread_t thread_Listen, udp_thread_Listen;
172 int master=option!=NULL && strcmp(option, "master")==0;
176 if (processConfigFile() != 0)
177 return 0; //TODO: return error value, cause main program to exit
184 printf("Trans stats is on\n");
188 //Initialize socket pool
189 transReadSockPool = createSockPool(transReadSockPool, DEFAULTSOCKPOOLSIZE);
190 transPrefetchSockPool = createSockPool(transPrefetchSockPool, DEFAULTSOCKPOOLSIZE);
191 transRequestSockPool = createSockPool(transRequestSockPool, DEFAULTSOCKPOOLSIZE);
197 pthread_attr_init(&attr);
198 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
201 pthread_create(&udp_thread_Listen, &attr, udpListenBroadcast, (void*)udpfd);
204 pthread_create(&thread_Listen, &attr, dstmListen, (void*)fd);
207 dstmListen((void *)fd);
212 //TODO Use this later
213 void *pCacheAlloc(objstr_t *store, unsigned int size) {
219 while(ptr->next != NULL) {
220 /* check if store is empty */
221 if(((unsigned int)ptr->top - (unsigned int)ptr - sizeof(objstr_t) + size) <= ptr->size) {
236 /* This function initiates the prefetch thread A queue is shared
237 * between the main thread of execution and the prefetch thread to
238 * process the prefetch call Call from compiler populates the shared
239 * queue with prefetch requests while prefetch thread processes the
240 * prefetch requests */
243 //Create and initialize prefetch cache structure
245 prefetchcache = objstrCreate(PREFETCH_CACHE_SIZE);
247 if((evalPrefetch = initPrefetchStats()) == NULL) {
248 printf("%s() Error allocating memory at %s, %d\n", __func__, __FILE__, __LINE__);
253 /* Initialize attributes for mutex */
254 pthread_mutexattr_init(&prefetchcache_mutex_attr);
255 pthread_mutexattr_settype(&prefetchcache_mutex_attr, PTHREAD_MUTEX_RECURSIVE_NP);
257 pthread_mutex_init(&prefetchcache_mutex, &prefetchcache_mutex_attr);
258 pthread_mutex_init(¬ifymutex, NULL);
259 pthread_mutex_init(&atomicObjLock, NULL);
261 //Create prefetch cache lookup table
262 if(prehashCreate(HASH_SIZE, LOADFACTOR)) {
267 //Initialize primary shared queue
269 //Initialize machine pile w/prefetch oids and offsets shared queue
272 //Create the primary prefetch thread
275 retval=pthread_create(&tPrefetch, NULL, transPrefetch, NULL);
277 pthread_detach(tPrefetch);
281 /* This function stops the threads spawned */
285 pthread_cancel(tPrefetch);
286 for(t = 0; t < NUM_THREADS; t++)
287 pthread_cancel(wthreads[t]);
293 /* This functions inserts randowm wait delays in the order of msec
294 * Mostly used when transaction commits retry*/
301 req.tv_nsec = (long)(1000000 + (t%10000000)); //1-11 msec
302 nanosleep(&req, NULL);
306 /* This function initializes things required in the transaction start*/
307 transrecord_t *transStart() {
309 if((tmp = calloc(1, sizeof(transrecord_t))) == NULL){
310 printf("%s() Calloc error at line %d, %s\n", __func__, __LINE__, __FILE__);
313 tmp->cache = objstrCreate(1048576);
314 tmp->lookupTable = chashCreate(CHASH_SIZE, CLOADFACTOR);
316 tmp->revertlist=NULL;
321 /* This function finds the location of the objects involved in a transaction
322 * and returns the pointer to the object if found in a remote location */
323 objheader_t *transRead(transrecord_t *record, unsigned int oid) {
324 unsigned int machinenumber;
325 objheader_t *tmp, *objheader;
326 objheader_t *objcopy;
334 if((objheader = chashSearch(record->lookupTable, oid)) != NULL){
338 /* Search local transaction cache */
340 return &objheader[1];
344 } else if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
348 /* Look up in machine lookup table and copy into cache*/
349 GETSIZE(size, objheader);
350 size += sizeof(objheader_t);
351 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
352 memcpy(objcopy, objheader, size);
353 /* Insert into cache's lookup table */
355 chashInsert(record->lookupTable, OID(objheader), objcopy);
363 if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) {
367 /* Look up in prefetch cache */
369 size+=sizeof(objheader_t);
370 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
371 memcpy(objcopy, tmp, size);
372 /* Insert into cache's lookup table */
373 chashInsert(record->lookupTable, OID(tmp), objcopy);
381 /* Get the object from the remote location */
382 if((machinenumber = lhashSearch(oid)) == 0) {
383 printf("Error: %s() No machine found for oid =% %s,%dx\n",__func__, machinenumber, __FILE__, __LINE__);
386 objcopy = getRemoteObj(record, machinenumber, oid);
388 if(objcopy == NULL) {
389 printf("Error: Object not found in Remote location %s, %d\n", __FILE__, __LINE__);
405 /* This function creates objects in the transaction record */
406 objheader_t *transCreateObj(transrecord_t *record, unsigned int size) {
407 objheader_t *tmp = (objheader_t *) objstrAlloc(record->cache, (sizeof(objheader_t) + size));
408 OID(tmp) = getNewOID();
412 chashInsert(record->lookupTable, OID(tmp), tmp);
415 return &tmp[1]; //want space after object header
421 /* This function creates machine piles based on all machines involved in a
422 * transaction commit request */
423 plistnode_t *createPiles(transrecord_t *record) {
425 plistnode_t *pile = NULL;
426 unsigned int machinenum;
427 objheader_t *headeraddr;
428 chashlistnode_t * ptr = record->lookupTable->table;
429 /* Represents number of bins in the chash table */
430 unsigned int size = record->lookupTable->size;
432 for(i = 0; i < size ; i++) {
433 chashlistnode_t * curr = &ptr[i];
434 /* Inner loop to traverse the linked list of the cache lookupTable */
435 while(curr != NULL) {
436 //if the first bin in hash table is empty
440 if ((headeraddr = (objheader_t *) chashSearch(record->lookupTable, curr->key)) == NULL) {
441 printf("Error: No such oid %s, %d\n", __FILE__, __LINE__);
445 //Get machine location for object id (and whether local or not)
446 if (STATUS(headeraddr) & NEW || (mhashSearch(curr->key) != NULL)) {
447 machinenum = myIpAddr;
448 } else if ((machinenum = lhashSearch(curr->key)) == 0) {
449 printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
453 //Make machine groups
454 pile = pInsert(pile, headeraddr, machinenum, record->lookupTable->numelements);
461 /* This function initiates the transaction commit process
462 * Spawns threads for each of the new connections with Participants
463 * and creates new piles by calling the createPiles(),
464 * Sends a transrequest() to each remote machines for objects found remotely
465 * and calls handleLocalReq() to process objects found locally */
466 int transCommit(transrecord_t *record) {
467 unsigned int tot_bytes_mod, *listmid;
468 plistnode_t *pile, *pile_ptr;
470 int pilecount, offset, threadnum, trecvcount;
472 char transid[TID_LEN];
473 trans_req_data_t *tosend;
474 trans_commit_data_t transinfo;
475 static int newtid = 0;
476 char treplyctrl, treplyretry; /* keeps track of the common response that needs to be sent */
477 thread_data_array_t *thread_data_array;
478 local_thread_data_array_t *ltdata;
486 thread_data_array = NULL;
489 /* Look through all the objects in the transaction record and make piles
490 * for each machine involved in the transaction*/
492 pile_ptr = pile = createPiles(record);
497 /* Create the packet to be sent in TRANS_REQUEST */
499 /* Count the number of participants */
500 pilecount = pCount(pile);
502 /* Create a list of machine ids(Participants) involved in transaction */
503 listmid = calloc(pilecount, sizeof(unsigned int));
504 pListMid(pile, listmid);
507 /* Initialize thread variables,
508 * Spawn a thread for each Participant involved in a transaction */
509 pthread_t thread[pilecount];
511 pthread_cond_t tcond;
512 pthread_mutex_t tlock;
513 pthread_mutex_t tlshrd;
515 thread_data_array = (thread_data_array_t *) calloc(pilecount, sizeof(thread_data_array_t));
516 ltdata = calloc(1, sizeof(local_thread_data_array_t));
518 thread_response_t rcvd_control_msg[pilecount]; /* Shared thread array that keeps track of responses of participants */
520 /* Initialize and set thread detach attribute */
521 pthread_attr_init(&attr);
522 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
523 pthread_mutex_init(&tlock, NULL);
524 pthread_cond_init(&tcond, NULL);
526 /* Process each machine pile */
527 while(pile != NULL) {
528 //Create transaction id
530 tosend = calloc(1, sizeof(trans_req_data_t));
531 tosend->f.control = TRANS_REQUEST;
532 sprintf(tosend->f.trans_id, "%x_%d", pile->mid, newtid);
533 tosend->f.mcount = pilecount;
534 tosend->f.numread = pile->numread;
535 tosend->f.nummod = pile->nummod;
536 tosend->f.numcreated = pile->numcreated;
537 tosend->f.sum_bytes = pile->sum_bytes;
538 tosend->listmid = listmid;
539 tosend->objread = pile->objread;
540 tosend->oidmod = pile->oidmod;
541 tosend->oidcreated = pile->oidcreated;
542 thread_data_array[threadnum].thread_id = threadnum;
543 thread_data_array[threadnum].mid = pile->mid;
544 thread_data_array[threadnum].buffer = tosend;
545 thread_data_array[threadnum].recvmsg = rcvd_control_msg;
546 thread_data_array[threadnum].threshold = &tcond;
547 thread_data_array[threadnum].lock = &tlock;
548 thread_data_array[threadnum].count = &trecvcount;
549 thread_data_array[threadnum].replyctrl = &treplyctrl;
550 thread_data_array[threadnum].replyretry = &treplyretry;
551 thread_data_array[threadnum].rec = record;
552 /* If local do not create any extra connection */
553 if(pile->mid != myIpAddr) { /* Not local */
555 rc = pthread_create(&thread[threadnum], &attr, transRequest, (void *) &thread_data_array[threadnum]);
558 perror("Error in pthread create\n");
559 pthread_cond_destroy(&tcond);
560 pthread_mutex_destroy(&tlock);
563 for (i = 0; i < threadnum; i++)
564 free(thread_data_array[i].buffer);
565 free(thread_data_array);
570 ltdata->tdata = &thread_data_array[threadnum];
571 ltdata->transinfo = &transinfo;
573 val = pthread_create(&thread[threadnum], &attr, handleLocalReq, (void *) ltdata);
576 perror("Error in pthread create\n");
577 pthread_cond_destroy(&tcond);
578 pthread_mutex_destroy(&tlock);
581 for (i = 0; i < threadnum; i++)
582 free(thread_data_array[i].buffer);
583 free(thread_data_array);
592 /* Free attribute and wait for the other threads */
593 pthread_attr_destroy(&attr);
595 for (i = 0; i < threadnum; i++) {
596 rc = pthread_join(thread[i], NULL);
599 printf("Error: return code from pthread_join() is %d\n", rc);
600 pthread_cond_destroy(&tcond);
601 pthread_mutex_destroy(&tlock);
604 for (j = i; j < threadnum; j++) {
605 free(thread_data_array[j].buffer);
609 free(thread_data_array[i].buffer);
613 pthread_cond_destroy(&tcond);
614 pthread_mutex_destroy(&tlock);
620 /* wait a random amount of time before retrying to commit transaction*/
622 free(thread_data_array);
627 /* Retry trans commit procedure during soft_abort case */
628 } while (treplyretry);
630 if(treplyctrl == TRANS_ABORT) {
635 objstrDelete(record->cache);
636 chashDelete(record->lookupTable);
638 free(thread_data_array);
641 } else if(treplyctrl == TRANS_COMMIT) {
646 objstrDelete(record->cache);
647 chashDelete(record->lookupTable);
649 free(thread_data_array);
653 //TODO Add other cases
654 printf("Error: in %s() THIS SHOULD NOT HAPPEN.....EXIT PROGRAM\n", __func__);
660 /* This function sends information involved in the transaction request
661 * to participants and accepts a response from particpants.
662 * It calls decideresponse() to decide on what control message
663 * to send next to participants and sends the message using sendResponse()*/
664 void *transRequest(void *threadarg) {
666 struct sockaddr_in serv_addr;
667 thread_data_array_t *tdata;
668 objheader_t *headeraddr;
669 char control, recvcontrol;
670 char machineip[16], retval;
672 tdata = (thread_data_array_t *) threadarg;
674 if((sd = getSock2WithLock(transRequestSockPool, tdata->mid)) < 0) {
675 printf("transRequest(): socket create error\n");
679 /* Send bytes of data with TRANS_REQUEST control message */
680 send_data(sd, &(tdata->buffer->f), sizeof(fixed_data_t));
682 /* Send list of machines involved in the transaction */
684 int size=sizeof(unsigned int)*tdata->buffer->f.mcount;
685 send_data(sd, tdata->buffer->listmid, size);
688 /* Send oids and version number tuples for objects that are read */
690 int size=(sizeof(unsigned int)+sizeof(unsigned short))*tdata->buffer->f.numread;
691 send_data(sd, tdata->buffer->objread, size);
694 /* Send objects that are modified */
695 for(i = 0; i < tdata->buffer->f.nummod ; i++) {
697 if((headeraddr = chashSearch(tdata->rec->lookupTable, tdata->buffer->oidmod[i])) == NULL) {
698 printf("%s() Error: No such oid %s, %d\n", __func__, __FILE__, __LINE__);
701 GETSIZE(size,headeraddr);
702 size+=sizeof(objheader_t);
703 send_data(sd, headeraddr, size);
706 /* Read control message from Participant */
707 recv_data(sd, &control, sizeof(char));
708 /* Recv Objects if participant sends TRANS_DISAGREE */
710 if(control == TRANS_DISAGREE) {
712 recv_data(sd, &length, sizeof(int));
714 pthread_mutex_lock(&prefetchcache_mutex);
715 if ((newAddr = prefetchobjstrAlloc((unsigned int)length)) == NULL) {
716 printf("Error: %s() objstrAlloc error for copying into prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
719 pthread_mutex_unlock(&prefetchcache_mutex);
720 recv_data(sd, newAddr, length);
723 unsigned int oidToPrefetch;
724 objheader_t * header;
725 header = (objheader_t *) (((char *)newAddr) + offset);
726 oidToPrefetch = OID(header);
728 GETSIZE(size, header);
729 size += sizeof(objheader_t);
730 //make an entry in prefetch hash table
732 if((oldptr = prehashSearch(oidToPrefetch)) != NULL) {
733 prehashRemove(oidToPrefetch);
734 prehashInsert(oidToPrefetch, header);
736 prehashInsert(oidToPrefetch, header);
738 length = length - size;
744 recvcontrol = control;
745 /* Update common data structure and increment count */
746 tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol;
748 /* Lock and update count */
749 /* Thread sleeps until all messages from pariticipants are received by coordinator */
750 pthread_mutex_lock(tdata->lock);
752 (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */
754 /* Wake up the threads and invoke decideResponse (once) */
755 if(*(tdata->count) == tdata->buffer->f.mcount) {
756 decideResponse(tdata);
757 pthread_cond_broadcast(tdata->threshold);
759 pthread_cond_wait(tdata->threshold, tdata->lock);
761 pthread_mutex_unlock(tdata->lock);
763 /* clear objects from prefetch cache */
765 if(*(tdata->replyctrl) == TRANS_ABORT) {
767 for(i=0; i<tdata->buffer->f.nummod; i++) {
768 unsigned int oid = tdata->buffer->oidmod[i];
770 if((header = prehashSearch(oid)) != NULL) {
774 for(i=0; i<tdata->buffer->f.numread; i++) {
775 char *objread = tdata->buffer->objread;
776 unsigned int oid = *((unsigned int *)(objread+(sizeof(unsigned int) +
777 sizeof(unsigned short))*i));
779 if((header = prehashSearch(oid)) != NULL) {
787 if(*(tdata->replyctrl) == TRANS_COMMIT) {
789 /* Update prefetch cache */
790 if((retval = updatePrefetchCache(tdata)) != 0) {
791 printf("Error: %s() in updating prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
795 /* Invalidate objects in other machine cache */
796 if(tdata->buffer->f.nummod > 0) {
797 if((retval = invalidateObj(tdata)) != 0) {
798 printf("Error: %s() in invalidating Objects %s, %d\n", __func__, __FILE__, __LINE__);
805 /* Send the final response such as TRANS_COMMIT or TRANS_ABORT
806 * to all participants in their respective socket */
807 if (sendResponse(tdata, sd) == 0) {
808 printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__);
812 recv_data((int)sd, &control, sizeof(char));
814 if(control == TRANS_UNSUCESSFUL) {
815 //printf("DEBUG-> TRANS_ABORTED\n");
816 } else if(control == TRANS_SUCESSFUL) {
817 //printf("DEBUG-> TRANS_SUCCESSFUL\n");
819 //printf("DEBUG-> Error: Incorrect Transaction End Message %d\n", control);
824 /* This function decides the reponse that needs to be sent to
825 * all Participant machines after the TRANS_REQUEST protocol */
826 void decideResponse(thread_data_array_t *tdata) {
828 int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
831 for (i = 0 ; i < tdata->buffer->f.mcount; i++) {
832 control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses
833 written onto the shared array */
836 printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
837 /* treat as disagree, pass thru */
846 case TRANS_SOFT_ABORT:
852 if(transdisagree > 0) {
854 *(tdata->replyctrl) = TRANS_ABORT;
855 *(tdata->replyretry) = 0;
857 /* clear objects from prefetch cache */
860 } else if(transagree == tdata->buffer->f.mcount){
862 *(tdata->replyctrl) = TRANS_COMMIT;
863 *(tdata->replyretry) = 0;
865 /* Send Abort in soft abort case followed by retry commiting transaction again*/
866 *(tdata->replyctrl) = TRANS_ABORT;
867 *(tdata->replyretry) = 1;
872 /* This function sends the final response to remote machines per
873 * thread in their respective socket id It returns a char that is only
874 * needed to check the correctness of execution of this function
875 * inside transRequest()*/
877 char sendResponse(thread_data_array_t *tdata, int sd) {
878 int n, size, sum, oidcount = 0, control;
879 char *ptr, retval = 0;
880 unsigned int *oidnotfound;
882 control = *(tdata->replyctrl);
883 send_data(sd, &control, sizeof(char));
885 //TODO read missing objects during object migration
886 /* If response is a soft abort due to missing objects at the
887 Participant's side */
889 /* If the decided response is TRANS_ABORT */
890 if(*(tdata->replyctrl) == TRANS_ABORT) {
891 retval = TRANS_ABORT;
892 } else if(*(tdata->replyctrl) == TRANS_COMMIT) {
893 /* If the decided response is TRANS_COMMIT */
894 retval = TRANS_COMMIT;
900 /* This function opens a connection, places an object read request to
901 * the remote machine, reads the control message and object if
902 * available and copies the object and its header to the local
905 void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
907 struct sockaddr_in serv_addr;
911 void *objcopy = NULL;
913 int sd = getSock2(transReadSockPool, mnum);
914 char readrequest[sizeof(char)+sizeof(unsigned int)];
915 readrequest[0] = READ_REQUEST;
916 *((unsigned int *)(&readrequest[1])) = oid;
917 send_data(sd, readrequest, sizeof(readrequest));
919 /* Read response from the Participant */
920 recv_data(sd, &control, sizeof(char));
922 if (control==OBJECT_NOT_FOUND) {
925 /* Read object if found into local cache */
926 recv_data(sd, &size, sizeof(int));
927 objcopy = objstrAlloc(record->cache, size);
928 recv_data(sd, objcopy, size);
929 /* Insert into cache's lookup table */
930 chashInsert(record->lookupTable, oid, objcopy);
936 /* This function handles the local objects involved in a transaction
937 * commiting process. It also makes a decision if this local machine
938 * sends AGREE or DISAGREE or SOFT_ABORT to coordinator. Note
939 * Coordinator = local machine It wakes up the other threads from
940 * remote participants that are waiting for the coordinator's decision
941 * and based on common agreement it either commits or aborts the
942 * transaction. It also frees the memory resources */
944 void *handleLocalReq(void *threadarg) {
945 unsigned int *oidnotfound = NULL, *oidlocked = NULL;
946 local_thread_data_array_t *localtdata;
947 int numoidnotfound = 0, numoidlocked = 0;
948 int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
951 unsigned short version;
953 objheader_t *headptr;
955 localtdata = (local_thread_data_array_t *) threadarg;
957 /* Counters and arrays to formulate decision on control message to be sent */
958 oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
959 oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
961 numread = localtdata->tdata->buffer->f.numread;
962 /* Process each oid in the machine pile/ group per thread */
963 for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) {
964 if (i < localtdata->tdata->buffer->f.numread) {
965 int incr = sizeof(unsigned int) + sizeof(unsigned short);// Offset that points to next position in the objread array
967 oid = *((unsigned int *)(((char *)localtdata->tdata->buffer->objread) + incr));
968 version = *((unsigned short *)(((char *)localtdata->tdata->buffer->objread) + incr + sizeof(unsigned int)));
969 } else { // Objects Modified
971 headptr = (objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidmod[i-numread]);
972 if (headptr == NULL) {
973 printf("Error: handleLocalReq() returning NULL, no such oid %s, %d\n", __FILE__, __LINE__);
977 version = headptr->version;
979 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
981 /* Save the oids not found and number of oids not found for later use */
982 if ((mobj = mhashSearch(oid)) == NULL) { /* Obj not found */
983 /* Save the oids not found and number of oids not found for later use */
984 oidnotfound[numoidnotfound] = oid;
986 } else { /* If Obj found in machine (i.e. has not moved) */
987 /* Check if Obj is locked by any previous transaction */
988 if (test_and_set(STATUSPTR(mobj))) {
989 if (version == ((objheader_t *)mobj)->version) { /* If locked then match versions */
991 } else {/* If versions don't match ...HARD ABORT */
993 /* Send TRANS_DISAGREE to Coordinator */
994 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
999 /* Save all object oids that are locked on this machine during this transaction request call */
1000 oidlocked[numoidlocked] = OID(((objheader_t *)mobj));
1002 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
1004 } else { /* If versions don't match ...HARD ABORT */
1006 /* Send TRANS_DISAGREE to Coordinator */
1007 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
1013 /* Condition to send TRANS_AGREE */
1014 if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
1015 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
1017 /* Condition to send TRANS_SOFT_ABORT */
1018 if((v_matchlock > 0 && v_nomatch == 0) || (numoidnotfound > 0 && v_nomatch == 0)) {
1019 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
1022 /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
1023 * if Participant receives a TRANS_COMMIT */
1024 localtdata->transinfo->objlocked = oidlocked;
1025 localtdata->transinfo->objnotfound = oidnotfound;
1026 localtdata->transinfo->modptr = NULL;
1027 localtdata->transinfo->numlocked = numoidlocked;
1028 localtdata->transinfo->numnotfound = numoidnotfound;
1029 /* Lock and update count */
1030 //Thread sleeps until all messages from pariticipants are received by coordinator
1031 pthread_mutex_lock(localtdata->tdata->lock);
1032 (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */
1034 /* Wake up the threads and invoke decideResponse (once) */
1035 if(*(localtdata->tdata->count) == localtdata->tdata->buffer->f.mcount) {
1036 decideResponse(localtdata->tdata);
1037 pthread_cond_broadcast(localtdata->tdata->threshold);
1039 pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock);
1041 pthread_mutex_unlock(localtdata->tdata->lock);
1042 if(*(localtdata->tdata->replyctrl) == TRANS_ABORT){
1043 if(transAbortProcess(localtdata) != 0) {
1044 printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
1048 } else if(*(localtdata->tdata->replyctrl) == TRANS_COMMIT) {
1050 /* Invalidate objects in other machine cache */
1051 if(localtdata->tdata->buffer->f.nummod > 0) {
1053 if((retval = invalidateObj(localtdata->tdata)) != 0) {
1054 printf("Error: %s() in invalidating Objects %s, %d\n", __func__, __FILE__, __LINE__);
1059 if(transComProcess(localtdata) != 0) {
1060 printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
1066 if (localtdata->transinfo->objlocked != NULL) {
1067 free(localtdata->transinfo->objlocked);
1069 if (localtdata->transinfo->objnotfound != NULL) {
1070 free(localtdata->transinfo->objnotfound);
1075 /* This function completes the ABORT process if the transaction is aborting */
1076 int transAbortProcess(local_thread_data_array_t *localtdata) {
1078 unsigned int *objlocked;
1081 numlocked = localtdata->transinfo->numlocked;
1082 objlocked = localtdata->transinfo->objlocked;
1084 for (i = 0; i < numlocked; i++) {
1085 if((header = mhashSearch(objlocked[i])) == NULL) {
1086 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1089 UnLock(STATUSPTR(header));
1095 /*This function completes the COMMIT process if the transaction is commiting*/
1096 int transComProcess(local_thread_data_array_t *localtdata) {
1097 objheader_t *header, *tcptr;
1098 int i, nummod, tmpsize, numcreated, numlocked;
1099 unsigned int *oidmod, *oidcreated, *oidlocked;
1102 nummod = localtdata->tdata->buffer->f.nummod;
1103 oidmod = localtdata->tdata->buffer->oidmod;
1104 numcreated = localtdata->tdata->buffer->f.numcreated;
1105 oidcreated = localtdata->tdata->buffer->oidcreated;
1106 numlocked = localtdata->transinfo->numlocked;
1107 oidlocked = localtdata->transinfo->objlocked;
1109 for (i = 0; i < nummod; i++) {
1110 if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
1111 printf("Error: transComProcess() mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1114 /* Copy from transaction cache -> main object store */
1115 if ((tcptr = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidmod[i]))) == NULL) {
1116 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1119 GETSIZE(tmpsize, header);
1120 char *tmptcptr = (char *) tcptr;
1121 memcpy((char*)header+sizeof(objheader_t), (char *)tmptcptr+ sizeof(objheader_t), tmpsize);
1122 header->version += 1;
1123 if(header->notifylist != NULL) {
1124 notifyAll(&header->notifylist, OID(header), header->version);
1127 /* If object is newly created inside transaction then commit it */
1128 for (i = 0; i < numcreated; i++) {
1129 if ((header = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidcreated[i]))) == NULL) {
1130 printf("Error: transComProcess() chashSearch returned NULL for oid = %x at %s, %d\n", oidcreated[i], __FILE__, __LINE__);
1133 GETSIZE(tmpsize, header);
1134 tmpsize += sizeof(objheader_t);
1135 pthread_mutex_lock(&mainobjstore_mutex);
1136 if ((ptrcreate = objstrAlloc(mainobjstore, tmpsize)) == NULL) {
1137 printf("Error: transComProcess() failed objstrAlloc %s, %d\n", __FILE__, __LINE__);
1138 pthread_mutex_unlock(&mainobjstore_mutex);
1141 pthread_mutex_unlock(&mainobjstore_mutex);
1142 memcpy(ptrcreate, header, tmpsize);
1143 mhashInsert(oidcreated[i], ptrcreate);
1144 lhashInsert(oidcreated[i], myIpAddr);
1146 /* Unlock locked objects */
1147 for(i = 0; i < numlocked; i++) {
1148 if((header = (objheader_t *) mhashSearch(oidlocked[i])) == NULL) {
1149 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1152 UnLock(STATUSPTR(header));
1158 prefetchpile_t *foundLocal(char *ptr) {
1159 int siteid = *(GET_SITEID(ptr));
1160 int ntuples = *(GET_NTUPLES(ptr));
1161 unsigned int * oidarray = GET_PTR_OID(ptr);
1162 unsigned short * endoffsets = GET_PTR_EOFF(ptr, ntuples);
1163 short * arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1164 prefetchpile_t * head=NULL;
1168 for(i=0;i<ntuples; i++) {
1169 unsigned short baseindex=(i==0)?0:endoffsets[i-1];
1170 unsigned short endindex=endoffsets[i];
1171 unsigned int oid=oidarray[i];
1176 //Look up fields locally
1177 for(newbase=baseindex;newbase<endindex;newbase++) {
1178 if (!lookupObject(&oid, arryfields[newbase]))
1180 //Ended in a null pointer...
1184 //Entire prefetch is local
1185 if (newbase==endindex&&checkoid(oid)){
1189 //Add to remote requests
1190 machinenum=lhashSearch(oid);
1191 insertPile(machinenum, oid, endindex-newbase, &arryfields[newbase], &head);
1196 /* handle dynamic prefetching */
1197 handleDynPrefetching(numLocal, ntuples, siteid);
1201 int checkoid(unsigned int oid) {
1202 objheader_t *header;
1203 if ((header=mhashSearch(oid))!=NULL) {
1206 } else if ((header=prehashSearch(oid))!=NULL) {
1214 int lookupObject(unsigned int * oid, short offset) {
1215 objheader_t *header;
1216 if ((header=mhashSearch(*oid))!=NULL) {
1219 } else if ((header=prehashSearch(*oid))!=NULL) {
1226 if(TYPE(header) > NUMCLASSES) {
1227 int elementsize = classsize[TYPE(header)];
1228 struct ArrayObject *ao = (struct ArrayObject *) (((char *)header) + sizeof(objheader_t));
1229 int length = ao->___length___;
1230 /* Check if array out of bounds */
1231 if(offset < 0 || offset >= length) {
1232 //if yes treat the object as found
1236 (*oid) = *((unsigned int *)(((char *)ao) + sizeof(struct ArrayObject) + (elementsize*offset)));
1239 (*oid) = *((unsigned int *)(((char *)header) + sizeof(objheader_t) + offset));
1245 /* This function is called by the thread calling transPrefetch */
1246 void *transPrefetch(void *t) {
1248 /* lock mutex of primary prefetch queue */
1249 void *node=gettail();
1250 /* Check if the tuples are found locally, if yes then reduce them further*/
1251 /* and group requests by remote machine ids by calling the makePreGroups() */
1252 prefetchpile_t *pilehead = foundLocal(node);
1254 if (pilehead!=NULL) {
1255 // Get sock from shared pool
1256 int sd = getSock2(transPrefetchSockPool, pilehead->mid);
1258 /* Send Prefetch Request */
1259 prefetchpile_t *ptr = pilehead;
1260 while(ptr != NULL) {
1261 sendPrefetchReq(ptr, sd);
1265 /* Release socket */
1266 // freeSock(transPrefetchSockPool, pilehead->mid, sd);
1268 /* Deallocated pilehead */
1269 mcdealloc(pilehead);
1271 // Deallocate the prefetch queue pile node
1276 void sendPrefetchReqnew(prefetchpile_t *mcpilenode, int sd) {
1279 int size=sizeof(char)+sizeof(int);
1280 for(tmp=mcpilenode->objpiles;tmp!=NULL;tmp=tmp->next) {
1281 size += sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1286 *buf=TRANS_PREFETCH;
1289 for(tmp=mcpilenode->objpiles;tmp!=NULL;tmp=tmp->next) {
1290 int len = sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1293 *((unsigned int *)buf)=tmp->oid;
1294 buf+=sizeof(unsigned int);
1295 *((unsigned int *)(buf)) = myIpAddr;
1296 buf+=sizeof(unsigned int);
1297 memcpy(buf, tmp->offset, tmp->numoffset*sizeof(short));
1298 buf+=tmp->numoffset*sizeof(short);
1301 send_data(sd, buft, size);
1305 void sendPrefetchReq(prefetchpile_t *mcpilenode, int sd) {
1310 /* Send TRANS_PREFETCH control message */
1311 control = TRANS_PREFETCH;
1312 send_data(sd, &control, sizeof(char));
1314 /* Send Oids and offsets in pairs */
1315 tmp = mcpilenode->objpiles;
1316 while(tmp != NULL) {
1317 len = sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1318 char oidnoffset[len];
1319 char *buf=oidnoffset;
1320 *((int*)buf) = tmp->numoffset;
1322 *((unsigned int *)buf) = tmp->oid;
1323 buf+=sizeof(unsigned int);
1324 *((unsigned int *)buf) = myIpAddr;
1325 buf += sizeof(unsigned int);
1326 memcpy(buf, tmp->offset, (tmp->numoffset)*sizeof(short));
1327 send_data(sd, oidnoffset, len);
1331 /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
1333 send_data(sd, &endpair, sizeof(int));
1338 int getPrefetchResponse(int sd) {
1339 int length = 0, size = 0;
1342 void *modptr, *oldptr;
1344 recv_data((int)sd, &length, sizeof(int));
1345 size = length - sizeof(int);
1346 char recvbuffer[size];
1348 recv_data((int)sd, recvbuffer, size);
1349 control = *((char *) recvbuffer);
1350 if(control == OBJECT_FOUND) {
1351 oid = *((unsigned int *)(recvbuffer + sizeof(char)));
1352 size = size - (sizeof(char) + sizeof(unsigned int));
1353 pthread_mutex_lock(&prefetchcache_mutex);
1354 if ((modptr = prefetchobjstrAlloc(size)) == NULL) {
1355 printf("Error: objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
1356 pthread_mutex_unlock(&prefetchcache_mutex);
1359 pthread_mutex_unlock(&prefetchcache_mutex);
1360 memcpy(modptr, recvbuffer + sizeof(char) + sizeof(unsigned int), size);
1363 /* Insert the oid and its address into the prefetch hash lookup table */
1364 /* Do a version comparison if the oid exists */
1365 if((oldptr = prehashSearch(oid)) != NULL) {
1366 /* If older version then update with new object ptr */
1367 if(((objheader_t *)oldptr)->version <= ((objheader_t *)modptr)->version) {
1369 prehashInsert(oid, modptr);
1371 } else {/* Else add the object ptr to hash table*/
1372 prehashInsert(oid, modptr);
1374 /* Lock the Prefetch Cache look up table*/
1375 pthread_mutex_lock(&pflookup.lock);
1376 /* Broadcast signal on prefetch cache condition variable */
1377 pthread_cond_broadcast(&pflookup.cond);
1378 /* Unlock the Prefetch Cache look up table*/
1379 pthread_mutex_unlock(&pflookup.lock);
1380 } else if(control == OBJECT_NOT_FOUND) {
1381 oid = *((unsigned int *)(recvbuffer + sizeof(char)));
1382 /* TODO: For each object not found query DHT for new location and retrieve the object */
1383 /* Throw an error */
1384 //printf("OBJECT %x NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n", oid);
1387 printf("Error: in decoding the control value %d, %s, %d\n",control, __FILE__, __LINE__);
1393 unsigned short getObjType(unsigned int oid) {
1394 objheader_t *objheader;
1395 unsigned short numoffset[] ={0};
1396 short fieldoffset[] ={};
1398 if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL) {
1400 if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL) {
1402 unsigned int mid = lhashSearch(oid);
1403 int sd = getSock2(transReadSockPool, mid);
1404 char remotereadrequest[sizeof(char)+sizeof(unsigned int)];
1405 remotereadrequest[0] = READ_REQUEST;
1406 *((unsigned int *)(&remotereadrequest[1])) = oid;
1407 send_data(sd, remotereadrequest, sizeof(remotereadrequest));
1409 /* Read response from the Participant */
1411 recv_data(sd, &control, sizeof(char));
1413 if (control==OBJECT_NOT_FOUND) {
1414 printf("Error: in %s() THIS SHOULD NOT HAPPEN.....EXIT PROGRAM\n", __func__);
1418 /* Read object if found into local cache */
1420 recv_data(sd, &size, sizeof(int));
1422 pthread_mutex_lock(&prefetchcache_mutex);
1423 if ((objheader = prefetchobjstrAlloc(size)) == NULL) {
1424 printf("Error: %s() objstrAlloc error for copying into prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
1427 pthread_mutex_unlock(&prefetchcache_mutex);
1428 recv_data(sd, objheader, size);
1429 prehashInsert(oid, objheader);
1430 return TYPE(objheader);
1433 if((buffer = calloc(1, size)) == NULL) {
1434 printf("%s() Calloc Error %s at line %d\n", __func__, __FILE__, __LINE__);
1438 recv_data(sd, buffer, size);
1439 objheader = (objheader_t *)buffer;
1440 unsigned short type = TYPE(objheader);
1449 return TYPE(objheader);
1452 int startRemoteThread(unsigned int oid, unsigned int mid)
1455 struct sockaddr_in remoteAddr;
1456 char msg[1 + sizeof(unsigned int)];
1460 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
1462 perror("startRemoteThread():socket()");
1466 bzero(&remoteAddr, sizeof(remoteAddr));
1467 remoteAddr.sin_family = AF_INET;
1468 remoteAddr.sin_port = htons(LISTEN_PORT);
1469 remoteAddr.sin_addr.s_addr = htonl(mid);
1471 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0)
1473 printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
1474 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1479 msg[0] = START_REMOTE_THREAD;
1480 *((unsigned int *) &msg[1]) = oid;
1481 send_data(sock, msg, 1 + sizeof(unsigned int));
1488 //TODO: when reusing oids, make sure they are not already in use!
1489 static unsigned int id = 0xFFFFFFFF;
1490 unsigned int getNewOID(void) {
1492 if (id > oidMax || id < oidMin)
1499 int processConfigFile()
1502 const int maxLineLength = 200;
1503 char lineBuffer[maxLineLength];
1505 const char *delimiters = " \t\n";
1509 configFile = fopen(CONFIG_FILENAME, "r");
1510 if (configFile == NULL)
1512 printf("error opening %s:\n", CONFIG_FILENAME);
1517 numHostsInSystem = 0;
1518 sizeOfHostArray = 8;
1519 hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
1521 while(fgets(lineBuffer, maxLineLength, configFile) != NULL)
1523 commentBegin = strchr(lineBuffer, '#');
1524 if (commentBegin != NULL)
1525 *commentBegin = '\0';
1526 token = strtok(lineBuffer, delimiters);
1527 while (token != NULL)
1529 tmpAddr = inet_addr(token);
1530 if ((int)tmpAddr == -1)
1532 printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
1537 addHost(htonl(tmpAddr));
1538 token = strtok(NULL, delimiters);
1544 if (numHostsInSystem < 1)
1546 printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
1550 myIpAddr = getMyIpAddr("en1");
1552 myIpAddr = getMyIpAddr("eth0");
1554 myIndexInHostArray = findHost(myIpAddr);
1555 if (myIndexInHostArray == -1)
1557 printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
1560 oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
1561 oidMin = oidsPerBlock * myIndexInHostArray;
1562 if (myIndexInHostArray == numHostsInSystem - 1)
1563 oidMax = 0xFFFFFFFF;
1565 oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
1570 void addHost(unsigned int hostIp)
1572 unsigned int *tmpArray;
1574 if (findHost(hostIp) != -1)
1577 if (numHostsInSystem == sizeOfHostArray)
1579 tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
1580 memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
1582 hostIpAddrs = tmpArray;
1585 hostIpAddrs[numHostsInSystem++] = hostIp;
1590 int findHost(unsigned int hostIp)
1593 for (i = 0; i < numHostsInSystem; i++)
1594 if (hostIpAddrs[i] == hostIp)
1601 /* This function sends notification request per thread waiting on object(s) whose version
1603 int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int numoid) {
1605 objheader_t *objheader;
1606 struct sockaddr_in remoteAddr;
1607 char msg[1 + numoid * (sizeof(unsigned short) + sizeof(unsigned int)) + 3 * sizeof(unsigned int)];
1611 unsigned short version;
1612 unsigned int oid,mid;
1613 static unsigned int threadid = 0;
1614 pthread_mutex_t threadnotify = PTHREAD_MUTEX_INITIALIZER; //Lock and condition var for threadjoin and notification
1615 pthread_cond_t threadcond = PTHREAD_COND_INITIALIZER;
1616 notifydata_t *ndata;
1619 if((mid = lhashSearch(oid)) == 0) {
1620 printf("Error: %s() No such machine found for oid =%x\n",__func__, oid);
1624 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1625 perror("reqNotify():socket()");
1629 bzero(&remoteAddr, sizeof(remoteAddr));
1630 remoteAddr.sin_family = AF_INET;
1631 remoteAddr.sin_port = htons(LISTEN_PORT);
1632 remoteAddr.sin_addr.s_addr = htonl(mid);
1634 /* Generate unique threadid */
1637 /* Save threadid, numoid, oidarray, versionarray, pthread_cond_variable for later processing */
1638 if((ndata = calloc(1, sizeof(notifydata_t))) == NULL) {
1639 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
1642 ndata->numoid = numoid;
1643 ndata->threadid = threadid;
1644 ndata->oidarry = oidarry;
1645 ndata->versionarry = versionarry;
1646 ndata->threadcond = threadcond;
1647 ndata->threadnotify = threadnotify;
1648 if((status = notifyhashInsert(threadid, ndata)) != 0) {
1649 printf("reqNotify(): Insert into notify hash table not successful %s, %d\n", __FILE__, __LINE__);
1654 /* Send number of oids, oidarry, version array, machine id and threadid */
1655 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1656 printf("reqNotify():error %d connecting to %s:%d\n", errno,
1657 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1661 msg[0] = THREAD_NOTIFY_REQUEST;
1662 *((unsigned int *)(&msg[1])) = numoid;
1663 /* Send array of oids */
1664 size = sizeof(unsigned int);
1669 *((unsigned int *)(&msg[1] + size)) = oid;
1670 size += sizeof(unsigned int);
1675 /* Send array of version */
1679 version = versionarry[i];
1680 *((unsigned short *)(&msg[1] + size)) = version;
1681 size += sizeof(unsigned short);
1686 *((unsigned int *)(&msg[1] + size)) = myIpAddr;
1687 size += sizeof(unsigned int);
1688 *((unsigned int *)(&msg[1] + size)) = threadid;
1689 pthread_mutex_lock(&(ndata->threadnotify));
1690 size = 1 + numoid * (sizeof(unsigned int) + sizeof(unsigned short)) + 3 * sizeof(unsigned int);
1691 send_data(sock, msg, size);
1692 pthread_cond_wait(&(ndata->threadcond), &(ndata->threadnotify));
1693 pthread_mutex_unlock(&(ndata->threadnotify));
1696 pthread_cond_destroy(&threadcond);
1697 pthread_mutex_destroy(&threadnotify);
1703 void threadNotify(unsigned int oid, unsigned short version, unsigned int tid) {
1704 notifydata_t *ndata;
1705 int i, objIsFound = 0, index;
1708 //Look up the tid and call the corresponding pthread_cond_signal
1709 if((ndata = notifyhashSearch(tid)) == NULL) {
1710 printf("threadnotify(): No such threadid is present %s, %d\n", __FILE__, __LINE__);
1713 for(i = 0; i < ndata->numoid; i++) {
1714 if(ndata->oidarry[i] == oid){
1719 if(objIsFound == 0){
1720 printf("threadNotify(): Oid not found %s, %d\n", __FILE__, __LINE__);
1723 if(version <= ndata->versionarry[index]){
1724 printf("threadNotify(): New version %d has not changed since last version for oid = %d, %s, %d\n", version, oid, __FILE__, __LINE__);
1728 /* Clear from prefetch cache and free thread related data structure */
1729 if((ptr = prehashSearch(oid)) != NULL) {
1733 pthread_cond_signal(&(ndata->threadcond));
1740 int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) {
1743 struct sockaddr_in remoteAddr;
1744 char msg[1 + sizeof(unsigned short) + 2*sizeof(unsigned int)];
1745 int sock, status, size, bytesSent;
1747 while(*head != NULL) {
1750 //create a socket connection to that machine
1751 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1752 perror("notifyAll():socket()");
1756 bzero(&remoteAddr, sizeof(remoteAddr));
1757 remoteAddr.sin_family = AF_INET;
1758 remoteAddr.sin_port = htons(LISTEN_PORT);
1759 remoteAddr.sin_addr.s_addr = htonl(mid);
1760 //send Thread Notify response and threadid to that machine
1761 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1762 printf("notifyAll():error %d connecting to %s:%d\n", errno,
1763 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1767 bzero(msg, (1+sizeof(unsigned short) + 2*sizeof(unsigned int)));
1768 msg[0] = THREAD_NOTIFY_RESPONSE;
1769 *((unsigned int *)&msg[1]) = oid;
1770 size = sizeof(unsigned int);
1771 *((unsigned short *)(&msg[1]+ size)) = version;
1772 size+= sizeof(unsigned short);
1773 *((unsigned int *)(&msg[1]+ size)) = ptr->threadid;
1775 size = 1 + 2*sizeof(unsigned int) + sizeof(unsigned short);
1776 send_data(sock, msg, size);
1787 void transAbort(transrecord_t *trans) {
1788 objstrDelete(trans->cache);
1789 chashDelete(trans->lookupTable);
1793 /* This function inserts necessary information into
1794 * a machine pile data structure */
1795 plistnode_t *pInsert(plistnode_t *pile, objheader_t *headeraddr, unsigned int mid, int num_objs) {
1796 plistnode_t *ptr, *tmp;
1797 int found = 0, offset = 0;
1800 //Add oid into a machine that is already present in the pile linked list structure
1801 while(tmp != NULL) {
1802 if (tmp->mid == mid) {
1805 if (STATUS(headeraddr) & NEW) {
1806 tmp->oidcreated[tmp->numcreated] = OID(headeraddr);
1808 GETSIZE(tmpsize, headeraddr);
1809 tmp->sum_bytes += sizeof(objheader_t) + tmpsize;
1810 }else if (STATUS(headeraddr) & DIRTY) {
1811 tmp->oidmod[tmp->nummod] = OID(headeraddr);
1813 GETSIZE(tmpsize, headeraddr);
1814 tmp->sum_bytes += sizeof(objheader_t) + tmpsize;
1816 offset = (sizeof(unsigned int) + sizeof(short)) * tmp->numread;
1817 *((unsigned int *)(((char *)tmp->objread) + offset))=OID(headeraddr);
1818 offset += sizeof(unsigned int);
1819 *((short *)(((char *)tmp->objread) + offset)) = headeraddr->version;
1827 //Add oid for any new machine
1830 if((ptr = pCreate(num_objs)) == NULL) {
1834 if (STATUS(headeraddr) & NEW) {
1835 ptr->oidcreated[ptr->numcreated] = OID(headeraddr);
1837 GETSIZE(tmpsize, headeraddr);
1838 ptr->sum_bytes += sizeof(objheader_t) + tmpsize;
1839 } else if (STATUS(headeraddr) & DIRTY) {
1840 ptr->oidmod[ptr->nummod] = OID(headeraddr);
1842 GETSIZE(tmpsize, headeraddr);
1843 ptr->sum_bytes += sizeof(objheader_t) + tmpsize;
1845 *((unsigned int *)ptr->objread)=OID(headeraddr);
1846 offset = sizeof(unsigned int);
1847 *((short *)(((char *)ptr->objread) + offset)) = headeraddr->version;
1855 STATUS(headeraddr) =0;