4 #include "machinepile.h"
9 #include "threadnotify.h"
12 #include <sys/types.h>
13 #include <sys/socket.h>
15 #include <netinet/in.h>
16 #include <sys/types.h>
25 #define LISTEN_PORT 2156
27 #define PREFETCH_CACHE_SIZE 1048576 //1MB
28 #define CONFIG_FILENAME "dstm.conf"
30 /* Global Variables */
31 extern int classsize[];
32 extern primarypfq_t pqueue; //Shared prefetch queue
33 extern mcpileq_t mcqueue; //Shared queue containing prefetch requests sorted by remote machineids
34 objstr_t *prefetchcache; //Global Prefetch cache
35 pthread_mutex_t prefetchcache_mutex;// Mutex to lock Prefetch Cache
36 pthread_mutexattr_t prefetchcache_mutex_attr; /* Attribute for lock to make it a recursive lock */
37 extern pthread_mutex_t mainobjstore_mutex;// Mutex to lock main Object store
38 extern prehashtable_t pflookup; //Global Prefetch cache's lookup table
39 pthread_t wthreads[NUM_THREADS]; //Worker threads for working on the prefetch queue
40 pthread_t tPrefetch; /* Primary Prefetch thread that processes the prefetch queue */
41 extern objstr_t *mainobjstore;
42 unsigned int myIpAddr;
43 unsigned int *hostIpAddrs;
46 int myIndexInHostArray;
47 unsigned int oidsPerBlock;
51 /************************************************************
52 * Global variables to map socketid and remote mid to
54 ***********************************************************/
55 midSocketInfo_t midSocketArray[NUM_MACHINES];
56 int sockCount; //number of connections with all remote machines(one socket per mc)
57 int sockIdFound; //track if socket file descriptor is already established
59 void printhex(unsigned char *, int);
60 plistnode_t *createPiles(transrecord_t *);
62 /*******************************
63 * Send and Recv function calls
64 *******************************/
65 void send_data(int fd , void *buf, int buflen) {
66 char *buffer = (char *)(buf);
70 numbytes = send(fd, buffer, size, MSG_NOSIGNAL);
73 printf("error: at %s, %d\n", __FILE__, __LINE__);
81 void recv_data(int fd , void *buf, int buflen) {
82 char *buffer = (char *)(buf);
86 numbytes = recv(fd, buffer, size, 0);
89 printf("error: at %s, %d\n", __FILE__, __LINE__);
97 void printhex(unsigned char *ptr, int numBytes)
100 for (i = 0; i < numBytes; i++)
103 printf("0%x ", ptr[i]);
105 printf("%x ", ptr[i]);
111 inline int arrayLength(int *array) {
113 for(i=0 ;array[i] != -1; i++)
117 inline int findmax(int *array, int arraylength) {
120 for(i = 0; i < arraylength; i++){
127 /* This function is a prefetch call generated by the compiler that
128 * populates the shared primary prefetch queue*/
129 void prefetch(int ntuples, unsigned int *oids, unsigned short *endoffsets, short *arrayfields) {
130 /* Allocate for the queue node*/
132 int qnodesize = sizeof(prefetchqelem_t) + sizeof(int) + ntuples * (sizeof(unsigned short) + sizeof(unsigned int)) + endoffsets[ntuples - 1] * sizeof(short);
135 if((node = calloc(1, qnodesize)) == NULL) {
136 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
139 /* Set queue node values */
140 int len = sizeof(prefetchqelem_t);
142 unsigned int *narray;
143 unsigned short *narray2;
145 int top=endoffsets[ntuples-1];
146 *((int *)(node+len))=ntuples;
148 narray=(unsigned int *)(node+len);
149 narray2=(unsigned short *)(narray+ntuples);
150 narray3=(short *)(narray2+ntuples);
152 for(i=0;i<ntuples;i++) {
154 narray2[i]=endoffsets[i];
157 narray3[i]=arrayfields[i];
159 /* Lock and insert into primary prefetch queue */
160 pthread_mutex_lock(&pqueue.qlock);
161 pre_enqueue((prefetchqelem_t *)node);
162 pthread_cond_signal(&pqueue.qcond);
163 pthread_mutex_unlock(&pqueue.qlock);
168 /* This function starts up the transaction runtime. */
169 int dstmStartup(const char * option) {
170 pthread_t thread_Listen;
172 int master=option!=NULL && strcmp(option, "master")==0;
174 if (processConfigFile() != 0)
175 return 0; //TODO: return error value, cause main program to exit
187 pthread_attr_init(&attr);
188 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
189 pthread_create(&thread_Listen, &attr, dstmListen, NULL);
198 //TODO Use this later
199 void *pCacheAlloc(objstr_t *store, unsigned int size) {
205 while(ptr->next != NULL) {
206 /* check if store is empty */
207 if(((unsigned int)ptr->top - (unsigned int)ptr - sizeof(objstr_t) + size) <= ptr->size) {
222 /* This function initiates the prefetch thread
223 * A queue is shared between the main thread of execution
224 * and the prefetch thread to process the prefetch call
225 * Call from compiler populates the shared queue with prefetch requests while prefetch thread
226 * processes the prefetch requests */
230 //Create and initialize prefetch cache structure
231 prefetchcache = objstrCreate(PREFETCH_CACHE_SIZE);
232 //prefetchcache->next = objstrCreate(PREFETCH_CACHE_SIZE);
233 //prefetchcache->next->next = objstrCreate(PREFETCH_CACHE_SIZE);
235 /* Initialize attributes for mutex */
236 pthread_mutexattr_init(&prefetchcache_mutex_attr);
237 pthread_mutexattr_settype(&prefetchcache_mutex_attr, PTHREAD_MUTEX_RECURSIVE_NP);
239 pthread_mutex_init(&prefetchcache_mutex, &prefetchcache_mutex_attr);
241 //Create prefetch cache lookup table
242 if(prehashCreate(HASH_SIZE, LOADFACTOR))
245 //Initialize primary shared queue
247 //Initialize machine pile w/prefetch oids and offsets shared queue
250 //Create the primary prefetch thread
252 retval=pthread_create(&tPrefetch, NULL, transPrefetch, NULL);
254 pthread_detach(tPrefetch);
256 //Initialize mid to socketid mapping array
258 for(t = 0; t < NUM_MACHINES; t++) {
259 midSocketArray[t].mid = 0;
260 midSocketArray[t].sockid = 0;
263 //Create and Initialize a pool of threads
264 /* Threads are active for the entire period runtime is running */
265 for(t = 0; t< NUM_THREADS; t++) {
267 rc = pthread_create(&wthreads[t], NULL, mcqProcess, (void *)t);
269 pthread_detach(wthreads[t]);
273 /* This function stops the threads spawned */
276 pthread_cancel(tPrefetch);
277 for(t = 0; t < NUM_THREADS; t++)
278 pthread_cancel(wthreads[t]);
283 /* This functions inserts randowm wait delays in the order of msec
284 * Mostly used when transaction commits retry*/
292 req.tv_nsec = (long)(1000000 + (t%10000000)); //1-11 msec
293 nanosleep(&req, NULL);
297 /* This function initializes things required in the transaction start*/
298 transrecord_t *transStart()
300 transrecord_t *tmp = calloc(1, sizeof(transrecord_t));
301 tmp->cache = objstrCreate(1048576);
302 tmp->lookupTable = chashCreate(HASH_SIZE, LOADFACTOR);
304 tmp->revertlist=NULL;
309 /* This function finds the location of the objects involved in a transaction
310 * and returns the pointer to the object if found in a remote location */
311 objheader_t *transRead(transrecord_t *record, unsigned int oid) {
312 unsigned int machinenumber;
313 objheader_t *tmp, *objheader;
314 objheader_t *objcopy;
315 int size, rc, found = 0;
321 printf("Error: %s, %d oid is NULL \n", __FILE__, __LINE__);
325 rc = gettimeofday(&tp, NULL);
329 if (tp.tv_usec >= 1000000)
331 tp.tv_usec -= 1000000;
334 /* Convert from timeval to timespec */
335 ts.tv_sec = tp.tv_sec;
336 ts.tv_nsec = tp.tv_usec * 1000;
338 /* Search local transaction cache */
339 if((objheader = (objheader_t *)chashSearch(record->lookupTable, oid)) != NULL){
342 return &objheader[1];
346 } else if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
347 /* Look up in machine lookup table and copy into cache*/
348 GETSIZE(size, objheader);
349 size += sizeof(objheader_t);
350 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
351 memcpy(objcopy, objheader, size);
352 /* Insert into cache's lookup table */
353 chashInsert(record->lookupTable, OID(objheader), objcopy);
359 } else if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) { /* Look up in prefetch cache */
361 size+=sizeof(objheader_t);
362 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
363 memcpy(objcopy, tmp, size);
364 /* Insert into cache's lookup table */
365 chashInsert(record->lookupTable, OID(tmp), objcopy);
372 /*If object not found in prefetch cache then block until object appears in the prefetch cache */
374 pthread_mutex_lock(&pflookup.lock);
376 rc = pthread_cond_timedwait(&pflookup.cond, &pflookup.lock, &ts);
377 // Check Prefetch cache again
378 if((tmp =(objheader_t *) prehashSearch(oid)) != NULL) {
381 size+=sizeof(objheader_t);
382 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
383 memcpy(objcopy, tmp, size);
384 chashInsert(record->lookupTable, OID(tmp), objcopy);
385 pthread_mutex_unlock(&pflookup.lock);
391 } else if (rc == ETIMEDOUT) {
392 pthread_mutex_unlock(&pflookup.lock);
398 /* Get the object from the remote location */
399 if((machinenumber = lhashSearch(oid)) == 0) {
400 printf("Error: %s() No machine found for oid =% %s,%dx\n",__func__, machinenumber, __FILE__, __LINE__);
403 objcopy = getRemoteObj(record, machinenumber, oid);
405 if(objcopy == NULL) {
406 printf("Error: Object not found in Remote location %s, %d\n", __FILE__, __LINE__);
419 /* This function creates objects in the transaction record */
420 objheader_t *transCreateObj(transrecord_t *record, unsigned int size)
422 objheader_t *tmp = (objheader_t *) objstrAlloc(record->cache, (sizeof(objheader_t) + size));
423 tmp->notifylist = NULL;
424 OID(tmp) = getNewOID();
428 chashInsert(record->lookupTable, OID(tmp), tmp);
431 return &tmp[1]; //want space after object header
437 /* This function creates machine piles based on all machines involved in a
438 * transaction commit request */
439 plistnode_t *createPiles(transrecord_t *record) {
441 unsigned int size;/* Represents number of bins in the chash table */
442 chashlistnode_t *curr, *ptr, *next;
443 plistnode_t *pile = NULL;
444 unsigned int machinenum;
445 void *localmachinenum;
446 objheader_t *headeraddr;
448 ptr = record->lookupTable->table;
449 size = record->lookupTable->size;
451 for(i = 0; i < size ; i++) {
453 /* Inner loop to traverse the linked list of the cache lookupTable */
454 while(curr != NULL) {
455 //if the first bin in hash table is empty
461 if ((headeraddr = chashSearch(record->lookupTable, curr->key)) == NULL) {
462 printf("Error: No such oid %s, %d\n", __FILE__, __LINE__);
466 //Get machine location for object id (and whether local or not)
467 if (STATUS(headeraddr) & NEW || (mhashSearch(curr->key) != NULL)) {
468 machinenum = myIpAddr;
469 } else if ((machinenum = lhashSearch(curr->key)) == 0) {
470 printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
474 //Make machine groups
475 if ((pile = pInsert(pile, headeraddr, machinenum, record->lookupTable->numelements)) == NULL) {
476 printf("pInsert error %s, %d\n", __FILE__, __LINE__);
486 /* This function initiates the transaction commit process
487 * Spawns threads for each of the new connections with Participants
488 * and creates new piles by calling the createPiles(),
489 * Sends a transrequest() to each remote machines for objects found remotely
490 * and calls handleLocalReq() to process objects found locally */
491 int transCommit(transrecord_t *record) {
492 unsigned int tot_bytes_mod, *listmid;
493 plistnode_t *pile, *pile_ptr;
495 int pilecount, offset, threadnum = 0, trecvcount = 0;
497 char transid[TID_LEN];
498 trans_req_data_t *tosend;
499 trans_commit_data_t transinfo;
500 static int newtid = 0;
501 char treplyctrl = 0, treplyretry = 0; /* keeps track of the common response that needs to be sent */
503 thread_data_array_t *thread_data_array;
504 local_thread_data_array_t *ltdata;
510 thread_data_array = NULL;
513 /* Look through all the objects in the transaction record and make piles
514 * for each machine involved in the transaction*/
515 pile_ptr = pile = createPiles(record);
517 /* Create the packet to be sent in TRANS_REQUEST */
519 /* Count the number of participants */
520 pilecount = pCount(pile);
522 /* Create a list of machine ids(Participants) involved in transaction */
523 if((listmid = calloc(pilecount, sizeof(unsigned int))) == NULL) {
524 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
527 pListMid(pile, listmid);
530 /* Initialize thread variables,
531 * Spawn a thread for each Participant involved in a transaction */
532 pthread_t thread[pilecount];
534 pthread_cond_t tcond;
535 pthread_mutex_t tlock;
536 pthread_mutex_t tlshrd;
538 if((thread_data_array = (thread_data_array_t *) calloc(pilecount, sizeof(thread_data_array_t))) == NULL) {
539 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
540 pthread_cond_destroy(&tcond);
541 pthread_mutex_destroy(&tlock);
547 if((ltdata = calloc(1, sizeof(local_thread_data_array_t))) == NULL) {
548 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
549 pthread_cond_destroy(&tcond);
550 pthread_mutex_destroy(&tlock);
553 free(thread_data_array);
557 thread_response_t rcvd_control_msg[pilecount]; /* Shared thread array that keeps track of responses of participants */
559 /* Initialize and set thread detach attribute */
560 pthread_attr_init(&attr);
561 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
562 pthread_mutex_init(&tlock, NULL);
563 pthread_cond_init(&tcond, NULL);
565 /* Process each machine pile */
566 while(pile != NULL) {
567 //Create transaction id
569 if ((tosend = calloc(1, sizeof(trans_req_data_t))) == NULL) {
570 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
571 pthread_cond_destroy(&tcond);
572 pthread_mutex_destroy(&tlock);
575 free(thread_data_array);
579 tosend->f.control = TRANS_REQUEST;
580 sprintf(tosend->f.trans_id, "%x_%d", pile->mid, newtid);
581 tosend->f.mcount = pilecount;
582 tosend->f.numread = pile->numread;
583 tosend->f.nummod = pile->nummod;
584 tosend->f.numcreated = pile->numcreated;
585 tosend->f.sum_bytes = pile->sum_bytes;
586 tosend->listmid = listmid;
587 tosend->objread = pile->objread;
588 tosend->oidmod = pile->oidmod;
589 tosend->oidcreated = pile->oidcreated;
590 thread_data_array[threadnum].thread_id = threadnum;
591 thread_data_array[threadnum].mid = pile->mid;
592 thread_data_array[threadnum].buffer = tosend;
593 thread_data_array[threadnum].recvmsg = rcvd_control_msg;
594 thread_data_array[threadnum].threshold = &tcond;
595 thread_data_array[threadnum].lock = &tlock;
596 thread_data_array[threadnum].count = &trecvcount;
597 thread_data_array[threadnum].replyctrl = &treplyctrl;
598 thread_data_array[threadnum].replyretry = &treplyretry;
599 thread_data_array[threadnum].rec = record;
600 /* If local do not create any extra connection */
601 if(pile->mid != myIpAddr) { /* Not local */
603 rc = pthread_create(&thread[threadnum], &attr, transRequest, (void *) &thread_data_array[threadnum]);
606 perror("Error in pthread create\n");
607 pthread_cond_destroy(&tcond);
608 pthread_mutex_destroy(&tlock);
611 for (i = 0; i < threadnum; i++)
612 free(thread_data_array[i].buffer);
613 free(thread_data_array);
618 ltdata->tdata = &thread_data_array[threadnum];
619 ltdata->transinfo = &transinfo;
621 val = pthread_create(&thread[threadnum], &attr, handleLocalReq, (void *) ltdata);
624 perror("Error in pthread create\n");
625 pthread_cond_destroy(&tcond);
626 pthread_mutex_destroy(&tlock);
629 for (i = 0; i < threadnum; i++)
630 free(thread_data_array[i].buffer);
631 free(thread_data_array);
640 /* Free attribute and wait for the other threads */
641 pthread_attr_destroy(&attr);
643 for (i = 0; i < threadnum; i++) {
644 rc = pthread_join(thread[i], NULL);
647 printf("Error: return code from pthread_join() is %d\n", rc);
648 pthread_cond_destroy(&tcond);
649 pthread_mutex_destroy(&tlock);
652 for (j = i; j < threadnum; j++) {
653 free(thread_data_array[j].buffer);
657 free(thread_data_array[i].buffer);
661 pthread_cond_destroy(&tcond);
662 pthread_mutex_destroy(&tlock);
666 /* wait a random amount of time before retrying to commit transaction*/
667 if(treplyretry == 1) {
668 free(thread_data_array);
673 /* Retry trans commit procedure during soft_abort case */
674 } while (treplyretry == 1);
677 if(treplyctrl == TRANS_ABORT) {
679 objstrDelete(record->cache);
680 chashDelete(record->lookupTable);
682 free(thread_data_array);
685 } else if(treplyctrl == TRANS_COMMIT) {
687 objstrDelete(record->cache);
688 chashDelete(record->lookupTable);
690 free(thread_data_array);
694 //TODO Add other cases
695 printf("Error: in %s() THIS SHOULD NOT HAPPEN.....EXIT PROGRAM\n", __func__);
702 /* This function sends information involved in the transaction request
703 * to participants and accepts a response from particpants.
704 * It calls decideresponse() to decide on what control message
705 * to send next to participants and sends the message using sendResponse()*/
706 void *transRequest(void *threadarg) {
708 struct sockaddr_in serv_addr;
709 thread_data_array_t *tdata;
710 objheader_t *headeraddr;
711 char control, recvcontrol;
712 char machineip[16], retval;
714 tdata = (thread_data_array_t *) threadarg;
716 /* Send Trans Request */
717 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
718 perror("Error in socket for TRANS_REQUEST\n");
721 bzero((char*) &serv_addr, sizeof(serv_addr));
722 serv_addr.sin_family = AF_INET;
723 serv_addr.sin_port = htons(LISTEN_PORT);
724 midtoIP(tdata->mid,machineip);
725 machineip[15] = '\0';
726 serv_addr.sin_addr.s_addr = inet_addr(machineip);
727 /* Open Connection */
728 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
729 perror("Error in connect for TRANS_REQUEST\n");
734 /* Send bytes of data with TRANS_REQUEST control message */
735 send_data(sd, &(tdata->buffer->f), sizeof(fixed_data_t));
737 /* Send list of machines involved in the transaction */
739 int size=sizeof(unsigned int)*tdata->buffer->f.mcount;
740 send_data(sd, tdata->buffer->listmid, size);
743 /* Send oids and version number tuples for objects that are read */
745 int size=(sizeof(unsigned int)+sizeof(unsigned short))*tdata->buffer->f.numread;
746 send_data(sd, tdata->buffer->objread, size);
749 /* Send objects that are modified */
750 for(i = 0; i < tdata->buffer->f.nummod ; i++) {
752 headeraddr = chashSearch(tdata->rec->lookupTable, tdata->buffer->oidmod[i]);
753 GETSIZE(size,headeraddr);
754 size+=sizeof(objheader_t);
755 send_data(sd, headeraddr, size);
758 /* Read control message from Participant */
759 recv_data(sd, &control, sizeof(char));
760 recvcontrol = control;
762 /* Update common data structure and increment count */
763 tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol;
765 /* Lock and update count */
766 /* Thread sleeps until all messages from pariticipants are received by coordinator */
767 pthread_mutex_lock(tdata->lock);
769 (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */
771 /* Wake up the threads and invoke decideResponse (once) */
772 if(*(tdata->count) == tdata->buffer->f.mcount) {
773 decideResponse(tdata);
774 pthread_cond_broadcast(tdata->threshold);
776 pthread_cond_wait(tdata->threshold, tdata->lock);
778 pthread_mutex_unlock(tdata->lock);
780 /* Send the final response such as TRANS_COMMIT or TRANS_ABORT t
781 * to all participants in their respective socket */
782 if (sendResponse(tdata, sd) == 0) {
783 printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__);
788 recv_data((int)sd, &control, sizeof(char));
790 if(control == TRANS_UNSUCESSFUL) {
791 //printf("DEBUG-> TRANS_ABORTED\n");
792 } else if(control == TRANS_SUCESSFUL) {
793 //printf("DEBUG-> TRANS_SUCCESSFUL\n");
795 //printf("DEBUG-> Error: Incorrect Transaction End Message %d\n", control);
798 /* Close connection */
803 /* This function decides the reponse that needs to be sent to
804 * all Participant machines after the TRANS_REQUEST protocol */
805 void decideResponse(thread_data_array_t *tdata) {
807 int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
810 for (i = 0 ; i < tdata->buffer->f.mcount; i++) {
811 control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses
812 written onto the shared array */
815 printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
816 /* treat as disagree, pass thru */
825 case TRANS_SOFT_ABORT:
831 if(transdisagree > 0) {
833 *(tdata->replyctrl) = TRANS_ABORT;
834 *(tdata->replyretry) = 0;
835 /* clear objects from prefetch cache */
836 for (i = 0; i < tdata->buffer->f.numread; i++)
837 prehashRemove(*((unsigned int *)(((char *)tdata->buffer->objread) + (sizeof(unsigned int) + sizeof(unsigned short))*i)));
838 for (i = 0; i < tdata->buffer->f.nummod; i++)
839 prehashRemove(tdata->buffer->oidmod[i]);
840 } else if(transagree == tdata->buffer->f.mcount){
842 *(tdata->replyctrl) = TRANS_COMMIT;
843 *(tdata->replyretry) = 0;
845 /* Send Abort in soft abort case followed by retry commiting transaction again*/
846 *(tdata->replyctrl) = TRANS_ABORT;
847 *(tdata->replyretry) = 1;
852 /* This function sends the final response to remote machines per thread in their respective socket id
853 * It returns a char that is only needed to check the correctness of execution of this function inside
855 char sendResponse(thread_data_array_t *tdata, int sd) {
856 int n, size, sum, oidcount = 0, control;
857 char *ptr, retval = 0;
858 unsigned int *oidnotfound;
860 control = *(tdata->replyctrl);
861 send_data(sd, &control, sizeof(char));
863 //TODO read missing objects to be used during object migration
864 /* If the decided response is due to a soft abort and missing objects at the Participant's side */
866 if(tdata->recvmsg[tdata->thread_id].rcv_status == TRANS_SOFT_ABORT) {
867 // Read list of objects missing
868 recv_data(sd, &oidcount, sizeof(int));
869 //if((read(sd, &oidcount, sizeof(int)) != 0) && (oidcount != 0)) {
871 size = oidcount * sizeof(unsigned int);
872 if((oidnotfound = calloc(oidcount, sizeof(unsigned int))) == NULL) {
873 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
876 ptr = (char *) oidnotfound;
877 recv_data(sd, ptr, size);
879 retval = TRANS_SOFT_ABORT;
883 /* If the decided response is TRANS_ABORT */
884 if(*(tdata->replyctrl) == TRANS_ABORT) {
885 retval = TRANS_ABORT;
886 } else if(*(tdata->replyctrl) == TRANS_COMMIT) { /* If the decided response is TRANS_COMMIT */
887 retval = TRANS_COMMIT;
893 /* This function opens a connection, places an object read request to the
894 * remote machine, reads the control message and object if available and
895 * copies the object and its header to the local cache.
898 void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
900 struct sockaddr_in serv_addr;
906 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
907 perror("Error in socket\n");
911 bzero((char*) &serv_addr, sizeof(serv_addr));
912 serv_addr.sin_family = AF_INET;
913 serv_addr.sin_port = htons(LISTEN_PORT);
914 midtoIP(mnum,machineip);
915 machineip[15] = '\0';
916 serv_addr.sin_addr.s_addr = inet_addr(machineip);
919 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
920 perror("getRemoteObj() Error in connect\n");
924 char readrequest[sizeof(char)+sizeof(unsigned int)];
925 readrequest[0] = READ_REQUEST;
926 *((unsigned int *)(&readrequest[1])) = oid;
927 send_data(sd, readrequest, sizeof(readrequest));
929 /* Read response from the Participant */
930 recv_data(sd, &control, sizeof(char));
933 case OBJECT_NOT_FOUND:
936 /* Read object if found into local cache */
937 recv_data(sd, &size, sizeof(int));
938 objcopy = objstrAlloc(record->cache, size);
939 recv_data(sd, objcopy, size);
941 /* Insert into cache's lookup table */
942 chashInsert(record->lookupTable, oid, objcopy);
945 printf("Error: in recv response from participant on a READ_REQUEST %s, %d\n",__FILE__, __LINE__);
954 /* This function handles the local objects involved in a transaction commiting process.
955 * It also makes a decision if this local machine sends AGREE or DISAGREE or SOFT_ABORT to coordinator.
956 * Note Coordinator = local machine
957 * It wakes up the other threads from remote participants that are waiting for the coordinator's decision and
958 * based on common agreement it either commits or aborts the transaction.
959 * It also frees the memory resources */
960 void *handleLocalReq(void *threadarg) {
961 unsigned int *oidnotfound = NULL, *oidlocked = NULL;
962 local_thread_data_array_t *localtdata;
963 int objnotfound = 0, objlocked = 0;
964 int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
967 unsigned short version;
969 objheader_t *headptr;
971 localtdata = (local_thread_data_array_t *) threadarg;
973 /* Counters and arrays to formulate decision on control message to be sent */
974 oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
975 oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
977 numread = localtdata->tdata->buffer->f.numread;
978 /* Process each oid in the machine pile/ group per thread */
979 for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) {
980 if (i < localtdata->tdata->buffer->f.numread) {
981 int incr = sizeof(unsigned int) + sizeof(unsigned short);// Offset that points to next position in the objread array
983 oid = *((unsigned int *)(((char *)localtdata->tdata->buffer->objread) + incr));
984 version = *((unsigned short *)(((char *)localtdata->tdata->buffer->objread) + incr + sizeof(unsigned int)));
985 } else { // Objects Modified
987 headptr = (objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidmod[i-numread]);
988 if (headptr == NULL) {
989 printf("Error: handleLocalReq() returning NULL %s, %d\n", __FILE__, __LINE__);
993 version = headptr->version;
995 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
997 /* Save the oids not found and number of oids not found for later use */
998 if ((mobj = mhashSearch(oid)) == NULL) { /* Obj not found */
999 /* Save the oids not found and number of oids not found for later use */
1000 oidnotfound[objnotfound] = oid;
1002 } else { /* If Obj found in machine (i.e. has not moved) */
1003 /* Check if Obj is locked by any previous transaction */
1004 if ((STATUS((objheader_t *)mobj) & LOCK) == LOCK) {
1005 if (version == ((objheader_t *)mobj)->version) { /* If locked then match versions */
1007 } else {/* If versions don't match ...HARD ABORT */
1009 /* Send TRANS_DISAGREE to Coordinator */
1010 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
1012 } else {/* If Obj is not locked then lock object */
1013 STATUS(((objheader_t *)mobj)) |= LOCK;
1014 /* Save all object oids that are locked on this machine during this transaction request call */
1015 oidlocked[objlocked] = OID(((objheader_t *)mobj));
1017 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
1019 } else { /* If versions don't match ...HARD ABORT */
1021 /* Send TRANS_DISAGREE to Coordinator */
1022 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
1027 /* Condition to send TRANS_AGREE */
1028 if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
1029 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
1031 /* Condition to send TRANS_SOFT_ABORT */
1032 if((v_matchlock > 0 && v_nomatch == 0) || (objnotfound > 0 && v_nomatch == 0)) {
1033 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
1036 /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
1037 * if Participant receives a TRANS_COMMIT */
1038 localtdata->transinfo->objlocked = oidlocked;
1039 localtdata->transinfo->objnotfound = oidnotfound;
1040 localtdata->transinfo->modptr = NULL;
1041 localtdata->transinfo->numlocked = objlocked;
1042 localtdata->transinfo->numnotfound = objnotfound;
1043 /* Lock and update count */
1044 //Thread sleeps until all messages from pariticipants are received by coordinator
1045 pthread_mutex_lock(localtdata->tdata->lock);
1046 (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */
1048 /* Wake up the threads and invoke decideResponse (once) */
1049 if(*(localtdata->tdata->count) == localtdata->tdata->buffer->f.mcount) {
1050 decideResponse(localtdata->tdata);
1051 pthread_cond_broadcast(localtdata->tdata->threshold);
1053 pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock);
1055 pthread_mutex_unlock(localtdata->tdata->lock);
1056 if(*(localtdata->tdata->replyctrl) == TRANS_ABORT){
1057 if(transAbortProcess(localtdata) != 0) {
1058 printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
1061 } else if(*(localtdata->tdata->replyctrl) == TRANS_COMMIT) {
1062 if(transComProcess(localtdata) != 0) {
1063 printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
1068 if (localtdata->transinfo->objlocked != NULL) {
1069 free(localtdata->transinfo->objlocked);
1071 if (localtdata->transinfo->objnotfound != NULL) {
1072 free(localtdata->transinfo->objnotfound);
1078 /* This function completes the ABORT process if the transaction is aborting */
1079 int transAbortProcess(local_thread_data_array_t *localtdata) {
1081 unsigned int *objlocked;
1084 numlocked = localtdata->transinfo->numlocked;
1085 objlocked = localtdata->transinfo->objlocked;
1087 for (i = 0; i < numlocked; i++) {
1088 if((header = mhashSearch(objlocked[i])) == NULL) {
1089 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1092 STATUS(((objheader_t *)header)) &= ~(LOCK);
1098 /*This function completes the COMMIT process is the transaction is commiting*/
1099 int transComProcess(local_thread_data_array_t *localtdata) {
1100 objheader_t *header, *tcptr;
1101 int i, nummod, tmpsize, numcreated, numlocked;
1102 unsigned int *oidmod, *oidcreated, *oidlocked;
1105 nummod = localtdata->tdata->buffer->f.nummod;
1106 oidmod = localtdata->tdata->buffer->oidmod;
1107 numcreated = localtdata->tdata->buffer->f.numcreated;
1108 oidcreated = localtdata->tdata->buffer->oidcreated;
1109 numlocked = localtdata->transinfo->numlocked;
1110 oidlocked = localtdata->transinfo->objlocked;
1112 for (i = 0; i < nummod; i++) {
1113 if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
1114 printf("Error: transComProcess() mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1117 /* Copy from transaction cache -> main object store */
1118 if ((tcptr = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidmod[i]))) == NULL) {
1119 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1122 GETSIZE(tmpsize, header);
1123 pthread_mutex_lock(&mainobjstore_mutex);
1124 memcpy((char*)header+sizeof(objheader_t), (char *)tcptr+ sizeof(objheader_t), tmpsize);
1125 header->version += 1;
1126 if(header->notifylist != NULL) {
1127 notifyAll(&header->notifylist, OID(header), header->version);
1129 pthread_mutex_unlock(&mainobjstore_mutex);
1131 /* If object is newly created inside transaction then commit it */
1132 for (i = 0; i < numcreated; i++) {
1133 if ((header = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidcreated[i]))) == NULL) {
1134 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1137 GETSIZE(tmpsize, header);
1138 tmpsize += sizeof(objheader_t);
1139 pthread_mutex_lock(&mainobjstore_mutex);
1140 if ((ptrcreate = objstrAlloc(mainobjstore, tmpsize)) == NULL) {
1141 printf("Error: transComProcess() failed objstrAlloc %s, %d\n", __FILE__, __LINE__);
1142 pthread_mutex_unlock(&mainobjstore_mutex);
1145 pthread_mutex_unlock(&mainobjstore_mutex);
1146 memcpy(ptrcreate, header, tmpsize);
1147 mhashInsert(oidcreated[i], ptrcreate);
1148 lhashInsert(oidcreated[i], myIpAddr);
1150 /* Unlock locked objects */
1151 for(i = 0; i < numlocked; i++) {
1152 if((header = (objheader_t *) mhashSearch(oidlocked[i])) == NULL) {
1153 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1156 STATUS(header) &= ~(LOCK);
1162 /* This function checks if the prefetch oids are same and have same offsets
1163 * for case x.a.b and y.a.b where x and y have same oid's
1164 * or if a.b.c is a subset of x.b.c.d*/
1165 /* check for case where the generated request a.y.z or x.y.z.g then
1166 * prefetch needs to be generated for x.y.z.g if oid of a and x are same*/
1167 void checkPrefetchTuples(prefetchqelem_t *node) {
1168 int i,j, count,k, sindex, index;
1170 int ntuples, slength;
1172 unsigned short *endoffsets;
1175 /* Check for the case x.y.z and a.b.c are same oids */
1176 ptr = (char *) node;
1177 ntuples = *(GET_NTUPLES(ptr));
1178 oid = GET_PTR_OID(ptr);
1179 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1180 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1182 /* Find offset length for each tuple */
1183 int numoffset[ntuples];
1184 numoffset[0] = endoffsets[0];
1185 for(i = 1; i<ntuples; i++) {
1186 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1188 /* Check for redundant tuples by comparing oids of each tuple */
1189 for(i = 0; i < ntuples; i++) {
1192 for(j = i+1 ; j < ntuples; j++) {
1195 /*If oids of tuples match */
1196 if (oid[i] == oid[j]) {
1197 /* Find the smallest offset length of two tuples*/
1198 if(numoffset[i] > numoffset[j]){
1199 slength = numoffset[j];
1203 slength = numoffset[i];
1207 /* Compare the offset values based on the current indices
1208 * break if they do not match
1209 * if all offset values match then pick the largest tuple*/
1214 k = endoffsets[i-1];
1216 index = endoffsets[j -1];
1217 for(count = 0; count < slength; count ++) {
1218 if (arryfields[k] != arryfields[index]) {
1224 if(slength == count) {
1231 /* This function makes machine piles to be added into the machine pile queue for each prefetch call */
1232 prefetchpile_t *makePreGroups(prefetchqelem_t *node, int *numoffset) {
1234 int ntuples, i, machinenum, count=0;
1236 unsigned short *endoffsets;
1237 short *arryfields, *offset;
1238 prefetchpile_t *head = NULL, *tmp = NULL;
1240 /* Check for the case x.y.z and a.b.c are same oids */
1241 ptr = (char *) node;
1242 ntuples = *(GET_NTUPLES(ptr));
1243 oid = GET_PTR_OID(ptr);
1244 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1245 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1247 if((head = (prefetchpile_t *) calloc(1, sizeof(prefetchpile_t))) == NULL) {
1248 printf("Calloc error: %s %d\n", __FILE__, __LINE__);
1252 /* Check for redundant tuples by comparing oids of each tuple */
1253 for(i = 0; i < ntuples; i++) {
1255 if(head->next != NULL) {
1256 if((tmp = (prefetchpile_t *) calloc(1, sizeof(prefetchpile_t))) == NULL) {
1257 printf("Calloc error: %s %d\n", __FILE__, __LINE__);
1260 tmp->mid = myIpAddr;
1264 head->mid = myIpAddr;
1268 /* For each tuple make piles */
1269 if ((machinenum = lhashSearch(oid[i])) == 0) {
1270 printf("Error: No such Machine %s, %d\n", __FILE__, __LINE__);
1273 /* Insert into machine pile */
1275 offset = &arryfields[0];
1277 offset = &arryfields[endoffsets[i-1]];
1280 if((head = insertPile(machinenum, oid[i], numoffset[i], offset, head)) == NULL){
1281 printf("Error: Couldn't create a pile %s, %d\n", __FILE__, __LINE__);
1289 prefetchpile_t *foundLocal(prefetchqelem_t *node) {
1290 int ntuples,i, j, k, oidnfound = 0, arryfieldindex,nextarryfieldindex, flag = 0, val;
1294 objheader_t *objheader;
1295 unsigned short *endoffsets;
1297 prefetchpile_t *head = NULL;
1299 ptr = (char *) node;
1300 ntuples = *(GET_NTUPLES(ptr));
1301 oid = GET_PTR_OID(ptr);
1302 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1303 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1305 /* Find offset length for each tuple */
1306 int numoffset[ntuples];//Number of offsets for each tuple
1307 numoffset[0] = endoffsets[0];
1308 for(i = 1; i<ntuples; i++) {
1309 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1312 for(i = 0; i < ntuples; i++) {
1316 nextarryfieldindex = endoffsets[0];
1318 arryfieldindex = endoffsets[i-1];
1319 nextarryfieldindex = endoffsets[i];
1322 endoffsets[0] = val = numoffset[0];
1323 for(k = 1; k < ntuples; k++) {
1324 val = val + numoffset[k];
1325 endoffsets[k] = val;
1328 for(k = 0; k<endoffsets[ntuples-1]; k++) {
1329 arryfields[arryfieldindex+k] = arryfields[nextarryfieldindex+k];
1334 /* If object found locally */
1335 if((objheader = (objheader_t*) mhashSearch(oid[i])) != NULL) {
1337 tmp = (char *) objheader;
1338 int orgnumoffset = numoffset[i];
1342 arryfieldindex = endoffsets[i-1];
1345 for(j = 0; j<orgnumoffset; j++) {
1346 unsigned int objoid = 0;
1347 /* Check for arrays */
1348 if(TYPE(objheader) > NUMCLASSES) {
1352 int elementsize = classsize[TYPE(objheader)];
1353 struct ArrayObject *ao = (struct ArrayObject *) (tmp + sizeof(objheader_t));
1354 int length = ao->___length___;
1355 /* Check if array out of bounds */
1356 if(arryfields[arryfieldindex] < 0 || arryfields[arryfieldindex] >= length) {
1357 break; //if yes then treat the object as found
1359 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*arryfields[arryfieldindex])));
1361 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + arryfields[arryfieldindex]));
1363 //Update numoffset array
1364 numoffset[i] = numoffset[i] - 1;
1367 //Update endoffset array
1368 endoffsets[0] = val = numoffset[0];
1369 for(k = 1; k < ntuples; k++) {
1370 val = val + numoffset[k];
1371 endoffsets[k] = val;
1373 //Update arrayfields array
1374 for(k = 0; k < endoffsets[ntuples-1]; k++) {
1375 arryfields[arryfieldindex+k] = arryfields[arryfieldindex+k+1];
1377 if((objheader = (objheader_t*) mhashSearch(oid[i])) == NULL) {
1379 checkPreCache(node, numoffset, oid[i], i);
1382 tmp = (char *) objheader;
1385 /*If all offset oids are found locally,make the prefetch tuple invalid */
1390 /* Look in Prefetch cache */
1391 checkPreCache(node, numoffset, oid[i],i);
1396 /* Make machine groups */
1397 if((head = makePreGroups(node, numoffset)) == NULL) {
1398 printf("Error in makePreGroups() %s %d\n", __FILE__, __LINE__);
1405 void checkPreCache(prefetchqelem_t *node, int *numoffset, unsigned int objoid, int index) {
1407 int ntuples, i, k, flag=0, isArray =0, arryfieldindex, val;
1409 unsigned short *endoffsets;
1411 objheader_t *header;
1413 ptr = (char *) node;
1414 ntuples = *(GET_NTUPLES(ptr));
1415 oid = GET_PTR_OID(ptr);
1416 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1417 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1419 if((header = (objheader_t *) prehashSearch(objoid)) == NULL) {
1421 } else { //Found in Prefetch Cache
1422 //TODO Decide if object is too old, if old remove from cache
1423 tmp = (char *) header;
1424 int loopcount = numoffset[index];
1428 arryfieldindex = endoffsets[(index - 1)];
1429 // Check if any of the offset oid is available in the Prefetch cache
1430 for(i = 0; i < loopcount; i++) {
1431 /* Check for arrays */
1432 if(TYPE(header) > NUMCLASSES) {
1437 int elementsize = classsize[TYPE(header)];
1438 struct ArrayObject *ao = (struct ArrayObject *) (tmp + sizeof(objheader_t));
1439 int length = ao->___length___;
1440 /* Check if array out of bounds */
1441 if(arryfields[arryfieldindex] < 0 || arryfields[arryfieldindex] >= length) {
1442 break; //if yes treat the object as found
1444 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*arryfields[arryfieldindex])));
1446 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + arryfields[arryfieldindex]));
1448 //Update numoffset array
1449 numoffset[index] = numoffset[index] - 1;
1451 oid[index] = objoid;
1452 //Update endoffset array
1453 endoffsets[0] = val = numoffset[0];
1454 for(k = 1; k < ntuples; k++) {
1455 val = val + numoffset[k];
1456 endoffsets[k] = val;
1458 //Update arrayfields array
1459 for(k = 0; k < endoffsets[ntuples-1]; k++) {
1460 arryfields[arryfieldindex+k] = arryfields[arryfieldindex+k+1];
1462 if((header = (objheader_t *)prehashSearch(oid[index])) != NULL) {
1463 tmp = (char *) header;
1471 //Found in the prefetch cache
1472 if(flag == 0 && (numoffset[index] == 0)) {
1479 /* This function is called by the thread calling transPrefetch */
1480 void *transPrefetch(void *t) {
1481 prefetchqelem_t *qnode;
1482 prefetchpile_t *pilehead = NULL;
1483 prefetchpile_t *ptr = NULL, *piletail = NULL;
1486 /* lock mutex of primary prefetch queue */
1487 pthread_mutex_lock(&pqueue.qlock);
1488 /* while primary queue is empty, then wait */
1489 while((pqueue.front == NULL) && (pqueue.rear == NULL)) {
1490 pthread_cond_wait(&pqueue.qcond, &pqueue.qlock);
1493 /* dequeue node to create a machine piles and finally unlock mutex */
1494 if((qnode = pre_dequeue()) == NULL) {
1495 printf("Error: No node returned %s, %d\n", __FILE__, __LINE__);
1496 pthread_mutex_unlock(&pqueue.qlock);
1499 pthread_mutex_unlock(&pqueue.qlock);
1501 /* Reduce redundant prefetch requests */
1502 checkPrefetchTuples(qnode);
1503 /* Check if the tuples are found locally, if yes then reduce them further*/
1504 /* and group requests by remote machine ids by calling the makePreGroups() */
1505 if((pilehead = foundLocal(qnode)) == NULL) {
1506 printf("Error: No node created for serving prefetch request %s %d\n", __FILE__, __LINE__);
1512 while(ptr != NULL) {
1513 if(ptr->next == NULL) {
1519 /* Lock mutex of pool queue */
1520 pthread_mutex_lock(&mcqueue.qlock);
1521 /* Update the pool queue with the new remote machine piles generated per prefetch call */
1522 mcpileenqueue(pilehead, piletail);
1523 /* Broadcast signal on machine pile queue */
1524 pthread_cond_broadcast(&mcqueue.qcond);
1525 /* Unlock mutex of machine pile queue */
1526 pthread_mutex_unlock(&mcqueue.qlock);
1527 /* Deallocate the prefetch queue pile node */
1532 /* Each thread in the pool of threads calls this function to establish connection with
1533 * remote machines, send the prefetch requests and process the reponses from
1534 * the remote machines .
1535 * The thread is active throughout the period of runtime */
1537 void *mcqProcess(void *threadid) {
1539 prefetchpile_t *mcpilenode;
1540 struct sockaddr_in remoteAddr;
1543 tid = (int) threadid;
1547 /* Lock mutex of mc pile queue */
1548 pthread_mutex_lock(&mcqueue.qlock);
1549 /* When mc pile queue is empty, wait */
1550 while((mcqueue.front == NULL) && (mcqueue.rear == NULL)) {
1551 pthread_cond_wait(&mcqueue.qcond, &mcqueue.qlock);
1553 /* Dequeue node to send remote machine connections*/
1554 if((mcpilenode = mcpiledequeue()) == NULL) {
1555 printf("Dequeue Error: No node returned %s %d\n", __FILE__, __LINE__);
1556 pthread_mutex_unlock(&mcqueue.qlock);
1560 pthread_mutex_unlock(&mcqueue.qlock);
1562 /*Initiate connection to remote host and send prefetch request */
1563 if(mcpilenode->mid != myIpAddr) {
1564 /* Check to see if socket exists */
1565 for(i = 0; i < NUM_MACHINES; i++) {
1566 if(midSocketArray[i].mid == mcpilenode->mid) {
1567 sendPrefetchReq(mcpilenode, midSocketArray[i].sockid);
1573 if(sockIdFound == 0) {
1574 if(sockCount < NUM_MACHINES) {
1576 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
1577 printf("%s() Error: In creating socket at %s, %d\n", __func__, __FILE__, __LINE__);
1581 bzero(&remoteAddr, sizeof(remoteAddr));
1582 remoteAddr.sin_family = AF_INET;
1583 remoteAddr.sin_port = htons(LISTEN_PORT);
1584 remoteAddr.sin_addr.s_addr = htonl(mcpilenode->mid);
1586 /* Open Connection */
1587 if (connect(sd, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0) {
1588 printf("%s():error %d connecting to %s:%d\n", __func__, errno,
1589 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1594 midSocketArray[sockCount].mid = mcpilenode->mid;
1595 midSocketArray[sockCount].sockid = sd;
1596 sendPrefetchReq(mcpilenode, midSocketArray[sockCount].sockid);
1599 //TODO Fix for connecting to more than 2 machines && close socket
1600 printf("%s(): Error: Currently works for only 2 machines\n", __func__);
1606 /* Deallocate the machine queue pile node */
1607 mcdealloc(mcpilenode);
1611 void sendPrefetchReq(prefetchpile_t *mcpilenode, int sd) {
1612 int i, off, len, endpair, count = 0;
1613 char machineip[16], control;
1616 /* Send TRANS_PREFETCH control message */
1617 control = TRANS_PREFETCH;
1618 send_data(sd, &control, sizeof(char));
1620 /* Send Oids and offsets in pairs */
1621 tmp = mcpilenode->objpiles;
1622 while(tmp != NULL) {
1624 count++; /* Keeps track of the number of oid and offset tuples sent per remote machine */
1625 len = sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1626 char oidnoffset[len];
1627 bzero(oidnoffset, len);
1628 *((int*)oidnoffset) = len;
1630 *((unsigned int *)(oidnoffset + off)) = tmp->oid;
1631 off += sizeof(unsigned int);
1632 *((unsigned int *)(oidnoffset + off)) = myIpAddr;
1633 off += sizeof(unsigned int);
1634 for(i = 0; i < tmp->numoffset; i++) {
1635 *((short*)(oidnoffset + off)) = tmp->offset[i];
1638 send_data(sd, oidnoffset, len);
1642 /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
1644 send_data(sd, &endpair, sizeof(int));
1649 int getPrefetchResponse(int sd) {
1650 int numbytes = 0, length = 0, size = 0;
1651 char *recvbuffer, control;
1653 void *modptr, *oldptr;
1655 recv_data((int)sd, &length, sizeof(int));
1656 size = length - sizeof(int);
1657 if((recvbuffer = calloc(1, size)) == NULL) {
1658 printf("%s() Calloc error at %s,%d\n", __func__, __FILE__, __LINE__);
1662 recv_data((int)sd, recvbuffer, size);
1664 control = *((char *) recvbuffer);
1665 if(control == OBJECT_FOUND) {
1667 oid = *((unsigned int *)(recvbuffer + sizeof(char)));
1668 size = size - (sizeof(char) + sizeof(unsigned int));
1669 pthread_mutex_lock(&prefetchcache_mutex);
1670 if ((modptr = objstrAlloc(prefetchcache, size)) == NULL) {
1671 printf("Error: objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
1672 pthread_mutex_unlock(&prefetchcache_mutex);
1676 pthread_mutex_unlock(&prefetchcache_mutex);
1677 memcpy(modptr, recvbuffer + sizeof(char) + sizeof(unsigned int), size);
1679 /* Insert the oid and its address into the prefetch hash lookup table */
1680 /* Do a version comparison if the oid exists */
1681 if((oldptr = prehashSearch(oid)) != NULL) {
1682 /* If older version then update with new object ptr */
1683 if(((objheader_t *)oldptr)->version <= ((objheader_t *)modptr)->version) {
1685 prehashInsert(oid, modptr);
1687 /* TODO modptr should be reference counted */
1689 } else {/* Else add the object ptr to hash table*/
1690 prehashInsert(oid, modptr);
1692 /* Lock the Prefetch Cache look up table*/
1693 pthread_mutex_lock(&pflookup.lock);
1694 /* Broadcast signal on prefetch cache condition variable */
1695 pthread_cond_broadcast(&pflookup.cond);
1696 /* Unlock the Prefetch Cache look up table*/
1697 pthread_mutex_unlock(&pflookup.lock);
1698 } else if(control == OBJECT_NOT_FOUND) {
1699 oid = *((unsigned int *)(recvbuffer + sizeof(char)));
1700 /* TODO: For each object not found query DHT for new location and retrieve the object */
1701 /* Throw an error */
1702 printf("OBJECT %x NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n", oid);
1706 printf("Error: in decoding the control value %d, %s, %d\n",control, __FILE__, __LINE__);
1714 unsigned short getObjType(unsigned int oid)
1716 objheader_t *objheader;
1717 unsigned short numoffset[] ={0};
1718 short fieldoffset[] ={};
1720 if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL)
1722 if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1724 prefetch(1, &oid, numoffset, fieldoffset);
1725 pthread_mutex_lock(&pflookup.lock);
1726 while ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1728 pthread_cond_wait(&pflookup.cond, &pflookup.lock);
1730 pthread_mutex_unlock(&pflookup.lock);
1734 return TYPE(objheader);
1737 int startRemoteThread(unsigned int oid, unsigned int mid)
1740 struct sockaddr_in remoteAddr;
1741 char msg[1 + sizeof(unsigned int)];
1745 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
1747 perror("startRemoteThread():socket()");
1751 bzero(&remoteAddr, sizeof(remoteAddr));
1752 remoteAddr.sin_family = AF_INET;
1753 remoteAddr.sin_port = htons(LISTEN_PORT);
1754 remoteAddr.sin_addr.s_addr = htonl(mid);
1756 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0)
1758 printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
1759 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1764 msg[0] = START_REMOTE_THREAD;
1765 memcpy(&msg[1], &oid, sizeof(unsigned int));
1766 send_data(sock, msg, 1 + sizeof(unsigned int));
1773 //TODO: when reusing oids, make sure they are not already in use!
1774 unsigned int getNewOID(void) {
1775 static unsigned int id = 0xFFFFFFFF;
1778 if (id > oidMax || id < oidMin)
1785 int processConfigFile()
1788 const int maxLineLength = 200;
1789 char lineBuffer[maxLineLength];
1791 const char *delimiters = " \t\n";
1795 configFile = fopen(CONFIG_FILENAME, "r");
1796 if (configFile == NULL)
1798 printf("error opening %s:\n", CONFIG_FILENAME);
1803 numHostsInSystem = 0;
1804 sizeOfHostArray = 8;
1805 hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
1807 while(fgets(lineBuffer, maxLineLength, configFile) != NULL)
1809 commentBegin = strchr(lineBuffer, '#');
1810 if (commentBegin != NULL)
1811 *commentBegin = '\0';
1812 token = strtok(lineBuffer, delimiters);
1813 while (token != NULL)
1815 tmpAddr = inet_addr(token);
1816 if ((int)tmpAddr == -1)
1818 printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
1823 addHost(htonl(tmpAddr));
1824 token = strtok(NULL, delimiters);
1830 if (numHostsInSystem < 1)
1832 printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
1836 myIpAddr = getMyIpAddr("en1");
1838 myIpAddr = getMyIpAddr("eth0");
1840 myIndexInHostArray = findHost(myIpAddr);
1841 if (myIndexInHostArray == -1)
1843 printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
1846 oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
1847 oidMin = oidsPerBlock * myIndexInHostArray;
1848 if (myIndexInHostArray == numHostsInSystem - 1)
1849 oidMax = 0xFFFFFFFF;
1851 oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
1856 void addHost(unsigned int hostIp)
1858 unsigned int *tmpArray;
1860 if (findHost(hostIp) != -1)
1863 if (numHostsInSystem == sizeOfHostArray)
1865 tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
1866 memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
1868 hostIpAddrs = tmpArray;
1871 hostIpAddrs[numHostsInSystem++] = hostIp;
1876 int findHost(unsigned int hostIp)
1879 for (i = 0; i < numHostsInSystem; i++)
1880 if (hostIpAddrs[i] == hostIp)
1887 /* This function sends notification request per thread waiting on object(s) whose version
1889 int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int numoid) {
1891 objheader_t *objheader;
1892 struct sockaddr_in remoteAddr;
1893 char msg[1 + numoid * (sizeof(unsigned short) + sizeof(unsigned int)) + 3 * sizeof(unsigned int)];
1897 unsigned short version;
1898 unsigned int oid,mid;
1899 static unsigned int threadid = 0;
1900 pthread_mutex_t threadnotify = PTHREAD_MUTEX_INITIALIZER; //Lock and condition var for threadjoin and notification
1901 pthread_cond_t threadcond = PTHREAD_COND_INITIALIZER;
1902 notifydata_t *ndata;
1904 //FIXME currently all oids belong to one machine
1906 if((mid = lhashSearch(oid)) == 0) {
1907 printf("Error: %s() No such machine found for oid =%x\n",__func__, oid);
1911 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1912 perror("reqNotify():socket()");
1916 bzero(&remoteAddr, sizeof(remoteAddr));
1917 remoteAddr.sin_family = AF_INET;
1918 remoteAddr.sin_port = htons(LISTEN_PORT);
1919 remoteAddr.sin_addr.s_addr = htonl(mid);
1921 /* Generate unique threadid */
1924 /* Save threadid, numoid, oidarray, versionarray, pthread_cond_variable for later processing */
1925 if((ndata = calloc(1, sizeof(notifydata_t))) == NULL) {
1926 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
1929 ndata->numoid = numoid;
1930 ndata->threadid = threadid;
1931 ndata->oidarry = oidarry;
1932 ndata->versionarry = versionarry;
1933 ndata->threadcond = threadcond;
1934 ndata->threadnotify = threadnotify;
1935 if((status = notifyhashInsert(threadid, ndata)) != 0) {
1936 printf("reqNotify(): Insert into notify hash table not successful %s, %d\n", __FILE__, __LINE__);
1941 /* Send number of oids, oidarry, version array, machine id and threadid */
1942 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1943 printf("reqNotify():error %d connecting to %s:%d\n", errno,
1944 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1948 msg[0] = THREAD_NOTIFY_REQUEST;
1949 *((unsigned int *)(&msg[1])) = numoid;
1950 /* Send array of oids */
1951 size = sizeof(unsigned int);
1956 *((unsigned int *)(&msg[1] + size)) = oid;
1957 size += sizeof(unsigned int);
1962 /* Send array of version */
1966 version = versionarry[i];
1967 *((unsigned short *)(&msg[1] + size)) = version;
1968 size += sizeof(unsigned short);
1973 *((unsigned int *)(&msg[1] + size)) = myIpAddr;
1974 size += sizeof(unsigned int);
1975 *((unsigned int *)(&msg[1] + size)) = threadid;
1977 pthread_mutex_lock(&(ndata->threadnotify));
1978 size = 1 + numoid * (sizeof(unsigned int) + sizeof(unsigned short)) + 3 * sizeof(unsigned int);
1979 send_data(sock, msg, size);
1980 pthread_cond_wait(&(ndata->threadcond), &(ndata->threadnotify));
1981 pthread_mutex_unlock(&(ndata->threadnotify));
1984 pthread_cond_destroy(&threadcond);
1985 pthread_mutex_destroy(&threadnotify);
1991 void threadNotify(unsigned int oid, unsigned short version, unsigned int tid) {
1992 notifydata_t *ndata;
1993 int i, objIsFound = 0, index;
1996 //Look up the tid and call the corresponding pthread_cond_signal
1997 if((ndata = notifyhashSearch(tid)) == NULL) {
1998 printf("threadnotify(): No such threadid is present %s, %d\n", __FILE__, __LINE__);
2001 for(i = 0; i < ndata->numoid; i++) {
2002 if(ndata->oidarry[i] == oid){
2007 if(objIsFound == 0){
2008 printf("threadNotify(): Oid not found %s, %d\n", __FILE__, __LINE__);
2011 if(version <= ndata->versionarry[index]){
2012 printf("threadNotify(): New version %d has not changed since last version %s, %d\n", version, __FILE__, __LINE__);
2015 /* Clear from prefetch cache and free thread related data structure */
2016 if((ptr = prehashSearch(oid)) != NULL) {
2019 pthread_cond_signal(&(ndata->threadcond));
2026 int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) {
2029 struct sockaddr_in remoteAddr;
2030 char msg[1 + sizeof(unsigned short) + 2*sizeof(unsigned int)];
2031 int sock, status, size, bytesSent;
2033 while(*head != NULL) {
2036 //create a socket connection to that machine
2037 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
2038 perror("notifyAll():socket()");
2042 bzero(&remoteAddr, sizeof(remoteAddr));
2043 remoteAddr.sin_family = AF_INET;
2044 remoteAddr.sin_port = htons(LISTEN_PORT);
2045 remoteAddr.sin_addr.s_addr = htonl(mid);
2046 //send Thread Notify response and threadid to that machine
2047 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
2048 printf("notifyAll():error %d connecting to %s:%d\n", errno,
2049 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
2052 bzero(msg, (1+sizeof(unsigned short) + 2*sizeof(unsigned int)));
2053 msg[0] = THREAD_NOTIFY_RESPONSE;
2054 *((unsigned int *)&msg[1]) = oid;
2055 size = sizeof(unsigned int);
2056 *((unsigned short *)(&msg[1]+ size)) = version;
2057 size+= sizeof(unsigned short);
2058 *((unsigned int *)(&msg[1]+ size)) = ptr->threadid;
2060 size = 1 + 2*sizeof(unsigned int) + sizeof(unsigned short);
2061 send_data(sock, msg, size);
2072 void transAbort(transrecord_t *trans) {
2073 objstrDelete(trans->cache);
2074 chashDelete(trans->lookupTable);