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 objstr_t *prefetchcache; //Global Prefetch cache
25 pthread_mutex_t prefetchcache_mutex;// Mutex to lock Prefetch Cache
26 pthread_mutexattr_t prefetchcache_mutex_attr; /* Attribute for lock to make it a recursive lock */
27 extern pthread_mutex_t mainobjstore_mutex;// Mutex to lock main Object store
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, 2*numHostsInSystem+1);
190 transPrefetchSockPool = createSockPool(transPrefetchSockPool, 2*numHostsInSystem+1);
191 transRequestSockPool = createSockPool(transRequestSockPool, 2*numHostsInSystem+1);
198 pthread_attr_init(&attr);
199 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
200 pthread_create(&udp_thread_Listen, &attr, udpListenBroadcast, (void*)udpfd);
202 pthread_create(&thread_Listen, &attr, dstmListen, (void*)fd);
205 dstmListen((void *)fd);
210 //TODO Use this later
211 void *pCacheAlloc(objstr_t *store, unsigned int size) {
217 while(ptr->next != NULL) {
218 /* check if store is empty */
219 if(((unsigned int)ptr->top - (unsigned int)ptr - sizeof(objstr_t) + size) <= ptr->size) {
234 /* This function initiates the prefetch thread A queue is shared
235 * between the main thread of execution and the prefetch thread to
236 * process the prefetch call Call from compiler populates the shared
237 * queue with prefetch requests while prefetch thread processes the
238 * prefetch requests */
243 //Create and initialize prefetch cache structure
244 prefetchcache = objstrCreate(PREFETCH_CACHE_SIZE);
246 if((evalPrefetch = initPrefetchStats()) == NULL) {
247 printf("%s() Error allocating memory at %s, %d\n", __func__, __FILE__, __LINE__);
251 /* Initialize attributes for mutex */
252 pthread_mutexattr_init(&prefetchcache_mutex_attr);
253 pthread_mutexattr_settype(&prefetchcache_mutex_attr, PTHREAD_MUTEX_RECURSIVE_NP);
255 pthread_mutex_init(&prefetchcache_mutex, &prefetchcache_mutex_attr);
257 pthread_mutex_init(¬ifymutex, NULL);
258 pthread_mutex_init(&atomicObjLock, NULL);
259 //Create prefetch cache lookup table
260 if(prehashCreate(HASH_SIZE, LOADFACTOR)) {
265 //Initialize primary shared queue
267 //Initialize machine pile w/prefetch oids and offsets shared queue
270 //Create the primary prefetch thread
272 retval=pthread_create(&tPrefetch, NULL, transPrefetch, NULL);
274 pthread_detach(tPrefetch);
277 /* This function stops the threads spawned */
280 pthread_cancel(tPrefetch);
281 for(t = 0; t < NUM_THREADS; t++)
282 pthread_cancel(wthreads[t]);
287 /* This functions inserts randowm wait delays in the order of msec
288 * Mostly used when transaction commits retry*/
295 req.tv_nsec = (long)(1000000 + (t%10000000)); //1-11 msec
296 nanosleep(&req, NULL);
300 /* This function initializes things required in the transaction start*/
301 transrecord_t *transStart() {
303 if((tmp = calloc(1, sizeof(transrecord_t))) == NULL){
304 printf("%s() Calloc error at line %d, %s\n", __func__, __LINE__, __FILE__);
307 tmp->cache = objstrCreate(1048576);
308 tmp->lookupTable = chashCreate(CHASH_SIZE, CLOADFACTOR);
310 tmp->revertlist=NULL;
315 /* This function finds the location of the objects involved in a transaction
316 * and returns the pointer to the object if found in a remote location */
317 objheader_t *transRead(transrecord_t *record, unsigned int oid) {
318 unsigned int machinenumber;
319 objheader_t *tmp, *objheader;
320 objheader_t *objcopy;
328 if((objheader = chashSearch(record->lookupTable, oid)) != NULL){
332 /* Search local transaction cache */
334 return &objheader[1];
338 } else if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
342 /* Look up in machine lookup table and copy into cache*/
343 GETSIZE(size, objheader);
344 size += sizeof(objheader_t);
345 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
346 memcpy(objcopy, objheader, size);
347 /* Insert into cache's lookup table */
349 chashInsert(record->lookupTable, OID(objheader), objcopy);
355 } else if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) {
360 printf("Prefetch cache read, oid = %x, oidtype =%d\n", oid, TYPE(tmp));
363 /* Look up in prefetch cache */
365 size+=sizeof(objheader_t);
366 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
367 memcpy(objcopy, tmp, size);
368 /* Insert into cache's lookup table */
369 chashInsert(record->lookupTable, OID(tmp), objcopy);
376 /* Get the object from the remote location */
377 if((machinenumber = lhashSearch(oid)) == 0) {
378 printf("Error: %s() No machine found for oid =% %s,%dx\n",__func__, machinenumber, __FILE__, __LINE__);
381 objcopy = getRemoteObj(record, machinenumber, oid);
383 if(objcopy == NULL) {
384 printf("Error: Object not found in Remote location %s, %d\n", __FILE__, __LINE__);
391 printf("Remote read, oid = %x, oidtype =%d\n", oid, TYPE(objcopy));
404 /* This function creates objects in the transaction record */
405 objheader_t *transCreateObj(transrecord_t *record, unsigned int size) {
406 objheader_t *tmp = (objheader_t *) objstrAlloc(record->cache, (sizeof(objheader_t) + size));
407 OID(tmp) = getNewOID();
411 chashInsert(record->lookupTable, OID(tmp), tmp);
414 return &tmp[1]; //want space after object header
420 /* This function creates machine piles based on all machines involved in a
421 * transaction commit request */
422 plistnode_t *createPiles(transrecord_t *record) {
424 plistnode_t *pile = NULL;
425 unsigned int machinenum;
426 objheader_t *headeraddr;
427 chashlistnode_t * ptr = record->lookupTable->table;
428 /* Represents number of bins in the chash table */
429 unsigned int size = record->lookupTable->size;
431 for(i = 0; i < size ; i++) {
432 chashlistnode_t * curr = &ptr[i];
433 /* Inner loop to traverse the linked list of the cache lookupTable */
434 while(curr != NULL) {
435 //if the first bin in hash table is empty
439 if ((headeraddr = (objheader_t *) chashSearch(record->lookupTable, curr->key)) == NULL) {
440 printf("Error: No such oid %s, %d\n", __FILE__, __LINE__);
444 //Get machine location for object id (and whether local or not)
445 if (STATUS(headeraddr) & NEW || (mhashSearch(curr->key) != NULL)) {
446 machinenum = myIpAddr;
447 } else if ((machinenum = lhashSearch(curr->key)) == 0) {
448 printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
452 //Make machine groups
453 pile = pInsert(pile, headeraddr, machinenum, record->lookupTable->numelements);
460 /* This function initiates the transaction commit process
461 * Spawns threads for each of the new connections with Participants
462 * and creates new piles by calling the createPiles(),
463 * Sends a transrequest() to each remote machines for objects found remotely
464 * and calls handleLocalReq() to process objects found locally */
465 int transCommit(transrecord_t *record) {
466 unsigned int tot_bytes_mod, *listmid;
467 plistnode_t *pile, *pile_ptr;
469 int pilecount, offset, threadnum, trecvcount;
471 char transid[TID_LEN];
472 trans_req_data_t *tosend;
473 trans_commit_data_t transinfo;
474 static int newtid = 0;
475 char treplyctrl, treplyretry; /* keeps track of the common response that needs to be sent */
476 thread_data_array_t *thread_data_array;
477 local_thread_data_array_t *ltdata;
485 thread_data_array = NULL;
488 /* Look through all the objects in the transaction record and make piles
489 * for each machine involved in the transaction*/
491 pile_ptr = pile = createPiles(record);
496 /* Create the packet to be sent in TRANS_REQUEST */
498 /* Count the number of participants */
499 pilecount = pCount(pile);
501 /* Create a list of machine ids(Participants) involved in transaction */
502 listmid = calloc(pilecount, sizeof(unsigned int));
503 pListMid(pile, listmid);
506 /* Initialize thread variables,
507 * Spawn a thread for each Participant involved in a transaction */
508 pthread_t thread[pilecount];
510 pthread_cond_t tcond;
511 pthread_mutex_t tlock;
512 pthread_mutex_t tlshrd;
514 thread_data_array = (thread_data_array_t *) calloc(pilecount, sizeof(thread_data_array_t));
515 ltdata = calloc(1, sizeof(local_thread_data_array_t));
517 thread_response_t rcvd_control_msg[pilecount]; /* Shared thread array that keeps track of responses of participants */
519 /* Initialize and set thread detach attribute */
520 pthread_attr_init(&attr);
521 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
522 pthread_mutex_init(&tlock, NULL);
523 pthread_cond_init(&tcond, NULL);
525 /* Process each machine pile */
526 while(pile != NULL) {
527 //Create transaction id
529 tosend = calloc(1, sizeof(trans_req_data_t));
530 tosend->f.control = TRANS_REQUEST;
531 sprintf(tosend->f.trans_id, "%x_%d", pile->mid, newtid);
532 tosend->f.mcount = pilecount;
533 tosend->f.numread = pile->numread;
534 tosend->f.nummod = pile->nummod;
535 tosend->f.numcreated = pile->numcreated;
536 tosend->f.sum_bytes = pile->sum_bytes;
537 tosend->listmid = listmid;
538 tosend->objread = pile->objread;
539 tosend->oidmod = pile->oidmod;
540 tosend->oidcreated = pile->oidcreated;
541 thread_data_array[threadnum].thread_id = threadnum;
542 thread_data_array[threadnum].mid = pile->mid;
543 thread_data_array[threadnum].buffer = tosend;
544 thread_data_array[threadnum].recvmsg = rcvd_control_msg;
545 thread_data_array[threadnum].threshold = &tcond;
546 thread_data_array[threadnum].lock = &tlock;
547 thread_data_array[threadnum].count = &trecvcount;
548 thread_data_array[threadnum].replyctrl = &treplyctrl;
549 thread_data_array[threadnum].replyretry = &treplyretry;
550 thread_data_array[threadnum].rec = record;
551 /* If local do not create any extra connection */
552 if(pile->mid != myIpAddr) { /* Not local */
554 rc = pthread_create(&thread[threadnum], &attr, transRequest, (void *) &thread_data_array[threadnum]);
557 perror("Error in pthread create\n");
558 pthread_cond_destroy(&tcond);
559 pthread_mutex_destroy(&tlock);
562 for (i = 0; i < threadnum; i++)
563 free(thread_data_array[i].buffer);
564 free(thread_data_array);
569 ltdata->tdata = &thread_data_array[threadnum];
570 ltdata->transinfo = &transinfo;
572 val = pthread_create(&thread[threadnum], &attr, handleLocalReq, (void *) ltdata);
575 perror("Error in pthread create\n");
576 pthread_cond_destroy(&tcond);
577 pthread_mutex_destroy(&tlock);
580 for (i = 0; i < threadnum; i++)
581 free(thread_data_array[i].buffer);
582 free(thread_data_array);
591 /* Free attribute and wait for the other threads */
592 pthread_attr_destroy(&attr);
594 for (i = 0; i < threadnum; i++) {
595 rc = pthread_join(thread[i], NULL);
598 printf("Error: return code from pthread_join() is %d\n", rc);
599 pthread_cond_destroy(&tcond);
600 pthread_mutex_destroy(&tlock);
603 for (j = i; j < threadnum; j++) {
604 free(thread_data_array[j].buffer);
608 free(thread_data_array[i].buffer);
612 pthread_cond_destroy(&tcond);
613 pthread_mutex_destroy(&tlock);
619 /* wait a random amount of time before retrying to commit transaction*/
621 free(thread_data_array);
626 /* Retry trans commit procedure during soft_abort case */
627 } while (treplyretry);
629 if(treplyctrl == TRANS_ABORT) {
634 char a[] = "Aborting";
638 objstrDelete(record->cache);
639 chashDelete(record->lookupTable);
641 free(thread_data_array);
644 } else if(treplyctrl == TRANS_COMMIT) {
649 char a[] = "Commiting";
653 objstrDelete(record->cache);
654 chashDelete(record->lookupTable);
656 free(thread_data_array);
660 //TODO Add other cases
661 printf("Error: in %s() THIS SHOULD NOT HAPPEN.....EXIT PROGRAM\n", __func__);
667 /* This function sends information involved in the transaction request
668 * to participants and accepts a response from particpants.
669 * It calls decideresponse() to decide on what control message
670 * to send next to participants and sends the message using sendResponse()*/
671 void *transRequest(void *threadarg) {
673 struct sockaddr_in serv_addr;
674 thread_data_array_t *tdata;
675 objheader_t *headeraddr;
676 char control, recvcontrol;
677 char machineip[16], retval;
679 tdata = (thread_data_array_t *) threadarg;
681 if((sd = getSock2WithLock(transRequestSockPool, tdata->mid)) < 0) {
682 printf("transRequest(): socket create error\n");
686 /* Send bytes of data with TRANS_REQUEST control message */
687 send_data(sd, &(tdata->buffer->f), sizeof(fixed_data_t));
689 /* Send list of machines involved in the transaction */
691 int size=sizeof(unsigned int)*tdata->buffer->f.mcount;
692 send_data(sd, tdata->buffer->listmid, size);
695 /* Send oids and version number tuples for objects that are read */
697 int size=(sizeof(unsigned int)+sizeof(unsigned short))*tdata->buffer->f.numread;
698 send_data(sd, tdata->buffer->objread, size);
701 /* Send objects that are modified */
702 for(i = 0; i < tdata->buffer->f.nummod ; i++) {
704 if((headeraddr = chashSearch(tdata->rec->lookupTable, tdata->buffer->oidmod[i])) == NULL) {
705 printf("%s() Error: No such oid %s, %d\n", __func__, __FILE__, __LINE__);
708 GETSIZE(size,headeraddr);
709 size+=sizeof(objheader_t);
710 send_data(sd, headeraddr, size);
713 /* Read control message from Participant */
714 recv_data(sd, &control, sizeof(char));
715 /* Recv Objects if participant sends TRANS_DISAGREE */
716 if(control == TRANS_DISAGREE) {
718 recv_data(sd, &length, sizeof(int));
720 pthread_mutex_lock(&prefetchcache_mutex);
721 if ((newAddr = prefetchobjstrAlloc((unsigned int)length)) == NULL) {
722 printf("Error: %s() objstrAlloc error for copying into prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
725 pthread_mutex_unlock(&prefetchcache_mutex);
726 recv_data(sd, newAddr, length);
729 unsigned int oidToPrefetch;
730 objheader_t * header;
731 header = (objheader_t *) (((char *)newAddr) + offset);
732 oidToPrefetch = OID(header);
734 printf("Trans disagree for oid = %x: ", OID(header));
735 char a[] = "object type";
736 TABORT8(__func__, a, TYPE(header));
739 GETSIZE(size, header);
740 size += sizeof(objheader_t);
741 //make an entry in prefetch hash table
743 if((oldptr = prehashSearch(oidToPrefetch)) != NULL) {
744 prehashRemove(oidToPrefetch);
745 prehashInsert(oidToPrefetch, header);
747 prehashInsert(oidToPrefetch, header);
749 length = length - size;
754 recvcontrol = control;
755 /* Update common data structure and increment count */
756 tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol;
758 /* Lock and update count */
759 /* Thread sleeps until all messages from pariticipants are received by coordinator */
760 pthread_mutex_lock(tdata->lock);
762 (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */
764 /* Wake up the threads and invoke decideResponse (once) */
765 if(*(tdata->count) == tdata->buffer->f.mcount) {
766 decideResponse(tdata);
767 pthread_cond_broadcast(tdata->threshold);
769 pthread_cond_wait(tdata->threshold, tdata->lock);
771 pthread_mutex_unlock(tdata->lock);
773 /* clear objects from prefetch cache */
775 if(*(tdata->replyctrl) == TRANS_ABORT) {
777 for(i=0; i<tdata->buffer->f.nummod; i++) {
778 unsigned int oid = tdata->buffer->oidmod[i];
780 if((header = prehashSearch(oid)) != NULL) {
784 for(i=0; i<tdata->buffer->f.numread; i++) {
785 char *objread = tdata->buffer->objread;
786 unsigned int oid = *((unsigned int *)(objread+(sizeof(unsigned int) +
787 sizeof(unsigned short))*i));
789 if((header = prehashSearch(oid)) != NULL) {
796 if(*(tdata->replyctrl) == TRANS_COMMIT) {
798 /* Update prefetch cache */
799 if((retval = updatePrefetchCache(tdata)) != 0) {
800 printf("Error: %s() in updating prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
804 /* Invalidate objects in other machine cache */
805 if(tdata->buffer->f.nummod > 0) {
806 if((retval = invalidateObj(tdata)) != 0) {
807 printf("Error: %s() in invalidating Objects %s, %d\n", __func__, __FILE__, __LINE__);
813 /* Send the final response such as TRANS_COMMIT or TRANS_ABORT
814 * to all participants in their respective socket */
815 if (sendResponse(tdata, sd) == 0) {
816 printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__);
820 recv_data((int)sd, &control, sizeof(char));
822 if(control == TRANS_UNSUCESSFUL) {
823 //printf("DEBUG-> TRANS_ABORTED\n");
824 } else if(control == TRANS_SUCESSFUL) {
825 //printf("DEBUG-> TRANS_SUCCESSFUL\n");
827 //printf("DEBUG-> Error: Incorrect Transaction End Message %d\n", control);
832 /* This function decides the reponse that needs to be sent to
833 * all Participant machines after the TRANS_REQUEST protocol */
834 void decideResponse(thread_data_array_t *tdata) {
836 int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
839 for (i = 0 ; i < tdata->buffer->f.mcount; i++) {
840 control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses
841 written onto the shared array */
844 printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
845 /* treat as disagree, pass thru */
854 case TRANS_SOFT_ABORT:
860 if(transdisagree > 0) {
862 *(tdata->replyctrl) = TRANS_ABORT;
863 *(tdata->replyretry) = 0;
864 /* clear objects from prefetch cache */
866 } else if(transagree == tdata->buffer->f.mcount){
868 *(tdata->replyctrl) = TRANS_COMMIT;
869 *(tdata->replyretry) = 0;
871 /* Send Abort in soft abort case followed by retry commiting transaction again*/
872 *(tdata->replyctrl) = TRANS_ABORT;
873 *(tdata->replyretry) = 1;
878 /* This function sends the final response to remote machines per
879 * thread in their respective socket id It returns a char that is only
880 * needed to check the correctness of execution of this function
881 * inside transRequest()*/
883 char sendResponse(thread_data_array_t *tdata, int sd) {
884 int n, size, sum, oidcount = 0, control;
885 char *ptr, retval = 0;
886 unsigned int *oidnotfound;
888 control = *(tdata->replyctrl);
889 send_data(sd, &control, sizeof(char));
891 //TODO read missing objects during object migration
892 /* If response is a soft abort due to missing objects at the
893 Participant's side */
895 /* If the decided response is TRANS_ABORT */
896 if(*(tdata->replyctrl) == TRANS_ABORT) {
897 retval = TRANS_ABORT;
898 } else if(*(tdata->replyctrl) == TRANS_COMMIT) {
899 /* If the decided response is TRANS_COMMIT */
900 retval = TRANS_COMMIT;
906 /* This function opens a connection, places an object read request to
907 * the remote machine, reads the control message and object if
908 * available and copies the object and its header to the local
911 void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
913 struct sockaddr_in serv_addr;
917 void *objcopy = NULL;
919 int sd = getSock2(transReadSockPool, mnum);
920 char readrequest[sizeof(char)+sizeof(unsigned int)];
921 readrequest[0] = READ_REQUEST;
922 *((unsigned int *)(&readrequest[1])) = oid;
923 send_data(sd, readrequest, sizeof(readrequest));
925 /* Read response from the Participant */
926 recv_data(sd, &control, sizeof(char));
928 if (control==OBJECT_NOT_FOUND) {
931 /* Read object if found into local cache */
932 recv_data(sd, &size, sizeof(int));
933 objcopy = objstrAlloc(record->cache, size);
934 recv_data(sd, objcopy, size);
935 /* Insert into cache's lookup table */
936 chashInsert(record->lookupTable, oid, objcopy);
942 /* This function handles the local objects involved in a transaction
943 * commiting process. It also makes a decision if this local machine
944 * sends AGREE or DISAGREE or SOFT_ABORT to coordinator. Note
945 * Coordinator = local machine It wakes up the other threads from
946 * remote participants that are waiting for the coordinator's decision
947 * and based on common agreement it either commits or aborts the
948 * transaction. It also frees the memory resources */
950 void *handleLocalReq(void *threadarg) {
951 unsigned int *oidnotfound = NULL, *oidlocked = NULL;
952 local_thread_data_array_t *localtdata;
953 int numoidnotfound = 0, numoidlocked = 0;
954 int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
957 unsigned short version;
959 objheader_t *headptr;
961 localtdata = (local_thread_data_array_t *) threadarg;
963 /* Counters and arrays to formulate decision on control message to be sent */
964 oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
965 oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
967 numread = localtdata->tdata->buffer->f.numread;
968 /* Process each oid in the machine pile/ group per thread */
969 for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) {
970 if (i < localtdata->tdata->buffer->f.numread) {
971 int incr = sizeof(unsigned int) + sizeof(unsigned short);// Offset that points to next position in the objread array
973 oid = *((unsigned int *)(((char *)localtdata->tdata->buffer->objread) + incr));
974 version = *((unsigned short *)(((char *)localtdata->tdata->buffer->objread) + incr + sizeof(unsigned int)));
975 } else { // Objects Modified
977 headptr = (objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidmod[i-numread]);
978 if (headptr == NULL) {
979 printf("Error: handleLocalReq() returning NULL, no such oid %s, %d\n", __FILE__, __LINE__);
983 version = headptr->version;
985 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
987 /* Save the oids not found and number of oids not found for later use */
988 if ((mobj = mhashSearch(oid)) == NULL) { /* Obj not found */
989 /* Save the oids not found and number of oids not found for later use */
990 oidnotfound[numoidnotfound] = oid;
992 } else { /* If Obj found in machine (i.e. has not moved) */
993 /* Check if Obj is locked by any previous transaction */
994 if (test_and_set(STATUSPTR(mobj))) {
995 if (version == ((objheader_t *)mobj)->version) { /* If locked then match versions */
997 } else {/* If versions don't match ...HARD ABORT */
999 /* Send TRANS_DISAGREE to Coordinator */
1000 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
1002 printf("Trans disagree for oid = %x: ", OID(mobj));
1003 char a[] = "object type";
1004 TABORT8(__func__, a, TYPE(mobj));
1009 //char b[] = "version mismatch";
1010 //char c[] = "object type";
1012 //TABORT9(__func__, b, a, c, d, localtdata->tdata->mid, TYPE(mobj), OID(mobj));
1018 /* Save all object oids that are locked on this machine during this transaction request call */
1019 oidlocked[numoidlocked] = OID(((objheader_t *)mobj));
1021 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
1023 } else { /* If versions don't match ...HARD ABORT */
1025 /* Send TRANS_DISAGREE to Coordinator */
1026 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
1028 printf("Trans disagree for oid = %x: ", OID(mobj));
1029 char a[] = "object type";
1030 TABORT8(__func__, a, TYPE(mobj));
1034 //char b[] = "version mismatch";
1035 //char c[] = "object type";
1037 //TABORT9(__func__, b, a, c, d, localtdata->tdata->mid, TYPE(mobj), OID(mobj));
1044 /* Condition to send TRANS_AGREE */
1045 if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
1046 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
1048 /* Condition to send TRANS_SOFT_ABORT */
1049 if((v_matchlock > 0 && v_nomatch == 0) || (numoidnotfound > 0 && v_nomatch == 0)) {
1052 //char b[] = "version mismatch";
1053 //char c[] = "object type";
1054 //TABORT7(__func__, b, a, c, localtdata->tdata->mid, TYPE(mobj));
1055 printf("%s() Soft abort\n", __func__);
1057 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
1060 /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
1061 * if Participant receives a TRANS_COMMIT */
1062 localtdata->transinfo->objlocked = oidlocked;
1063 localtdata->transinfo->objnotfound = oidnotfound;
1064 localtdata->transinfo->modptr = NULL;
1065 localtdata->transinfo->numlocked = numoidlocked;
1066 localtdata->transinfo->numnotfound = numoidnotfound;
1067 /* Lock and update count */
1068 //Thread sleeps until all messages from pariticipants are received by coordinator
1069 pthread_mutex_lock(localtdata->tdata->lock);
1070 (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */
1072 /* Wake up the threads and invoke decideResponse (once) */
1073 if(*(localtdata->tdata->count) == localtdata->tdata->buffer->f.mcount) {
1074 decideResponse(localtdata->tdata);
1075 pthread_cond_broadcast(localtdata->tdata->threshold);
1077 pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock);
1079 pthread_mutex_unlock(localtdata->tdata->lock);
1080 if(*(localtdata->tdata->replyctrl) == TRANS_ABORT){
1081 if(transAbortProcess(localtdata) != 0) {
1082 printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
1086 } else if(*(localtdata->tdata->replyctrl) == TRANS_COMMIT) {
1087 /* Invalidate objects in other machine cache */
1088 if(localtdata->tdata->buffer->f.nummod > 0) {
1090 if((retval = invalidateObj(localtdata->tdata)) != 0) {
1091 printf("Error: %s() in invalidating Objects %s, %d\n", __func__, __FILE__, __LINE__);
1095 if(transComProcess(localtdata) != 0) {
1096 printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
1102 if (localtdata->transinfo->objlocked != NULL) {
1103 free(localtdata->transinfo->objlocked);
1105 if (localtdata->transinfo->objnotfound != NULL) {
1106 free(localtdata->transinfo->objnotfound);
1111 /* This function completes the ABORT process if the transaction is aborting */
1112 int transAbortProcess(local_thread_data_array_t *localtdata) {
1114 unsigned int *objlocked;
1117 numlocked = localtdata->transinfo->numlocked;
1118 objlocked = localtdata->transinfo->objlocked;
1120 for (i = 0; i < numlocked; i++) {
1121 if((header = mhashSearch(objlocked[i])) == NULL) {
1122 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1125 UnLock(STATUSPTR(header));
1131 /*This function completes the COMMIT process if the transaction is commiting*/
1132 int transComProcess(local_thread_data_array_t *localtdata) {
1133 objheader_t *header, *tcptr;
1134 int i, nummod, tmpsize, numcreated, numlocked;
1135 unsigned int *oidmod, *oidcreated, *oidlocked;
1138 nummod = localtdata->tdata->buffer->f.nummod;
1139 oidmod = localtdata->tdata->buffer->oidmod;
1140 numcreated = localtdata->tdata->buffer->f.numcreated;
1141 oidcreated = localtdata->tdata->buffer->oidcreated;
1142 numlocked = localtdata->transinfo->numlocked;
1143 oidlocked = localtdata->transinfo->objlocked;
1145 for (i = 0; i < nummod; i++) {
1146 if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
1147 printf("Error: transComProcess() mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1150 /* Copy from transaction cache -> main object store */
1151 if ((tcptr = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidmod[i]))) == NULL) {
1152 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1155 GETSIZE(tmpsize, header);
1156 char *tmptcptr = (char *) tcptr;
1157 memcpy((char*)header+sizeof(objheader_t), (char *)tmptcptr+ sizeof(objheader_t), tmpsize);
1158 header->version += 1;
1159 if(header->notifylist != NULL) {
1160 notifyAll(&header->notifylist, OID(header), header->version);
1163 /* If object is newly created inside transaction then commit it */
1164 for (i = 0; i < numcreated; i++) {
1165 if ((header = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidcreated[i]))) == NULL) {
1166 printf("Error: transComProcess() chashSearch returned NULL for oid = %x at %s, %d\n", oidcreated[i], __FILE__, __LINE__);
1169 GETSIZE(tmpsize, header);
1170 tmpsize += sizeof(objheader_t);
1171 pthread_mutex_lock(&mainobjstore_mutex);
1172 if ((ptrcreate = objstrAlloc(mainobjstore, tmpsize)) == NULL) {
1173 printf("Error: transComProcess() failed objstrAlloc %s, %d\n", __FILE__, __LINE__);
1174 pthread_mutex_unlock(&mainobjstore_mutex);
1177 pthread_mutex_unlock(&mainobjstore_mutex);
1178 memcpy(ptrcreate, header, tmpsize);
1179 mhashInsert(oidcreated[i], ptrcreate);
1180 lhashInsert(oidcreated[i], myIpAddr);
1182 /* Unlock locked objects */
1183 for(i = 0; i < numlocked; i++) {
1184 if((header = (objheader_t *) mhashSearch(oidlocked[i])) == NULL) {
1185 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1188 UnLock(STATUSPTR(header));
1194 prefetchpile_t *foundLocal(char *ptr) {
1195 int siteid = *(GET_SITEID(ptr));
1196 int ntuples = *(GET_NTUPLES(ptr));
1197 unsigned int * oidarray = GET_PTR_OID(ptr);
1198 unsigned short * endoffsets = GET_PTR_EOFF(ptr, ntuples);
1199 short * arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1200 prefetchpile_t * head=NULL;
1204 for(i=0;i<ntuples; i++) {
1205 unsigned short baseindex=(i==0)?0:endoffsets[i-1];
1206 unsigned short endindex=endoffsets[i];
1207 unsigned int oid=oidarray[i];
1212 //Look up fields locally
1213 for(newbase=baseindex;newbase<endindex;newbase++) {
1214 if (!lookupObject(&oid, arryfields[newbase]))
1216 //Ended in a null pointer...
1220 //Entire prefetch is local
1221 if (newbase==endindex&&checkoid(oid)){
1225 //Add to remote requests
1226 machinenum=lhashSearch(oid);
1227 insertPile(machinenum, oid, endindex-newbase, &arryfields[newbase], &head);
1232 /* handle dynamic prefetching */
1233 handleDynPrefetching(numLocal, ntuples, siteid);
1237 int checkoid(unsigned int oid) {
1238 objheader_t *header;
1239 if ((header=mhashSearch(oid))!=NULL) {
1242 } else if ((header=prehashSearch(oid))!=NULL) {
1250 int lookupObject(unsigned int * oid, short offset) {
1251 objheader_t *header;
1252 if ((header=mhashSearch(*oid))!=NULL) {
1255 } else if ((header=prehashSearch(*oid))!=NULL) {
1262 if(TYPE(header) > NUMCLASSES) {
1263 int elementsize = classsize[TYPE(header)];
1264 struct ArrayObject *ao = (struct ArrayObject *) (((char *)header) + sizeof(objheader_t));
1265 int length = ao->___length___;
1266 /* Check if array out of bounds */
1267 if(offset < 0 || offset >= length) {
1268 //if yes treat the object as found
1272 (*oid) = *((unsigned int *)(((char *)ao) + sizeof(struct ArrayObject) + (elementsize*offset)));
1275 (*oid) = *((unsigned int *)(((char *)header) + sizeof(objheader_t) + offset));
1281 /* This function is called by the thread calling transPrefetch */
1282 void *transPrefetch(void *t) {
1284 /* lock mutex of primary prefetch queue */
1285 void *node=gettail();
1286 /* Check if the tuples are found locally, if yes then reduce them further*/
1287 /* and group requests by remote machine ids by calling the makePreGroups() */
1288 prefetchpile_t *pilehead = foundLocal(node);
1290 if (pilehead!=NULL) {
1291 // Get sock from shared pool
1292 int sd = getSock2(transPrefetchSockPool, pilehead->mid);
1294 /* Send Prefetch Request */
1295 prefetchpile_t *ptr = pilehead;
1296 while(ptr != NULL) {
1297 sendPrefetchReq(ptr, sd);
1301 /* Release socket */
1302 // freeSock(transPrefetchSockPool, pilehead->mid, sd);
1304 /* Deallocated pilehead */
1305 mcdealloc(pilehead);
1307 // Deallocate the prefetch queue pile node
1312 void sendPrefetchReqnew(prefetchpile_t *mcpilenode, int sd) {
1315 int size=sizeof(char)+sizeof(int);
1316 for(tmp=mcpilenode->objpiles;tmp!=NULL;tmp=tmp->next) {
1317 size += sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1322 *buf=TRANS_PREFETCH;
1325 for(tmp=mcpilenode->objpiles;tmp!=NULL;tmp=tmp->next) {
1326 int len = sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1329 *((unsigned int *)buf)=tmp->oid;
1330 buf+=sizeof(unsigned int);
1331 *((unsigned int *)(buf)) = myIpAddr;
1332 buf+=sizeof(unsigned int);
1333 memcpy(buf, tmp->offset, tmp->numoffset*sizeof(short));
1334 buf+=tmp->numoffset*sizeof(short);
1337 send_data(sd, buft, size);
1341 void sendPrefetchReq(prefetchpile_t *mcpilenode, int sd) {
1346 /* Send TRANS_PREFETCH control message */
1347 control = TRANS_PREFETCH;
1348 send_data(sd, &control, sizeof(char));
1350 /* Send Oids and offsets in pairs */
1351 tmp = mcpilenode->objpiles;
1352 while(tmp != NULL) {
1353 len = sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1354 char oidnoffset[len];
1355 char *buf=oidnoffset;
1356 *((int*)buf) = tmp->numoffset;
1358 *((unsigned int *)buf) = tmp->oid;
1359 buf+=sizeof(unsigned int);
1360 *((unsigned int *)buf) = myIpAddr;
1361 buf += sizeof(unsigned int);
1362 memcpy(buf, tmp->offset, (tmp->numoffset)*sizeof(short));
1363 send_data(sd, oidnoffset, len);
1367 /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
1369 send_data(sd, &endpair, sizeof(int));
1374 int getPrefetchResponse(int sd) {
1375 int length = 0, size = 0;
1378 void *modptr, *oldptr;
1380 recv_data((int)sd, &length, sizeof(int));
1381 size = length - sizeof(int);
1382 char recvbuffer[size];
1384 recv_data((int)sd, recvbuffer, size);
1385 control = *((char *) recvbuffer);
1386 if(control == OBJECT_FOUND) {
1387 oid = *((unsigned int *)(recvbuffer + sizeof(char)));
1388 size = size - (sizeof(char) + sizeof(unsigned int));
1389 pthread_mutex_lock(&prefetchcache_mutex);
1390 if ((modptr = prefetchobjstrAlloc(size)) == NULL) {
1391 printf("Error: objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
1392 pthread_mutex_unlock(&prefetchcache_mutex);
1395 pthread_mutex_unlock(&prefetchcache_mutex);
1396 memcpy(modptr, recvbuffer + sizeof(char) + sizeof(unsigned int), size);
1399 /* Insert the oid and its address into the prefetch hash lookup table */
1400 /* Do a version comparison if the oid exists */
1401 if((oldptr = prehashSearch(oid)) != NULL) {
1402 /* If older version then update with new object ptr */
1403 if(((objheader_t *)oldptr)->version <= ((objheader_t *)modptr)->version) {
1405 prehashInsert(oid, modptr);
1407 } else {/* Else add the object ptr to hash table*/
1408 prehashInsert(oid, modptr);
1410 /* Lock the Prefetch Cache look up table*/
1411 pthread_mutex_lock(&pflookup.lock);
1412 /* Broadcast signal on prefetch cache condition variable */
1413 pthread_cond_broadcast(&pflookup.cond);
1414 /* Unlock the Prefetch Cache look up table*/
1415 pthread_mutex_unlock(&pflookup.lock);
1416 } else if(control == OBJECT_NOT_FOUND) {
1417 oid = *((unsigned int *)(recvbuffer + sizeof(char)));
1418 /* TODO: For each object not found query DHT for new location and retrieve the object */
1419 /* Throw an error */
1420 //printf("OBJECT %x NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n", oid);
1423 printf("Error: in decoding the control value %d, %s, %d\n",control, __FILE__, __LINE__);
1429 unsigned short getObjType(unsigned int oid) {
1430 objheader_t *objheader;
1431 unsigned short numoffset[] ={0};
1432 short fieldoffset[] ={};
1434 if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL) {
1435 if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL) {
1436 unsigned int mid = lhashSearch(oid);
1437 int sd = getSock2(transReadSockPool, mid);
1438 char remotereadrequest[sizeof(char)+sizeof(unsigned int)];
1439 remotereadrequest[0] = READ_REQUEST;
1440 *((unsigned int *)(&remotereadrequest[1])) = oid;
1441 send_data(sd, remotereadrequest, sizeof(remotereadrequest));
1443 /* Read response from the Participant */
1445 recv_data(sd, &control, sizeof(char));
1447 if (control==OBJECT_NOT_FOUND) {
1448 printf("Error: in %s() THIS SHOULD NOT HAPPEN.....EXIT PROGRAM\n", __func__);
1452 /* Read object if found into local cache */
1454 recv_data(sd, &size, sizeof(int));
1455 pthread_mutex_lock(&prefetchcache_mutex);
1456 if ((objheader = prefetchobjstrAlloc(size)) == NULL) {
1457 printf("Error: %s() objstrAlloc error for copying into prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
1460 pthread_mutex_unlock(&prefetchcache_mutex);
1461 recv_data(sd, objheader, size);
1462 prehashInsert(oid, objheader);
1466 return TYPE(objheader);
1469 int startRemoteThread(unsigned int oid, unsigned int mid)
1472 struct sockaddr_in remoteAddr;
1473 char msg[1 + sizeof(unsigned int)];
1477 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
1479 perror("startRemoteThread():socket()");
1483 bzero(&remoteAddr, sizeof(remoteAddr));
1484 remoteAddr.sin_family = AF_INET;
1485 remoteAddr.sin_port = htons(LISTEN_PORT);
1486 remoteAddr.sin_addr.s_addr = htonl(mid);
1488 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0)
1490 printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
1491 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1496 msg[0] = START_REMOTE_THREAD;
1497 *((unsigned int *) &msg[1]) = oid;
1498 send_data(sock, msg, 1 + sizeof(unsigned int));
1505 //TODO: when reusing oids, make sure they are not already in use!
1506 static unsigned int id = 0xFFFFFFFF;
1507 unsigned int getNewOID(void) {
1509 if (id > oidMax || id < oidMin)
1516 int processConfigFile()
1519 const int maxLineLength = 200;
1520 char lineBuffer[maxLineLength];
1522 const char *delimiters = " \t\n";
1526 configFile = fopen(CONFIG_FILENAME, "r");
1527 if (configFile == NULL)
1529 printf("error opening %s:\n", CONFIG_FILENAME);
1534 numHostsInSystem = 0;
1535 sizeOfHostArray = 8;
1536 hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
1538 while(fgets(lineBuffer, maxLineLength, configFile) != NULL)
1540 commentBegin = strchr(lineBuffer, '#');
1541 if (commentBegin != NULL)
1542 *commentBegin = '\0';
1543 token = strtok(lineBuffer, delimiters);
1544 while (token != NULL)
1546 tmpAddr = inet_addr(token);
1547 if ((int)tmpAddr == -1)
1549 printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
1554 addHost(htonl(tmpAddr));
1555 token = strtok(NULL, delimiters);
1561 if (numHostsInSystem < 1)
1563 printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
1567 myIpAddr = getMyIpAddr("en1");
1569 myIpAddr = getMyIpAddr("eth0");
1571 myIndexInHostArray = findHost(myIpAddr);
1572 if (myIndexInHostArray == -1)
1574 printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
1577 oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
1578 oidMin = oidsPerBlock * myIndexInHostArray;
1579 if (myIndexInHostArray == numHostsInSystem - 1)
1580 oidMax = 0xFFFFFFFF;
1582 oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
1587 void addHost(unsigned int hostIp)
1589 unsigned int *tmpArray;
1591 if (findHost(hostIp) != -1)
1594 if (numHostsInSystem == sizeOfHostArray)
1596 tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
1597 memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
1599 hostIpAddrs = tmpArray;
1602 hostIpAddrs[numHostsInSystem++] = hostIp;
1607 int findHost(unsigned int hostIp)
1610 for (i = 0; i < numHostsInSystem; i++)
1611 if (hostIpAddrs[i] == hostIp)
1618 /* This function sends notification request per thread waiting on object(s) whose version
1620 int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int numoid) {
1622 objheader_t *objheader;
1623 struct sockaddr_in remoteAddr;
1624 char msg[1 + numoid * (sizeof(unsigned short) + sizeof(unsigned int)) + 3 * sizeof(unsigned int)];
1628 unsigned short version;
1629 unsigned int oid,mid;
1630 static unsigned int threadid = 0;
1631 pthread_mutex_t threadnotify = PTHREAD_MUTEX_INITIALIZER; //Lock and condition var for threadjoin and notification
1632 pthread_cond_t threadcond = PTHREAD_COND_INITIALIZER;
1633 notifydata_t *ndata;
1636 if((mid = lhashSearch(oid)) == 0) {
1637 printf("Error: %s() No such machine found for oid =%x\n",__func__, oid);
1641 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1642 perror("reqNotify():socket()");
1646 bzero(&remoteAddr, sizeof(remoteAddr));
1647 remoteAddr.sin_family = AF_INET;
1648 remoteAddr.sin_port = htons(LISTEN_PORT);
1649 remoteAddr.sin_addr.s_addr = htonl(mid);
1651 /* Generate unique threadid */
1654 /* Save threadid, numoid, oidarray, versionarray, pthread_cond_variable for later processing */
1655 if((ndata = calloc(1, sizeof(notifydata_t))) == NULL) {
1656 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
1659 ndata->numoid = numoid;
1660 ndata->threadid = threadid;
1661 ndata->oidarry = oidarry;
1662 ndata->versionarry = versionarry;
1663 ndata->threadcond = threadcond;
1664 ndata->threadnotify = threadnotify;
1665 if((status = notifyhashInsert(threadid, ndata)) != 0) {
1666 printf("reqNotify(): Insert into notify hash table not successful %s, %d\n", __FILE__, __LINE__);
1671 /* Send number of oids, oidarry, version array, machine id and threadid */
1672 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1673 printf("reqNotify():error %d connecting to %s:%d\n", errno,
1674 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1678 msg[0] = THREAD_NOTIFY_REQUEST;
1679 *((unsigned int *)(&msg[1])) = numoid;
1680 /* Send array of oids */
1681 size = sizeof(unsigned int);
1686 *((unsigned int *)(&msg[1] + size)) = oid;
1687 size += sizeof(unsigned int);
1692 /* Send array of version */
1696 version = versionarry[i];
1697 *((unsigned short *)(&msg[1] + size)) = version;
1698 size += sizeof(unsigned short);
1703 *((unsigned int *)(&msg[1] + size)) = myIpAddr;
1704 size += sizeof(unsigned int);
1705 *((unsigned int *)(&msg[1] + size)) = threadid;
1706 pthread_mutex_lock(&(ndata->threadnotify));
1707 size = 1 + numoid * (sizeof(unsigned int) + sizeof(unsigned short)) + 3 * sizeof(unsigned int);
1708 send_data(sock, msg, size);
1709 pthread_cond_wait(&(ndata->threadcond), &(ndata->threadnotify));
1710 pthread_mutex_unlock(&(ndata->threadnotify));
1713 pthread_cond_destroy(&threadcond);
1714 pthread_mutex_destroy(&threadnotify);
1720 void threadNotify(unsigned int oid, unsigned short version, unsigned int tid) {
1721 notifydata_t *ndata;
1722 int i, objIsFound = 0, index;
1725 //Look up the tid and call the corresponding pthread_cond_signal
1726 if((ndata = notifyhashSearch(tid)) == NULL) {
1727 printf("threadnotify(): No such threadid is present %s, %d\n", __FILE__, __LINE__);
1730 for(i = 0; i < ndata->numoid; i++) {
1731 if(ndata->oidarry[i] == oid){
1736 if(objIsFound == 0){
1737 printf("threadNotify(): Oid not found %s, %d\n", __FILE__, __LINE__);
1740 if(version <= ndata->versionarry[index]){
1741 printf("threadNotify(): New version %d has not changed since last version for oid = %d, %s, %d\n", version, oid, __FILE__, __LINE__);
1744 /* Clear from prefetch cache and free thread related data structure */
1745 if((ptr = prehashSearch(oid)) != NULL) {
1748 pthread_cond_signal(&(ndata->threadcond));
1755 int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) {
1758 struct sockaddr_in remoteAddr;
1759 char msg[1 + sizeof(unsigned short) + 2*sizeof(unsigned int)];
1760 int sock, status, size, bytesSent;
1762 while(*head != NULL) {
1765 //create a socket connection to that machine
1766 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1767 perror("notifyAll():socket()");
1771 bzero(&remoteAddr, sizeof(remoteAddr));
1772 remoteAddr.sin_family = AF_INET;
1773 remoteAddr.sin_port = htons(LISTEN_PORT);
1774 remoteAddr.sin_addr.s_addr = htonl(mid);
1775 //send Thread Notify response and threadid to that machine
1776 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1777 printf("notifyAll():error %d connecting to %s:%d\n", errno,
1778 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1782 bzero(msg, (1+sizeof(unsigned short) + 2*sizeof(unsigned int)));
1783 msg[0] = THREAD_NOTIFY_RESPONSE;
1784 *((unsigned int *)&msg[1]) = oid;
1785 size = sizeof(unsigned int);
1786 *((unsigned short *)(&msg[1]+ size)) = version;
1787 size+= sizeof(unsigned short);
1788 *((unsigned int *)(&msg[1]+ size)) = ptr->threadid;
1790 size = 1 + 2*sizeof(unsigned int) + sizeof(unsigned short);
1791 send_data(sock, msg, size);
1802 void transAbort(transrecord_t *trans) {
1803 objstrDelete(trans->cache);
1804 chashDelete(trans->lookupTable);
1808 /* This function inserts necessary information into
1809 * a machine pile data structure */
1810 plistnode_t *pInsert(plistnode_t *pile, objheader_t *headeraddr, unsigned int mid, int num_objs) {
1811 plistnode_t *ptr, *tmp;
1812 int found = 0, offset = 0;
1815 //Add oid into a machine that is already present in the pile linked list structure
1816 while(tmp != NULL) {
1817 if (tmp->mid == mid) {
1820 if (STATUS(headeraddr) & NEW) {
1821 tmp->oidcreated[tmp->numcreated] = OID(headeraddr);
1823 GETSIZE(tmpsize, headeraddr);
1824 tmp->sum_bytes += sizeof(objheader_t) + tmpsize;
1825 }else if (STATUS(headeraddr) & DIRTY) {
1826 tmp->oidmod[tmp->nummod] = OID(headeraddr);
1828 GETSIZE(tmpsize, headeraddr);
1829 tmp->sum_bytes += sizeof(objheader_t) + tmpsize;
1831 offset = (sizeof(unsigned int) + sizeof(short)) * tmp->numread;
1832 *((unsigned int *)(((char *)tmp->objread) + offset))=OID(headeraddr);
1833 offset += sizeof(unsigned int);
1834 *((short *)(((char *)tmp->objread) + offset)) = headeraddr->version;
1842 //Add oid for any new machine
1845 if((ptr = pCreate(num_objs)) == NULL) {
1849 if (STATUS(headeraddr) & NEW) {
1850 ptr->oidcreated[ptr->numcreated] = OID(headeraddr);
1852 GETSIZE(tmpsize, headeraddr);
1853 ptr->sum_bytes += sizeof(objheader_t) + tmpsize;
1854 } else if (STATUS(headeraddr) & DIRTY) {
1855 ptr->oidmod[ptr->nummod] = OID(headeraddr);
1857 GETSIZE(tmpsize, headeraddr);
1858 ptr->sum_bytes += sizeof(objheader_t) + tmpsize;
1860 *((unsigned int *)ptr->objread)=OID(headeraddr);
1861 offset = sizeof(unsigned int);
1862 *((short *)(((char *)ptr->objread) + offset)) = headeraddr->version;
1870 STATUS(headeraddr) =0;