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) {
134 /* Allocate for the queue node*/
137 qnodesize = sizeof(prefetchqelem_t) + sizeof(int) + ntuples * (sizeof(unsigned short) + sizeof(unsigned int)) + endoffsets[ntuples - 1] * sizeof(short);
138 if((node = calloc(1, qnodesize)) == NULL) {
139 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
142 /* Set queue node values */
143 len = sizeof(prefetchqelem_t);
144 memcpy(node + len, &ntuples, sizeof(int));
146 memcpy(node + len, oids, ntuples*sizeof(unsigned int));
147 len += ntuples * sizeof(unsigned int);
148 memcpy(node + len, endoffsets, ntuples*sizeof(unsigned short));
149 len += ntuples * sizeof(unsigned short);
150 memcpy(node + len, arrayfields, endoffsets[ntuples-1]*sizeof(short));
151 /* Lock and insert into primary prefetch queue */
152 pthread_mutex_lock(&pqueue.qlock);
153 pre_enqueue((prefetchqelem_t *)node);
154 pthread_cond_signal(&pqueue.qcond);
155 pthread_mutex_unlock(&pqueue.qlock);
159 /* This function starts up the transaction runtime. */
160 int dstmStartup(const char * option) {
161 pthread_t thread_Listen;
163 int master=option!=NULL && strcmp(option, "master")==0;
165 if (processConfigFile() != 0)
166 return 0; //TODO: return error value, cause main program to exit
178 pthread_attr_init(&attr);
179 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
180 pthread_create(&thread_Listen, &attr, dstmListen, NULL);
189 //TODO Use this later
190 void *pCacheAlloc(objstr_t *store, unsigned int size) {
196 while(ptr->next != NULL) {
197 /* check if store is empty */
198 if(((unsigned int)ptr->top - (unsigned int)ptr - sizeof(objstr_t) + size) <= ptr->size) {
213 /* This function initiates the prefetch thread
214 * A queue is shared between the main thread of execution
215 * and the prefetch thread to process the prefetch call
216 * Call from compiler populates the shared queue with prefetch requests while prefetch thread
217 * processes the prefetch requests */
221 //Create and initialize prefetch cache structure
222 prefetchcache = objstrCreate(PREFETCH_CACHE_SIZE);
223 //prefetchcache->next = objstrCreate(PREFETCH_CACHE_SIZE);
224 //prefetchcache->next->next = objstrCreate(PREFETCH_CACHE_SIZE);
226 /* Initialize attributes for mutex */
227 pthread_mutexattr_init(&prefetchcache_mutex_attr);
228 pthread_mutexattr_settype(&prefetchcache_mutex_attr, PTHREAD_MUTEX_RECURSIVE_NP);
230 pthread_mutex_init(&prefetchcache_mutex, &prefetchcache_mutex_attr);
232 //Create prefetch cache lookup table
233 if(prehashCreate(HASH_SIZE, LOADFACTOR))
236 //Initialize primary shared queue
238 //Initialize machine pile w/prefetch oids and offsets shared queue
241 //Create the primary prefetch thread
243 retval=pthread_create(&tPrefetch, NULL, transPrefetch, NULL);
245 pthread_detach(tPrefetch);
247 //Initialize mid to socketid mapping array
249 for(t = 0; t < NUM_MACHINES; t++) {
250 midSocketArray[t].mid = 0;
251 midSocketArray[t].sockid = 0;
254 //Create and Initialize a pool of threads
255 /* Threads are active for the entire period runtime is running */
256 for(t = 0; t< NUM_THREADS; t++) {
258 rc = pthread_create(&wthreads[t], NULL, mcqProcess, (void *)t);
260 pthread_detach(wthreads[t]);
264 /* This function stops the threads spawned */
267 pthread_cancel(tPrefetch);
268 for(t = 0; t < NUM_THREADS; t++)
269 pthread_cancel(wthreads[t]);
274 /* This functions inserts randowm wait delays in the order of msec
275 * Mostly used when transaction commits retry*/
283 req.tv_nsec = (long)(1000000 + (t%10000000)); //1-11 msec
284 nanosleep(&req, NULL);
288 /* This function initializes things required in the transaction start*/
289 transrecord_t *transStart()
291 transrecord_t *tmp = calloc(1, sizeof(transrecord_t));
292 tmp->cache = objstrCreate(1048576);
293 tmp->lookupTable = chashCreate(HASH_SIZE, LOADFACTOR);
295 tmp->revertlist=NULL;
300 /* This function finds the location of the objects involved in a transaction
301 * and returns the pointer to the object if found in a remote location */
302 objheader_t *transRead(transrecord_t *record, unsigned int oid) {
303 unsigned int machinenumber;
304 objheader_t *tmp, *objheader;
305 objheader_t *objcopy;
306 int size, rc, found = 0;
312 printf("Error: %s, %d oid is NULL \n", __FILE__, __LINE__);
316 rc = gettimeofday(&tp, NULL);
320 if (tp.tv_usec >= 1000000)
322 tp.tv_usec -= 1000000;
325 /* Convert from timeval to timespec */
326 ts.tv_sec = tp.tv_sec;
327 ts.tv_nsec = tp.tv_usec * 1000;
329 /* Search local transaction cache */
330 if((objheader = (objheader_t *)chashSearch(record->lookupTable, oid)) != NULL){
333 return &objheader[1];
337 } else if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
338 /* Look up in machine lookup table and copy into cache*/
339 GETSIZE(size, objheader);
340 size += sizeof(objheader_t);
341 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
342 memcpy(objcopy, objheader, size);
343 /* Insert into cache's lookup table */
344 chashInsert(record->lookupTable, OID(objheader), objcopy);
350 } else if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) { /* Look up in prefetch cache */
352 size+=sizeof(objheader_t);
353 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
354 memcpy(objcopy, tmp, size);
355 /* Insert into cache's lookup table */
356 chashInsert(record->lookupTable, OID(tmp), objcopy);
363 /*If object not found in prefetch cache then block until object appears in the prefetch cache */
365 pthread_mutex_lock(&pflookup.lock);
367 rc = pthread_cond_timedwait(&pflookup.cond, &pflookup.lock, &ts);
368 // Check Prefetch cache again
369 if((tmp =(objheader_t *) prehashSearch(oid)) != NULL) {
372 size+=sizeof(objheader_t);
373 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
374 memcpy(objcopy, tmp, size);
375 chashInsert(record->lookupTable, OID(tmp), objcopy);
376 pthread_mutex_unlock(&pflookup.lock);
382 } else if (rc == ETIMEDOUT) {
383 pthread_mutex_unlock(&pflookup.lock);
389 /* Get the object from the remote location */
390 if((machinenumber = lhashSearch(oid)) == 0) {
391 printf("Error: %s() No machine found for oid =% %s,%dx\n",__func__, machinenumber, __FILE__, __LINE__);
394 objcopy = getRemoteObj(record, machinenumber, oid);
396 if(objcopy == NULL) {
397 printf("Error: Object not found in Remote location %s, %d\n", __FILE__, __LINE__);
410 /* This function creates objects in the transaction record */
411 objheader_t *transCreateObj(transrecord_t *record, unsigned int size)
413 objheader_t *tmp = (objheader_t *) objstrAlloc(record->cache, (sizeof(objheader_t) + size));
414 tmp->notifylist = NULL;
415 OID(tmp) = getNewOID();
419 chashInsert(record->lookupTable, OID(tmp), tmp);
422 return &tmp[1]; //want space after object header
428 /* This function creates machine piles based on all machines involved in a
429 * transaction commit request */
430 plistnode_t *createPiles(transrecord_t *record) {
432 unsigned int size;/* Represents number of bins in the chash table */
433 chashlistnode_t *curr, *ptr, *next;
434 plistnode_t *pile = NULL;
435 unsigned int machinenum;
436 void *localmachinenum;
437 objheader_t *headeraddr;
439 ptr = record->lookupTable->table;
440 size = record->lookupTable->size;
442 for(i = 0; i < size ; i++) {
444 /* Inner loop to traverse the linked list of the cache lookupTable */
445 while(curr != NULL) {
446 //if the first bin in hash table is empty
452 if ((headeraddr = chashSearch(record->lookupTable, curr->key)) == NULL) {
453 printf("Error: No such oid %s, %d\n", __FILE__, __LINE__);
457 //Get machine location for object id (and whether local or not)
458 if (STATUS(headeraddr) & NEW || (mhashSearch(curr->key) != NULL)) {
459 machinenum = myIpAddr;
460 } else if ((machinenum = lhashSearch(curr->key)) == 0) {
461 printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
465 //Make machine groups
466 if ((pile = pInsert(pile, headeraddr, machinenum, record->lookupTable->numelements)) == NULL) {
467 printf("pInsert error %s, %d\n", __FILE__, __LINE__);
477 /* This function initiates the transaction commit process
478 * Spawns threads for each of the new connections with Participants
479 * and creates new piles by calling the createPiles(),
480 * Sends a transrequest() to each remote machines for objects found remotely
481 * and calls handleLocalReq() to process objects found locally */
482 int transCommit(transrecord_t *record) {
483 unsigned int tot_bytes_mod, *listmid;
484 plistnode_t *pile, *pile_ptr;
486 int pilecount, offset, threadnum = 0, trecvcount = 0;
488 char transid[TID_LEN];
489 trans_req_data_t *tosend;
490 trans_commit_data_t transinfo;
491 static int newtid = 0;
492 char treplyctrl = 0, treplyretry = 0; /* keeps track of the common response that needs to be sent */
494 thread_data_array_t *thread_data_array;
495 local_thread_data_array_t *ltdata;
501 thread_data_array = NULL;
504 /* Look through all the objects in the transaction record and make piles
505 * for each machine involved in the transaction*/
506 pile_ptr = pile = createPiles(record);
508 /* Create the packet to be sent in TRANS_REQUEST */
510 /* Count the number of participants */
511 pilecount = pCount(pile);
513 /* Create a list of machine ids(Participants) involved in transaction */
514 if((listmid = calloc(pilecount, sizeof(unsigned int))) == NULL) {
515 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
518 pListMid(pile, listmid);
521 /* Initialize thread variables,
522 * Spawn a thread for each Participant involved in a transaction */
523 pthread_t thread[pilecount];
525 pthread_cond_t tcond;
526 pthread_mutex_t tlock;
527 pthread_mutex_t tlshrd;
529 if((thread_data_array = (thread_data_array_t *) calloc(pilecount, sizeof(thread_data_array_t))) == NULL) {
530 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
531 pthread_cond_destroy(&tcond);
532 pthread_mutex_destroy(&tlock);
538 if((ltdata = calloc(1, sizeof(local_thread_data_array_t))) == NULL) {
539 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
540 pthread_cond_destroy(&tcond);
541 pthread_mutex_destroy(&tlock);
544 free(thread_data_array);
548 thread_response_t rcvd_control_msg[pilecount]; /* Shared thread array that keeps track of responses of participants */
550 /* Initialize and set thread detach attribute */
551 pthread_attr_init(&attr);
552 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
553 pthread_mutex_init(&tlock, NULL);
554 pthread_cond_init(&tcond, NULL);
556 /* Process each machine pile */
557 while(pile != NULL) {
558 //Create transaction id
560 if ((tosend = calloc(1, sizeof(trans_req_data_t))) == NULL) {
561 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
562 pthread_cond_destroy(&tcond);
563 pthread_mutex_destroy(&tlock);
566 free(thread_data_array);
570 tosend->f.control = TRANS_REQUEST;
571 sprintf(tosend->f.trans_id, "%x_%d", pile->mid, newtid);
572 tosend->f.mcount = pilecount;
573 tosend->f.numread = pile->numread;
574 tosend->f.nummod = pile->nummod;
575 tosend->f.numcreated = pile->numcreated;
576 tosend->f.sum_bytes = pile->sum_bytes;
577 tosend->listmid = listmid;
578 tosend->objread = pile->objread;
579 tosend->oidmod = pile->oidmod;
580 tosend->oidcreated = pile->oidcreated;
581 thread_data_array[threadnum].thread_id = threadnum;
582 thread_data_array[threadnum].mid = pile->mid;
583 thread_data_array[threadnum].buffer = tosend;
584 thread_data_array[threadnum].recvmsg = rcvd_control_msg;
585 thread_data_array[threadnum].threshold = &tcond;
586 thread_data_array[threadnum].lock = &tlock;
587 thread_data_array[threadnum].count = &trecvcount;
588 thread_data_array[threadnum].replyctrl = &treplyctrl;
589 thread_data_array[threadnum].replyretry = &treplyretry;
590 thread_data_array[threadnum].rec = record;
591 /* If local do not create any extra connection */
592 if(pile->mid != myIpAddr) { /* Not local */
594 rc = pthread_create(&thread[threadnum], &attr, transRequest, (void *) &thread_data_array[threadnum]);
597 perror("Error in pthread create\n");
598 pthread_cond_destroy(&tcond);
599 pthread_mutex_destroy(&tlock);
602 for (i = 0; i < threadnum; i++)
603 free(thread_data_array[i].buffer);
604 free(thread_data_array);
609 ltdata->tdata = &thread_data_array[threadnum];
610 ltdata->transinfo = &transinfo;
612 val = pthread_create(&thread[threadnum], &attr, handleLocalReq, (void *) ltdata);
615 perror("Error in pthread create\n");
616 pthread_cond_destroy(&tcond);
617 pthread_mutex_destroy(&tlock);
620 for (i = 0; i < threadnum; i++)
621 free(thread_data_array[i].buffer);
622 free(thread_data_array);
631 /* Free attribute and wait for the other threads */
632 pthread_attr_destroy(&attr);
634 for (i = 0; i < threadnum; i++) {
635 rc = pthread_join(thread[i], NULL);
638 printf("Error: return code from pthread_join() is %d\n", rc);
639 pthread_cond_destroy(&tcond);
640 pthread_mutex_destroy(&tlock);
643 for (j = i; j < threadnum; j++) {
644 free(thread_data_array[j].buffer);
648 free(thread_data_array[i].buffer);
652 pthread_cond_destroy(&tcond);
653 pthread_mutex_destroy(&tlock);
657 /* wait a random amount of time before retrying to commit transaction*/
658 if(treplyretry == 1) {
659 free(thread_data_array);
664 /* Retry trans commit procedure during soft_abort case */
665 } while (treplyretry == 1);
668 if(treplyctrl == TRANS_ABORT) {
670 objstrDelete(record->cache);
671 chashDelete(record->lookupTable);
673 free(thread_data_array);
676 } else if(treplyctrl == TRANS_COMMIT) {
678 objstrDelete(record->cache);
679 chashDelete(record->lookupTable);
681 free(thread_data_array);
685 //TODO Add other cases
686 printf("Error: in %s() THIS SHOULD NOT HAPPEN.....EXIT PROGRAM\n", __func__);
693 /* This function sends information involved in the transaction request
694 * to participants and accepts a response from particpants.
695 * It calls decideresponse() to decide on what control message
696 * to send next to participants and sends the message using sendResponse()*/
697 void *transRequest(void *threadarg) {
699 struct sockaddr_in serv_addr;
700 thread_data_array_t *tdata;
701 objheader_t *headeraddr;
702 char control, recvcontrol;
703 char machineip[16], retval;
705 tdata = (thread_data_array_t *) threadarg;
707 /* Send Trans Request */
708 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
709 perror("Error in socket for TRANS_REQUEST\n");
712 bzero((char*) &serv_addr, sizeof(serv_addr));
713 serv_addr.sin_family = AF_INET;
714 serv_addr.sin_port = htons(LISTEN_PORT);
715 midtoIP(tdata->mid,machineip);
716 machineip[15] = '\0';
717 serv_addr.sin_addr.s_addr = inet_addr(machineip);
718 /* Open Connection */
719 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
720 perror("Error in connect for TRANS_REQUEST\n");
725 /* Send bytes of data with TRANS_REQUEST control message */
726 send_data(sd, &(tdata->buffer->f), sizeof(fixed_data_t));
728 /* Send list of machines involved in the transaction */
730 int size=sizeof(unsigned int)*tdata->buffer->f.mcount;
731 send_data(sd, tdata->buffer->listmid, size);
734 /* Send oids and version number tuples for objects that are read */
736 int size=(sizeof(unsigned int)+sizeof(unsigned short))*tdata->buffer->f.numread;
737 send_data(sd, tdata->buffer->objread, size);
740 /* Send objects that are modified */
741 for(i = 0; i < tdata->buffer->f.nummod ; i++) {
743 headeraddr = chashSearch(tdata->rec->lookupTable, tdata->buffer->oidmod[i]);
744 GETSIZE(size,headeraddr);
745 size+=sizeof(objheader_t);
746 send_data(sd, headeraddr, size);
749 /* Read control message from Participant */
750 recv_data(sd, &control, sizeof(char));
751 recvcontrol = control;
753 /* Update common data structure and increment count */
754 tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol;
756 /* Lock and update count */
757 /* Thread sleeps until all messages from pariticipants are received by coordinator */
758 pthread_mutex_lock(tdata->lock);
760 (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */
762 /* Wake up the threads and invoke decideResponse (once) */
763 if(*(tdata->count) == tdata->buffer->f.mcount) {
764 decideResponse(tdata);
765 pthread_cond_broadcast(tdata->threshold);
767 pthread_cond_wait(tdata->threshold, tdata->lock);
769 pthread_mutex_unlock(tdata->lock);
771 /* Send the final response such as TRANS_COMMIT or TRANS_ABORT t
772 * to all participants in their respective socket */
773 if (sendResponse(tdata, sd) == 0) {
774 printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__);
779 recv_data((int)sd, &control, sizeof(char));
781 if(control == TRANS_UNSUCESSFUL) {
782 //printf("DEBUG-> TRANS_ABORTED\n");
783 } else if(control == TRANS_SUCESSFUL) {
784 //printf("DEBUG-> TRANS_SUCCESSFUL\n");
786 //printf("DEBUG-> Error: Incorrect Transaction End Message %d\n", control);
789 /* Close connection */
794 /* This function decides the reponse that needs to be sent to
795 * all Participant machines after the TRANS_REQUEST protocol */
796 void decideResponse(thread_data_array_t *tdata) {
798 int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
801 for (i = 0 ; i < tdata->buffer->f.mcount; i++) {
802 control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses
803 written onto the shared array */
806 printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
807 /* treat as disagree, pass thru */
816 case TRANS_SOFT_ABORT:
822 if(transdisagree > 0) {
824 *(tdata->replyctrl) = TRANS_ABORT;
825 *(tdata->replyretry) = 0;
826 /* clear objects from prefetch cache */
827 for (i = 0; i < tdata->buffer->f.numread; i++)
828 prehashRemove(*((unsigned int *)(((char *)tdata->buffer->objread) + (sizeof(unsigned int) + sizeof(unsigned short))*i)));
829 for (i = 0; i < tdata->buffer->f.nummod; i++)
830 prehashRemove(tdata->buffer->oidmod[i]);
831 } else if(transagree == tdata->buffer->f.mcount){
833 *(tdata->replyctrl) = TRANS_COMMIT;
834 *(tdata->replyretry) = 0;
836 /* Send Abort in soft abort case followed by retry commiting transaction again*/
837 *(tdata->replyctrl) = TRANS_ABORT;
838 *(tdata->replyretry) = 1;
843 /* This function sends the final response to remote machines per thread in their respective socket id
844 * It returns a char that is only needed to check the correctness of execution of this function inside
846 char sendResponse(thread_data_array_t *tdata, int sd) {
847 int n, size, sum, oidcount = 0, control;
848 char *ptr, retval = 0;
849 unsigned int *oidnotfound;
851 control = *(tdata->replyctrl);
852 send_data(sd, &control, sizeof(char));
854 //TODO read missing objects to be used during object migration
855 /* If the decided response is due to a soft abort and missing objects at the Participant's side */
857 if(tdata->recvmsg[tdata->thread_id].rcv_status == TRANS_SOFT_ABORT) {
858 // Read list of objects missing
859 recv_data(sd, &oidcount, sizeof(int));
860 //if((read(sd, &oidcount, sizeof(int)) != 0) && (oidcount != 0)) {
862 size = oidcount * sizeof(unsigned int);
863 if((oidnotfound = calloc(oidcount, sizeof(unsigned int))) == NULL) {
864 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
867 ptr = (char *) oidnotfound;
868 recv_data(sd, ptr, size);
870 retval = TRANS_SOFT_ABORT;
874 /* If the decided response is TRANS_ABORT */
875 if(*(tdata->replyctrl) == TRANS_ABORT) {
876 retval = TRANS_ABORT;
877 } else if(*(tdata->replyctrl) == TRANS_COMMIT) { /* If the decided response is TRANS_COMMIT */
878 retval = TRANS_COMMIT;
884 /* This function opens a connection, places an object read request to the
885 * remote machine, reads the control message and object if available and
886 * copies the object and its header to the local cache.
889 void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
891 struct sockaddr_in serv_addr;
897 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
898 perror("Error in socket\n");
902 bzero((char*) &serv_addr, sizeof(serv_addr));
903 serv_addr.sin_family = AF_INET;
904 serv_addr.sin_port = htons(LISTEN_PORT);
905 midtoIP(mnum,machineip);
906 machineip[15] = '\0';
907 serv_addr.sin_addr.s_addr = inet_addr(machineip);
910 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
911 perror("getRemoteObj() Error in connect\n");
915 char readrequest[sizeof(char)+sizeof(unsigned int)];
916 readrequest[0] = READ_REQUEST;
917 *((unsigned int *)(&readrequest[1])) = oid;
918 send_data(sd, readrequest, sizeof(readrequest));
920 /* Read response from the Participant */
921 recv_data(sd, &control, sizeof(char));
924 case OBJECT_NOT_FOUND:
927 /* Read object if found into local cache */
928 recv_data(sd, &size, sizeof(int));
929 objcopy = objstrAlloc(record->cache, size);
930 recv_data(sd, objcopy, size);
932 /* Insert into cache's lookup table */
933 chashInsert(record->lookupTable, oid, objcopy);
936 printf("Error: in recv response from participant on a READ_REQUEST %s, %d\n",__FILE__, __LINE__);
945 /* This function handles the local objects involved in a transaction commiting process.
946 * It also makes a decision if this local machine sends AGREE or DISAGREE or SOFT_ABORT to coordinator.
947 * Note Coordinator = local machine
948 * It wakes up the other threads from remote participants that are waiting for the coordinator's decision and
949 * based on common agreement it either commits or aborts the transaction.
950 * It also frees the memory resources */
951 void *handleLocalReq(void *threadarg) {
952 unsigned int *oidnotfound = NULL, *oidlocked = NULL;
953 local_thread_data_array_t *localtdata;
954 int objnotfound = 0, objlocked = 0;
955 int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
958 unsigned short version;
960 objheader_t *headptr;
962 localtdata = (local_thread_data_array_t *) threadarg;
964 /* Counters and arrays to formulate decision on control message to be sent */
965 oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
966 oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
968 numread = localtdata->tdata->buffer->f.numread;
969 /* Process each oid in the machine pile/ group per thread */
970 for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) {
971 if (i < localtdata->tdata->buffer->f.numread) {
972 int incr = sizeof(unsigned int) + sizeof(unsigned short);// Offset that points to next position in the objread array
974 oid = *((unsigned int *)(((char *)localtdata->tdata->buffer->objread) + incr));
975 version = *((unsigned short *)(((char *)localtdata->tdata->buffer->objread) + incr + sizeof(unsigned int)));
976 } else { // Objects Modified
978 headptr = (objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidmod[i-numread]);
979 if (headptr == NULL) {
980 printf("Error: handleLocalReq() returning NULL %s, %d\n", __FILE__, __LINE__);
984 version = headptr->version;
986 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
988 /* Save the oids not found and number of oids not found for later use */
989 if ((mobj = mhashSearch(oid)) == NULL) { /* Obj not found */
990 /* Save the oids not found and number of oids not found for later use */
991 oidnotfound[objnotfound] = oid;
993 } else { /* If Obj found in machine (i.e. has not moved) */
994 /* Check if Obj is locked by any previous transaction */
995 if ((STATUS((objheader_t *)mobj) & LOCK) == LOCK) {
996 if (version == ((objheader_t *)mobj)->version) { /* If locked then match versions */
998 } else {/* If versions don't match ...HARD ABORT */
1000 /* Send TRANS_DISAGREE to Coordinator */
1001 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
1003 } else {/* If Obj is not locked then lock object */
1004 STATUS(((objheader_t *)mobj)) |= LOCK;
1005 /* Save all object oids that are locked on this machine during this transaction request call */
1006 oidlocked[objlocked] = OID(((objheader_t *)mobj));
1008 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
1010 } else { /* If versions don't match ...HARD ABORT */
1012 /* Send TRANS_DISAGREE to Coordinator */
1013 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
1018 /* Condition to send TRANS_AGREE */
1019 if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
1020 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
1022 /* Condition to send TRANS_SOFT_ABORT */
1023 if((v_matchlock > 0 && v_nomatch == 0) || (objnotfound > 0 && v_nomatch == 0)) {
1024 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
1027 /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
1028 * if Participant receives a TRANS_COMMIT */
1029 localtdata->transinfo->objlocked = oidlocked;
1030 localtdata->transinfo->objnotfound = oidnotfound;
1031 localtdata->transinfo->modptr = NULL;
1032 localtdata->transinfo->numlocked = objlocked;
1033 localtdata->transinfo->numnotfound = objnotfound;
1034 /* Lock and update count */
1035 //Thread sleeps until all messages from pariticipants are received by coordinator
1036 pthread_mutex_lock(localtdata->tdata->lock);
1037 (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */
1039 /* Wake up the threads and invoke decideResponse (once) */
1040 if(*(localtdata->tdata->count) == localtdata->tdata->buffer->f.mcount) {
1041 decideResponse(localtdata->tdata);
1042 pthread_cond_broadcast(localtdata->tdata->threshold);
1044 pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock);
1046 pthread_mutex_unlock(localtdata->tdata->lock);
1047 if(*(localtdata->tdata->replyctrl) == TRANS_ABORT){
1048 if(transAbortProcess(localtdata) != 0) {
1049 printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
1052 } else if(*(localtdata->tdata->replyctrl) == TRANS_COMMIT) {
1053 if(transComProcess(localtdata) != 0) {
1054 printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
1059 if (localtdata->transinfo->objlocked != NULL) {
1060 free(localtdata->transinfo->objlocked);
1062 if (localtdata->transinfo->objnotfound != NULL) {
1063 free(localtdata->transinfo->objnotfound);
1069 /* This function completes the ABORT process if the transaction is aborting */
1070 int transAbortProcess(local_thread_data_array_t *localtdata) {
1072 unsigned int *objlocked;
1075 numlocked = localtdata->transinfo->numlocked;
1076 objlocked = localtdata->transinfo->objlocked;
1078 for (i = 0; i < numlocked; i++) {
1079 if((header = mhashSearch(objlocked[i])) == NULL) {
1080 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1083 STATUS(((objheader_t *)header)) &= ~(LOCK);
1089 /*This function completes the COMMIT process is the transaction is commiting*/
1090 int transComProcess(local_thread_data_array_t *localtdata) {
1091 objheader_t *header, *tcptr;
1092 int i, nummod, tmpsize, numcreated, numlocked;
1093 unsigned int *oidmod, *oidcreated, *oidlocked;
1096 nummod = localtdata->tdata->buffer->f.nummod;
1097 oidmod = localtdata->tdata->buffer->oidmod;
1098 numcreated = localtdata->tdata->buffer->f.numcreated;
1099 oidcreated = localtdata->tdata->buffer->oidcreated;
1100 numlocked = localtdata->transinfo->numlocked;
1101 oidlocked = localtdata->transinfo->objlocked;
1103 for (i = 0; i < nummod; i++) {
1104 if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
1105 printf("Error: transComProcess() mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1108 /* Copy from transaction cache -> main object store */
1109 if ((tcptr = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidmod[i]))) == NULL) {
1110 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1113 GETSIZE(tmpsize, header);
1114 pthread_mutex_lock(&mainobjstore_mutex);
1115 memcpy((char*)header+sizeof(objheader_t), (char *)tcptr+ sizeof(objheader_t), tmpsize);
1116 header->version += 1;
1117 if(header->notifylist != NULL) {
1118 notifyAll(&header->notifylist, OID(header), header->version);
1120 pthread_mutex_unlock(&mainobjstore_mutex);
1122 /* If object is newly created inside transaction then commit it */
1123 for (i = 0; i < numcreated; i++) {
1124 if ((header = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidcreated[i]))) == NULL) {
1125 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1128 GETSIZE(tmpsize, header);
1129 tmpsize += sizeof(objheader_t);
1130 pthread_mutex_lock(&mainobjstore_mutex);
1131 if ((ptrcreate = objstrAlloc(mainobjstore, tmpsize)) == NULL) {
1132 printf("Error: transComProcess() failed objstrAlloc %s, %d\n", __FILE__, __LINE__);
1133 pthread_mutex_unlock(&mainobjstore_mutex);
1136 pthread_mutex_unlock(&mainobjstore_mutex);
1137 memcpy(ptrcreate, header, tmpsize);
1138 mhashInsert(oidcreated[i], ptrcreate);
1139 lhashInsert(oidcreated[i], myIpAddr);
1141 /* Unlock locked objects */
1142 for(i = 0; i < numlocked; i++) {
1143 if((header = (objheader_t *) mhashSearch(oidlocked[i])) == NULL) {
1144 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1147 STATUS(header) &= ~(LOCK);
1153 /* This function checks if the prefetch oids are same and have same offsets
1154 * for case x.a.b and y.a.b where x and y have same oid's
1155 * or if a.b.c is a subset of x.b.c.d*/
1156 /* check for case where the generated request a.y.z or x.y.z.g then
1157 * prefetch needs to be generated for x.y.z.g if oid of a and x are same*/
1158 void checkPrefetchTuples(prefetchqelem_t *node) {
1159 int i,j, count,k, sindex, index;
1161 int ntuples, slength;
1163 unsigned short *endoffsets;
1166 /* Check for the case x.y.z and a.b.c are same oids */
1167 ptr = (char *) node;
1168 ntuples = *(GET_NTUPLES(ptr));
1169 oid = GET_PTR_OID(ptr);
1170 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1171 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1173 /* Find offset length for each tuple */
1174 int numoffset[ntuples];
1175 numoffset[0] = endoffsets[0];
1176 for(i = 1; i<ntuples; i++) {
1177 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1179 /* Check for redundant tuples by comparing oids of each tuple */
1180 for(i = 0; i < ntuples; i++) {
1183 for(j = i+1 ; j < ntuples; j++) {
1186 /*If oids of tuples match */
1187 if (oid[i] == oid[j]) {
1188 /* Find the smallest offset length of two tuples*/
1189 if(numoffset[i] > numoffset[j]){
1190 slength = numoffset[j];
1194 slength = numoffset[i];
1198 /* Compare the offset values based on the current indices
1199 * break if they do not match
1200 * if all offset values match then pick the largest tuple*/
1205 k = endoffsets[i-1];
1207 index = endoffsets[j -1];
1208 for(count = 0; count < slength; count ++) {
1209 if (arryfields[k] != arryfields[index]) {
1215 if(slength == count) {
1222 /* This function makes machine piles to be added into the machine pile queue for each prefetch call */
1223 prefetchpile_t *makePreGroups(prefetchqelem_t *node, int *numoffset) {
1225 int ntuples, i, machinenum, count=0;
1227 unsigned short *endoffsets;
1228 short *arryfields, *offset;
1229 prefetchpile_t *head = NULL, *tmp = NULL;
1231 /* Check for the case x.y.z and a.b.c are same oids */
1232 ptr = (char *) node;
1233 ntuples = *(GET_NTUPLES(ptr));
1234 oid = GET_PTR_OID(ptr);
1235 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1236 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1238 if((head = (prefetchpile_t *) calloc(1, sizeof(prefetchpile_t))) == NULL) {
1239 printf("Calloc error: %s %d\n", __FILE__, __LINE__);
1243 /* Check for redundant tuples by comparing oids of each tuple */
1244 for(i = 0; i < ntuples; i++) {
1246 if(head->next != NULL) {
1247 if((tmp = (prefetchpile_t *) calloc(1, sizeof(prefetchpile_t))) == NULL) {
1248 printf("Calloc error: %s %d\n", __FILE__, __LINE__);
1251 tmp->mid = myIpAddr;
1255 head->mid = myIpAddr;
1259 /* For each tuple make piles */
1260 if ((machinenum = lhashSearch(oid[i])) == 0) {
1261 printf("Error: No such Machine %s, %d\n", __FILE__, __LINE__);
1264 /* Insert into machine pile */
1266 offset = &arryfields[0];
1268 offset = &arryfields[endoffsets[i-1]];
1271 if((head = insertPile(machinenum, oid[i], numoffset[i], offset, head)) == NULL){
1272 printf("Error: Couldn't create a pile %s, %d\n", __FILE__, __LINE__);
1280 prefetchpile_t *foundLocal(prefetchqelem_t *node) {
1281 int ntuples,i, j, k, oidnfound = 0, arryfieldindex,nextarryfieldindex, flag = 0, val;
1285 objheader_t *objheader;
1286 unsigned short *endoffsets;
1288 prefetchpile_t *head = NULL;
1290 ptr = (char *) node;
1291 ntuples = *(GET_NTUPLES(ptr));
1292 oid = GET_PTR_OID(ptr);
1293 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1294 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1296 /* Find offset length for each tuple */
1297 int numoffset[ntuples];//Number of offsets for each tuple
1298 numoffset[0] = endoffsets[0];
1299 for(i = 1; i<ntuples; i++) {
1300 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1303 for(i = 0; i < ntuples; i++) {
1307 nextarryfieldindex = endoffsets[0];
1309 arryfieldindex = endoffsets[i-1];
1310 nextarryfieldindex = endoffsets[i];
1313 endoffsets[0] = val = numoffset[0];
1314 for(k = 1; k < ntuples; k++) {
1315 val = val + numoffset[k];
1316 endoffsets[k] = val;
1319 for(k = 0; k<endoffsets[ntuples-1]; k++) {
1320 arryfields[arryfieldindex+k] = arryfields[nextarryfieldindex+k];
1325 /* If object found locally */
1326 if((objheader = (objheader_t*) mhashSearch(oid[i])) != NULL) {
1328 tmp = (char *) objheader;
1329 int orgnumoffset = numoffset[i];
1333 arryfieldindex = endoffsets[i-1];
1336 for(j = 0; j<orgnumoffset; j++) {
1337 unsigned int objoid = 0;
1338 /* Check for arrays */
1339 if(TYPE(objheader) > NUMCLASSES) {
1343 int elementsize = classsize[TYPE(objheader)];
1344 struct ArrayObject *ao = (struct ArrayObject *) (tmp + sizeof(objheader_t));
1345 int length = ao->___length___;
1346 /* Check if array out of bounds */
1347 if(arryfields[arryfieldindex] < 0 || arryfields[arryfieldindex] >= length) {
1348 break; //if yes then treat the object as found
1350 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*arryfields[arryfieldindex])));
1352 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + arryfields[arryfieldindex]));
1354 //Update numoffset array
1355 numoffset[i] = numoffset[i] - 1;
1358 //Update endoffset array
1359 endoffsets[0] = val = numoffset[0];
1360 for(k = 1; k < ntuples; k++) {
1361 val = val + numoffset[k];
1362 endoffsets[k] = val;
1364 //Update arrayfields array
1365 for(k = 0; k < endoffsets[ntuples-1]; k++) {
1366 arryfields[arryfieldindex+k] = arryfields[arryfieldindex+k+1];
1368 if((objheader = (objheader_t*) mhashSearch(oid[i])) == NULL) {
1370 checkPreCache(node, numoffset, oid[i], i);
1373 tmp = (char *) objheader;
1376 /*If all offset oids are found locally,make the prefetch tuple invalid */
1381 /* Look in Prefetch cache */
1382 checkPreCache(node, numoffset, oid[i],i);
1387 /* Make machine groups */
1388 if((head = makePreGroups(node, numoffset)) == NULL) {
1389 printf("Error in makePreGroups() %s %d\n", __FILE__, __LINE__);
1396 void checkPreCache(prefetchqelem_t *node, int *numoffset, unsigned int objoid, int index) {
1398 int ntuples, i, k, flag=0, isArray =0, arryfieldindex, val;
1400 unsigned short *endoffsets;
1402 objheader_t *header;
1404 ptr = (char *) node;
1405 ntuples = *(GET_NTUPLES(ptr));
1406 oid = GET_PTR_OID(ptr);
1407 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1408 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1410 if((header = (objheader_t *) prehashSearch(objoid)) == NULL) {
1412 } else { //Found in Prefetch Cache
1413 //TODO Decide if object is too old, if old remove from cache
1414 tmp = (char *) header;
1415 int loopcount = numoffset[index];
1419 arryfieldindex = endoffsets[(index - 1)];
1420 // Check if any of the offset oid is available in the Prefetch cache
1421 for(i = 0; i < loopcount; i++) {
1422 /* Check for arrays */
1423 if(TYPE(header) > NUMCLASSES) {
1428 int elementsize = classsize[TYPE(header)];
1429 struct ArrayObject *ao = (struct ArrayObject *) (tmp + sizeof(objheader_t));
1430 int length = ao->___length___;
1431 /* Check if array out of bounds */
1432 if(arryfields[arryfieldindex] < 0 || arryfields[arryfieldindex] >= length) {
1433 break; //if yes treat the object as found
1435 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*arryfields[arryfieldindex])));
1437 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + arryfields[arryfieldindex]));
1439 //Update numoffset array
1440 numoffset[index] = numoffset[index] - 1;
1442 oid[index] = objoid;
1443 //Update endoffset array
1444 endoffsets[0] = val = numoffset[0];
1445 for(k = 1; k < ntuples; k++) {
1446 val = val + numoffset[k];
1447 endoffsets[k] = val;
1449 //Update arrayfields array
1450 for(k = 0; k < endoffsets[ntuples-1]; k++) {
1451 arryfields[arryfieldindex+k] = arryfields[arryfieldindex+k+1];
1453 if((header = (objheader_t *)prehashSearch(oid[index])) != NULL) {
1454 tmp = (char *) header;
1462 //Found in the prefetch cache
1463 if(flag == 0 && (numoffset[index] == 0)) {
1470 /* This function is called by the thread calling transPrefetch */
1471 void *transPrefetch(void *t) {
1472 prefetchqelem_t *qnode;
1473 prefetchpile_t *pilehead = NULL;
1474 prefetchpile_t *ptr = NULL, *piletail = NULL;
1477 /* lock mutex of primary prefetch queue */
1478 pthread_mutex_lock(&pqueue.qlock);
1479 /* while primary queue is empty, then wait */
1480 while((pqueue.front == NULL) && (pqueue.rear == NULL)) {
1481 pthread_cond_wait(&pqueue.qcond, &pqueue.qlock);
1484 /* dequeue node to create a machine piles and finally unlock mutex */
1485 if((qnode = pre_dequeue()) == NULL) {
1486 printf("Error: No node returned %s, %d\n", __FILE__, __LINE__);
1487 pthread_mutex_unlock(&pqueue.qlock);
1490 pthread_mutex_unlock(&pqueue.qlock);
1492 /* Reduce redundant prefetch requests */
1493 checkPrefetchTuples(qnode);
1494 /* Check if the tuples are found locally, if yes then reduce them further*/
1495 /* and group requests by remote machine ids by calling the makePreGroups() */
1496 if((pilehead = foundLocal(qnode)) == NULL) {
1497 printf("Error: No node created for serving prefetch request %s %d\n", __FILE__, __LINE__);
1503 while(ptr != NULL) {
1504 if(ptr->next == NULL) {
1510 /* Lock mutex of pool queue */
1511 pthread_mutex_lock(&mcqueue.qlock);
1512 /* Update the pool queue with the new remote machine piles generated per prefetch call */
1513 mcpileenqueue(pilehead, piletail);
1514 /* Broadcast signal on machine pile queue */
1515 pthread_cond_broadcast(&mcqueue.qcond);
1516 /* Unlock mutex of machine pile queue */
1517 pthread_mutex_unlock(&mcqueue.qlock);
1518 /* Deallocate the prefetch queue pile node */
1523 /* Each thread in the pool of threads calls this function to establish connection with
1524 * remote machines, send the prefetch requests and process the reponses from
1525 * the remote machines .
1526 * The thread is active throughout the period of runtime */
1528 void *mcqProcess(void *threadid) {
1530 prefetchpile_t *mcpilenode;
1531 struct sockaddr_in remoteAddr;
1534 tid = (int) threadid;
1538 /* Lock mutex of mc pile queue */
1539 pthread_mutex_lock(&mcqueue.qlock);
1540 /* When mc pile queue is empty, wait */
1541 while((mcqueue.front == NULL) && (mcqueue.rear == NULL)) {
1542 pthread_cond_wait(&mcqueue.qcond, &mcqueue.qlock);
1544 /* Dequeue node to send remote machine connections*/
1545 if((mcpilenode = mcpiledequeue()) == NULL) {
1546 printf("Dequeue Error: No node returned %s %d\n", __FILE__, __LINE__);
1547 pthread_mutex_unlock(&mcqueue.qlock);
1551 pthread_mutex_unlock(&mcqueue.qlock);
1553 /*Initiate connection to remote host and send prefetch request */
1554 if(mcpilenode->mid != myIpAddr) {
1555 /* Check to see if socket exists */
1556 for(i = 0; i < NUM_MACHINES; i++) {
1557 if(midSocketArray[i].mid == mcpilenode->mid) {
1558 sendPrefetchReq(mcpilenode, midSocketArray[i].sockid);
1564 if(sockIdFound == 0) {
1565 if(sockCount < NUM_MACHINES) {
1567 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
1568 printf("%s() Error: In creating socket at %s, %d\n", __func__, __FILE__, __LINE__);
1572 bzero(&remoteAddr, sizeof(remoteAddr));
1573 remoteAddr.sin_family = AF_INET;
1574 remoteAddr.sin_port = htons(LISTEN_PORT);
1575 remoteAddr.sin_addr.s_addr = htonl(mcpilenode->mid);
1577 /* Open Connection */
1578 if (connect(sd, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0) {
1579 printf("%s():error %d connecting to %s:%d\n", __func__, errno,
1580 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1585 midSocketArray[sockCount].mid = mcpilenode->mid;
1586 midSocketArray[sockCount].sockid = sd;
1587 sendPrefetchReq(mcpilenode, midSocketArray[sockCount].sockid);
1590 //TODO Fix for connecting to more than 2 machines && close socket
1591 printf("%s(): Error: Currently works for only 2 machines\n", __func__);
1597 /* Deallocate the machine queue pile node */
1598 mcdealloc(mcpilenode);
1602 void sendPrefetchReq(prefetchpile_t *mcpilenode, int sd) {
1603 int i, off, len, endpair, count = 0;
1604 char machineip[16], control;
1607 /* Send TRANS_PREFETCH control message */
1608 control = TRANS_PREFETCH;
1609 send_data(sd, &control, sizeof(char));
1611 /* Send Oids and offsets in pairs */
1612 tmp = mcpilenode->objpiles;
1613 while(tmp != NULL) {
1615 count++; /* Keeps track of the number of oid and offset tuples sent per remote machine */
1616 len = sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1617 char oidnoffset[len];
1618 bzero(oidnoffset, len);
1619 *((int*)oidnoffset) = len;
1621 *((unsigned int *)(oidnoffset + off)) = tmp->oid;
1622 off += sizeof(unsigned int);
1623 *((unsigned int *)(oidnoffset + off)) = myIpAddr;
1624 off += sizeof(unsigned int);
1625 for(i = 0; i < tmp->numoffset; i++) {
1626 *((short*)(oidnoffset + off)) = tmp->offset[i];
1629 send_data(sd, oidnoffset, len);
1633 /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
1635 send_data(sd, &endpair, sizeof(int));
1640 int getPrefetchResponse(int sd) {
1641 int numbytes = 0, length = 0, size = 0;
1642 char *recvbuffer, control;
1644 void *modptr, *oldptr;
1646 recv_data((int)sd, &length, sizeof(int));
1647 size = length - sizeof(int);
1648 if((recvbuffer = calloc(1, size)) == NULL) {
1649 printf("%s() Calloc error at %s,%d\n", __func__, __FILE__, __LINE__);
1653 recv_data((int)sd, recvbuffer, size);
1655 control = *((char *) recvbuffer);
1656 if(control == OBJECT_FOUND) {
1658 oid = *((unsigned int *)(recvbuffer + sizeof(char)));
1659 size = size - (sizeof(char) + sizeof(unsigned int));
1660 pthread_mutex_lock(&prefetchcache_mutex);
1661 if ((modptr = objstrAlloc(prefetchcache, size)) == NULL) {
1662 printf("Error: objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
1663 pthread_mutex_unlock(&prefetchcache_mutex);
1667 pthread_mutex_unlock(&prefetchcache_mutex);
1668 memcpy(modptr, recvbuffer + sizeof(char) + sizeof(unsigned int), size);
1670 /* Insert the oid and its address into the prefetch hash lookup table */
1671 /* Do a version comparison if the oid exists */
1672 if((oldptr = prehashSearch(oid)) != NULL) {
1673 /* If older version then update with new object ptr */
1674 if(((objheader_t *)oldptr)->version <= ((objheader_t *)modptr)->version) {
1676 prehashInsert(oid, modptr);
1678 /* TODO modptr should be reference counted */
1680 } else {/* Else add the object ptr to hash table*/
1681 prehashInsert(oid, modptr);
1683 /* Lock the Prefetch Cache look up table*/
1684 pthread_mutex_lock(&pflookup.lock);
1685 /* Broadcast signal on prefetch cache condition variable */
1686 pthread_cond_broadcast(&pflookup.cond);
1687 /* Unlock the Prefetch Cache look up table*/
1688 pthread_mutex_unlock(&pflookup.lock);
1689 } else if(control == OBJECT_NOT_FOUND) {
1690 oid = *((unsigned int *)(recvbuffer + sizeof(char)));
1691 /* TODO: For each object not found query DHT for new location and retrieve the object */
1692 /* Throw an error */
1693 printf("OBJECT %x NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n", oid);
1697 printf("Error: in decoding the control value %d, %s, %d\n",control, __FILE__, __LINE__);
1705 unsigned short getObjType(unsigned int oid)
1707 objheader_t *objheader;
1708 unsigned short numoffset[] ={0};
1709 short fieldoffset[] ={};
1711 if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL)
1713 if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1715 prefetch(1, &oid, numoffset, fieldoffset);
1716 pthread_mutex_lock(&pflookup.lock);
1717 while ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1719 pthread_cond_wait(&pflookup.cond, &pflookup.lock);
1721 pthread_mutex_unlock(&pflookup.lock);
1725 return TYPE(objheader);
1728 int startRemoteThread(unsigned int oid, unsigned int mid)
1731 struct sockaddr_in remoteAddr;
1732 char msg[1 + sizeof(unsigned int)];
1736 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
1738 perror("startRemoteThread():socket()");
1742 bzero(&remoteAddr, sizeof(remoteAddr));
1743 remoteAddr.sin_family = AF_INET;
1744 remoteAddr.sin_port = htons(LISTEN_PORT);
1745 remoteAddr.sin_addr.s_addr = htonl(mid);
1747 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0)
1749 printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
1750 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1755 msg[0] = START_REMOTE_THREAD;
1756 memcpy(&msg[1], &oid, sizeof(unsigned int));
1757 send_data(sock, msg, 1 + sizeof(unsigned int));
1764 //TODO: when reusing oids, make sure they are not already in use!
1765 unsigned int getNewOID(void) {
1766 static unsigned int id = 0xFFFFFFFF;
1769 if (id > oidMax || id < oidMin)
1776 int processConfigFile()
1779 const int maxLineLength = 200;
1780 char lineBuffer[maxLineLength];
1782 const char *delimiters = " \t\n";
1786 configFile = fopen(CONFIG_FILENAME, "r");
1787 if (configFile == NULL)
1789 printf("error opening %s:\n", CONFIG_FILENAME);
1794 numHostsInSystem = 0;
1795 sizeOfHostArray = 8;
1796 hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
1798 while(fgets(lineBuffer, maxLineLength, configFile) != NULL)
1800 commentBegin = strchr(lineBuffer, '#');
1801 if (commentBegin != NULL)
1802 *commentBegin = '\0';
1803 token = strtok(lineBuffer, delimiters);
1804 while (token != NULL)
1806 tmpAddr = inet_addr(token);
1807 if ((int)tmpAddr == -1)
1809 printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
1814 addHost(htonl(tmpAddr));
1815 token = strtok(NULL, delimiters);
1821 if (numHostsInSystem < 1)
1823 printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
1827 myIpAddr = getMyIpAddr("en1");
1829 myIpAddr = getMyIpAddr("eth0");
1831 myIndexInHostArray = findHost(myIpAddr);
1832 if (myIndexInHostArray == -1)
1834 printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
1837 oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
1838 oidMin = oidsPerBlock * myIndexInHostArray;
1839 if (myIndexInHostArray == numHostsInSystem - 1)
1840 oidMax = 0xFFFFFFFF;
1842 oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
1847 void addHost(unsigned int hostIp)
1849 unsigned int *tmpArray;
1851 if (findHost(hostIp) != -1)
1854 if (numHostsInSystem == sizeOfHostArray)
1856 tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
1857 memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
1859 hostIpAddrs = tmpArray;
1862 hostIpAddrs[numHostsInSystem++] = hostIp;
1867 int findHost(unsigned int hostIp)
1870 for (i = 0; i < numHostsInSystem; i++)
1871 if (hostIpAddrs[i] == hostIp)
1878 /* This function sends notification request per thread waiting on object(s) whose version
1880 int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int numoid) {
1882 objheader_t *objheader;
1883 struct sockaddr_in remoteAddr;
1884 char msg[1 + numoid * (sizeof(unsigned short) + sizeof(unsigned int)) + 3 * sizeof(unsigned int)];
1888 unsigned short version;
1889 unsigned int oid,mid;
1890 static unsigned int threadid = 0;
1891 pthread_mutex_t threadnotify = PTHREAD_MUTEX_INITIALIZER; //Lock and condition var for threadjoin and notification
1892 pthread_cond_t threadcond = PTHREAD_COND_INITIALIZER;
1893 notifydata_t *ndata;
1895 //FIXME currently all oids belong to one machine
1897 if((mid = lhashSearch(oid)) == 0) {
1898 printf("Error: %s() No such machine found for oid =%x\n",__func__, oid);
1902 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1903 perror("reqNotify():socket()");
1907 bzero(&remoteAddr, sizeof(remoteAddr));
1908 remoteAddr.sin_family = AF_INET;
1909 remoteAddr.sin_port = htons(LISTEN_PORT);
1910 remoteAddr.sin_addr.s_addr = htonl(mid);
1912 /* Generate unique threadid */
1915 /* Save threadid, numoid, oidarray, versionarray, pthread_cond_variable for later processing */
1916 if((ndata = calloc(1, sizeof(notifydata_t))) == NULL) {
1917 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
1920 ndata->numoid = numoid;
1921 ndata->threadid = threadid;
1922 ndata->oidarry = oidarry;
1923 ndata->versionarry = versionarry;
1924 ndata->threadcond = threadcond;
1925 ndata->threadnotify = threadnotify;
1926 if((status = notifyhashInsert(threadid, ndata)) != 0) {
1927 printf("reqNotify(): Insert into notify hash table not successful %s, %d\n", __FILE__, __LINE__);
1932 /* Send number of oids, oidarry, version array, machine id and threadid */
1933 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1934 printf("reqNotify():error %d connecting to %s:%d\n", errno,
1935 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1939 msg[0] = THREAD_NOTIFY_REQUEST;
1940 *((unsigned int *)(&msg[1])) = numoid;
1941 /* Send array of oids */
1942 size = sizeof(unsigned int);
1947 *((unsigned int *)(&msg[1] + size)) = oid;
1948 size += sizeof(unsigned int);
1953 /* Send array of version */
1957 version = versionarry[i];
1958 *((unsigned short *)(&msg[1] + size)) = version;
1959 size += sizeof(unsigned short);
1964 *((unsigned int *)(&msg[1] + size)) = myIpAddr;
1965 size += sizeof(unsigned int);
1966 *((unsigned int *)(&msg[1] + size)) = threadid;
1968 pthread_mutex_lock(&(ndata->threadnotify));
1969 size = 1 + numoid * (sizeof(unsigned int) + sizeof(unsigned short)) + 3 * sizeof(unsigned int);
1970 send_data(sock, msg, size);
1971 pthread_cond_wait(&(ndata->threadcond), &(ndata->threadnotify));
1972 pthread_mutex_unlock(&(ndata->threadnotify));
1975 pthread_cond_destroy(&threadcond);
1976 pthread_mutex_destroy(&threadnotify);
1982 void threadNotify(unsigned int oid, unsigned short version, unsigned int tid) {
1983 notifydata_t *ndata;
1984 int i, objIsFound = 0, index;
1987 //Look up the tid and call the corresponding pthread_cond_signal
1988 if((ndata = notifyhashSearch(tid)) == NULL) {
1989 printf("threadnotify(): No such threadid is present %s, %d\n", __FILE__, __LINE__);
1992 for(i = 0; i < ndata->numoid; i++) {
1993 if(ndata->oidarry[i] == oid){
1998 if(objIsFound == 0){
1999 printf("threadNotify(): Oid not found %s, %d\n", __FILE__, __LINE__);
2002 if(version <= ndata->versionarry[index]){
2003 printf("threadNotify(): New version %d has not changed since last version %s, %d\n", version, __FILE__, __LINE__);
2006 /* Clear from prefetch cache and free thread related data structure */
2007 if((ptr = prehashSearch(oid)) != NULL) {
2010 pthread_cond_signal(&(ndata->threadcond));
2017 int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) {
2020 struct sockaddr_in remoteAddr;
2021 char msg[1 + sizeof(unsigned short) + 2*sizeof(unsigned int)];
2022 int sock, status, size, bytesSent;
2024 while(*head != NULL) {
2027 //create a socket connection to that machine
2028 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
2029 perror("notifyAll():socket()");
2033 bzero(&remoteAddr, sizeof(remoteAddr));
2034 remoteAddr.sin_family = AF_INET;
2035 remoteAddr.sin_port = htons(LISTEN_PORT);
2036 remoteAddr.sin_addr.s_addr = htonl(mid);
2037 //send Thread Notify response and threadid to that machine
2038 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
2039 printf("notifyAll():error %d connecting to %s:%d\n", errno,
2040 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
2043 bzero(msg, (1+sizeof(unsigned short) + 2*sizeof(unsigned int)));
2044 msg[0] = THREAD_NOTIFY_RESPONSE;
2045 *((unsigned int *)&msg[1]) = oid;
2046 size = sizeof(unsigned int);
2047 *((unsigned short *)(&msg[1]+ size)) = version;
2048 size+= sizeof(unsigned short);
2049 *((unsigned int *)(&msg[1]+ size)) = ptr->threadid;
2051 size = 1 + 2*sizeof(unsigned int) + sizeof(unsigned short);
2052 send_data(sock, msg, size);
2063 void transAbort(transrecord_t *trans) {
2064 objstrDelete(trans->cache);
2065 chashDelete(trans->lookupTable);