4 #include "machinepile.h"
9 #include "threadnotify.h"
11 #include "addUdpEnhance.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 pthread_mutex_t notifymutex;
44 pthread_mutex_t atomicObjLock;
46 /***********************************
47 * Global Variables for statistics
48 **********************************/
49 int numTransCommit = 0;
50 int numTransAbort = 0;
52 void printhex(unsigned char *, int);
53 plistnode_t *createPiles(transrecord_t *);
55 /*******************************
56 * Send and Recv function calls
57 *******************************/
58 void send_data(int fd , void *buf, int buflen) {
59 char *buffer = (char *)(buf);
63 numbytes = send(fd, buffer, size, MSG_NOSIGNAL);
73 void recv_data(int fd , void *buf, int buflen) {
74 char *buffer = (char *)(buf);
78 numbytes = recv(fd, buffer, size, 0);
88 int recv_data_errorcode(int fd , void *buf, int buflen) {
89 char *buffer = (char *)(buf);
93 numbytes = recv(fd, buffer, size, 0);
106 void printhex(unsigned char *ptr, int numBytes) {
108 for (i = 0; i < numBytes; i++) {
110 printf("0%x ", ptr[i]);
112 printf("%x ", ptr[i]);
118 inline int arrayLength(int *array) {
120 for(i=0 ;array[i] != -1; i++)
125 inline int findmax(int *array, int arraylength) {
128 for(i = 0; i < arraylength; i++){
136 /* This function is a prefetch call generated by the compiler that
137 * populates the shared primary prefetch queue*/
138 void prefetch(int siteid, int ntuples, unsigned int *oids, unsigned short *endoffsets, short *arrayfields) {
139 /* Allocate for the queue node*/
140 int qnodesize = 2*sizeof(int) + ntuples * (sizeof(unsigned short) + sizeof(unsigned int)) + endoffsets[ntuples - 1] * sizeof(short);
141 char * node= getmemory(qnodesize);
142 /* Set queue node values */
144 int top=endoffsets[ntuples-1];
146 /* TODO: Remove this after testing */
147 evalPrefetch[siteid].callcount++;
149 *((int *)(node))=siteid;
150 *((int *)(node + sizeof(int))) = ntuples;
152 memcpy(node+len, oids, ntuples*sizeof(unsigned int));
153 memcpy(node+len+ntuples*sizeof(unsigned int), endoffsets, ntuples*sizeof(unsigned short));
154 memcpy(node+len+ntuples*(sizeof(unsigned int)+sizeof(short)), arrayfields, top*sizeof(short));
156 /* Lock and insert into primary prefetch queue */
160 /* This function starts up the transaction runtime. */
161 int dstmStartup(const char * option) {
162 pthread_t thread_Listen, udp_thread_Listen;
164 int master=option!=NULL && strcmp(option, "master")==0;
168 if (processConfigFile() != 0)
169 return 0; //TODO: return error value, cause main program to exit
176 printf("Trans stats is on\n");
180 //Initialize socket pool
181 transReadSockPool = createSockPool(transReadSockPool, 2*numHostsInSystem+1);
182 transPrefetchSockPool = createSockPool(transPrefetchSockPool, 2*numHostsInSystem+1);
189 pthread_create(&udp_thread_Listen, &attr, udpListenBroadcast, (void*)udpfd);
191 pthread_attr_init(&attr);
192 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
193 pthread_create(&thread_Listen, &attr, dstmListen, (void*)fd);
196 dstmListen((void *)fd);
201 //TODO Use this later
202 void *pCacheAlloc(objstr_t *store, unsigned int size) {
208 while(ptr->next != NULL) {
209 /* check if store is empty */
210 if(((unsigned int)ptr->top - (unsigned int)ptr - sizeof(objstr_t) + size) <= ptr->size) {
225 /* This function initiates the prefetch thread A queue is shared
226 * between the main thread of execution and the prefetch thread to
227 * process the prefetch call Call from compiler populates the shared
228 * queue with prefetch requests while prefetch thread processes the
229 * prefetch requests */
234 //Create and initialize prefetch cache structure
235 prefetchcache = objstrCreate(PREFETCH_CACHE_SIZE);
237 if((evalPrefetch = initPrefetchStats()) == NULL) {
238 printf("%s() Error allocating memory at %s, %d\n", __func__, __FILE__, __LINE__);
242 /* Initialize attributes for mutex */
243 pthread_mutexattr_init(&prefetchcache_mutex_attr);
244 pthread_mutexattr_settype(&prefetchcache_mutex_attr, PTHREAD_MUTEX_RECURSIVE_NP);
246 pthread_mutex_init(&prefetchcache_mutex, &prefetchcache_mutex_attr);
248 pthread_mutex_init(¬ifymutex, NULL);
249 pthread_mutex_init(&atomicObjLock, NULL);
250 //Create prefetch cache lookup table
251 if(prehashCreate(HASH_SIZE, LOADFACTOR)) {
256 //Initialize primary shared queue
258 //Initialize machine pile w/prefetch oids and offsets shared queue
261 //Create the primary prefetch thread
263 retval=pthread_create(&tPrefetch, NULL, transPrefetch, NULL);
265 pthread_detach(tPrefetch);
268 /* This function stops the threads spawned */
271 pthread_cancel(tPrefetch);
272 for(t = 0; t < NUM_THREADS; t++)
273 pthread_cancel(wthreads[t]);
278 /* This functions inserts randowm wait delays in the order of msec
279 * Mostly used when transaction commits retry*/
286 req.tv_nsec = (long)(1000000 + (t%10000000)); //1-11 msec
287 nanosleep(&req, NULL);
291 /* This function initializes things required in the transaction start*/
292 transrecord_t *transStart() {
294 if((tmp = calloc(1, sizeof(transrecord_t))) == NULL){
295 printf("%s() Calloc error at line %d, %s\n", __func__, __LINE__, __FILE__);
298 tmp->cache = objstrCreate(1048576);
299 tmp->lookupTable = chashCreate(HASH_SIZE, LOADFACTOR);
301 tmp->revertlist=NULL;
306 /* This function finds the location of the objects involved in a transaction
307 * and returns the pointer to the object if found in a remote location */
308 objheader_t *transRead(transrecord_t *record, unsigned int oid) {
309 unsigned int machinenumber;
310 objheader_t *tmp, *objheader;
311 objheader_t *objcopy;
319 if((objheader = (objheader_t *)chashSearch(record->lookupTable, oid)) != NULL){
320 /* Search local transaction cache */
322 return &objheader[1];
326 } else if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
327 /* Look up in machine lookup table and copy into cache*/
328 GETSIZE(size, objheader);
329 size += sizeof(objheader_t);
330 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
331 memcpy(objcopy, objheader, size);
332 /* Insert into cache's lookup table */
334 chashInsert(record->lookupTable, OID(objheader), objcopy);
340 } else if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) {
341 /* Look up in prefetch cache */
343 size+=sizeof(objheader_t);
344 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
345 memcpy(objcopy, tmp, size);
346 /* Insert into cache's lookup table */
347 chashInsert(record->lookupTable, OID(tmp), objcopy);
354 /* Get the object from the remote location */
355 if((machinenumber = lhashSearch(oid)) == 0) {
356 printf("Error: %s() No machine found for oid =% %s,%dx\n",__func__, machinenumber, __FILE__, __LINE__);
359 objcopy = getRemoteObj(record, machinenumber, oid);
361 if(objcopy == NULL) {
362 printf("Error: Object not found in Remote location %s, %d\n", __FILE__, __LINE__);
375 /* This function creates objects in the transaction record */
376 objheader_t *transCreateObj(transrecord_t *record, unsigned int size) {
377 objheader_t *tmp = (objheader_t *) objstrAlloc(record->cache, (sizeof(objheader_t) + size));
378 OID(tmp) = getNewOID();
382 chashInsert(record->lookupTable, OID(tmp), tmp);
385 return &tmp[1]; //want space after object header
391 /* This function creates machine piles based on all machines involved in a
392 * transaction commit request */
393 plistnode_t *createPiles(transrecord_t *record) {
395 plistnode_t *pile = NULL;
396 unsigned int machinenum;
397 objheader_t *headeraddr;
398 chashlistnode_t * ptr = record->lookupTable->table;
399 /* Represents number of bins in the chash table */
400 unsigned int size = record->lookupTable->size;
402 for(i = 0; i < size ; i++) {
403 chashlistnode_t * curr = &ptr[i];
404 /* Inner loop to traverse the linked list of the cache lookupTable */
405 while(curr != NULL) {
406 //if the first bin in hash table is empty
410 if ((headeraddr = chashSearch(record->lookupTable, curr->key)) == NULL) {
411 printf("Error: No such oid %s, %d\n", __FILE__, __LINE__);
415 //Get machine location for object id (and whether local or not)
416 if (STATUS(headeraddr) & NEW || (mhashSearch(curr->key) != NULL)) {
417 machinenum = myIpAddr;
418 } else if ((machinenum = lhashSearch(curr->key)) == 0) {
419 printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
423 //Make machine groups
424 pile = pInsert(pile, headeraddr, machinenum, record->lookupTable->numelements);
431 /* This function initiates the transaction commit process
432 * Spawns threads for each of the new connections with Participants
433 * and creates new piles by calling the createPiles(),
434 * Sends a transrequest() to each remote machines for objects found remotely
435 * and calls handleLocalReq() to process objects found locally */
436 int transCommit(transrecord_t *record) {
437 unsigned int tot_bytes_mod, *listmid;
438 plistnode_t *pile, *pile_ptr;
440 int pilecount, offset, threadnum, trecvcount;
442 char transid[TID_LEN];
443 trans_req_data_t *tosend;
444 trans_commit_data_t transinfo;
445 static int newtid = 0;
446 char treplyctrl, treplyretry; /* keeps track of the common response that needs to be sent */
447 thread_data_array_t *thread_data_array;
448 local_thread_data_array_t *ltdata;
456 thread_data_array = NULL;
459 /* Look through all the objects in the transaction record and make piles
460 * for each machine involved in the transaction*/
462 pile_ptr = pile = createPiles(record);
467 /* Create the packet to be sent in TRANS_REQUEST */
469 /* Count the number of participants */
470 pilecount = pCount(pile);
472 /* Create a list of machine ids(Participants) involved in transaction */
473 listmid = calloc(pilecount, sizeof(unsigned int));
474 pListMid(pile, listmid);
477 /* Initialize thread variables,
478 * Spawn a thread for each Participant involved in a transaction */
479 pthread_t thread[pilecount];
481 pthread_cond_t tcond;
482 pthread_mutex_t tlock;
483 pthread_mutex_t tlshrd;
485 thread_data_array = (thread_data_array_t *) calloc(pilecount, sizeof(thread_data_array_t));
487 ltdata = calloc(1, sizeof(local_thread_data_array_t));
489 thread_response_t rcvd_control_msg[pilecount]; /* Shared thread array that keeps track of responses of participants */
491 /* Initialize and set thread detach attribute */
492 pthread_attr_init(&attr);
493 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
494 pthread_mutex_init(&tlock, NULL);
495 pthread_cond_init(&tcond, NULL);
497 /* Process each machine pile */
498 while(pile != NULL) {
499 //Create transaction id
501 tosend = calloc(1, sizeof(trans_req_data_t));
502 tosend->f.control = TRANS_REQUEST;
503 sprintf(tosend->f.trans_id, "%x_%d", pile->mid, newtid);
504 tosend->f.mcount = pilecount;
505 tosend->f.numread = pile->numread;
506 tosend->f.nummod = pile->nummod;
507 tosend->f.numcreated = pile->numcreated;
508 tosend->f.sum_bytes = pile->sum_bytes;
509 tosend->listmid = listmid;
510 tosend->objread = pile->objread;
511 tosend->oidmod = pile->oidmod;
512 tosend->oidcreated = pile->oidcreated;
513 thread_data_array[threadnum].thread_id = threadnum;
514 thread_data_array[threadnum].mid = pile->mid;
515 thread_data_array[threadnum].buffer = tosend;
516 thread_data_array[threadnum].recvmsg = rcvd_control_msg;
517 thread_data_array[threadnum].threshold = &tcond;
518 thread_data_array[threadnum].lock = &tlock;
519 thread_data_array[threadnum].count = &trecvcount;
520 thread_data_array[threadnum].replyctrl = &treplyctrl;
521 thread_data_array[threadnum].replyretry = &treplyretry;
522 thread_data_array[threadnum].rec = record;
523 /* If local do not create any extra connection */
524 if(pile->mid != myIpAddr) { /* Not local */
526 rc = pthread_create(&thread[threadnum], &attr, transRequest, (void *) &thread_data_array[threadnum]);
529 perror("Error in pthread create\n");
530 pthread_cond_destroy(&tcond);
531 pthread_mutex_destroy(&tlock);
534 for (i = 0; i < threadnum; i++)
535 free(thread_data_array[i].buffer);
536 free(thread_data_array);
541 ltdata->tdata = &thread_data_array[threadnum];
542 ltdata->transinfo = &transinfo;
544 val = pthread_create(&thread[threadnum], &attr, handleLocalReq, (void *) ltdata);
547 perror("Error in pthread create\n");
548 pthread_cond_destroy(&tcond);
549 pthread_mutex_destroy(&tlock);
552 for (i = 0; i < threadnum; i++)
553 free(thread_data_array[i].buffer);
554 free(thread_data_array);
563 /* Free attribute and wait for the other threads */
564 pthread_attr_destroy(&attr);
566 for (i = 0; i < threadnum; i++) {
567 rc = pthread_join(thread[i], NULL);
570 printf("Error: return code from pthread_join() is %d\n", rc);
571 pthread_cond_destroy(&tcond);
572 pthread_mutex_destroy(&tlock);
575 for (j = i; j < threadnum; j++) {
576 free(thread_data_array[j].buffer);
580 free(thread_data_array[i].buffer);
584 pthread_cond_destroy(&tcond);
585 pthread_mutex_destroy(&tlock);
591 /* wait a random amount of time before retrying to commit transaction*/
593 free(thread_data_array);
598 /* Retry trans commit procedure during soft_abort case */
599 } while (treplyretry);
601 if(treplyctrl == TRANS_ABORT) {
606 objstrDelete(record->cache);
607 chashDelete(record->lookupTable);
609 free(thread_data_array);
612 } else if(treplyctrl == TRANS_COMMIT) {
617 objstrDelete(record->cache);
618 chashDelete(record->lookupTable);
620 free(thread_data_array);
624 //TODO Add other cases
625 printf("Error: in %s() THIS SHOULD NOT HAPPEN.....EXIT PROGRAM\n", __func__);
631 /* This function sends information involved in the transaction request
632 * to participants and accepts a response from particpants.
633 * It calls decideresponse() to decide on what control message
634 * to send next to participants and sends the message using sendResponse()*/
635 void *transRequest(void *threadarg) {
637 struct sockaddr_in serv_addr;
638 thread_data_array_t *tdata;
639 objheader_t *headeraddr;
640 char control, recvcontrol;
641 char machineip[16], retval;
643 tdata = (thread_data_array_t *) threadarg;
645 /* Send Trans Request */
646 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) <= 0) {
647 printf("transRequest():error %d\n", errno);
648 perror("transRequest() socket error");
651 bzero((char*) &serv_addr, sizeof(serv_addr));
652 serv_addr.sin_family = AF_INET;
653 serv_addr.sin_port = htons(LISTEN_PORT);
654 serv_addr.sin_addr.s_addr = htonl(tdata->mid);
656 /* Open Connection */
657 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
658 printf("transRequest():error %d, sd= %d\n", errno, sd);
659 perror("transRequest() connect");
664 /* Send bytes of data with TRANS_REQUEST control message */
665 send_data(sd, &(tdata->buffer->f), sizeof(fixed_data_t));
667 /* Send list of machines involved in the transaction */
669 int size=sizeof(unsigned int)*tdata->buffer->f.mcount;
670 send_data(sd, tdata->buffer->listmid, size);
673 /* Send oids and version number tuples for objects that are read */
675 int size=(sizeof(unsigned int)+sizeof(unsigned short))*tdata->buffer->f.numread;
676 send_data(sd, tdata->buffer->objread, size);
679 /* Send objects that are modified */
680 for(i = 0; i < tdata->buffer->f.nummod ; i++) {
682 headeraddr = chashSearch(tdata->rec->lookupTable, tdata->buffer->oidmod[i]);
683 GETSIZE(size,headeraddr);
684 size+=sizeof(objheader_t);
685 send_data(sd, headeraddr, size);
688 /* Read control message from Participant */
689 recv_data(sd, &control, sizeof(char));
690 /* Recv Objects if participant sends TRANS_DISAGREE */
691 if(control == TRANS_DISAGREE) {
693 recv_data(sd, &length, sizeof(int));
695 pthread_mutex_lock(&prefetchcache_mutex);
696 if ((newAddr = prefetchobjstrAlloc((unsigned int)length)) == NULL) {
697 printf("Error: %s() objstrAlloc error for copying into prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
701 pthread_mutex_unlock(&prefetchcache_mutex);
702 recv_data(sd, newAddr, length);
705 unsigned int oidToPrefetch;
706 objheader_t * header;
707 header = (objheader_t *) (((char *)newAddr) + offset);
708 oidToPrefetch = OID(header);
710 GETSIZE(size, header);
711 size += sizeof(objheader_t);
712 //make an entry in prefetch hash table
714 if((oldptr = prehashSearch(oidToPrefetch)) != NULL) {
715 prehashRemove(oidToPrefetch);
716 prehashInsert(oidToPrefetch, header);
718 prehashInsert(oidToPrefetch, header);
720 length = length - size;
724 recvcontrol = control;
725 /* Update common data structure and increment count */
726 tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol;
728 /* Lock and update count */
729 /* Thread sleeps until all messages from pariticipants are received by coordinator */
730 pthread_mutex_lock(tdata->lock);
732 (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */
734 /* Wake up the threads and invoke decideResponse (once) */
735 if(*(tdata->count) == tdata->buffer->f.mcount) {
736 decideResponse(tdata);
737 pthread_cond_broadcast(tdata->threshold);
739 pthread_cond_wait(tdata->threshold, tdata->lock);
741 pthread_mutex_unlock(tdata->lock);
743 /* Send the final response such as TRANS_COMMIT or TRANS_ABORT
744 * to all participants in their respective socket */
745 if (sendResponse(tdata, sd) == 0) {
746 printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__);
751 recv_data((int)sd, &control, sizeof(char));
753 if(control == TRANS_UNSUCESSFUL) {
754 //printf("DEBUG-> TRANS_ABORTED\n");
755 } else if(control == TRANS_SUCESSFUL) {
756 //printf("DEBUG-> TRANS_SUCCESSFUL\n");
758 //printf("DEBUG-> Error: Incorrect Transaction End Message %d\n", control);
761 /* Close connection */
766 /* This function decides the reponse that needs to be sent to
767 * all Participant machines after the TRANS_REQUEST protocol */
768 void decideResponse(thread_data_array_t *tdata) {
770 int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
773 for (i = 0 ; i < tdata->buffer->f.mcount; i++) {
774 control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses
775 written onto the shared array */
778 printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
779 /* treat as disagree, pass thru */
788 case TRANS_SOFT_ABORT:
794 if(transdisagree > 0) {
796 *(tdata->replyctrl) = TRANS_ABORT;
797 *(tdata->replyretry) = 0;
798 /* clear objects from prefetch cache */
799 for (i = 0; i < tdata->buffer->f.numread; i++) {
800 prehashRemove(*((unsigned int *)(((char *)tdata->buffer->objread) + (sizeof(unsigned int) + sizeof(unsigned short))*i)));
802 for (i = 0; i < tdata->buffer->f.nummod; i++) {
803 prehashRemove(tdata->buffer->oidmod[i]);
805 } else if(transagree == tdata->buffer->f.mcount){
807 *(tdata->replyctrl) = TRANS_COMMIT;
808 *(tdata->replyretry) = 0;
809 /* update prefetch cache */
810 /* For objects read */
814 if((retval = updatePrefetchCache(tdata, tdata->buffer->f.numread, oidType)) != 0) {
815 printf("Error: %s() in updating prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
819 if((retval = updatePrefetchCache(tdata, tdata->buffer->f.nummod, oidType)) != 0) {
820 printf("Error: %s() in updating prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
823 /* Invalidate objects in other machine cache */
824 if(tdata->buffer->f.nummod > 0) {
825 if((retval = invalidateObj(tdata)) != 0) {
826 printf("Error: %s() in invalidating Objects %s, %d\n", __func__, __FILE__, __LINE__);
831 /* Send Abort in soft abort case followed by retry commiting transaction again*/
832 *(tdata->replyctrl) = TRANS_ABORT;
833 *(tdata->replyretry) = 1;
838 /* This function updates the prefetch cache when commiting objects
839 * based on the type of oid i.e. if oid is read or oid is modified
840 * Return -1 on error else returns 0
842 int updatePrefetchCache(thread_data_array_t* tdata, int numoid, char oidType) {
844 for (i = 0; i < numoid; i++) {
845 //find address object
846 objheader_t *header, *newAddr;
850 oid = *((unsigned int *)(tdata->buffer->objread + (sizeof(unsigned int) + sizeof(unsigned short))*i));
852 oid = tdata->buffer->oidmod[i];
854 pthread_mutex_lock(&prefetchcache_mutex);
855 header = (objheader_t *) chashSearch(tdata->rec->lookupTable, oid);
856 //copy object into prefetch cache
857 GETSIZE(size, header);
858 if ((newAddr = prefetchobjstrAlloc(size + sizeof(objheader_t))) == NULL) {
859 printf("Error: %s() objstrAlloc error for copying into prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
860 pthread_mutex_unlock(&prefetchcache_mutex);
863 pthread_mutex_unlock(&prefetchcache_mutex);
864 memcpy(newAddr, header, (size + sizeof(objheader_t)));
865 //make an entry in prefetch hash table
867 if((oldptr = prehashSearch(oid)) != NULL) {
869 prehashInsert(oid, newAddr);
871 prehashInsert(oid, newAddr);
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 %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;
1004 /* Save all object oids that are locked on this machine during this transaction request call */
1005 oidlocked[numoidlocked] = OID(((objheader_t *)mobj));
1007 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
1009 } else { /* If versions don't match ...HARD ABORT */
1011 /* Send TRANS_DISAGREE to Coordinator */
1012 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
1017 /* Condition to send TRANS_AGREE */
1018 if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
1019 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
1021 /* Condition to send TRANS_SOFT_ABORT */
1022 if((v_matchlock > 0 && v_nomatch == 0) || (numoidnotfound > 0 && v_nomatch == 0)) {
1023 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
1026 /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
1027 * if Participant receives a TRANS_COMMIT */
1028 localtdata->transinfo->objlocked = oidlocked;
1029 localtdata->transinfo->objnotfound = oidnotfound;
1030 localtdata->transinfo->modptr = NULL;
1031 localtdata->transinfo->numlocked = numoidlocked;
1032 localtdata->transinfo->numnotfound = numoidnotfound;
1033 /* Lock and update count */
1034 //Thread sleeps until all messages from pariticipants are received by coordinator
1035 pthread_mutex_lock(localtdata->tdata->lock);
1036 (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */
1038 /* Wake up the threads and invoke decideResponse (once) */
1039 if(*(localtdata->tdata->count) == localtdata->tdata->buffer->f.mcount) {
1040 decideResponse(localtdata->tdata);
1041 pthread_cond_broadcast(localtdata->tdata->threshold);
1043 pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock);
1045 pthread_mutex_unlock(localtdata->tdata->lock);
1046 if(*(localtdata->tdata->replyctrl) == TRANS_ABORT){
1047 if(transAbortProcess(localtdata) != 0) {
1048 printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
1051 } else if(*(localtdata->tdata->replyctrl) == TRANS_COMMIT) {
1052 if(transComProcess(localtdata) != 0) {
1053 printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
1058 if (localtdata->transinfo->objlocked != NULL) {
1059 free(localtdata->transinfo->objlocked);
1061 if (localtdata->transinfo->objnotfound != NULL) {
1062 free(localtdata->transinfo->objnotfound);
1068 /* This function completes the ABORT process if the transaction is aborting */
1069 int transAbortProcess(local_thread_data_array_t *localtdata) {
1071 unsigned int *objlocked;
1074 numlocked = localtdata->transinfo->numlocked;
1075 objlocked = localtdata->transinfo->objlocked;
1077 for (i = 0; i < numlocked; i++) {
1078 if((header = mhashSearch(objlocked[i])) == NULL) {
1079 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1082 UnLock(STATUSPTR(header));
1088 /*This function completes the COMMIT process is the transaction is commiting*/
1089 int transComProcess(local_thread_data_array_t *localtdata) {
1090 objheader_t *header, *tcptr;
1091 int i, nummod, tmpsize, numcreated, numlocked;
1092 unsigned int *oidmod, *oidcreated, *oidlocked;
1095 nummod = localtdata->tdata->buffer->f.nummod;
1096 oidmod = localtdata->tdata->buffer->oidmod;
1097 numcreated = localtdata->tdata->buffer->f.numcreated;
1098 oidcreated = localtdata->tdata->buffer->oidcreated;
1099 numlocked = localtdata->transinfo->numlocked;
1100 oidlocked = localtdata->transinfo->objlocked;
1102 for (i = 0; i < nummod; i++) {
1103 if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
1104 printf("Error: transComProcess() mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1107 /* Copy from transaction cache -> main object store */
1108 if ((tcptr = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidmod[i]))) == NULL) {
1109 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1112 GETSIZE(tmpsize, header);
1113 char *tmptcptr = (char *) tcptr;
1114 memcpy((char*)header+sizeof(objheader_t), (char *)tmptcptr+ sizeof(objheader_t), tmpsize);
1115 header->version += 1;
1116 if(header->notifylist != NULL) {
1117 notifyAll(&header->notifylist, OID(header), header->version);
1120 /* If object is newly created inside transaction then commit it */
1121 for (i = 0; i < numcreated; i++) {
1122 if ((header = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidcreated[i]))) == NULL) {
1123 printf("Error: transComProcess() chashSearch returned NULL for oid = %x at %s, %d\n", oidcreated[i], __FILE__, __LINE__);
1126 GETSIZE(tmpsize, header);
1127 tmpsize += sizeof(objheader_t);
1128 pthread_mutex_lock(&mainobjstore_mutex);
1129 if ((ptrcreate = objstrAlloc(mainobjstore, tmpsize)) == NULL) {
1130 printf("Error: transComProcess() failed objstrAlloc %s, %d\n", __FILE__, __LINE__);
1131 pthread_mutex_unlock(&mainobjstore_mutex);
1134 pthread_mutex_unlock(&mainobjstore_mutex);
1135 memcpy(ptrcreate, header, tmpsize);
1136 mhashInsert(oidcreated[i], ptrcreate);
1137 lhashInsert(oidcreated[i], myIpAddr);
1139 /* Unlock locked objects */
1140 for(i = 0; i < numlocked; i++) {
1141 if((header = (objheader_t *) mhashSearch(oidlocked[i])) == NULL) {
1142 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1145 UnLock(STATUSPTR(header));
1151 prefetchpile_t *foundLocal(char *ptr) {
1152 int siteid = *(GET_SITEID(ptr));
1153 int ntuples = *(GET_NTUPLES(ptr));
1154 unsigned int * oidarray = GET_PTR_OID(ptr);
1155 unsigned short * endoffsets = GET_PTR_EOFF(ptr, ntuples);
1156 short * arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1157 prefetchpile_t * head=NULL;
1161 for(i=0;i<ntuples; i++) {
1162 unsigned short baseindex=(i==0)?0:endoffsets[i-1];
1163 unsigned short endindex=endoffsets[i];
1164 unsigned int oid=oidarray[i];
1169 //Look up fields locally
1170 for(newbase=baseindex;newbase<endindex;newbase++) {
1171 if (!lookupObject(&oid, arryfields[newbase]))
1173 //Ended in a null pointer...
1177 //Entire prefetch is local
1178 if (newbase==endindex&&checkoid(oid)){
1182 //Add to remote requests
1183 machinenum=lhashSearch(oid);
1184 insertPile(machinenum, oid, endindex-newbase, &arryfields[newbase], &head);
1189 /* handle dynamic prefetching */
1190 handleDynPrefetching(numLocal, ntuples, siteid);
1194 int checkoid(unsigned int oid) {
1195 objheader_t *header;
1196 if ((header=mhashSearch(oid))!=NULL) {
1199 } else if ((header=prehashSearch(oid))!=NULL) {
1207 int lookupObject(unsigned int * oid, short offset) {
1208 objheader_t *header;
1209 if ((header=mhashSearch(*oid))!=NULL) {
1212 } else if ((header=prehashSearch(*oid))!=NULL) {
1219 if(TYPE(header) > NUMCLASSES) {
1220 int elementsize = classsize[TYPE(header)];
1221 struct ArrayObject *ao = (struct ArrayObject *) (((char *)header) + sizeof(objheader_t));
1222 int length = ao->___length___;
1223 /* Check if array out of bounds */
1224 if(offset < 0 || offset >= length) {
1225 //if yes treat the object as found
1229 (*oid) = *((unsigned int *)(((char *)ao) + sizeof(struct ArrayObject) + (elementsize*offset)));
1232 (*oid) = *((unsigned int *)(((char *)header) + sizeof(objheader_t) + offset));
1238 /* This function is called by the thread calling transPrefetch */
1239 void *transPrefetch(void *t) {
1241 /* lock mutex of primary prefetch queue */
1242 void *node=gettail();
1243 /* Check if the tuples are found locally, if yes then reduce them further*/
1244 /* and group requests by remote machine ids by calling the makePreGroups() */
1245 prefetchpile_t *pilehead = foundLocal(node);
1247 if (pilehead!=NULL) {
1248 // Get sock from shared pool
1249 int sd = getSock2(transPrefetchSockPool, pilehead->mid);
1251 /* Send Prefetch Request */
1252 prefetchpile_t *ptr = pilehead;
1253 while(ptr != NULL) {
1254 sendPrefetchReq(ptr, sd);
1258 /* Release socket */
1259 // freeSock(transPrefetchSockPool, pilehead->mid, sd);
1261 /* Deallocated pilehead */
1262 mcdealloc(pilehead);
1264 // Deallocate the prefetch queue pile node
1269 void sendPrefetchReqnew(prefetchpile_t *mcpilenode, int sd) {
1272 int size=sizeof(char)+sizeof(int);
1273 for(tmp=mcpilenode->objpiles;tmp!=NULL;tmp=tmp->next) {
1274 size += sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1279 *buf=TRANS_PREFETCH;
1282 for(tmp=mcpilenode->objpiles;tmp!=NULL;tmp=tmp->next) {
1283 int len = sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1286 *((unsigned int *)buf)=tmp->oid;
1287 buf+=sizeof(unsigned int);
1288 *((unsigned int *)(buf)) = myIpAddr;
1289 buf+=sizeof(unsigned int);
1290 memcpy(buf, tmp->offset, tmp->numoffset*sizeof(short));
1291 buf+=tmp->numoffset*sizeof(short);
1294 send_data(sd, buft, size);
1298 void sendPrefetchReq(prefetchpile_t *mcpilenode, int sd) {
1303 /* Send TRANS_PREFETCH control message */
1304 control = TRANS_PREFETCH;
1305 send_data(sd, &control, sizeof(char));
1307 /* Send Oids and offsets in pairs */
1308 tmp = mcpilenode->objpiles;
1309 while(tmp != NULL) {
1310 len = sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1311 char oidnoffset[len];
1312 char *buf=oidnoffset;
1313 *((int*)buf) = tmp->numoffset;
1315 *((unsigned int *)buf) = tmp->oid;
1316 buf+=sizeof(unsigned int);
1317 *((unsigned int *)buf) = myIpAddr;
1318 buf += sizeof(unsigned int);
1319 memcpy(buf, tmp->offset, (tmp->numoffset)*sizeof(short));
1320 send_data(sd, oidnoffset, len);
1324 /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
1326 send_data(sd, &endpair, sizeof(int));
1331 int getPrefetchResponse(int sd) {
1332 int length = 0, size = 0;
1335 void *modptr, *oldptr;
1337 recv_data((int)sd, &length, sizeof(int));
1338 size = length - sizeof(int);
1339 char recvbuffer[size];
1341 recv_data((int)sd, recvbuffer, size);
1342 control = *((char *) recvbuffer);
1343 if(control == OBJECT_FOUND) {
1344 oid = *((unsigned int *)(recvbuffer + sizeof(char)));
1345 size = size - (sizeof(char) + sizeof(unsigned int));
1346 pthread_mutex_lock(&prefetchcache_mutex);
1347 if ((modptr = prefetchobjstrAlloc(size)) == NULL) {
1348 printf("Error: objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
1349 pthread_mutex_unlock(&prefetchcache_mutex);
1352 pthread_mutex_unlock(&prefetchcache_mutex);
1353 memcpy(modptr, recvbuffer + sizeof(char) + sizeof(unsigned int), size);
1356 /* Insert the oid and its address into the prefetch hash lookup table */
1357 /* Do a version comparison if the oid exists */
1358 if((oldptr = prehashSearch(oid)) != NULL) {
1359 /* If older version then update with new object ptr */
1360 if(((objheader_t *)oldptr)->version <= ((objheader_t *)modptr)->version) {
1362 prehashInsert(oid, modptr);
1364 } else {/* Else add the object ptr to hash table*/
1365 prehashInsert(oid, modptr);
1367 /* Lock the Prefetch Cache look up table*/
1368 pthread_mutex_lock(&pflookup.lock);
1369 /* Broadcast signal on prefetch cache condition variable */
1370 pthread_cond_broadcast(&pflookup.cond);
1371 /* Unlock the Prefetch Cache look up table*/
1372 pthread_mutex_unlock(&pflookup.lock);
1373 } else if(control == OBJECT_NOT_FOUND) {
1374 oid = *((unsigned int *)(recvbuffer + sizeof(char)));
1375 /* TODO: For each object not found query DHT for new location and retrieve the object */
1376 /* Throw an error */
1377 printf("OBJECT %x NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n", oid);
1380 printf("Error: in decoding the control value %d, %s, %d\n",control, __FILE__, __LINE__);
1386 unsigned short getObjType(unsigned int oid) {
1387 objheader_t *objheader;
1388 unsigned short numoffset[] ={0};
1389 short fieldoffset[] ={};
1391 if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL) {
1392 if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL) {
1393 prefetch(0, 1, &oid, numoffset, fieldoffset);
1394 pthread_mutex_lock(&pflookup.lock);
1395 while ((objheader = (objheader_t *) prehashSearch(oid)) == NULL) {
1396 pthread_cond_wait(&pflookup.cond, &pflookup.lock);
1398 pthread_mutex_unlock(&pflookup.lock);
1402 return TYPE(objheader);
1405 int startRemoteThread(unsigned int oid, unsigned int mid)
1408 struct sockaddr_in remoteAddr;
1409 char msg[1 + sizeof(unsigned int)];
1413 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
1415 perror("startRemoteThread():socket()");
1419 bzero(&remoteAddr, sizeof(remoteAddr));
1420 remoteAddr.sin_family = AF_INET;
1421 remoteAddr.sin_port = htons(LISTEN_PORT);
1422 remoteAddr.sin_addr.s_addr = htonl(mid);
1424 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0)
1426 printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
1427 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1432 msg[0] = START_REMOTE_THREAD;
1433 *((unsigned int *) &msg[1]) = oid;
1434 send_data(sock, msg, 1 + sizeof(unsigned int));
1441 //TODO: when reusing oids, make sure they are not already in use!
1442 static unsigned int id = 0xFFFFFFFF;
1443 unsigned int getNewOID(void) {
1445 if (id > oidMax || id < oidMin)
1452 int processConfigFile()
1455 const int maxLineLength = 200;
1456 char lineBuffer[maxLineLength];
1458 const char *delimiters = " \t\n";
1462 configFile = fopen(CONFIG_FILENAME, "r");
1463 if (configFile == NULL)
1465 printf("error opening %s:\n", CONFIG_FILENAME);
1470 numHostsInSystem = 0;
1471 sizeOfHostArray = 8;
1472 hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
1474 while(fgets(lineBuffer, maxLineLength, configFile) != NULL)
1476 commentBegin = strchr(lineBuffer, '#');
1477 if (commentBegin != NULL)
1478 *commentBegin = '\0';
1479 token = strtok(lineBuffer, delimiters);
1480 while (token != NULL)
1482 tmpAddr = inet_addr(token);
1483 if ((int)tmpAddr == -1)
1485 printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
1490 addHost(htonl(tmpAddr));
1491 token = strtok(NULL, delimiters);
1497 if (numHostsInSystem < 1)
1499 printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
1503 myIpAddr = getMyIpAddr("en1");
1505 myIpAddr = getMyIpAddr("eth0");
1507 myIndexInHostArray = findHost(myIpAddr);
1508 if (myIndexInHostArray == -1)
1510 printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
1513 oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
1514 oidMin = oidsPerBlock * myIndexInHostArray;
1515 if (myIndexInHostArray == numHostsInSystem - 1)
1516 oidMax = 0xFFFFFFFF;
1518 oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
1523 void addHost(unsigned int hostIp)
1525 unsigned int *tmpArray;
1527 if (findHost(hostIp) != -1)
1530 if (numHostsInSystem == sizeOfHostArray)
1532 tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
1533 memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
1535 hostIpAddrs = tmpArray;
1538 hostIpAddrs[numHostsInSystem++] = hostIp;
1543 int findHost(unsigned int hostIp)
1546 for (i = 0; i < numHostsInSystem; i++)
1547 if (hostIpAddrs[i] == hostIp)
1554 /* This function sends notification request per thread waiting on object(s) whose version
1556 int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int numoid) {
1558 objheader_t *objheader;
1559 struct sockaddr_in remoteAddr;
1560 char msg[1 + numoid * (sizeof(unsigned short) + sizeof(unsigned int)) + 3 * sizeof(unsigned int)];
1564 unsigned short version;
1565 unsigned int oid,mid;
1566 static unsigned int threadid = 0;
1567 pthread_mutex_t threadnotify = PTHREAD_MUTEX_INITIALIZER; //Lock and condition var for threadjoin and notification
1568 pthread_cond_t threadcond = PTHREAD_COND_INITIALIZER;
1569 notifydata_t *ndata;
1572 if((mid = lhashSearch(oid)) == 0) {
1573 printf("Error: %s() No such machine found for oid =%x\n",__func__, oid);
1577 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1578 perror("reqNotify():socket()");
1582 bzero(&remoteAddr, sizeof(remoteAddr));
1583 remoteAddr.sin_family = AF_INET;
1584 remoteAddr.sin_port = htons(LISTEN_PORT);
1585 remoteAddr.sin_addr.s_addr = htonl(mid);
1587 /* Generate unique threadid */
1590 /* Save threadid, numoid, oidarray, versionarray, pthread_cond_variable for later processing */
1591 if((ndata = calloc(1, sizeof(notifydata_t))) == NULL) {
1592 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
1595 ndata->numoid = numoid;
1596 ndata->threadid = threadid;
1597 ndata->oidarry = oidarry;
1598 ndata->versionarry = versionarry;
1599 ndata->threadcond = threadcond;
1600 ndata->threadnotify = threadnotify;
1601 if((status = notifyhashInsert(threadid, ndata)) != 0) {
1602 printf("reqNotify(): Insert into notify hash table not successful %s, %d\n", __FILE__, __LINE__);
1607 /* Send number of oids, oidarry, version array, machine id and threadid */
1608 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1609 printf("reqNotify():error %d connecting to %s:%d\n", errno,
1610 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1614 msg[0] = THREAD_NOTIFY_REQUEST;
1615 *((unsigned int *)(&msg[1])) = numoid;
1616 /* Send array of oids */
1617 size = sizeof(unsigned int);
1622 *((unsigned int *)(&msg[1] + size)) = oid;
1623 size += sizeof(unsigned int);
1628 /* Send array of version */
1632 version = versionarry[i];
1633 *((unsigned short *)(&msg[1] + size)) = version;
1634 size += sizeof(unsigned short);
1639 *((unsigned int *)(&msg[1] + size)) = myIpAddr;
1640 size += sizeof(unsigned int);
1641 *((unsigned int *)(&msg[1] + size)) = threadid;
1642 pthread_mutex_lock(&(ndata->threadnotify));
1643 size = 1 + numoid * (sizeof(unsigned int) + sizeof(unsigned short)) + 3 * sizeof(unsigned int);
1644 send_data(sock, msg, size);
1645 pthread_cond_wait(&(ndata->threadcond), &(ndata->threadnotify));
1646 pthread_mutex_unlock(&(ndata->threadnotify));
1649 pthread_cond_destroy(&threadcond);
1650 pthread_mutex_destroy(&threadnotify);
1656 void threadNotify(unsigned int oid, unsigned short version, unsigned int tid) {
1657 notifydata_t *ndata;
1658 int i, objIsFound = 0, index;
1661 //Look up the tid and call the corresponding pthread_cond_signal
1662 if((ndata = notifyhashSearch(tid)) == NULL) {
1663 printf("threadnotify(): No such threadid is present %s, %d\n", __FILE__, __LINE__);
1666 for(i = 0; i < ndata->numoid; i++) {
1667 if(ndata->oidarry[i] == oid){
1672 if(objIsFound == 0){
1673 printf("threadNotify(): Oid not found %s, %d\n", __FILE__, __LINE__);
1676 if(version <= ndata->versionarry[index]){
1677 printf("threadNotify(): New version %d has not changed since last version %s, %d\n", version, __FILE__, __LINE__);
1680 /* Clear from prefetch cache and free thread related data structure */
1681 if((ptr = prehashSearch(oid)) != NULL) {
1684 pthread_cond_signal(&(ndata->threadcond));
1691 int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) {
1694 struct sockaddr_in remoteAddr;
1695 char msg[1 + sizeof(unsigned short) + 2*sizeof(unsigned int)];
1696 int sock, status, size, bytesSent;
1698 while(*head != NULL) {
1701 //create a socket connection to that machine
1702 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1703 perror("notifyAll():socket()");
1707 bzero(&remoteAddr, sizeof(remoteAddr));
1708 remoteAddr.sin_family = AF_INET;
1709 remoteAddr.sin_port = htons(LISTEN_PORT);
1710 remoteAddr.sin_addr.s_addr = htonl(mid);
1711 //send Thread Notify response and threadid to that machine
1712 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1713 printf("notifyAll():error %d connecting to %s:%d\n", errno,
1714 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1718 bzero(msg, (1+sizeof(unsigned short) + 2*sizeof(unsigned int)));
1719 msg[0] = THREAD_NOTIFY_RESPONSE;
1720 *((unsigned int *)&msg[1]) = oid;
1721 size = sizeof(unsigned int);
1722 *((unsigned short *)(&msg[1]+ size)) = version;
1723 size+= sizeof(unsigned short);
1724 *((unsigned int *)(&msg[1]+ size)) = ptr->threadid;
1726 size = 1 + 2*sizeof(unsigned int) + sizeof(unsigned short);
1727 send_data(sock, msg, size);
1738 void transAbort(transrecord_t *trans) {
1739 objstrDelete(trans->cache);
1740 chashDelete(trans->lookupTable);