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 header->version += 1;
857 //copy object into prefetch cache
858 GETSIZE(size, header);
859 if ((newAddr = prefetchobjstrAlloc(size + sizeof(objheader_t))) == NULL) {
860 printf("Error: %s() objstrAlloc error for copying into prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
861 pthread_mutex_unlock(&prefetchcache_mutex);
864 pthread_mutex_unlock(&prefetchcache_mutex);
865 memcpy(newAddr, header, (size + sizeof(objheader_t)));
866 //make an entry in prefetch hash table
868 if((oldptr = prehashSearch(oid)) != NULL) {
870 prehashInsert(oid, newAddr);
872 prehashInsert(oid, newAddr);
879 /* This function sends the final response to remote machines per
880 * thread in their respective socket id It returns a char that is only
881 * needed to check the correctness of execution of this function
882 * inside transRequest()*/
884 char sendResponse(thread_data_array_t *tdata, int sd) {
885 int n, size, sum, oidcount = 0, control;
886 char *ptr, retval = 0;
887 unsigned int *oidnotfound;
889 control = *(tdata->replyctrl);
890 send_data(sd, &control, sizeof(char));
892 //TODO read missing objects during object migration
893 /* If response is a soft abort due to missing objects at the
894 Participant's side */
896 /* If the decided response is TRANS_ABORT */
897 if(*(tdata->replyctrl) == TRANS_ABORT) {
898 retval = TRANS_ABORT;
899 } else if(*(tdata->replyctrl) == TRANS_COMMIT) {
900 /* If the decided response is TRANS_COMMIT */
901 retval = TRANS_COMMIT;
907 /* This function opens a connection, places an object read request to
908 * the remote machine, reads the control message and object if
909 * available and copies the object and its header to the local
912 void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
914 struct sockaddr_in serv_addr;
918 void *objcopy = NULL;
920 int sd = getSock2(transReadSockPool, mnum);
921 char readrequest[sizeof(char)+sizeof(unsigned int)];
922 readrequest[0] = READ_REQUEST;
923 *((unsigned int *)(&readrequest[1])) = oid;
924 send_data(sd, readrequest, sizeof(readrequest));
926 /* Read response from the Participant */
927 recv_data(sd, &control, sizeof(char));
929 if (control==OBJECT_NOT_FOUND) {
932 /* Read object if found into local cache */
933 recv_data(sd, &size, sizeof(int));
934 objcopy = objstrAlloc(record->cache, size);
935 recv_data(sd, objcopy, size);
936 /* Insert into cache's lookup table */
937 chashInsert(record->lookupTable, oid, objcopy);
943 /* This function handles the local objects involved in a transaction
944 * commiting process. It also makes a decision if this local machine
945 * sends AGREE or DISAGREE or SOFT_ABORT to coordinator. Note
946 * Coordinator = local machine It wakes up the other threads from
947 * remote participants that are waiting for the coordinator's decision
948 * and based on common agreement it either commits or aborts the
949 * transaction. It also frees the memory resources */
951 void *handleLocalReq(void *threadarg) {
952 unsigned int *oidnotfound = NULL, *oidlocked = NULL;
953 local_thread_data_array_t *localtdata;
954 int numoidnotfound = 0, numoidlocked = 0;
955 int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
958 unsigned short version;
960 objheader_t *headptr;
962 localtdata = (local_thread_data_array_t *) threadarg;
964 /* Counters and arrays to formulate decision on control message to be sent */
965 oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
966 oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
968 numread = localtdata->tdata->buffer->f.numread;
969 /* Process each oid in the machine pile/ group per thread */
970 for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) {
971 if (i < localtdata->tdata->buffer->f.numread) {
972 int incr = sizeof(unsigned int) + sizeof(unsigned short);// Offset that points to next position in the objread array
974 oid = *((unsigned int *)(((char *)localtdata->tdata->buffer->objread) + incr));
975 version = *((unsigned short *)(((char *)localtdata->tdata->buffer->objread) + incr + sizeof(unsigned int)));
976 } else { // Objects Modified
978 headptr = (objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidmod[i-numread]);
979 if (headptr == NULL) {
980 printf("Error: handleLocalReq() returning NULL %s, %d\n", __FILE__, __LINE__);
984 version = headptr->version;
986 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
988 /* Save the oids not found and number of oids not found for later use */
989 if ((mobj = mhashSearch(oid)) == NULL) { /* Obj not found */
990 /* Save the oids not found and number of oids not found for later use */
991 oidnotfound[numoidnotfound] = oid;
993 } else { /* If Obj found in machine (i.e. has not moved) */
994 /* Check if Obj is locked by any previous transaction */
995 if (test_and_set(STATUSPTR(mobj))) {
996 if (version == ((objheader_t *)mobj)->version) { /* If locked then match versions */
998 } else {/* If versions don't match ...HARD ABORT */
1000 /* Send TRANS_DISAGREE to Coordinator */
1001 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
1005 /* Save all object oids that are locked on this machine during this transaction request call */
1006 oidlocked[numoidlocked] = OID(((objheader_t *)mobj));
1008 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
1010 } else { /* If versions don't match ...HARD ABORT */
1012 /* Send TRANS_DISAGREE to Coordinator */
1013 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
1018 /* Condition to send TRANS_AGREE */
1019 if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
1020 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
1022 /* Condition to send TRANS_SOFT_ABORT */
1023 if((v_matchlock > 0 && v_nomatch == 0) || (numoidnotfound > 0 && v_nomatch == 0)) {
1024 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
1027 /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
1028 * if Participant receives a TRANS_COMMIT */
1029 localtdata->transinfo->objlocked = oidlocked;
1030 localtdata->transinfo->objnotfound = oidnotfound;
1031 localtdata->transinfo->modptr = NULL;
1032 localtdata->transinfo->numlocked = numoidlocked;
1033 localtdata->transinfo->numnotfound = numoidnotfound;
1034 /* Lock and update count */
1035 //Thread sleeps until all messages from pariticipants are received by coordinator
1036 pthread_mutex_lock(localtdata->tdata->lock);
1037 (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */
1039 /* Wake up the threads and invoke decideResponse (once) */
1040 if(*(localtdata->tdata->count) == localtdata->tdata->buffer->f.mcount) {
1041 decideResponse(localtdata->tdata);
1042 pthread_cond_broadcast(localtdata->tdata->threshold);
1044 pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock);
1046 pthread_mutex_unlock(localtdata->tdata->lock);
1047 if(*(localtdata->tdata->replyctrl) == TRANS_ABORT){
1048 if(transAbortProcess(localtdata) != 0) {
1049 printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
1052 } else if(*(localtdata->tdata->replyctrl) == TRANS_COMMIT) {
1053 if(transComProcess(localtdata) != 0) {
1054 printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
1059 if (localtdata->transinfo->objlocked != NULL) {
1060 free(localtdata->transinfo->objlocked);
1062 if (localtdata->transinfo->objnotfound != NULL) {
1063 free(localtdata->transinfo->objnotfound);
1069 /* This function completes the ABORT process if the transaction is aborting */
1070 int transAbortProcess(local_thread_data_array_t *localtdata) {
1072 unsigned int *objlocked;
1075 numlocked = localtdata->transinfo->numlocked;
1076 objlocked = localtdata->transinfo->objlocked;
1078 for (i = 0; i < numlocked; i++) {
1079 if((header = mhashSearch(objlocked[i])) == NULL) {
1080 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1083 UnLock(STATUSPTR(header));
1089 /*This function completes the COMMIT process if the transaction is commiting*/
1090 int transComProcess(local_thread_data_array_t *localtdata) {
1091 objheader_t *header, *tcptr;
1092 int i, nummod, tmpsize, numcreated, numlocked;
1093 unsigned int *oidmod, *oidcreated, *oidlocked;
1096 nummod = localtdata->tdata->buffer->f.nummod;
1097 oidmod = localtdata->tdata->buffer->oidmod;
1098 numcreated = localtdata->tdata->buffer->f.numcreated;
1099 oidcreated = localtdata->tdata->buffer->oidcreated;
1100 numlocked = localtdata->transinfo->numlocked;
1101 oidlocked = localtdata->transinfo->objlocked;
1103 for (i = 0; i < nummod; i++) {
1104 if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
1105 printf("Error: transComProcess() mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1108 /* Copy from transaction cache -> main object store */
1109 if ((tcptr = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidmod[i]))) == NULL) {
1110 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1113 GETSIZE(tmpsize, header);
1114 char *tmptcptr = (char *) tcptr;
1115 memcpy((char*)header+sizeof(objheader_t), (char *)tmptcptr+ sizeof(objheader_t), tmpsize);
1116 header->version += 1;
1117 if(header->notifylist != NULL) {
1118 notifyAll(&header->notifylist, OID(header), header->version);
1121 /* If object is newly created inside transaction then commit it */
1122 for (i = 0; i < numcreated; i++) {
1123 if ((header = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidcreated[i]))) == NULL) {
1124 printf("Error: transComProcess() chashSearch returned NULL for oid = %x at %s, %d\n", oidcreated[i], __FILE__, __LINE__);
1127 GETSIZE(tmpsize, header);
1128 tmpsize += sizeof(objheader_t);
1129 pthread_mutex_lock(&mainobjstore_mutex);
1130 if ((ptrcreate = objstrAlloc(mainobjstore, tmpsize)) == NULL) {
1131 printf("Error: transComProcess() failed objstrAlloc %s, %d\n", __FILE__, __LINE__);
1132 pthread_mutex_unlock(&mainobjstore_mutex);
1135 pthread_mutex_unlock(&mainobjstore_mutex);
1136 memcpy(ptrcreate, header, tmpsize);
1137 mhashInsert(oidcreated[i], ptrcreate);
1138 lhashInsert(oidcreated[i], myIpAddr);
1140 /* Unlock locked objects */
1141 for(i = 0; i < numlocked; i++) {
1142 if((header = (objheader_t *) mhashSearch(oidlocked[i])) == NULL) {
1143 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1146 UnLock(STATUSPTR(header));
1152 prefetchpile_t *foundLocal(char *ptr) {
1153 int siteid = *(GET_SITEID(ptr));
1154 int ntuples = *(GET_NTUPLES(ptr));
1155 unsigned int * oidarray = GET_PTR_OID(ptr);
1156 unsigned short * endoffsets = GET_PTR_EOFF(ptr, ntuples);
1157 short * arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1158 prefetchpile_t * head=NULL;
1162 for(i=0;i<ntuples; i++) {
1163 unsigned short baseindex=(i==0)?0:endoffsets[i-1];
1164 unsigned short endindex=endoffsets[i];
1165 unsigned int oid=oidarray[i];
1170 //Look up fields locally
1171 for(newbase=baseindex;newbase<endindex;newbase++) {
1172 if (!lookupObject(&oid, arryfields[newbase]))
1174 //Ended in a null pointer...
1178 //Entire prefetch is local
1179 if (newbase==endindex&&checkoid(oid)){
1183 //Add to remote requests
1184 machinenum=lhashSearch(oid);
1185 insertPile(machinenum, oid, endindex-newbase, &arryfields[newbase], &head);
1190 /* handle dynamic prefetching */
1191 handleDynPrefetching(numLocal, ntuples, siteid);
1195 int checkoid(unsigned int oid) {
1196 objheader_t *header;
1197 if ((header=mhashSearch(oid))!=NULL) {
1200 } else if ((header=prehashSearch(oid))!=NULL) {
1208 int lookupObject(unsigned int * oid, short offset) {
1209 objheader_t *header;
1210 if ((header=mhashSearch(*oid))!=NULL) {
1213 } else if ((header=prehashSearch(*oid))!=NULL) {
1220 if(TYPE(header) > NUMCLASSES) {
1221 int elementsize = classsize[TYPE(header)];
1222 struct ArrayObject *ao = (struct ArrayObject *) (((char *)header) + sizeof(objheader_t));
1223 int length = ao->___length___;
1224 /* Check if array out of bounds */
1225 if(offset < 0 || offset >= length) {
1226 //if yes treat the object as found
1230 (*oid) = *((unsigned int *)(((char *)ao) + sizeof(struct ArrayObject) + (elementsize*offset)));
1233 (*oid) = *((unsigned int *)(((char *)header) + sizeof(objheader_t) + offset));
1239 /* This function is called by the thread calling transPrefetch */
1240 void *transPrefetch(void *t) {
1242 /* lock mutex of primary prefetch queue */
1243 void *node=gettail();
1244 /* Check if the tuples are found locally, if yes then reduce them further*/
1245 /* and group requests by remote machine ids by calling the makePreGroups() */
1246 prefetchpile_t *pilehead = foundLocal(node);
1248 if (pilehead!=NULL) {
1249 // Get sock from shared pool
1250 int sd = getSock2(transPrefetchSockPool, pilehead->mid);
1252 /* Send Prefetch Request */
1253 prefetchpile_t *ptr = pilehead;
1254 while(ptr != NULL) {
1255 sendPrefetchReq(ptr, sd);
1259 /* Release socket */
1260 // freeSock(transPrefetchSockPool, pilehead->mid, sd);
1262 /* Deallocated pilehead */
1263 mcdealloc(pilehead);
1265 // Deallocate the prefetch queue pile node
1270 void sendPrefetchReqnew(prefetchpile_t *mcpilenode, int sd) {
1273 int size=sizeof(char)+sizeof(int);
1274 for(tmp=mcpilenode->objpiles;tmp!=NULL;tmp=tmp->next) {
1275 size += sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1280 *buf=TRANS_PREFETCH;
1283 for(tmp=mcpilenode->objpiles;tmp!=NULL;tmp=tmp->next) {
1284 int len = sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1287 *((unsigned int *)buf)=tmp->oid;
1288 buf+=sizeof(unsigned int);
1289 *((unsigned int *)(buf)) = myIpAddr;
1290 buf+=sizeof(unsigned int);
1291 memcpy(buf, tmp->offset, tmp->numoffset*sizeof(short));
1292 buf+=tmp->numoffset*sizeof(short);
1295 send_data(sd, buft, size);
1299 void sendPrefetchReq(prefetchpile_t *mcpilenode, int sd) {
1304 /* Send TRANS_PREFETCH control message */
1305 control = TRANS_PREFETCH;
1306 send_data(sd, &control, sizeof(char));
1308 /* Send Oids and offsets in pairs */
1309 tmp = mcpilenode->objpiles;
1310 while(tmp != NULL) {
1311 len = sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1312 char oidnoffset[len];
1313 char *buf=oidnoffset;
1314 *((int*)buf) = tmp->numoffset;
1316 *((unsigned int *)buf) = tmp->oid;
1317 buf+=sizeof(unsigned int);
1318 *((unsigned int *)buf) = myIpAddr;
1319 buf += sizeof(unsigned int);
1320 memcpy(buf, tmp->offset, (tmp->numoffset)*sizeof(short));
1321 send_data(sd, oidnoffset, len);
1325 /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
1327 send_data(sd, &endpair, sizeof(int));
1332 int getPrefetchResponse(int sd) {
1333 int length = 0, size = 0;
1336 void *modptr, *oldptr;
1338 recv_data((int)sd, &length, sizeof(int));
1339 size = length - sizeof(int);
1340 char recvbuffer[size];
1342 recv_data((int)sd, recvbuffer, size);
1343 control = *((char *) recvbuffer);
1344 if(control == OBJECT_FOUND) {
1345 oid = *((unsigned int *)(recvbuffer + sizeof(char)));
1346 size = size - (sizeof(char) + sizeof(unsigned int));
1347 pthread_mutex_lock(&prefetchcache_mutex);
1348 if ((modptr = prefetchobjstrAlloc(size)) == NULL) {
1349 printf("Error: objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
1350 pthread_mutex_unlock(&prefetchcache_mutex);
1353 pthread_mutex_unlock(&prefetchcache_mutex);
1354 memcpy(modptr, recvbuffer + sizeof(char) + sizeof(unsigned int), size);
1357 /* Insert the oid and its address into the prefetch hash lookup table */
1358 /* Do a version comparison if the oid exists */
1359 if((oldptr = prehashSearch(oid)) != NULL) {
1360 /* If older version then update with new object ptr */
1361 if(((objheader_t *)oldptr)->version <= ((objheader_t *)modptr)->version) {
1363 prehashInsert(oid, modptr);
1365 } else {/* Else add the object ptr to hash table*/
1366 prehashInsert(oid, modptr);
1368 /* Lock the Prefetch Cache look up table*/
1369 pthread_mutex_lock(&pflookup.lock);
1370 /* Broadcast signal on prefetch cache condition variable */
1371 pthread_cond_broadcast(&pflookup.cond);
1372 /* Unlock the Prefetch Cache look up table*/
1373 pthread_mutex_unlock(&pflookup.lock);
1374 } else if(control == OBJECT_NOT_FOUND) {
1375 oid = *((unsigned int *)(recvbuffer + sizeof(char)));
1376 /* TODO: For each object not found query DHT for new location and retrieve the object */
1377 /* Throw an error */
1378 printf("OBJECT %x NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n", oid);
1381 printf("Error: in decoding the control value %d, %s, %d\n",control, __FILE__, __LINE__);
1387 unsigned short getObjType(unsigned int oid) {
1388 objheader_t *objheader;
1389 unsigned short numoffset[] ={0};
1390 short fieldoffset[] ={};
1392 if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL) {
1393 if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL) {
1394 prefetch(0, 1, &oid, numoffset, fieldoffset);
1395 pthread_mutex_lock(&pflookup.lock);
1396 while ((objheader = (objheader_t *) prehashSearch(oid)) == NULL) {
1397 pthread_cond_wait(&pflookup.cond, &pflookup.lock);
1399 pthread_mutex_unlock(&pflookup.lock);
1403 return TYPE(objheader);
1406 int startRemoteThread(unsigned int oid, unsigned int mid)
1409 struct sockaddr_in remoteAddr;
1410 char msg[1 + sizeof(unsigned int)];
1414 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
1416 perror("startRemoteThread():socket()");
1420 bzero(&remoteAddr, sizeof(remoteAddr));
1421 remoteAddr.sin_family = AF_INET;
1422 remoteAddr.sin_port = htons(LISTEN_PORT);
1423 remoteAddr.sin_addr.s_addr = htonl(mid);
1425 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0)
1427 printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
1428 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1433 msg[0] = START_REMOTE_THREAD;
1434 *((unsigned int *) &msg[1]) = oid;
1435 send_data(sock, msg, 1 + sizeof(unsigned int));
1442 //TODO: when reusing oids, make sure they are not already in use!
1443 static unsigned int id = 0xFFFFFFFF;
1444 unsigned int getNewOID(void) {
1446 if (id > oidMax || id < oidMin)
1453 int processConfigFile()
1456 const int maxLineLength = 200;
1457 char lineBuffer[maxLineLength];
1459 const char *delimiters = " \t\n";
1463 configFile = fopen(CONFIG_FILENAME, "r");
1464 if (configFile == NULL)
1466 printf("error opening %s:\n", CONFIG_FILENAME);
1471 numHostsInSystem = 0;
1472 sizeOfHostArray = 8;
1473 hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
1475 while(fgets(lineBuffer, maxLineLength, configFile) != NULL)
1477 commentBegin = strchr(lineBuffer, '#');
1478 if (commentBegin != NULL)
1479 *commentBegin = '\0';
1480 token = strtok(lineBuffer, delimiters);
1481 while (token != NULL)
1483 tmpAddr = inet_addr(token);
1484 if ((int)tmpAddr == -1)
1486 printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
1491 addHost(htonl(tmpAddr));
1492 token = strtok(NULL, delimiters);
1498 if (numHostsInSystem < 1)
1500 printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
1504 myIpAddr = getMyIpAddr("en1");
1506 myIpAddr = getMyIpAddr("eth0");
1508 myIndexInHostArray = findHost(myIpAddr);
1509 if (myIndexInHostArray == -1)
1511 printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
1514 oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
1515 oidMin = oidsPerBlock * myIndexInHostArray;
1516 if (myIndexInHostArray == numHostsInSystem - 1)
1517 oidMax = 0xFFFFFFFF;
1519 oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
1524 void addHost(unsigned int hostIp)
1526 unsigned int *tmpArray;
1528 if (findHost(hostIp) != -1)
1531 if (numHostsInSystem == sizeOfHostArray)
1533 tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
1534 memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
1536 hostIpAddrs = tmpArray;
1539 hostIpAddrs[numHostsInSystem++] = hostIp;
1544 int findHost(unsigned int hostIp)
1547 for (i = 0; i < numHostsInSystem; i++)
1548 if (hostIpAddrs[i] == hostIp)
1555 /* This function sends notification request per thread waiting on object(s) whose version
1557 int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int numoid) {
1559 objheader_t *objheader;
1560 struct sockaddr_in remoteAddr;
1561 char msg[1 + numoid * (sizeof(unsigned short) + sizeof(unsigned int)) + 3 * sizeof(unsigned int)];
1565 unsigned short version;
1566 unsigned int oid,mid;
1567 static unsigned int threadid = 0;
1568 pthread_mutex_t threadnotify = PTHREAD_MUTEX_INITIALIZER; //Lock and condition var for threadjoin and notification
1569 pthread_cond_t threadcond = PTHREAD_COND_INITIALIZER;
1570 notifydata_t *ndata;
1573 if((mid = lhashSearch(oid)) == 0) {
1574 printf("Error: %s() No such machine found for oid =%x\n",__func__, oid);
1578 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1579 perror("reqNotify():socket()");
1583 bzero(&remoteAddr, sizeof(remoteAddr));
1584 remoteAddr.sin_family = AF_INET;
1585 remoteAddr.sin_port = htons(LISTEN_PORT);
1586 remoteAddr.sin_addr.s_addr = htonl(mid);
1588 /* Generate unique threadid */
1591 /* Save threadid, numoid, oidarray, versionarray, pthread_cond_variable for later processing */
1592 if((ndata = calloc(1, sizeof(notifydata_t))) == NULL) {
1593 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
1596 ndata->numoid = numoid;
1597 ndata->threadid = threadid;
1598 ndata->oidarry = oidarry;
1599 ndata->versionarry = versionarry;
1600 ndata->threadcond = threadcond;
1601 ndata->threadnotify = threadnotify;
1602 if((status = notifyhashInsert(threadid, ndata)) != 0) {
1603 printf("reqNotify(): Insert into notify hash table not successful %s, %d\n", __FILE__, __LINE__);
1608 /* Send number of oids, oidarry, version array, machine id and threadid */
1609 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1610 printf("reqNotify():error %d connecting to %s:%d\n", errno,
1611 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1615 msg[0] = THREAD_NOTIFY_REQUEST;
1616 *((unsigned int *)(&msg[1])) = numoid;
1617 /* Send array of oids */
1618 size = sizeof(unsigned int);
1623 *((unsigned int *)(&msg[1] + size)) = oid;
1624 size += sizeof(unsigned int);
1629 /* Send array of version */
1633 version = versionarry[i];
1634 *((unsigned short *)(&msg[1] + size)) = version;
1635 size += sizeof(unsigned short);
1640 *((unsigned int *)(&msg[1] + size)) = myIpAddr;
1641 size += sizeof(unsigned int);
1642 *((unsigned int *)(&msg[1] + size)) = threadid;
1643 pthread_mutex_lock(&(ndata->threadnotify));
1644 size = 1 + numoid * (sizeof(unsigned int) + sizeof(unsigned short)) + 3 * sizeof(unsigned int);
1645 send_data(sock, msg, size);
1646 pthread_cond_wait(&(ndata->threadcond), &(ndata->threadnotify));
1647 pthread_mutex_unlock(&(ndata->threadnotify));
1650 pthread_cond_destroy(&threadcond);
1651 pthread_mutex_destroy(&threadnotify);
1657 void threadNotify(unsigned int oid, unsigned short version, unsigned int tid) {
1658 notifydata_t *ndata;
1659 int i, objIsFound = 0, index;
1662 //Look up the tid and call the corresponding pthread_cond_signal
1663 if((ndata = notifyhashSearch(tid)) == NULL) {
1664 printf("threadnotify(): No such threadid is present %s, %d\n", __FILE__, __LINE__);
1667 for(i = 0; i < ndata->numoid; i++) {
1668 if(ndata->oidarry[i] == oid){
1673 if(objIsFound == 0){
1674 printf("threadNotify(): Oid not found %s, %d\n", __FILE__, __LINE__);
1677 if(version <= ndata->versionarry[index]){
1678 printf("threadNotify(): New version %d has not changed since last version %s, %d\n", version, __FILE__, __LINE__);
1681 /* Clear from prefetch cache and free thread related data structure */
1682 if((ptr = prehashSearch(oid)) != NULL) {
1685 pthread_cond_signal(&(ndata->threadcond));
1692 int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) {
1695 struct sockaddr_in remoteAddr;
1696 char msg[1 + sizeof(unsigned short) + 2*sizeof(unsigned int)];
1697 int sock, status, size, bytesSent;
1699 while(*head != NULL) {
1702 //create a socket connection to that machine
1703 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1704 perror("notifyAll():socket()");
1708 bzero(&remoteAddr, sizeof(remoteAddr));
1709 remoteAddr.sin_family = AF_INET;
1710 remoteAddr.sin_port = htons(LISTEN_PORT);
1711 remoteAddr.sin_addr.s_addr = htonl(mid);
1712 //send Thread Notify response and threadid to that machine
1713 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1714 printf("notifyAll():error %d connecting to %s:%d\n", errno,
1715 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1719 bzero(msg, (1+sizeof(unsigned short) + 2*sizeof(unsigned int)));
1720 msg[0] = THREAD_NOTIFY_RESPONSE;
1721 *((unsigned int *)&msg[1]) = oid;
1722 size = sizeof(unsigned int);
1723 *((unsigned short *)(&msg[1]+ size)) = version;
1724 size+= sizeof(unsigned short);
1725 *((unsigned int *)(&msg[1]+ size)) = ptr->threadid;
1727 size = 1 + 2*sizeof(unsigned int) + sizeof(unsigned short);
1728 send_data(sock, msg, size);
1739 void transAbort(transrecord_t *trans) {
1740 objstrDelete(trans->cache);
1741 chashDelete(trans->lookupTable);