4 #include "machinepile.h"
9 #include "threadnotify.h"
16 #define PREFETCH_CACHE_SIZE 1048576 //1MB
17 #define CONFIG_FILENAME "dstm.conf"
19 /* Global Variables */
20 extern int classsize[];
21 extern primarypfq_t pqueue; //Shared prefetch queue
22 objstr_t *prefetchcache; //Global Prefetch cache
23 pthread_mutex_t prefetchcache_mutex;// Mutex to lock Prefetch Cache
24 pthread_mutexattr_t prefetchcache_mutex_attr; /* Attribute for lock to make it a recursive lock */
25 extern pthread_mutex_t mainobjstore_mutex;// Mutex to lock main Object store
26 extern prehashtable_t pflookup; //Global Prefetch cache's lookup table
27 pthread_t wthreads[NUM_THREADS]; //Worker threads for working on the prefetch queue
28 pthread_t tPrefetch; /* Primary Prefetch thread that processes the prefetch queue */
29 extern objstr_t *mainobjstore;
30 unsigned int myIpAddr;
31 unsigned int *hostIpAddrs;
34 int myIndexInHostArray;
35 unsigned int oidsPerBlock;
39 sockPoolHashTable_t *transReadSockPool;
40 sockPoolHashTable_t *transPrefetchSockPool;
42 void printhex(unsigned char *, int);
43 plistnode_t *createPiles(transrecord_t *);
45 /*******************************
46 * Send and Recv function calls
47 *******************************/
48 void send_data(int fd , void *buf, int buflen) {
49 char *buffer = (char *)(buf);
53 numbytes = send(fd, buffer, size, MSG_NOSIGNAL);
63 void recv_data(int fd , void *buf, int buflen) {
64 char *buffer = (char *)(buf);
68 numbytes = recv(fd, buffer, size, 0);
78 int recv_data_errorcode(int fd , void *buf, int buflen) {
79 char *buffer = (char *)(buf);
83 numbytes = recv(fd, buffer, size, 0);
93 void printhex(unsigned char *ptr, int numBytes)
96 for (i = 0; i < numBytes; i++)
99 printf("0%x ", ptr[i]);
101 printf("%x ", ptr[i]);
107 inline int arrayLength(int *array) {
109 for(i=0 ;array[i] != -1; i++)
113 inline int findmax(int *array, int arraylength) {
116 for(i = 0; i < arraylength; i++){
123 /* This function is a prefetch call generated by the compiler that
124 * populates the shared primary prefetch queue*/
125 void prefetch(int ntuples, unsigned int *oids, unsigned short *endoffsets, short *arrayfields) {
126 /* Allocate for the queue node*/
128 int qnodesize = sizeof(prefetchqelem_t) + sizeof(int) + ntuples * (sizeof(unsigned short) + sizeof(unsigned int)) + endoffsets[ntuples - 1] * sizeof(short);
131 if((node = calloc(1, qnodesize)) == NULL) {
132 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
135 /* Set queue node values */
136 int len = sizeof(prefetchqelem_t);
138 unsigned int *narray;
139 unsigned short *narray2;
141 int top=endoffsets[ntuples-1];
142 *((int *)(node+len))=ntuples;
144 narray=(unsigned int *)(node+len);
145 narray2=(unsigned short *)(narray+ntuples);
146 narray3=(short *)(narray2+ntuples);
148 for(i=0;i<ntuples;i++) {
150 narray2[i]=endoffsets[i];
153 narray3[i]=arrayfields[i];
155 /* Lock and insert into primary prefetch queue */
156 pthread_mutex_lock(&pqueue.qlock);
157 pre_enqueue((prefetchqelem_t *)node);
158 pthread_cond_signal(&pqueue.qcond);
159 pthread_mutex_unlock(&pqueue.qlock);
164 /* This function starts up the transaction runtime. */
165 int dstmStartup(const char * option) {
166 pthread_t thread_Listen;
168 int master=option!=NULL && strcmp(option, "master")==0;
170 if (processConfigFile() != 0)
171 return 0; //TODO: return error value, cause main program to exit
177 //Initialize socket pool
178 if((transReadSockPool = createSockPool(transReadSockPool, 2*numHostsInSystem+1, 0.5)) == NULL) {
179 printf("Error in creating new socket pool at %s line %d\n", __FILE__, __LINE__);
182 if((transPrefetchSockPool = createSockPool(transPrefetchSockPool, 2*numHostsInSystem+1, 0.5)) == NULL) {
183 printf("Error in creating new socket pool at %s line %d\n", __FILE__, __LINE__);
191 pthread_attr_init(&attr);
192 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
193 pthread_create(&thread_Listen, &attr, dstmListen, NULL);
202 //TODO Use this later
203 void *pCacheAlloc(objstr_t *store, unsigned int size) {
209 while(ptr->next != NULL) {
210 /* check if store is empty */
211 if(((unsigned int)ptr->top - (unsigned int)ptr - sizeof(objstr_t) + size) <= ptr->size) {
226 /* This function initiates the prefetch thread
227 * A queue is shared between the main thread of execution
228 * and the prefetch thread to process the prefetch call
229 * Call from compiler populates the shared queue with prefetch requests while prefetch thread
230 * processes the prefetch requests */
234 //Create and initialize prefetch cache structure
235 prefetchcache = objstrCreate(PREFETCH_CACHE_SIZE);
236 //prefetchcache->next = objstrCreate(PREFETCH_CACHE_SIZE);
237 //prefetchcache->next->next = objstrCreate(PREFETCH_CACHE_SIZE);
239 /* Initialize attributes for mutex */
240 pthread_mutexattr_init(&prefetchcache_mutex_attr);
241 pthread_mutexattr_settype(&prefetchcache_mutex_attr, PTHREAD_MUTEX_RECURSIVE_NP);
243 pthread_mutex_init(&prefetchcache_mutex, &prefetchcache_mutex_attr);
245 //Create prefetch cache lookup table
246 if(prehashCreate(HASH_SIZE, LOADFACTOR))
249 //Initialize primary shared queue
251 //Initialize machine pile w/prefetch oids and offsets shared queue
254 //Create the primary prefetch thread
256 retval=pthread_create(&tPrefetch, NULL, transPrefetch, NULL);
258 pthread_detach(tPrefetch);
261 /* This function stops the threads spawned */
264 pthread_cancel(tPrefetch);
265 for(t = 0; t < NUM_THREADS; t++)
266 pthread_cancel(wthreads[t]);
271 /* This functions inserts randowm wait delays in the order of msec
272 * Mostly used when transaction commits retry*/
280 req.tv_nsec = (long)(1000000 + (t%10000000)); //1-11 msec
281 nanosleep(&req, NULL);
285 /* This function initializes things required in the transaction start*/
286 transrecord_t *transStart()
288 transrecord_t *tmp = calloc(1, sizeof(transrecord_t));
289 tmp->cache = objstrCreate(1048576);
290 tmp->lookupTable = chashCreate(HASH_SIZE, LOADFACTOR);
292 tmp->revertlist=NULL;
297 /* This function finds the location of the objects involved in a transaction
298 * and returns the pointer to the object if found in a remote location */
299 objheader_t *transRead(transrecord_t *record, unsigned int oid) {
300 unsigned int machinenumber;
301 objheader_t *tmp, *objheader;
302 objheader_t *objcopy;
307 printf("Error: %s, %d oid is NULL \n", __FILE__, __LINE__);
311 /* Search local transaction cache */
312 if((objheader = (objheader_t *)chashSearch(record->lookupTable, oid)) != NULL){
314 return &objheader[1];
318 } else if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
319 /* Look up in machine lookup table and copy into cache*/
320 GETSIZE(size, objheader);
321 size += sizeof(objheader_t);
322 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
323 memcpy(objcopy, objheader, size);
324 /* Insert into cache's lookup table */
325 chashInsert(record->lookupTable, OID(objheader), objcopy);
331 } else if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) { /* Look up in prefetch cache */
333 size+=sizeof(objheader_t);
334 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
335 memcpy(objcopy, tmp, size);
336 /* Insert into cache's lookup table */
337 chashInsert(record->lookupTable, OID(tmp), objcopy);
344 /* Get the object from the remote location */
345 if((machinenumber = lhashSearch(oid)) == 0) {
346 printf("Error: %s() No machine found for oid =% %s,%dx\n",__func__, machinenumber, __FILE__, __LINE__);
349 objcopy = getRemoteObj(record, machinenumber, oid);
351 if(objcopy == NULL) {
352 printf("Error: Object not found in Remote location %s, %d\n", __FILE__, __LINE__);
365 /* This function creates objects in the transaction record */
366 objheader_t *transCreateObj(transrecord_t *record, unsigned int size)
368 objheader_t *tmp = (objheader_t *) objstrAlloc(record->cache, (sizeof(objheader_t) + size));
369 tmp->notifylist = NULL;
370 OID(tmp) = getNewOID();
374 chashInsert(record->lookupTable, OID(tmp), tmp);
377 return &tmp[1]; //want space after object header
383 /* This function creates machine piles based on all machines involved in a
384 * transaction commit request */
385 plistnode_t *createPiles(transrecord_t *record) {
387 unsigned int size;/* Represents number of bins in the chash table */
388 chashlistnode_t *curr, *ptr, *next;
389 plistnode_t *pile = NULL;
390 unsigned int machinenum;
391 void *localmachinenum;
392 objheader_t *headeraddr;
394 ptr = record->lookupTable->table;
395 size = record->lookupTable->size;
397 for(i = 0; i < size ; i++) {
399 /* Inner loop to traverse the linked list of the cache lookupTable */
400 while(curr != NULL) {
401 //if the first bin in hash table is empty
407 if ((headeraddr = chashSearch(record->lookupTable, curr->key)) == NULL) {
408 printf("Error: No such oid %s, %d\n", __FILE__, __LINE__);
412 //Get machine location for object id (and whether local or not)
413 if (STATUS(headeraddr) & NEW || (mhashSearch(curr->key) != NULL)) {
414 machinenum = myIpAddr;
415 } else if ((machinenum = lhashSearch(curr->key)) == 0) {
416 printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
420 //Make machine groups
421 if ((pile = pInsert(pile, headeraddr, machinenum, record->lookupTable->numelements)) == NULL) {
422 printf("pInsert error %s, %d\n", __FILE__, __LINE__);
432 /* This function initiates the transaction commit process
433 * Spawns threads for each of the new connections with Participants
434 * and creates new piles by calling the createPiles(),
435 * Sends a transrequest() to each remote machines for objects found remotely
436 * and calls handleLocalReq() to process objects found locally */
437 int transCommit(transrecord_t *record) {
438 unsigned int tot_bytes_mod, *listmid;
439 plistnode_t *pile, *pile_ptr;
441 int pilecount, offset, threadnum = 0, trecvcount = 0;
443 char transid[TID_LEN];
444 trans_req_data_t *tosend;
445 trans_commit_data_t transinfo;
446 static int newtid = 0;
447 char treplyctrl = 0, treplyretry = 0; /* keeps track of the common response that needs to be sent */
449 thread_data_array_t *thread_data_array;
450 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*/
461 pile_ptr = pile = createPiles(record);
463 /* Create the packet to be sent in TRANS_REQUEST */
465 /* Count the number of participants */
466 pilecount = pCount(pile);
468 /* Create a list of machine ids(Participants) involved in transaction */
469 if((listmid = calloc(pilecount, sizeof(unsigned int))) == NULL) {
470 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
473 pListMid(pile, listmid);
476 /* Initialize thread variables,
477 * Spawn a thread for each Participant involved in a transaction */
478 pthread_t thread[pilecount];
480 pthread_cond_t tcond;
481 pthread_mutex_t tlock;
482 pthread_mutex_t tlshrd;
484 if((thread_data_array = (thread_data_array_t *) calloc(pilecount, sizeof(thread_data_array_t))) == NULL) {
485 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
486 pthread_cond_destroy(&tcond);
487 pthread_mutex_destroy(&tlock);
493 if((ltdata = calloc(1, sizeof(local_thread_data_array_t))) == NULL) {
494 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
495 pthread_cond_destroy(&tcond);
496 pthread_mutex_destroy(&tlock);
499 free(thread_data_array);
503 thread_response_t rcvd_control_msg[pilecount]; /* Shared thread array that keeps track of responses of participants */
505 /* Initialize and set thread detach attribute */
506 pthread_attr_init(&attr);
507 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
508 pthread_mutex_init(&tlock, NULL);
509 pthread_cond_init(&tcond, NULL);
511 /* Process each machine pile */
512 while(pile != NULL) {
513 //Create transaction id
515 if ((tosend = calloc(1, sizeof(trans_req_data_t))) == NULL) {
516 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
517 pthread_cond_destroy(&tcond);
518 pthread_mutex_destroy(&tlock);
521 free(thread_data_array);
525 tosend->f.control = TRANS_REQUEST;
526 sprintf(tosend->f.trans_id, "%x_%d", pile->mid, newtid);
527 tosend->f.mcount = pilecount;
528 tosend->f.numread = pile->numread;
529 tosend->f.nummod = pile->nummod;
530 tosend->f.numcreated = pile->numcreated;
531 tosend->f.sum_bytes = pile->sum_bytes;
532 tosend->listmid = listmid;
533 tosend->objread = pile->objread;
534 tosend->oidmod = pile->oidmod;
535 tosend->oidcreated = pile->oidcreated;
536 thread_data_array[threadnum].thread_id = threadnum;
537 thread_data_array[threadnum].mid = pile->mid;
538 thread_data_array[threadnum].buffer = tosend;
539 thread_data_array[threadnum].recvmsg = rcvd_control_msg;
540 thread_data_array[threadnum].threshold = &tcond;
541 thread_data_array[threadnum].lock = &tlock;
542 thread_data_array[threadnum].count = &trecvcount;
543 thread_data_array[threadnum].replyctrl = &treplyctrl;
544 thread_data_array[threadnum].replyretry = &treplyretry;
545 thread_data_array[threadnum].rec = record;
546 /* If local do not create any extra connection */
547 if(pile->mid != myIpAddr) { /* Not local */
549 rc = pthread_create(&thread[threadnum], &attr, transRequest, (void *) &thread_data_array[threadnum]);
552 perror("Error in pthread create\n");
553 pthread_cond_destroy(&tcond);
554 pthread_mutex_destroy(&tlock);
557 for (i = 0; i < threadnum; i++)
558 free(thread_data_array[i].buffer);
559 free(thread_data_array);
564 ltdata->tdata = &thread_data_array[threadnum];
565 ltdata->transinfo = &transinfo;
567 val = pthread_create(&thread[threadnum], &attr, handleLocalReq, (void *) ltdata);
570 perror("Error in pthread create\n");
571 pthread_cond_destroy(&tcond);
572 pthread_mutex_destroy(&tlock);
575 for (i = 0; i < threadnum; i++)
576 free(thread_data_array[i].buffer);
577 free(thread_data_array);
586 /* Free attribute and wait for the other threads */
587 pthread_attr_destroy(&attr);
589 for (i = 0; i < threadnum; i++) {
590 rc = pthread_join(thread[i], NULL);
593 printf("Error: return code from pthread_join() is %d\n", rc);
594 pthread_cond_destroy(&tcond);
595 pthread_mutex_destroy(&tlock);
598 for (j = i; j < threadnum; j++) {
599 free(thread_data_array[j].buffer);
603 free(thread_data_array[i].buffer);
607 pthread_cond_destroy(&tcond);
608 pthread_mutex_destroy(&tlock);
612 /* wait a random amount of time before retrying to commit transaction*/
613 if(treplyretry == 1) {
614 free(thread_data_array);
619 /* Retry trans commit procedure during soft_abort case */
620 } while (treplyretry == 1);
623 if(treplyctrl == TRANS_ABORT) {
625 objstrDelete(record->cache);
626 chashDelete(record->lookupTable);
628 free(thread_data_array);
631 } else if(treplyctrl == TRANS_COMMIT) {
633 objstrDelete(record->cache);
634 chashDelete(record->lookupTable);
636 free(thread_data_array);
640 //TODO Add other cases
641 printf("Error: in %s() THIS SHOULD NOT HAPPEN.....EXIT PROGRAM\n", __func__);
647 /* This function sends information involved in the transaction request
648 * to participants and accepts a response from particpants.
649 * It calls decideresponse() to decide on what control message
650 * to send next to participants and sends the message using sendResponse()*/
651 void *transRequest(void *threadarg) {
653 struct sockaddr_in serv_addr;
654 thread_data_array_t *tdata;
655 objheader_t *headeraddr;
656 char control, recvcontrol;
657 char machineip[16], retval;
659 tdata = (thread_data_array_t *) threadarg;
661 /* Send Trans Request */
662 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
663 perror("Error in socket for TRANS_REQUEST\n");
666 bzero((char*) &serv_addr, sizeof(serv_addr));
667 serv_addr.sin_family = AF_INET;
668 serv_addr.sin_port = htons(LISTEN_PORT);
669 midtoIP(tdata->mid,machineip);
670 machineip[15] = '\0';
671 serv_addr.sin_addr.s_addr = inet_addr(machineip);
672 /* Open Connection */
673 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
674 perror("Error in connect for TRANS_REQUEST\n");
679 /* Send bytes of data with TRANS_REQUEST control message */
680 send_data(sd, &(tdata->buffer->f), sizeof(fixed_data_t));
682 /* Send list of machines involved in the transaction */
684 int size=sizeof(unsigned int)*tdata->buffer->f.mcount;
685 send_data(sd, tdata->buffer->listmid, size);
688 /* Send oids and version number tuples for objects that are read */
690 int size=(sizeof(unsigned int)+sizeof(unsigned short))*tdata->buffer->f.numread;
691 send_data(sd, tdata->buffer->objread, size);
694 /* Send objects that are modified */
695 for(i = 0; i < tdata->buffer->f.nummod ; i++) {
697 headeraddr = chashSearch(tdata->rec->lookupTable, tdata->buffer->oidmod[i]);
698 GETSIZE(size,headeraddr);
699 size+=sizeof(objheader_t);
700 send_data(sd, headeraddr, size);
703 /* Read control message from Participant */
704 recv_data(sd, &control, sizeof(char));
705 recvcontrol = control;
707 /* Update common data structure and increment count */
708 tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol;
710 /* Lock and update count */
711 /* Thread sleeps until all messages from pariticipants are received by coordinator */
712 pthread_mutex_lock(tdata->lock);
714 (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */
716 /* Wake up the threads and invoke decideResponse (once) */
717 if(*(tdata->count) == tdata->buffer->f.mcount) {
718 decideResponse(tdata);
719 pthread_cond_broadcast(tdata->threshold);
721 pthread_cond_wait(tdata->threshold, tdata->lock);
723 pthread_mutex_unlock(tdata->lock);
725 /* Send the final response such as TRANS_COMMIT or TRANS_ABORT t
726 * to all participants in their respective socket */
727 if (sendResponse(tdata, sd) == 0) {
728 printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__);
733 recv_data((int)sd, &control, sizeof(char));
735 if(control == TRANS_UNSUCESSFUL) {
736 //printf("DEBUG-> TRANS_ABORTED\n");
737 } else if(control == TRANS_SUCESSFUL) {
738 //printf("DEBUG-> TRANS_SUCCESSFUL\n");
740 //printf("DEBUG-> Error: Incorrect Transaction End Message %d\n", control);
743 /* Close connection */
748 /* This function decides the reponse that needs to be sent to
749 * all Participant machines after the TRANS_REQUEST protocol */
750 void decideResponse(thread_data_array_t *tdata) {
752 int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
755 for (i = 0 ; i < tdata->buffer->f.mcount; i++) {
756 control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses
757 written onto the shared array */
760 printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
761 /* treat as disagree, pass thru */
770 case TRANS_SOFT_ABORT:
776 if(transdisagree > 0) {
778 *(tdata->replyctrl) = TRANS_ABORT;
779 *(tdata->replyretry) = 0;
780 /* clear objects from prefetch cache */
781 for (i = 0; i < tdata->buffer->f.numread; i++)
782 prehashRemove(*((unsigned int *)(((char *)tdata->buffer->objread) + (sizeof(unsigned int) + sizeof(unsigned short))*i)));
783 for (i = 0; i < tdata->buffer->f.nummod; i++)
784 prehashRemove(tdata->buffer->oidmod[i]);
785 } else if(transagree == tdata->buffer->f.mcount){
787 *(tdata->replyctrl) = TRANS_COMMIT;
788 *(tdata->replyretry) = 0;
790 /* Send Abort in soft abort case followed by retry commiting transaction again*/
791 *(tdata->replyctrl) = TRANS_ABORT;
792 *(tdata->replyretry) = 1;
797 /* This function sends the final response to remote machines per thread in their respective socket id
798 * It returns a char that is only needed to check the correctness of execution of this function inside
800 char sendResponse(thread_data_array_t *tdata, int sd) {
801 int n, size, sum, oidcount = 0, control;
802 char *ptr, retval = 0;
803 unsigned int *oidnotfound;
805 control = *(tdata->replyctrl);
806 send_data(sd, &control, sizeof(char));
808 //TODO read missing objects during object migration
809 /* If response is a soft abort due to missing objects at the Participant's side */
811 if(tdata->recvmsg[tdata->thread_id].rcv_status == TRANS_SOFT_ABORT) {
812 // Read list of objects missing
813 recv_data(sd, &oidcount, sizeof(int));
814 //if((read(sd, &oidcount, sizeof(int)) != 0) && (oidcount != 0)) {
816 size = oidcount * sizeof(unsigned int);
817 if((oidnotfound = calloc(oidcount, sizeof(unsigned int))) == NULL) {
818 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
821 ptr = (char *) oidnotfound;
822 recv_data(sd, ptr, size);
824 retval = TRANS_SOFT_ABORT;
828 /* If the decided response is TRANS_ABORT */
829 if(*(tdata->replyctrl) == TRANS_ABORT) {
830 retval = TRANS_ABORT;
831 } else if(*(tdata->replyctrl) == TRANS_COMMIT) { /* If the decided response is TRANS_COMMIT */
832 retval = TRANS_COMMIT;
838 /* This function opens a connection, places an object read request to the
839 * remote machine, reads the control message and object if available and
840 * copies the object and its header to the local cache.
843 void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
845 struct sockaddr_in serv_addr;
849 void *objcopy = NULL;
852 if((sd = getSock(transReadSockPool, mnum)) == -1) {
853 printf("%s(): Error: no socket id in the pool of sockets at %s, %d\n", __func__, __FILE__, __LINE__);
857 char readrequest[sizeof(char)+sizeof(unsigned int)];
858 readrequest[0] = READ_REQUEST;
859 *((unsigned int *)(&readrequest[1])) = oid;
860 send_data(sd, readrequest, sizeof(readrequest));
862 /* Read response from the Participant */
863 recv_data(sd, &control, sizeof(char));
866 case OBJECT_NOT_FOUND:
870 /* Read object if found into local cache */
871 recv_data(sd, &size, sizeof(int));
872 objcopy = objstrAlloc(record->cache, size);
873 recv_data(sd, objcopy, size);
875 /* Insert into cache's lookup table */
876 chashInsert(record->lookupTable, oid, objcopy);
879 printf("Error: in recv response from participant on a READ_REQUEST %s, %d\n",__FILE__, __LINE__);
884 if((status = freeSock(transReadSockPool, mnum, sd)) == -1) {
885 printf("Error in releasing socket at %s line %d\n", __FILE__, __LINE__);
892 /* This function handles the local objects involved in a transaction commiting process.
893 * It also makes a decision if this local machine sends AGREE or DISAGREE or SOFT_ABORT to coordinator.
894 * Note Coordinator = local machine
895 * It wakes up the other threads from remote participants that are waiting for the coordinator's decision and
896 * based on common agreement it either commits or aborts the transaction.
897 * It also frees the memory resources */
898 void *handleLocalReq(void *threadarg) {
899 unsigned int *oidnotfound = NULL, *oidlocked = NULL;
900 local_thread_data_array_t *localtdata;
901 int objnotfound = 0, objlocked = 0;
902 int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
905 unsigned short version;
907 objheader_t *headptr;
909 localtdata = (local_thread_data_array_t *) threadarg;
911 /* Counters and arrays to formulate decision on control message to be sent */
912 oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
913 oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
915 numread = localtdata->tdata->buffer->f.numread;
916 /* Process each oid in the machine pile/ group per thread */
917 for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) {
918 if (i < localtdata->tdata->buffer->f.numread) {
919 int incr = sizeof(unsigned int) + sizeof(unsigned short);// Offset that points to next position in the objread array
921 oid = *((unsigned int *)(((char *)localtdata->tdata->buffer->objread) + incr));
922 version = *((unsigned short *)(((char *)localtdata->tdata->buffer->objread) + incr + sizeof(unsigned int)));
923 } else { // Objects Modified
925 headptr = (objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidmod[i-numread]);
926 if (headptr == NULL) {
927 printf("Error: handleLocalReq() returning NULL %s, %d\n", __FILE__, __LINE__);
931 version = headptr->version;
933 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
935 /* Save the oids not found and number of oids not found for later use */
936 if ((mobj = mhashSearch(oid)) == NULL) { /* Obj not found */
937 /* Save the oids not found and number of oids not found for later use */
938 oidnotfound[objnotfound] = oid;
940 } else { /* If Obj found in machine (i.e. has not moved) */
941 /* Check if Obj is locked by any previous transaction */
942 if ((STATUS((objheader_t *)mobj) & LOCK) == LOCK) {
943 if (version == ((objheader_t *)mobj)->version) { /* If locked then match versions */
945 } else {/* If versions don't match ...HARD ABORT */
947 /* Send TRANS_DISAGREE to Coordinator */
948 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
950 } else {/* If Obj is not locked then lock object */
951 STATUS(((objheader_t *)mobj)) |= LOCK;
952 /* Save all object oids that are locked on this machine during this transaction request call */
953 oidlocked[objlocked] = OID(((objheader_t *)mobj));
955 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
957 } else { /* If versions don't match ...HARD ABORT */
959 /* Send TRANS_DISAGREE to Coordinator */
960 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
965 /* Condition to send TRANS_AGREE */
966 if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
967 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
969 /* Condition to send TRANS_SOFT_ABORT */
970 if((v_matchlock > 0 && v_nomatch == 0) || (objnotfound > 0 && v_nomatch == 0)) {
971 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
974 /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
975 * if Participant receives a TRANS_COMMIT */
976 localtdata->transinfo->objlocked = oidlocked;
977 localtdata->transinfo->objnotfound = oidnotfound;
978 localtdata->transinfo->modptr = NULL;
979 localtdata->transinfo->numlocked = objlocked;
980 localtdata->transinfo->numnotfound = objnotfound;
981 /* Lock and update count */
982 //Thread sleeps until all messages from pariticipants are received by coordinator
983 pthread_mutex_lock(localtdata->tdata->lock);
984 (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */
986 /* Wake up the threads and invoke decideResponse (once) */
987 if(*(localtdata->tdata->count) == localtdata->tdata->buffer->f.mcount) {
988 decideResponse(localtdata->tdata);
989 pthread_cond_broadcast(localtdata->tdata->threshold);
991 pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock);
993 pthread_mutex_unlock(localtdata->tdata->lock);
994 if(*(localtdata->tdata->replyctrl) == TRANS_ABORT){
995 if(transAbortProcess(localtdata) != 0) {
996 printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
999 } else if(*(localtdata->tdata->replyctrl) == TRANS_COMMIT) {
1000 if(transComProcess(localtdata) != 0) {
1001 printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
1006 if (localtdata->transinfo->objlocked != NULL) {
1007 free(localtdata->transinfo->objlocked);
1009 if (localtdata->transinfo->objnotfound != NULL) {
1010 free(localtdata->transinfo->objnotfound);
1016 /* This function completes the ABORT process if the transaction is aborting */
1017 int transAbortProcess(local_thread_data_array_t *localtdata) {
1019 unsigned int *objlocked;
1022 numlocked = localtdata->transinfo->numlocked;
1023 objlocked = localtdata->transinfo->objlocked;
1025 for (i = 0; i < numlocked; i++) {
1026 if((header = mhashSearch(objlocked[i])) == NULL) {
1027 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1030 STATUS(((objheader_t *)header)) &= ~(LOCK);
1036 /*This function completes the COMMIT process is the transaction is commiting*/
1037 int transComProcess(local_thread_data_array_t *localtdata) {
1038 objheader_t *header, *tcptr;
1039 int i, nummod, tmpsize, numcreated, numlocked;
1040 unsigned int *oidmod, *oidcreated, *oidlocked;
1043 nummod = localtdata->tdata->buffer->f.nummod;
1044 oidmod = localtdata->tdata->buffer->oidmod;
1045 numcreated = localtdata->tdata->buffer->f.numcreated;
1046 oidcreated = localtdata->tdata->buffer->oidcreated;
1047 numlocked = localtdata->transinfo->numlocked;
1048 oidlocked = localtdata->transinfo->objlocked;
1050 for (i = 0; i < nummod; i++) {
1051 if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
1052 printf("Error: transComProcess() mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1055 /* Copy from transaction cache -> main object store */
1056 if ((tcptr = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidmod[i]))) == NULL) {
1057 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1060 GETSIZE(tmpsize, header);
1061 pthread_mutex_lock(&mainobjstore_mutex);
1062 memcpy((char*)header+sizeof(objheader_t), (char *)tcptr+ sizeof(objheader_t), tmpsize);
1063 header->version += 1;
1064 if(header->notifylist != NULL) {
1065 notifyAll(&header->notifylist, OID(header), header->version);
1067 pthread_mutex_unlock(&mainobjstore_mutex);
1069 /* If object is newly created inside transaction then commit it */
1070 for (i = 0; i < numcreated; i++) {
1071 if ((header = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidcreated[i]))) == NULL) {
1072 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1075 GETSIZE(tmpsize, header);
1076 tmpsize += sizeof(objheader_t);
1077 pthread_mutex_lock(&mainobjstore_mutex);
1078 if ((ptrcreate = objstrAlloc(mainobjstore, tmpsize)) == NULL) {
1079 printf("Error: transComProcess() failed objstrAlloc %s, %d\n", __FILE__, __LINE__);
1080 pthread_mutex_unlock(&mainobjstore_mutex);
1083 pthread_mutex_unlock(&mainobjstore_mutex);
1084 memcpy(ptrcreate, header, tmpsize);
1085 mhashInsert(oidcreated[i], ptrcreate);
1086 lhashInsert(oidcreated[i], myIpAddr);
1088 /* Unlock locked objects */
1089 for(i = 0; i < numlocked; i++) {
1090 if((header = (objheader_t *) mhashSearch(oidlocked[i])) == NULL) {
1091 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1094 STATUS(header) &= ~(LOCK);
1100 /* This function checks if the prefetch oids are same and have same offsets
1101 * for case x.a.b and y.a.b where x and y have same oid's
1102 * or if a.b.c is a subset of x.b.c.d*/
1103 /* check for case where the generated request a.y.z or x.y.z.g then
1104 * prefetch needs to be generated for x.y.z.g if oid of a and x are same*/
1105 void checkPrefetchTuples(prefetchqelem_t *node) {
1106 int i,j, count,k, sindex, index;
1108 int ntuples, slength;
1110 unsigned short *endoffsets;
1113 /* Check for the case x.y.z and a.b.c are same oids */
1114 ptr = (char *) node;
1115 ntuples = *(GET_NTUPLES(ptr));
1116 oid = GET_PTR_OID(ptr);
1117 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1118 offsets = GET_PTR_ARRYFLD(ptr, ntuples);
1120 /* Find offset length for each tuple */
1121 int numoffset[ntuples];
1122 numoffset[0] = endoffsets[0];
1123 for(i = 1; i<ntuples; i++) {
1124 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1126 /* Check for redundant tuples by comparing oids of each tuple */
1127 for(i = 0; i < ntuples; i++) {
1130 for(j = i+1 ; j < ntuples; j++) {
1133 /*If oids of tuples match */
1134 if (oid[i] == oid[j]) {
1135 /* Find the smallest offset length of two tuples*/
1136 if(numoffset[i] > numoffset[j]){
1137 slength = numoffset[j];
1141 slength = numoffset[i];
1145 /* Compare the offset values based on the current indices
1146 * break if they do not match
1147 * if all offset values match then pick the largest tuple*/
1152 k = endoffsets[i-1];
1154 index = endoffsets[j -1];
1155 for(count = 0; count < slength; count ++) {
1156 if (offsets[k] != offsets[index]) {
1162 if(slength == count) {
1169 /* This function makes machine piles to be added into the machine pile queue for each prefetch call */
1170 prefetchpile_t *makePreGroups(prefetchqelem_t *node, int *numoffset) {
1172 int ntuples, i, machinenum, count=0;
1174 unsigned short *endoffsets;
1175 short *arryfields, *offset;
1176 prefetchpile_t *head = NULL, *tmp = NULL;
1178 /* Check for the case x.y.z and a.b.c are same oids */
1179 ptr = (char *) node;
1180 ntuples = *(GET_NTUPLES(ptr));
1181 oid = GET_PTR_OID(ptr);
1182 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1183 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1185 if((head = (prefetchpile_t *) calloc(1, sizeof(prefetchpile_t))) == NULL) {
1186 printf("Calloc error: %s %d\n", __FILE__, __LINE__);
1190 /* Check for redundant tuples by comparing oids of each tuple */
1191 for(i = 0; i < ntuples; i++) {
1193 if(head->next != NULL) {
1194 if((tmp = (prefetchpile_t *) calloc(1, sizeof(prefetchpile_t))) == NULL) {
1195 printf("Calloc error: %s %d\n", __FILE__, __LINE__);
1198 tmp->mid = myIpAddr;
1202 head->mid = myIpAddr;
1206 /* For each tuple make piles */
1207 if ((machinenum = lhashSearch(oid[i])) == 0) {
1208 printf("Error: No such Machine %s, %d\n", __FILE__, __LINE__);
1211 /* Insert into machine pile */
1213 offset = &arryfields[0];
1215 offset = &arryfields[endoffsets[i-1]];
1218 if((head = insertPile(machinenum, oid[i], numoffset[i], offset, head)) == NULL){
1219 printf("Error: Couldn't create a pile %s, %d\n", __FILE__, __LINE__);
1227 prefetchpile_t *foundLocal(prefetchqelem_t *node) {
1228 int ntuples,i, j, k, oidnfound = 0, arryfieldindex,nextarryfieldindex, flag = 0, val;
1232 objheader_t *objheader;
1233 unsigned short *endoffsets;
1236 ptr = (char *) node;
1237 ntuples = *(GET_NTUPLES(ptr));
1238 oid = GET_PTR_OID(ptr);
1239 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1240 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1242 /* Find offset length for each tuple */
1243 int numoffset[ntuples];//Number of offsets for each tuple
1244 numoffset[0] = endoffsets[0];
1245 for(i = 1; i<ntuples; i++) {
1246 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1249 for(i = 0; i < ntuples; i++) {
1253 nextarryfieldindex = endoffsets[0];
1255 arryfieldindex = endoffsets[i-1];
1256 nextarryfieldindex = endoffsets[i];
1259 endoffsets[0] = val = numoffset[0];
1260 for(k = 1; k < ntuples; k++) {
1261 val = val + numoffset[k];
1262 endoffsets[k] = val;
1265 for(k = 0; k<endoffsets[ntuples-1]; k++) {
1266 arryfields[arryfieldindex+k] = arryfields[nextarryfieldindex+k];
1271 /* If object found locally */
1272 if((objheader = (objheader_t*) mhashSearch(oid[i])) != NULL) {
1274 tmp = (char *) objheader;
1275 int orgnumoffset = numoffset[i];
1279 arryfieldindex = endoffsets[i-1];
1282 for(j = 0; j<orgnumoffset; j++) {
1283 unsigned int objoid = 0;
1284 /* Check for arrays */
1285 if(TYPE(objheader) > NUMCLASSES) {
1289 int elementsize = classsize[TYPE(objheader)];
1290 struct ArrayObject *ao = (struct ArrayObject *) (tmp + sizeof(objheader_t));
1291 int length = ao->___length___;
1292 /* Check if array out of bounds */
1293 if(arryfields[arryfieldindex] < 0 || arryfields[arryfieldindex] >= length) {
1294 break; //if yes then treat the object as found
1296 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*arryfields[arryfieldindex])));
1298 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + arryfields[arryfieldindex]));
1300 //Update numoffset array
1301 numoffset[i] = numoffset[i] - 1;
1304 //Update endoffset array
1305 endoffsets[0] = val = numoffset[0];
1306 for(k = 1; k < ntuples; k++) {
1307 val = val + numoffset[k];
1308 endoffsets[k] = val;
1310 //Update arrayfields array
1311 for(k = 0; k < endoffsets[ntuples-1]; k++) {
1312 arryfields[arryfieldindex+k] = arryfields[arryfieldindex+k+1];
1314 if((objheader = (objheader_t*) mhashSearch(oid[i])) == NULL) {
1316 checkPreCache(node, numoffset, oid[i], i);
1319 tmp = (char *) objheader;
1322 /*If all offset oids are found locally,make the prefetch tuple invalid */
1327 /* Look in Prefetch cache */
1328 checkPreCache(node, numoffset, oid[i],i);
1333 /* Make machine groups */
1334 prefetchpile_t *head = NULL;
1335 if((head = makePreGroups(node, numoffset)) == NULL) {
1336 printf("Error in makePreGroups() %s %d\n", __FILE__, __LINE__);
1343 void checkPreCache(prefetchqelem_t *node, int *numoffset, unsigned int objoid, int index) {
1345 int ntuples, i, k, flag=0, isArray =0, arryfieldindex, val;
1347 unsigned short *endoffsets;
1349 objheader_t *header;
1351 ptr = (char *) node;
1352 ntuples = *(GET_NTUPLES(ptr));
1353 oid = GET_PTR_OID(ptr);
1354 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1355 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1357 if((header = (objheader_t *) prehashSearch(objoid)) == NULL) {
1359 } else { //Found in Prefetch Cache
1360 //TODO Decide if object is too old, if old remove from cache
1361 tmp = (char *) header;
1362 int loopcount = numoffset[index];
1366 arryfieldindex = endoffsets[(index - 1)];
1367 // Check if any of the offset oid is available in the Prefetch cache
1368 for(i = 0; i < loopcount; i++) {
1369 /* Check for arrays */
1370 if(TYPE(header) > NUMCLASSES) {
1375 int elementsize = classsize[TYPE(header)];
1376 struct ArrayObject *ao = (struct ArrayObject *) (tmp + sizeof(objheader_t));
1377 int length = ao->___length___;
1378 /* Check if array out of bounds */
1379 if(arryfields[arryfieldindex] < 0 || arryfields[arryfieldindex] >= length) {
1380 break; //if yes treat the object as found
1382 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*arryfields[arryfieldindex])));
1384 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + arryfields[arryfieldindex]));
1386 //Update numoffset array
1387 numoffset[index] = numoffset[index] - 1;
1389 oid[index] = objoid;
1390 //Update endoffset array
1391 endoffsets[0] = val = numoffset[0];
1392 for(k = 1; k < ntuples; k++) {
1393 val = val + numoffset[k];
1394 endoffsets[k] = val;
1396 //Update arrayfields array
1397 for(k = 0; k < endoffsets[ntuples-1]; k++) {
1398 arryfields[arryfieldindex+k] = arryfields[arryfieldindex+k+1];
1400 if((header = (objheader_t *)prehashSearch(oid[index])) != NULL) {
1401 tmp = (char *) header;
1409 //Found in the prefetch cache
1410 if(flag == 0 && (numoffset[index] == 0)) {
1417 /* This function is called by the thread calling transPrefetch */
1418 void *transPrefetch(void *t) {
1420 /* lock mutex of primary prefetch queue */
1421 pthread_mutex_lock(&pqueue.qlock);
1422 /* while primary queue is empty, then wait */
1423 while((pqueue.front == NULL) && (pqueue.rear == NULL)) {
1424 pthread_cond_wait(&pqueue.qcond, &pqueue.qlock);
1427 /* dequeue node to create a machine piles and finally unlock mutex */
1428 prefetchqelem_t *qnode;
1429 if((qnode = pre_dequeue()) == NULL) {
1430 printf("Error: No node returned %s, %d\n", __FILE__, __LINE__);
1431 pthread_mutex_unlock(&pqueue.qlock);
1434 pthread_mutex_unlock(&pqueue.qlock);
1436 /* Reduce redundant prefetch requests */
1437 checkPrefetchTuples(qnode);
1438 /* Check if the tuples are found locally, if yes then reduce them further*/
1439 /* and group requests by remote machine ids by calling the makePreGroups() */
1440 prefetchpile_t *pilehead = NULL;
1441 if((pilehead = foundLocal(qnode)) == NULL) {
1442 printf("Error: No node created for serving prefetch request %s %d\n", __FILE__, __LINE__);
1447 // Get sock from shared pool
1449 if((sd = getSock(transPrefetchSockPool, pilehead->mid)) == -1) {
1450 printf("Error: No socket id in pool of sockets at %s line %d\n", __FILE__, __LINE__);
1454 /* Send Prefetch Request */
1455 prefetchpile_t *ptr = pilehead;
1456 while(ptr != NULL) {
1457 sendPrefetchReq(ptr, sd);
1461 /* Release socket */
1463 if((status = freeSock(transPrefetchSockPool, pilehead->mid, sd)) == -1) {
1464 printf("Error: In realeasing socket at %s line %d\n", __FILE__, __LINE__);
1468 /* Deallocated pilehead */
1469 mcdealloc(pilehead);
1471 // Deallocate the prefetch queue pile node
1476 void sendPrefetchReq(prefetchpile_t *mcpilenode, int sd) {
1477 int off, len, endpair, count = 0;
1481 /* Send TRANS_PREFETCH control message */
1482 control = TRANS_PREFETCH;
1483 send_data(sd, &control, sizeof(char));
1485 /* Send Oids and offsets in pairs */
1486 tmp = mcpilenode->objpiles;
1487 while(tmp != NULL) {
1489 count++; /* Keeps track of the number of oid and offset tuples sent per remote machine */
1490 len = sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1491 char oidnoffset[len];
1492 bzero(oidnoffset, len);
1493 *((int*)oidnoffset) = len;
1495 *((unsigned int *)(oidnoffset + off)) = tmp->oid;
1496 off += sizeof(unsigned int);
1497 *((unsigned int *)(oidnoffset + off)) = myIpAddr;
1498 off += sizeof(unsigned int);
1500 for(i = 0; i < tmp->numoffset; i++) {
1501 *((short*)(oidnoffset + off)) = tmp->offset[i];
1504 send_data(sd, oidnoffset, len);
1508 /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
1510 send_data(sd, &endpair, sizeof(int));
1515 int getPrefetchResponse(int sd) {
1516 int numbytes = 0, length = 0, size = 0;
1517 char *recvbuffer, control;
1519 void *modptr, *oldptr;
1521 recv_data((int)sd, &length, sizeof(int));
1522 size = length - sizeof(int);
1523 if((recvbuffer = calloc(1, size)) == NULL) {
1524 printf("%s() Calloc error at %s,%d\n", __func__, __FILE__, __LINE__);
1528 recv_data((int)sd, recvbuffer, size);
1530 control = *((char *) recvbuffer);
1531 if(control == OBJECT_FOUND) {
1533 oid = *((unsigned int *)(recvbuffer + sizeof(char)));
1534 size = size - (sizeof(char) + sizeof(unsigned int));
1535 pthread_mutex_lock(&prefetchcache_mutex);
1536 if ((modptr = objstrAlloc(prefetchcache, size)) == NULL) {
1537 printf("Error: objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
1538 pthread_mutex_unlock(&prefetchcache_mutex);
1542 pthread_mutex_unlock(&prefetchcache_mutex);
1543 memcpy(modptr, recvbuffer + sizeof(char) + sizeof(unsigned int), size);
1545 /* Insert the oid and its address into the prefetch hash lookup table */
1546 /* Do a version comparison if the oid exists */
1547 if((oldptr = prehashSearch(oid)) != NULL) {
1548 /* If older version then update with new object ptr */
1549 if(((objheader_t *)oldptr)->version <= ((objheader_t *)modptr)->version) {
1551 prehashInsert(oid, modptr);
1553 /* TODO modptr should be reference counted */
1555 } else {/* Else add the object ptr to hash table*/
1556 prehashInsert(oid, modptr);
1558 /* Lock the Prefetch Cache look up table*/
1559 pthread_mutex_lock(&pflookup.lock);
1560 /* Broadcast signal on prefetch cache condition variable */
1561 pthread_cond_broadcast(&pflookup.cond);
1562 /* Unlock the Prefetch Cache look up table*/
1563 pthread_mutex_unlock(&pflookup.lock);
1564 } else if(control == OBJECT_NOT_FOUND) {
1565 oid = *((unsigned int *)(recvbuffer + sizeof(char)));
1566 /* TODO: For each object not found query DHT for new location and retrieve the object */
1567 /* Throw an error */
1568 printf("OBJECT %x NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n", oid);
1572 printf("Error: in decoding the control value %d, %s, %d\n",control, __FILE__, __LINE__);
1580 unsigned short getObjType(unsigned int oid)
1582 objheader_t *objheader;
1583 unsigned short numoffset[] ={0};
1584 short fieldoffset[] ={};
1586 if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL)
1588 if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1590 prefetch(1, &oid, numoffset, fieldoffset);
1591 pthread_mutex_lock(&pflookup.lock);
1592 while ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1594 pthread_cond_wait(&pflookup.cond, &pflookup.lock);
1596 pthread_mutex_unlock(&pflookup.lock);
1600 return TYPE(objheader);
1603 int startRemoteThread(unsigned int oid, unsigned int mid)
1606 struct sockaddr_in remoteAddr;
1607 char msg[1 + sizeof(unsigned int)];
1611 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
1613 perror("startRemoteThread():socket()");
1617 bzero(&remoteAddr, sizeof(remoteAddr));
1618 remoteAddr.sin_family = AF_INET;
1619 remoteAddr.sin_port = htons(LISTEN_PORT);
1620 remoteAddr.sin_addr.s_addr = htonl(mid);
1622 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0)
1624 printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
1625 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1630 msg[0] = START_REMOTE_THREAD;
1631 *((unsigned int *) &msg[1]) = oid;
1632 send_data(sock, msg, 1 + sizeof(unsigned int));
1639 //TODO: when reusing oids, make sure they are not already in use!
1640 unsigned int getNewOID(void) {
1641 static unsigned int id = 0xFFFFFFFF;
1644 if (id > oidMax || id < oidMin)
1651 int processConfigFile()
1654 const int maxLineLength = 200;
1655 char lineBuffer[maxLineLength];
1657 const char *delimiters = " \t\n";
1661 configFile = fopen(CONFIG_FILENAME, "r");
1662 if (configFile == NULL)
1664 printf("error opening %s:\n", CONFIG_FILENAME);
1669 numHostsInSystem = 0;
1670 sizeOfHostArray = 8;
1671 hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
1673 while(fgets(lineBuffer, maxLineLength, configFile) != NULL)
1675 commentBegin = strchr(lineBuffer, '#');
1676 if (commentBegin != NULL)
1677 *commentBegin = '\0';
1678 token = strtok(lineBuffer, delimiters);
1679 while (token != NULL)
1681 tmpAddr = inet_addr(token);
1682 if ((int)tmpAddr == -1)
1684 printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
1689 addHost(htonl(tmpAddr));
1690 token = strtok(NULL, delimiters);
1696 if (numHostsInSystem < 1)
1698 printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
1702 myIpAddr = getMyIpAddr("en1");
1704 myIpAddr = getMyIpAddr("eth0");
1706 myIndexInHostArray = findHost(myIpAddr);
1707 if (myIndexInHostArray == -1)
1709 printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
1712 oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
1713 oidMin = oidsPerBlock * myIndexInHostArray;
1714 if (myIndexInHostArray == numHostsInSystem - 1)
1715 oidMax = 0xFFFFFFFF;
1717 oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
1722 void addHost(unsigned int hostIp)
1724 unsigned int *tmpArray;
1726 if (findHost(hostIp) != -1)
1729 if (numHostsInSystem == sizeOfHostArray)
1731 tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
1732 memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
1734 hostIpAddrs = tmpArray;
1737 hostIpAddrs[numHostsInSystem++] = hostIp;
1742 int findHost(unsigned int hostIp)
1745 for (i = 0; i < numHostsInSystem; i++)
1746 if (hostIpAddrs[i] == hostIp)
1753 /* This function sends notification request per thread waiting on object(s) whose version
1755 int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int numoid) {
1757 objheader_t *objheader;
1758 struct sockaddr_in remoteAddr;
1759 char msg[1 + numoid * (sizeof(unsigned short) + sizeof(unsigned int)) + 3 * sizeof(unsigned int)];
1763 unsigned short version;
1764 unsigned int oid,mid;
1765 static unsigned int threadid = 0;
1766 pthread_mutex_t threadnotify = PTHREAD_MUTEX_INITIALIZER; //Lock and condition var for threadjoin and notification
1767 pthread_cond_t threadcond = PTHREAD_COND_INITIALIZER;
1768 notifydata_t *ndata;
1770 //FIXME currently all oids belong to one machine
1772 if((mid = lhashSearch(oid)) == 0) {
1773 printf("Error: %s() No such machine found for oid =%x\n",__func__, oid);
1777 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1778 perror("reqNotify():socket()");
1782 bzero(&remoteAddr, sizeof(remoteAddr));
1783 remoteAddr.sin_family = AF_INET;
1784 remoteAddr.sin_port = htons(LISTEN_PORT);
1785 remoteAddr.sin_addr.s_addr = htonl(mid);
1787 /* Generate unique threadid */
1790 /* Save threadid, numoid, oidarray, versionarray, pthread_cond_variable for later processing */
1791 if((ndata = calloc(1, sizeof(notifydata_t))) == NULL) {
1792 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
1795 ndata->numoid = numoid;
1796 ndata->threadid = threadid;
1797 ndata->oidarry = oidarry;
1798 ndata->versionarry = versionarry;
1799 ndata->threadcond = threadcond;
1800 ndata->threadnotify = threadnotify;
1801 if((status = notifyhashInsert(threadid, ndata)) != 0) {
1802 printf("reqNotify(): Insert into notify hash table not successful %s, %d\n", __FILE__, __LINE__);
1807 /* Send number of oids, oidarry, version array, machine id and threadid */
1808 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1809 printf("reqNotify():error %d connecting to %s:%d\n", errno,
1810 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1814 msg[0] = THREAD_NOTIFY_REQUEST;
1815 *((unsigned int *)(&msg[1])) = numoid;
1816 /* Send array of oids */
1817 size = sizeof(unsigned int);
1822 *((unsigned int *)(&msg[1] + size)) = oid;
1823 size += sizeof(unsigned int);
1828 /* Send array of version */
1832 version = versionarry[i];
1833 *((unsigned short *)(&msg[1] + size)) = version;
1834 size += sizeof(unsigned short);
1839 *((unsigned int *)(&msg[1] + size)) = myIpAddr;
1840 size += sizeof(unsigned int);
1841 *((unsigned int *)(&msg[1] + size)) = threadid;
1843 pthread_mutex_lock(&(ndata->threadnotify));
1844 size = 1 + numoid * (sizeof(unsigned int) + sizeof(unsigned short)) + 3 * sizeof(unsigned int);
1845 send_data(sock, msg, size);
1846 pthread_cond_wait(&(ndata->threadcond), &(ndata->threadnotify));
1847 pthread_mutex_unlock(&(ndata->threadnotify));
1850 pthread_cond_destroy(&threadcond);
1851 pthread_mutex_destroy(&threadnotify);
1857 void threadNotify(unsigned int oid, unsigned short version, unsigned int tid) {
1858 notifydata_t *ndata;
1859 int i, objIsFound = 0, index;
1862 //Look up the tid and call the corresponding pthread_cond_signal
1863 if((ndata = notifyhashSearch(tid)) == NULL) {
1864 printf("threadnotify(): No such threadid is present %s, %d\n", __FILE__, __LINE__);
1867 for(i = 0; i < ndata->numoid; i++) {
1868 if(ndata->oidarry[i] == oid){
1873 if(objIsFound == 0){
1874 printf("threadNotify(): Oid not found %s, %d\n", __FILE__, __LINE__);
1877 if(version <= ndata->versionarry[index]){
1878 printf("threadNotify(): New version %d has not changed since last version %s, %d\n", version, __FILE__, __LINE__);
1881 /* Clear from prefetch cache and free thread related data structure */
1882 if((ptr = prehashSearch(oid)) != NULL) {
1885 pthread_cond_signal(&(ndata->threadcond));
1892 int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) {
1895 struct sockaddr_in remoteAddr;
1896 char msg[1 + sizeof(unsigned short) + 2*sizeof(unsigned int)];
1897 int sock, status, size, bytesSent;
1899 while(*head != NULL) {
1902 //create a socket connection to that machine
1903 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1904 perror("notifyAll():socket()");
1908 bzero(&remoteAddr, sizeof(remoteAddr));
1909 remoteAddr.sin_family = AF_INET;
1910 remoteAddr.sin_port = htons(LISTEN_PORT);
1911 remoteAddr.sin_addr.s_addr = htonl(mid);
1912 //send Thread Notify response and threadid to that machine
1913 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1914 printf("notifyAll():error %d connecting to %s:%d\n", errno,
1915 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1918 bzero(msg, (1+sizeof(unsigned short) + 2*sizeof(unsigned int)));
1919 msg[0] = THREAD_NOTIFY_RESPONSE;
1920 *((unsigned int *)&msg[1]) = oid;
1921 size = sizeof(unsigned int);
1922 *((unsigned short *)(&msg[1]+ size)) = version;
1923 size+= sizeof(unsigned short);
1924 *((unsigned int *)(&msg[1]+ size)) = ptr->threadid;
1926 size = 1 + 2*sizeof(unsigned int) + sizeof(unsigned short);
1927 send_data(sock, msg, size);
1938 void transAbort(transrecord_t *trans) {
1939 objstrDelete(trans->cache);
1940 chashDelete(trans->lookupTable);