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
53 * reuse sockets for sending prefetches and making remote read requests
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
58 midSocketInfo_t sockArrayRemoteRead[NUM_MACHINES];
59 int sockCountRemoteRead; //number of connections with all remote machines(one socket per mc)
60 int sockIdFoundRemoteRead; //track if socket file descriptor is already established
62 void printhex(unsigned char *, int);
63 plistnode_t *createPiles(transrecord_t *);
65 /*******************************
66 * Send and Recv function calls
67 *******************************/
68 void send_data(int fd , void *buf, int buflen) {
69 char *buffer = (char *)(buf);
73 numbytes = send(fd, buffer, size, MSG_NOSIGNAL);
83 void recv_data(int fd , void *buf, int buflen) {
84 char *buffer = (char *)(buf);
88 numbytes = recv(fd, buffer, size, 0);
98 void printhex(unsigned char *ptr, int numBytes)
101 for (i = 0; i < numBytes; i++)
104 printf("0%x ", ptr[i]);
106 printf("%x ", ptr[i]);
112 inline int arrayLength(int *array) {
114 for(i=0 ;array[i] != -1; i++)
118 inline int findmax(int *array, int arraylength) {
121 for(i = 0; i < arraylength; i++){
128 /* This function is a prefetch call generated by the compiler that
129 * populates the shared primary prefetch queue*/
130 void prefetch(int ntuples, unsigned int *oids, unsigned short *endoffsets, short *arrayfields) {
131 /* Allocate for the queue node*/
133 int qnodesize = sizeof(prefetchqelem_t) + sizeof(int) + ntuples * (sizeof(unsigned short) + sizeof(unsigned int)) + endoffsets[ntuples - 1] * sizeof(short);
136 if((node = calloc(1, qnodesize)) == NULL) {
137 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
140 /* Set queue node values */
141 int len = sizeof(prefetchqelem_t);
143 unsigned int *narray;
144 unsigned short *narray2;
146 int top=endoffsets[ntuples-1];
147 *((int *)(node+len))=ntuples;
149 narray=(unsigned int *)(node+len);
150 narray2=(unsigned short *)(narray+ntuples);
151 narray3=(short *)(narray2+ntuples);
153 for(i=0;i<ntuples;i++) {
155 narray2[i]=endoffsets[i];
158 narray3[i]=arrayfields[i];
160 /* Lock and insert into primary prefetch queue */
161 pthread_mutex_lock(&pqueue.qlock);
162 pre_enqueue((prefetchqelem_t *)node);
163 pthread_cond_signal(&pqueue.qcond);
164 pthread_mutex_unlock(&pqueue.qlock);
169 /* This function starts up the transaction runtime. */
170 int dstmStartup(const char * option) {
171 pthread_t thread_Listen;
173 int master=option!=NULL && strcmp(option, "master")==0;
175 if (processConfigFile() != 0)
176 return 0; //TODO: return error value, cause main program to exit
188 pthread_attr_init(&attr);
189 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
190 pthread_create(&thread_Listen, &attr, dstmListen, NULL);
199 //TODO Use this later
200 void *pCacheAlloc(objstr_t *store, unsigned int size) {
206 while(ptr->next != NULL) {
207 /* check if store is empty */
208 if(((unsigned int)ptr->top - (unsigned int)ptr - sizeof(objstr_t) + size) <= ptr->size) {
223 /* This function initiates the prefetch thread
224 * A queue is shared between the main thread of execution
225 * and the prefetch thread to process the prefetch call
226 * Call from compiler populates the shared queue with prefetch requests while prefetch thread
227 * processes the prefetch requests */
231 //Create and initialize prefetch cache structure
232 prefetchcache = objstrCreate(PREFETCH_CACHE_SIZE);
233 //prefetchcache->next = objstrCreate(PREFETCH_CACHE_SIZE);
234 //prefetchcache->next->next = objstrCreate(PREFETCH_CACHE_SIZE);
236 /* Initialize attributes for mutex */
237 pthread_mutexattr_init(&prefetchcache_mutex_attr);
238 pthread_mutexattr_settype(&prefetchcache_mutex_attr, PTHREAD_MUTEX_RECURSIVE_NP);
240 pthread_mutex_init(&prefetchcache_mutex, &prefetchcache_mutex_attr);
242 //Create prefetch cache lookup table
243 if(prehashCreate(HASH_SIZE, LOADFACTOR))
246 //Initialize primary shared queue
248 //Initialize machine pile w/prefetch oids and offsets shared queue
251 //Create the primary prefetch thread
253 retval=pthread_create(&tPrefetch, NULL, transPrefetch, NULL);
255 pthread_detach(tPrefetch);
257 //Initialize mid to socketid mapping array
259 for(t = 0; t < NUM_MACHINES; t++) {
260 midSocketArray[t].mid = 0;
261 midSocketArray[t].sockid = 0;
264 //Create and Initialize a pool of threads
265 /* Threads are active for the entire period runtime is running */
266 for(t = 0; t< NUM_THREADS; t++) {
268 rc = pthread_create(&wthreads[t], NULL, mcqProcess, (void *)t);
270 pthread_detach(wthreads[t]);
274 /* This function stops the threads spawned */
277 pthread_cancel(tPrefetch);
278 for(t = 0; t < NUM_THREADS; t++)
279 pthread_cancel(wthreads[t]);
284 /* This functions inserts randowm wait delays in the order of msec
285 * Mostly used when transaction commits retry*/
293 req.tv_nsec = (long)(1000000 + (t%10000000)); //1-11 msec
294 nanosleep(&req, NULL);
298 /* This function initializes things required in the transaction start*/
299 transrecord_t *transStart()
301 transrecord_t *tmp = calloc(1, sizeof(transrecord_t));
302 tmp->cache = objstrCreate(1048576);
303 tmp->lookupTable = chashCreate(HASH_SIZE, LOADFACTOR);
305 tmp->revertlist=NULL;
310 /* This function finds the location of the objects involved in a transaction
311 * and returns the pointer to the object if found in a remote location */
312 objheader_t *transRead(transrecord_t *record, unsigned int oid) {
313 unsigned int machinenumber;
314 objheader_t *tmp, *objheader;
315 objheader_t *objcopy;
320 printf("Error: %s, %d oid is NULL \n", __FILE__, __LINE__);
324 /* Search local transaction cache */
325 if((objheader = (objheader_t *)chashSearch(record->lookupTable, oid)) != NULL){
327 return &objheader[1];
331 } else if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
332 /* Look up in machine lookup table and copy into cache*/
333 GETSIZE(size, objheader);
334 size += sizeof(objheader_t);
335 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
336 memcpy(objcopy, objheader, size);
337 /* Insert into cache's lookup table */
338 chashInsert(record->lookupTable, OID(objheader), objcopy);
344 } else if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) { /* Look up in prefetch cache */
346 size+=sizeof(objheader_t);
347 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
348 memcpy(objcopy, tmp, size);
349 /* Insert into cache's lookup table */
350 chashInsert(record->lookupTable, OID(tmp), objcopy);
357 /* Get the object from the remote location */
358 if((machinenumber = lhashSearch(oid)) == 0) {
359 printf("Error: %s() No machine found for oid =% %s,%dx\n",__func__, machinenumber, __FILE__, __LINE__);
362 objcopy = getRemoteObj(record, machinenumber, oid);
364 if(objcopy == NULL) {
365 printf("Error: Object not found in Remote location %s, %d\n", __FILE__, __LINE__);
378 /* This function creates objects in the transaction record */
379 objheader_t *transCreateObj(transrecord_t *record, unsigned int size)
381 objheader_t *tmp = (objheader_t *) objstrAlloc(record->cache, (sizeof(objheader_t) + size));
382 tmp->notifylist = NULL;
383 OID(tmp) = getNewOID();
387 chashInsert(record->lookupTable, OID(tmp), tmp);
390 return &tmp[1]; //want space after object header
396 /* This function creates machine piles based on all machines involved in a
397 * transaction commit request */
398 plistnode_t *createPiles(transrecord_t *record) {
400 unsigned int size;/* Represents number of bins in the chash table */
401 chashlistnode_t *curr, *ptr, *next;
402 plistnode_t *pile = NULL;
403 unsigned int machinenum;
404 void *localmachinenum;
405 objheader_t *headeraddr;
407 ptr = record->lookupTable->table;
408 size = record->lookupTable->size;
410 for(i = 0; i < size ; i++) {
412 /* Inner loop to traverse the linked list of the cache lookupTable */
413 while(curr != NULL) {
414 //if the first bin in hash table is empty
420 if ((headeraddr = chashSearch(record->lookupTable, curr->key)) == NULL) {
421 printf("Error: No such oid %s, %d\n", __FILE__, __LINE__);
425 //Get machine location for object id (and whether local or not)
426 if (STATUS(headeraddr) & NEW || (mhashSearch(curr->key) != NULL)) {
427 machinenum = myIpAddr;
428 } else if ((machinenum = lhashSearch(curr->key)) == 0) {
429 printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
433 //Make machine groups
434 if ((pile = pInsert(pile, headeraddr, machinenum, record->lookupTable->numelements)) == NULL) {
435 printf("pInsert error %s, %d\n", __FILE__, __LINE__);
445 /* This function initiates the transaction commit process
446 * Spawns threads for each of the new connections with Participants
447 * and creates new piles by calling the createPiles(),
448 * Sends a transrequest() to each remote machines for objects found remotely
449 * and calls handleLocalReq() to process objects found locally */
450 int transCommit(transrecord_t *record) {
451 unsigned int tot_bytes_mod, *listmid;
452 plistnode_t *pile, *pile_ptr;
454 int pilecount, offset, threadnum = 0, trecvcount = 0;
456 char transid[TID_LEN];
457 trans_req_data_t *tosend;
458 trans_commit_data_t transinfo;
459 static int newtid = 0;
460 char treplyctrl = 0, treplyretry = 0; /* keeps track of the common response that needs to be sent */
462 thread_data_array_t *thread_data_array;
463 local_thread_data_array_t *ltdata;
469 thread_data_array = NULL;
472 /* Look through all the objects in the transaction record and make piles
473 * for each machine involved in the transaction*/
474 pile_ptr = pile = createPiles(record);
476 /* Create the packet to be sent in TRANS_REQUEST */
478 /* Count the number of participants */
479 pilecount = pCount(pile);
481 /* Create a list of machine ids(Participants) involved in transaction */
482 if((listmid = calloc(pilecount, sizeof(unsigned int))) == NULL) {
483 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
486 pListMid(pile, listmid);
489 /* Initialize thread variables,
490 * Spawn a thread for each Participant involved in a transaction */
491 pthread_t thread[pilecount];
493 pthread_cond_t tcond;
494 pthread_mutex_t tlock;
495 pthread_mutex_t tlshrd;
497 if((thread_data_array = (thread_data_array_t *) calloc(pilecount, sizeof(thread_data_array_t))) == NULL) {
498 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
499 pthread_cond_destroy(&tcond);
500 pthread_mutex_destroy(&tlock);
506 if((ltdata = calloc(1, sizeof(local_thread_data_array_t))) == NULL) {
507 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
508 pthread_cond_destroy(&tcond);
509 pthread_mutex_destroy(&tlock);
512 free(thread_data_array);
516 thread_response_t rcvd_control_msg[pilecount]; /* Shared thread array that keeps track of responses of participants */
518 /* Initialize and set thread detach attribute */
519 pthread_attr_init(&attr);
520 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
521 pthread_mutex_init(&tlock, NULL);
522 pthread_cond_init(&tcond, NULL);
524 /* Process each machine pile */
525 while(pile != NULL) {
526 //Create transaction id
528 if ((tosend = calloc(1, sizeof(trans_req_data_t))) == NULL) {
529 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
530 pthread_cond_destroy(&tcond);
531 pthread_mutex_destroy(&tlock);
534 free(thread_data_array);
538 tosend->f.control = TRANS_REQUEST;
539 sprintf(tosend->f.trans_id, "%x_%d", pile->mid, newtid);
540 tosend->f.mcount = pilecount;
541 tosend->f.numread = pile->numread;
542 tosend->f.nummod = pile->nummod;
543 tosend->f.numcreated = pile->numcreated;
544 tosend->f.sum_bytes = pile->sum_bytes;
545 tosend->listmid = listmid;
546 tosend->objread = pile->objread;
547 tosend->oidmod = pile->oidmod;
548 tosend->oidcreated = pile->oidcreated;
549 thread_data_array[threadnum].thread_id = threadnum;
550 thread_data_array[threadnum].mid = pile->mid;
551 thread_data_array[threadnum].buffer = tosend;
552 thread_data_array[threadnum].recvmsg = rcvd_control_msg;
553 thread_data_array[threadnum].threshold = &tcond;
554 thread_data_array[threadnum].lock = &tlock;
555 thread_data_array[threadnum].count = &trecvcount;
556 thread_data_array[threadnum].replyctrl = &treplyctrl;
557 thread_data_array[threadnum].replyretry = &treplyretry;
558 thread_data_array[threadnum].rec = record;
559 /* If local do not create any extra connection */
560 if(pile->mid != myIpAddr) { /* Not local */
562 rc = pthread_create(&thread[threadnum], &attr, transRequest, (void *) &thread_data_array[threadnum]);
565 perror("Error in pthread create\n");
566 pthread_cond_destroy(&tcond);
567 pthread_mutex_destroy(&tlock);
570 for (i = 0; i < threadnum; i++)
571 free(thread_data_array[i].buffer);
572 free(thread_data_array);
577 ltdata->tdata = &thread_data_array[threadnum];
578 ltdata->transinfo = &transinfo;
580 val = pthread_create(&thread[threadnum], &attr, handleLocalReq, (void *) ltdata);
583 perror("Error in pthread create\n");
584 pthread_cond_destroy(&tcond);
585 pthread_mutex_destroy(&tlock);
588 for (i = 0; i < threadnum; i++)
589 free(thread_data_array[i].buffer);
590 free(thread_data_array);
599 /* Free attribute and wait for the other threads */
600 pthread_attr_destroy(&attr);
602 for (i = 0; i < threadnum; i++) {
603 rc = pthread_join(thread[i], NULL);
606 printf("Error: return code from pthread_join() is %d\n", rc);
607 pthread_cond_destroy(&tcond);
608 pthread_mutex_destroy(&tlock);
611 for (j = i; j < threadnum; j++) {
612 free(thread_data_array[j].buffer);
616 free(thread_data_array[i].buffer);
620 pthread_cond_destroy(&tcond);
621 pthread_mutex_destroy(&tlock);
625 /* wait a random amount of time before retrying to commit transaction*/
626 if(treplyretry == 1) {
627 free(thread_data_array);
632 /* Retry trans commit procedure during soft_abort case */
633 } while (treplyretry == 1);
636 if(treplyctrl == TRANS_ABORT) {
638 objstrDelete(record->cache);
639 chashDelete(record->lookupTable);
641 free(thread_data_array);
644 } else if(treplyctrl == TRANS_COMMIT) {
646 objstrDelete(record->cache);
647 chashDelete(record->lookupTable);
649 free(thread_data_array);
653 //TODO Add other cases
654 printf("Error: in %s() THIS SHOULD NOT HAPPEN.....EXIT PROGRAM\n", __func__);
660 /* This function sends information involved in the transaction request
661 * to participants and accepts a response from particpants.
662 * It calls decideresponse() to decide on what control message
663 * to send next to participants and sends the message using sendResponse()*/
664 void *transRequest(void *threadarg) {
666 struct sockaddr_in serv_addr;
667 thread_data_array_t *tdata;
668 objheader_t *headeraddr;
669 char control, recvcontrol;
670 char machineip[16], retval;
672 tdata = (thread_data_array_t *) threadarg;
674 /* Send Trans Request */
675 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
676 perror("Error in socket for TRANS_REQUEST\n");
679 bzero((char*) &serv_addr, sizeof(serv_addr));
680 serv_addr.sin_family = AF_INET;
681 serv_addr.sin_port = htons(LISTEN_PORT);
682 midtoIP(tdata->mid,machineip);
683 machineip[15] = '\0';
684 serv_addr.sin_addr.s_addr = inet_addr(machineip);
685 /* Open Connection */
686 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
687 perror("Error in connect for TRANS_REQUEST\n");
692 /* Send bytes of data with TRANS_REQUEST control message */
693 send_data(sd, &(tdata->buffer->f), sizeof(fixed_data_t));
695 /* Send list of machines involved in the transaction */
697 int size=sizeof(unsigned int)*tdata->buffer->f.mcount;
698 send_data(sd, tdata->buffer->listmid, size);
701 /* Send oids and version number tuples for objects that are read */
703 int size=(sizeof(unsigned int)+sizeof(unsigned short))*tdata->buffer->f.numread;
704 send_data(sd, tdata->buffer->objread, size);
707 /* Send objects that are modified */
708 for(i = 0; i < tdata->buffer->f.nummod ; i++) {
710 headeraddr = chashSearch(tdata->rec->lookupTable, tdata->buffer->oidmod[i]);
711 GETSIZE(size,headeraddr);
712 size+=sizeof(objheader_t);
713 send_data(sd, headeraddr, size);
716 /* Read control message from Participant */
717 recv_data(sd, &control, sizeof(char));
718 recvcontrol = control;
720 /* Update common data structure and increment count */
721 tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol;
723 /* Lock and update count */
724 /* Thread sleeps until all messages from pariticipants are received by coordinator */
725 pthread_mutex_lock(tdata->lock);
727 (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */
729 /* Wake up the threads and invoke decideResponse (once) */
730 if(*(tdata->count) == tdata->buffer->f.mcount) {
731 decideResponse(tdata);
732 pthread_cond_broadcast(tdata->threshold);
734 pthread_cond_wait(tdata->threshold, tdata->lock);
736 pthread_mutex_unlock(tdata->lock);
738 /* Send the final response such as TRANS_COMMIT or TRANS_ABORT t
739 * to all participants in their respective socket */
740 if (sendResponse(tdata, sd) == 0) {
741 printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__);
746 recv_data((int)sd, &control, sizeof(char));
748 if(control == TRANS_UNSUCESSFUL) {
749 //printf("DEBUG-> TRANS_ABORTED\n");
750 } else if(control == TRANS_SUCESSFUL) {
751 //printf("DEBUG-> TRANS_SUCCESSFUL\n");
753 //printf("DEBUG-> Error: Incorrect Transaction End Message %d\n", control);
756 /* Close connection */
761 /* This function decides the reponse that needs to be sent to
762 * all Participant machines after the TRANS_REQUEST protocol */
763 void decideResponse(thread_data_array_t *tdata) {
765 int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
768 for (i = 0 ; i < tdata->buffer->f.mcount; i++) {
769 control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses
770 written onto the shared array */
773 printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
774 /* treat as disagree, pass thru */
783 case TRANS_SOFT_ABORT:
789 if(transdisagree > 0) {
791 *(tdata->replyctrl) = TRANS_ABORT;
792 *(tdata->replyretry) = 0;
793 /* clear objects from prefetch cache */
794 for (i = 0; i < tdata->buffer->f.numread; i++)
795 prehashRemove(*((unsigned int *)(((char *)tdata->buffer->objread) + (sizeof(unsigned int) + sizeof(unsigned short))*i)));
796 for (i = 0; i < tdata->buffer->f.nummod; i++)
797 prehashRemove(tdata->buffer->oidmod[i]);
798 } else if(transagree == tdata->buffer->f.mcount){
800 *(tdata->replyctrl) = TRANS_COMMIT;
801 *(tdata->replyretry) = 0;
803 /* Send Abort in soft abort case followed by retry commiting transaction again*/
804 *(tdata->replyctrl) = TRANS_ABORT;
805 *(tdata->replyretry) = 1;
810 /* This function sends the final response to remote machines per thread in their respective socket id
811 * It returns a char that is only needed to check the correctness of execution of this function inside
813 char sendResponse(thread_data_array_t *tdata, int sd) {
814 int n, size, sum, oidcount = 0, control;
815 char *ptr, retval = 0;
816 unsigned int *oidnotfound;
818 control = *(tdata->replyctrl);
819 send_data(sd, &control, sizeof(char));
821 //TODO read missing objects to be used during object migration
822 /* If the decided response is due to a soft abort and missing objects at the Participant's side */
824 if(tdata->recvmsg[tdata->thread_id].rcv_status == TRANS_SOFT_ABORT) {
825 // Read list of objects missing
826 recv_data(sd, &oidcount, sizeof(int));
827 //if((read(sd, &oidcount, sizeof(int)) != 0) && (oidcount != 0)) {
829 size = oidcount * sizeof(unsigned int);
830 if((oidnotfound = calloc(oidcount, sizeof(unsigned int))) == NULL) {
831 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
834 ptr = (char *) oidnotfound;
835 recv_data(sd, ptr, size);
837 retval = TRANS_SOFT_ABORT;
841 /* If the decided response is TRANS_ABORT */
842 if(*(tdata->replyctrl) == TRANS_ABORT) {
843 retval = TRANS_ABORT;
844 } else if(*(tdata->replyctrl) == TRANS_COMMIT) { /* If the decided response is TRANS_COMMIT */
845 retval = TRANS_COMMIT;
851 /* This function opens a connection, places an object read request to the
852 * remote machine, reads the control message and object if available and
853 * copies the object and its header to the local cache.
856 void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
858 struct sockaddr_in serv_addr;
865 for(i = 0; i < NUM_MACHINES; i++) {
866 if(sockArrayRemoteRead[i].mid == mnum) {
867 sd = sockArrayRemoteRead[i].sockid;
868 sockIdFoundRemoteRead = 1;
873 if(sockIdFoundRemoteRead == 0) {
874 if(sockCountRemoteRead < NUM_MACHINES) {
876 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
877 perror("Error in socket\n");
881 bzero((char*) &serv_addr, sizeof(serv_addr));
882 serv_addr.sin_family = AF_INET;
883 serv_addr.sin_port = htons(LISTEN_PORT);
884 serv_addr.sin_addr.s_addr = htonl(mnum);
886 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
887 perror("getRemoteObj() Error in connect\n");
891 sockArrayRemoteRead[sockCountRemoteRead].mid = mnum;
892 sockArrayRemoteRead[sockCountRemoteRead].sockid = sd;
893 sockCountRemoteRead++;
895 //TODO Fix for connecting to more than 2 machines && close socket
896 printf("%s(): Error: Currently works for two remote machines\n", __func__);
901 char readrequest[sizeof(char)+sizeof(unsigned int)];
902 readrequest[0] = READ_REQUEST;
903 *((unsigned int *)(&readrequest[1])) = oid;
904 send_data(sd, readrequest, sizeof(readrequest));
906 /* Read response from the Participant */
907 recv_data(sd, &control, sizeof(char));
910 case OBJECT_NOT_FOUND:
913 /* Read object if found into local cache */
914 recv_data(sd, &size, sizeof(int));
915 objcopy = objstrAlloc(record->cache, size);
916 recv_data(sd, objcopy, size);
918 /* Insert into cache's lookup table */
919 chashInsert(record->lookupTable, oid, objcopy);
922 printf("Error: in recv response from participant on a READ_REQUEST %s, %d\n",__FILE__, __LINE__);
929 /* This function handles the local objects involved in a transaction commiting process.
930 * It also makes a decision if this local machine sends AGREE or DISAGREE or SOFT_ABORT to coordinator.
931 * Note Coordinator = local machine
932 * It wakes up the other threads from remote participants that are waiting for the coordinator's decision and
933 * based on common agreement it either commits or aborts the transaction.
934 * It also frees the memory resources */
935 void *handleLocalReq(void *threadarg) {
936 unsigned int *oidnotfound = NULL, *oidlocked = NULL;
937 local_thread_data_array_t *localtdata;
938 int objnotfound = 0, objlocked = 0;
939 int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
942 unsigned short version;
944 objheader_t *headptr;
946 localtdata = (local_thread_data_array_t *) threadarg;
948 /* Counters and arrays to formulate decision on control message to be sent */
949 oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
950 oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
952 numread = localtdata->tdata->buffer->f.numread;
953 /* Process each oid in the machine pile/ group per thread */
954 for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) {
955 if (i < localtdata->tdata->buffer->f.numread) {
956 int incr = sizeof(unsigned int) + sizeof(unsigned short);// Offset that points to next position in the objread array
958 oid = *((unsigned int *)(((char *)localtdata->tdata->buffer->objread) + incr));
959 version = *((unsigned short *)(((char *)localtdata->tdata->buffer->objread) + incr + sizeof(unsigned int)));
960 } else { // Objects Modified
962 headptr = (objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidmod[i-numread]);
963 if (headptr == NULL) {
964 printf("Error: handleLocalReq() returning NULL %s, %d\n", __FILE__, __LINE__);
968 version = headptr->version;
970 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
972 /* Save the oids not found and number of oids not found for later use */
973 if ((mobj = mhashSearch(oid)) == NULL) { /* Obj not found */
974 /* Save the oids not found and number of oids not found for later use */
975 oidnotfound[objnotfound] = oid;
977 } else { /* If Obj found in machine (i.e. has not moved) */
978 /* Check if Obj is locked by any previous transaction */
979 if ((STATUS((objheader_t *)mobj) & LOCK) == LOCK) {
980 if (version == ((objheader_t *)mobj)->version) { /* If locked then match versions */
982 } else {/* If versions don't match ...HARD ABORT */
984 /* Send TRANS_DISAGREE to Coordinator */
985 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
987 } else {/* If Obj is not locked then lock object */
988 STATUS(((objheader_t *)mobj)) |= LOCK;
989 /* Save all object oids that are locked on this machine during this transaction request call */
990 oidlocked[objlocked] = OID(((objheader_t *)mobj));
992 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
994 } else { /* If versions don't match ...HARD ABORT */
996 /* Send TRANS_DISAGREE to Coordinator */
997 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
1002 /* Condition to send TRANS_AGREE */
1003 if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
1004 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
1006 /* Condition to send TRANS_SOFT_ABORT */
1007 if((v_matchlock > 0 && v_nomatch == 0) || (objnotfound > 0 && v_nomatch == 0)) {
1008 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
1011 /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
1012 * if Participant receives a TRANS_COMMIT */
1013 localtdata->transinfo->objlocked = oidlocked;
1014 localtdata->transinfo->objnotfound = oidnotfound;
1015 localtdata->transinfo->modptr = NULL;
1016 localtdata->transinfo->numlocked = objlocked;
1017 localtdata->transinfo->numnotfound = objnotfound;
1018 /* Lock and update count */
1019 //Thread sleeps until all messages from pariticipants are received by coordinator
1020 pthread_mutex_lock(localtdata->tdata->lock);
1021 (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */
1023 /* Wake up the threads and invoke decideResponse (once) */
1024 if(*(localtdata->tdata->count) == localtdata->tdata->buffer->f.mcount) {
1025 decideResponse(localtdata->tdata);
1026 pthread_cond_broadcast(localtdata->tdata->threshold);
1028 pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock);
1030 pthread_mutex_unlock(localtdata->tdata->lock);
1031 if(*(localtdata->tdata->replyctrl) == TRANS_ABORT){
1032 if(transAbortProcess(localtdata) != 0) {
1033 printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
1036 } else if(*(localtdata->tdata->replyctrl) == TRANS_COMMIT) {
1037 if(transComProcess(localtdata) != 0) {
1038 printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
1043 if (localtdata->transinfo->objlocked != NULL) {
1044 free(localtdata->transinfo->objlocked);
1046 if (localtdata->transinfo->objnotfound != NULL) {
1047 free(localtdata->transinfo->objnotfound);
1053 /* This function completes the ABORT process if the transaction is aborting */
1054 int transAbortProcess(local_thread_data_array_t *localtdata) {
1056 unsigned int *objlocked;
1059 numlocked = localtdata->transinfo->numlocked;
1060 objlocked = localtdata->transinfo->objlocked;
1062 for (i = 0; i < numlocked; i++) {
1063 if((header = mhashSearch(objlocked[i])) == NULL) {
1064 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1067 STATUS(((objheader_t *)header)) &= ~(LOCK);
1073 /*This function completes the COMMIT process is the transaction is commiting*/
1074 int transComProcess(local_thread_data_array_t *localtdata) {
1075 objheader_t *header, *tcptr;
1076 int i, nummod, tmpsize, numcreated, numlocked;
1077 unsigned int *oidmod, *oidcreated, *oidlocked;
1080 nummod = localtdata->tdata->buffer->f.nummod;
1081 oidmod = localtdata->tdata->buffer->oidmod;
1082 numcreated = localtdata->tdata->buffer->f.numcreated;
1083 oidcreated = localtdata->tdata->buffer->oidcreated;
1084 numlocked = localtdata->transinfo->numlocked;
1085 oidlocked = localtdata->transinfo->objlocked;
1087 for (i = 0; i < nummod; i++) {
1088 if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
1089 printf("Error: transComProcess() mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1092 /* Copy from transaction cache -> main object store */
1093 if ((tcptr = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidmod[i]))) == NULL) {
1094 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1097 GETSIZE(tmpsize, header);
1098 pthread_mutex_lock(&mainobjstore_mutex);
1099 memcpy((char*)header+sizeof(objheader_t), (char *)tcptr+ sizeof(objheader_t), tmpsize);
1100 header->version += 1;
1101 if(header->notifylist != NULL) {
1102 notifyAll(&header->notifylist, OID(header), header->version);
1104 pthread_mutex_unlock(&mainobjstore_mutex);
1106 /* If object is newly created inside transaction then commit it */
1107 for (i = 0; i < numcreated; i++) {
1108 if ((header = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidcreated[i]))) == NULL) {
1109 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1112 GETSIZE(tmpsize, header);
1113 tmpsize += sizeof(objheader_t);
1114 pthread_mutex_lock(&mainobjstore_mutex);
1115 if ((ptrcreate = objstrAlloc(mainobjstore, tmpsize)) == NULL) {
1116 printf("Error: transComProcess() failed objstrAlloc %s, %d\n", __FILE__, __LINE__);
1117 pthread_mutex_unlock(&mainobjstore_mutex);
1120 pthread_mutex_unlock(&mainobjstore_mutex);
1121 memcpy(ptrcreate, header, tmpsize);
1122 mhashInsert(oidcreated[i], ptrcreate);
1123 lhashInsert(oidcreated[i], myIpAddr);
1125 /* Unlock locked objects */
1126 for(i = 0; i < numlocked; i++) {
1127 if((header = (objheader_t *) mhashSearch(oidlocked[i])) == NULL) {
1128 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1131 STATUS(header) &= ~(LOCK);
1137 /* This function checks if the prefetch oids are same and have same offsets
1138 * for case x.a.b and y.a.b where x and y have same oid's
1139 * or if a.b.c is a subset of x.b.c.d*/
1140 /* check for case where the generated request a.y.z or x.y.z.g then
1141 * prefetch needs to be generated for x.y.z.g if oid of a and x are same*/
1142 void checkPrefetchTuples(prefetchqelem_t *node) {
1143 int i,j, count,k, sindex, index;
1145 int ntuples, slength;
1147 unsigned short *endoffsets;
1150 /* Check for the case x.y.z and a.b.c are same oids */
1151 ptr = (char *) node;
1152 ntuples = *(GET_NTUPLES(ptr));
1153 oid = GET_PTR_OID(ptr);
1154 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1155 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1157 /* Find offset length for each tuple */
1158 int numoffset[ntuples];
1159 numoffset[0] = endoffsets[0];
1160 for(i = 1; i<ntuples; i++) {
1161 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1163 /* Check for redundant tuples by comparing oids of each tuple */
1164 for(i = 0; i < ntuples; i++) {
1167 for(j = i+1 ; j < ntuples; j++) {
1170 /*If oids of tuples match */
1171 if (oid[i] == oid[j]) {
1172 /* Find the smallest offset length of two tuples*/
1173 if(numoffset[i] > numoffset[j]){
1174 slength = numoffset[j];
1178 slength = numoffset[i];
1182 /* Compare the offset values based on the current indices
1183 * break if they do not match
1184 * if all offset values match then pick the largest tuple*/
1189 k = endoffsets[i-1];
1191 index = endoffsets[j -1];
1192 for(count = 0; count < slength; count ++) {
1193 if (arryfields[k] != arryfields[index]) {
1199 if(slength == count) {
1206 /* This function makes machine piles to be added into the machine pile queue for each prefetch call */
1207 prefetchpile_t *makePreGroups(prefetchqelem_t *node, int *numoffset) {
1209 int ntuples, i, machinenum, count=0;
1211 unsigned short *endoffsets;
1212 short *arryfields, *offset;
1213 prefetchpile_t *head = NULL, *tmp = NULL;
1215 /* Check for the case x.y.z and a.b.c are same oids */
1216 ptr = (char *) node;
1217 ntuples = *(GET_NTUPLES(ptr));
1218 oid = GET_PTR_OID(ptr);
1219 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1220 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1222 if((head = (prefetchpile_t *) calloc(1, sizeof(prefetchpile_t))) == NULL) {
1223 printf("Calloc error: %s %d\n", __FILE__, __LINE__);
1227 /* Check for redundant tuples by comparing oids of each tuple */
1228 for(i = 0; i < ntuples; i++) {
1230 if(head->next != NULL) {
1231 if((tmp = (prefetchpile_t *) calloc(1, sizeof(prefetchpile_t))) == NULL) {
1232 printf("Calloc error: %s %d\n", __FILE__, __LINE__);
1235 tmp->mid = myIpAddr;
1239 head->mid = myIpAddr;
1243 /* For each tuple make piles */
1244 if ((machinenum = lhashSearch(oid[i])) == 0) {
1245 printf("Error: No such Machine %s, %d\n", __FILE__, __LINE__);
1248 /* Insert into machine pile */
1250 offset = &arryfields[0];
1252 offset = &arryfields[endoffsets[i-1]];
1255 if((head = insertPile(machinenum, oid[i], numoffset[i], offset, head)) == NULL){
1256 printf("Error: Couldn't create a pile %s, %d\n", __FILE__, __LINE__);
1264 prefetchpile_t *foundLocal(prefetchqelem_t *node) {
1265 int ntuples,i, j, k, oidnfound = 0, arryfieldindex,nextarryfieldindex, flag = 0, val;
1269 objheader_t *objheader;
1270 unsigned short *endoffsets;
1272 prefetchpile_t *head = NULL;
1274 ptr = (char *) node;
1275 ntuples = *(GET_NTUPLES(ptr));
1276 oid = GET_PTR_OID(ptr);
1277 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1278 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1280 /* Find offset length for each tuple */
1281 int numoffset[ntuples];//Number of offsets for each tuple
1282 numoffset[0] = endoffsets[0];
1283 for(i = 1; i<ntuples; i++) {
1284 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1287 for(i = 0; i < ntuples; i++) {
1291 nextarryfieldindex = endoffsets[0];
1293 arryfieldindex = endoffsets[i-1];
1294 nextarryfieldindex = endoffsets[i];
1297 endoffsets[0] = val = numoffset[0];
1298 for(k = 1; k < ntuples; k++) {
1299 val = val + numoffset[k];
1300 endoffsets[k] = val;
1303 for(k = 0; k<endoffsets[ntuples-1]; k++) {
1304 arryfields[arryfieldindex+k] = arryfields[nextarryfieldindex+k];
1309 /* If object found locally */
1310 if((objheader = (objheader_t*) mhashSearch(oid[i])) != NULL) {
1312 tmp = (char *) objheader;
1313 int orgnumoffset = numoffset[i];
1317 arryfieldindex = endoffsets[i-1];
1320 for(j = 0; j<orgnumoffset; j++) {
1321 unsigned int objoid = 0;
1322 /* Check for arrays */
1323 if(TYPE(objheader) > NUMCLASSES) {
1327 int elementsize = classsize[TYPE(objheader)];
1328 struct ArrayObject *ao = (struct ArrayObject *) (tmp + sizeof(objheader_t));
1329 int length = ao->___length___;
1330 /* Check if array out of bounds */
1331 if(arryfields[arryfieldindex] < 0 || arryfields[arryfieldindex] >= length) {
1332 break; //if yes then treat the object as found
1334 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*arryfields[arryfieldindex])));
1336 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + arryfields[arryfieldindex]));
1338 //Update numoffset array
1339 numoffset[i] = numoffset[i] - 1;
1342 //Update endoffset array
1343 endoffsets[0] = val = numoffset[0];
1344 for(k = 1; k < ntuples; k++) {
1345 val = val + numoffset[k];
1346 endoffsets[k] = val;
1348 //Update arrayfields array
1349 for(k = 0; k < endoffsets[ntuples-1]; k++) {
1350 arryfields[arryfieldindex+k] = arryfields[arryfieldindex+k+1];
1352 if((objheader = (objheader_t*) mhashSearch(oid[i])) == NULL) {
1354 checkPreCache(node, numoffset, oid[i], i);
1357 tmp = (char *) objheader;
1360 /*If all offset oids are found locally,make the prefetch tuple invalid */
1365 /* Look in Prefetch cache */
1366 checkPreCache(node, numoffset, oid[i],i);
1371 /* Make machine groups */
1372 if((head = makePreGroups(node, numoffset)) == NULL) {
1373 printf("Error in makePreGroups() %s %d\n", __FILE__, __LINE__);
1380 void checkPreCache(prefetchqelem_t *node, int *numoffset, unsigned int objoid, int index) {
1382 int ntuples, i, k, flag=0, isArray =0, arryfieldindex, val;
1384 unsigned short *endoffsets;
1386 objheader_t *header;
1388 ptr = (char *) node;
1389 ntuples = *(GET_NTUPLES(ptr));
1390 oid = GET_PTR_OID(ptr);
1391 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1392 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1394 if((header = (objheader_t *) prehashSearch(objoid)) == NULL) {
1396 } else { //Found in Prefetch Cache
1397 //TODO Decide if object is too old, if old remove from cache
1398 tmp = (char *) header;
1399 int loopcount = numoffset[index];
1403 arryfieldindex = endoffsets[(index - 1)];
1404 // Check if any of the offset oid is available in the Prefetch cache
1405 for(i = 0; i < loopcount; i++) {
1406 /* Check for arrays */
1407 if(TYPE(header) > NUMCLASSES) {
1412 int elementsize = classsize[TYPE(header)];
1413 struct ArrayObject *ao = (struct ArrayObject *) (tmp + sizeof(objheader_t));
1414 int length = ao->___length___;
1415 /* Check if array out of bounds */
1416 if(arryfields[arryfieldindex] < 0 || arryfields[arryfieldindex] >= length) {
1417 break; //if yes treat the object as found
1419 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*arryfields[arryfieldindex])));
1421 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + arryfields[arryfieldindex]));
1423 //Update numoffset array
1424 numoffset[index] = numoffset[index] - 1;
1426 oid[index] = objoid;
1427 //Update endoffset array
1428 endoffsets[0] = val = numoffset[0];
1429 for(k = 1; k < ntuples; k++) {
1430 val = val + numoffset[k];
1431 endoffsets[k] = val;
1433 //Update arrayfields array
1434 for(k = 0; k < endoffsets[ntuples-1]; k++) {
1435 arryfields[arryfieldindex+k] = arryfields[arryfieldindex+k+1];
1437 if((header = (objheader_t *)prehashSearch(oid[index])) != NULL) {
1438 tmp = (char *) header;
1446 //Found in the prefetch cache
1447 if(flag == 0 && (numoffset[index] == 0)) {
1454 /* This function is called by the thread calling transPrefetch */
1455 void *transPrefetch(void *t) {
1456 prefetchqelem_t *qnode;
1457 prefetchpile_t *pilehead = NULL;
1458 prefetchpile_t *ptr = NULL, *piletail = NULL;
1461 /* lock mutex of primary prefetch queue */
1462 pthread_mutex_lock(&pqueue.qlock);
1463 /* while primary queue is empty, then wait */
1464 while((pqueue.front == NULL) && (pqueue.rear == NULL)) {
1465 pthread_cond_wait(&pqueue.qcond, &pqueue.qlock);
1468 /* dequeue node to create a machine piles and finally unlock mutex */
1469 if((qnode = pre_dequeue()) == NULL) {
1470 printf("Error: No node returned %s, %d\n", __FILE__, __LINE__);
1471 pthread_mutex_unlock(&pqueue.qlock);
1474 pthread_mutex_unlock(&pqueue.qlock);
1476 /* Reduce redundant prefetch requests */
1477 checkPrefetchTuples(qnode);
1478 /* Check if the tuples are found locally, if yes then reduce them further*/
1479 /* and group requests by remote machine ids by calling the makePreGroups() */
1480 if((pilehead = foundLocal(qnode)) == NULL) {
1481 printf("Error: No node created for serving prefetch request %s %d\n", __FILE__, __LINE__);
1487 while(ptr != NULL) {
1488 if(ptr->next == NULL) {
1494 /* Lock mutex of pool queue */
1495 pthread_mutex_lock(&mcqueue.qlock);
1496 /* Update the pool queue with the new remote machine piles generated per prefetch call */
1497 mcpileenqueue(pilehead, piletail);
1498 /* Broadcast signal on machine pile queue */
1499 pthread_cond_broadcast(&mcqueue.qcond);
1500 /* Unlock mutex of machine pile queue */
1501 pthread_mutex_unlock(&mcqueue.qlock);
1502 /* Deallocate the prefetch queue pile node */
1507 /* Each thread in the pool of threads calls this function to establish connection with
1508 * remote machines, send the prefetch requests and process the reponses from
1509 * the remote machines .
1510 * The thread is active throughout the period of runtime */
1512 void *mcqProcess(void *threadid) {
1514 prefetchpile_t *mcpilenode;
1515 struct sockaddr_in remoteAddr;
1518 tid = (int) threadid;
1522 /* Lock mutex of mc pile queue */
1523 pthread_mutex_lock(&mcqueue.qlock);
1524 /* When mc pile queue is empty, wait */
1525 while((mcqueue.front == NULL) && (mcqueue.rear == NULL)) {
1526 pthread_cond_wait(&mcqueue.qcond, &mcqueue.qlock);
1528 /* Dequeue node to send remote machine connections*/
1529 if((mcpilenode = mcpiledequeue()) == NULL) {
1530 printf("Dequeue Error: No node returned %s %d\n", __FILE__, __LINE__);
1531 pthread_mutex_unlock(&mcqueue.qlock);
1535 pthread_mutex_unlock(&mcqueue.qlock);
1537 /*Initiate connection to remote host and send prefetch request */
1538 if(mcpilenode->mid != myIpAddr) {
1539 /* Check to see if socket exists */
1540 for(i = 0; i < NUM_MACHINES; i++) {
1541 if(midSocketArray[i].mid == mcpilenode->mid) {
1542 sendPrefetchReq(mcpilenode, midSocketArray[i].sockid);
1548 if(sockIdFound == 0) {
1549 if(sockCount < NUM_MACHINES) {
1551 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
1552 printf("%s() Error: In creating socket at %s, %d\n", __func__, __FILE__, __LINE__);
1556 bzero(&remoteAddr, sizeof(remoteAddr));
1557 remoteAddr.sin_family = AF_INET;
1558 remoteAddr.sin_port = htons(LISTEN_PORT);
1559 remoteAddr.sin_addr.s_addr = htonl(mcpilenode->mid);
1561 /* Open Connection */
1562 if (connect(sd, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0) {
1563 printf("%s():error %d connecting to %s:%d\n", __func__, errno,
1564 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1569 midSocketArray[sockCount].mid = mcpilenode->mid;
1570 midSocketArray[sockCount].sockid = sd;
1571 sendPrefetchReq(mcpilenode, midSocketArray[sockCount].sockid);
1574 //TODO Fix for connecting to more than 2 machines && close socket
1575 printf("%s(): Error: Currently works for only 2 machines\n", __func__);
1581 /* Deallocate the machine queue pile node */
1582 mcdealloc(mcpilenode);
1586 void sendPrefetchReq(prefetchpile_t *mcpilenode, int sd) {
1587 int i, off, len, endpair, count = 0;
1588 char machineip[16], control;
1591 /* Send TRANS_PREFETCH control message */
1592 control = TRANS_PREFETCH;
1593 send_data(sd, &control, sizeof(char));
1595 /* Send Oids and offsets in pairs */
1596 tmp = mcpilenode->objpiles;
1597 while(tmp != NULL) {
1599 count++; /* Keeps track of the number of oid and offset tuples sent per remote machine */
1600 len = sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1601 char oidnoffset[len];
1602 bzero(oidnoffset, len);
1603 *((int*)oidnoffset) = len;
1605 *((unsigned int *)(oidnoffset + off)) = tmp->oid;
1606 off += sizeof(unsigned int);
1607 *((unsigned int *)(oidnoffset + off)) = myIpAddr;
1608 off += sizeof(unsigned int);
1609 for(i = 0; i < tmp->numoffset; i++) {
1610 *((short*)(oidnoffset + off)) = tmp->offset[i];
1613 send_data(sd, oidnoffset, len);
1617 /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
1619 send_data(sd, &endpair, sizeof(int));
1624 int getPrefetchResponse(int sd) {
1625 int numbytes = 0, length = 0, size = 0;
1626 char *recvbuffer, control;
1628 void *modptr, *oldptr;
1630 recv_data((int)sd, &length, sizeof(int));
1631 size = length - sizeof(int);
1632 if((recvbuffer = calloc(1, size)) == NULL) {
1633 printf("%s() Calloc error at %s,%d\n", __func__, __FILE__, __LINE__);
1637 recv_data((int)sd, recvbuffer, size);
1639 control = *((char *) recvbuffer);
1640 if(control == OBJECT_FOUND) {
1642 oid = *((unsigned int *)(recvbuffer + sizeof(char)));
1643 size = size - (sizeof(char) + sizeof(unsigned int));
1644 pthread_mutex_lock(&prefetchcache_mutex);
1645 if ((modptr = objstrAlloc(prefetchcache, size)) == NULL) {
1646 printf("Error: objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
1647 pthread_mutex_unlock(&prefetchcache_mutex);
1651 pthread_mutex_unlock(&prefetchcache_mutex);
1652 memcpy(modptr, recvbuffer + sizeof(char) + sizeof(unsigned int), size);
1654 /* Insert the oid and its address into the prefetch hash lookup table */
1655 /* Do a version comparison if the oid exists */
1656 if((oldptr = prehashSearch(oid)) != NULL) {
1657 /* If older version then update with new object ptr */
1658 if(((objheader_t *)oldptr)->version <= ((objheader_t *)modptr)->version) {
1660 prehashInsert(oid, modptr);
1662 /* TODO modptr should be reference counted */
1664 } else {/* Else add the object ptr to hash table*/
1665 prehashInsert(oid, modptr);
1667 /* Lock the Prefetch Cache look up table*/
1668 pthread_mutex_lock(&pflookup.lock);
1669 /* Broadcast signal on prefetch cache condition variable */
1670 pthread_cond_broadcast(&pflookup.cond);
1671 /* Unlock the Prefetch Cache look up table*/
1672 pthread_mutex_unlock(&pflookup.lock);
1673 } else if(control == OBJECT_NOT_FOUND) {
1674 oid = *((unsigned int *)(recvbuffer + sizeof(char)));
1675 /* TODO: For each object not found query DHT for new location and retrieve the object */
1676 /* Throw an error */
1677 printf("OBJECT %x NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n", oid);
1681 printf("Error: in decoding the control value %d, %s, %d\n",control, __FILE__, __LINE__);
1689 unsigned short getObjType(unsigned int oid)
1691 objheader_t *objheader;
1692 unsigned short numoffset[] ={0};
1693 short fieldoffset[] ={};
1695 if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL)
1697 if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1699 prefetch(1, &oid, numoffset, fieldoffset);
1700 pthread_mutex_lock(&pflookup.lock);
1701 while ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1703 pthread_cond_wait(&pflookup.cond, &pflookup.lock);
1705 pthread_mutex_unlock(&pflookup.lock);
1709 return TYPE(objheader);
1712 int startRemoteThread(unsigned int oid, unsigned int mid)
1715 struct sockaddr_in remoteAddr;
1716 char msg[1 + sizeof(unsigned int)];
1720 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
1722 perror("startRemoteThread():socket()");
1726 bzero(&remoteAddr, sizeof(remoteAddr));
1727 remoteAddr.sin_family = AF_INET;
1728 remoteAddr.sin_port = htons(LISTEN_PORT);
1729 remoteAddr.sin_addr.s_addr = htonl(mid);
1731 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0)
1733 printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
1734 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1739 msg[0] = START_REMOTE_THREAD;
1740 memcpy(&msg[1], &oid, sizeof(unsigned int));
1741 send_data(sock, msg, 1 + sizeof(unsigned int));
1748 //TODO: when reusing oids, make sure they are not already in use!
1749 unsigned int getNewOID(void) {
1750 static unsigned int id = 0xFFFFFFFF;
1753 if (id > oidMax || id < oidMin)
1760 int processConfigFile()
1763 const int maxLineLength = 200;
1764 char lineBuffer[maxLineLength];
1766 const char *delimiters = " \t\n";
1770 configFile = fopen(CONFIG_FILENAME, "r");
1771 if (configFile == NULL)
1773 printf("error opening %s:\n", CONFIG_FILENAME);
1778 numHostsInSystem = 0;
1779 sizeOfHostArray = 8;
1780 hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
1782 while(fgets(lineBuffer, maxLineLength, configFile) != NULL)
1784 commentBegin = strchr(lineBuffer, '#');
1785 if (commentBegin != NULL)
1786 *commentBegin = '\0';
1787 token = strtok(lineBuffer, delimiters);
1788 while (token != NULL)
1790 tmpAddr = inet_addr(token);
1791 if ((int)tmpAddr == -1)
1793 printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
1798 addHost(htonl(tmpAddr));
1799 token = strtok(NULL, delimiters);
1805 if (numHostsInSystem < 1)
1807 printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
1811 myIpAddr = getMyIpAddr("en1");
1813 myIpAddr = getMyIpAddr("eth0");
1815 myIndexInHostArray = findHost(myIpAddr);
1816 if (myIndexInHostArray == -1)
1818 printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
1821 oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
1822 oidMin = oidsPerBlock * myIndexInHostArray;
1823 if (myIndexInHostArray == numHostsInSystem - 1)
1824 oidMax = 0xFFFFFFFF;
1826 oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
1831 void addHost(unsigned int hostIp)
1833 unsigned int *tmpArray;
1835 if (findHost(hostIp) != -1)
1838 if (numHostsInSystem == sizeOfHostArray)
1840 tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
1841 memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
1843 hostIpAddrs = tmpArray;
1846 hostIpAddrs[numHostsInSystem++] = hostIp;
1851 int findHost(unsigned int hostIp)
1854 for (i = 0; i < numHostsInSystem; i++)
1855 if (hostIpAddrs[i] == hostIp)
1862 /* This function sends notification request per thread waiting on object(s) whose version
1864 int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int numoid) {
1866 objheader_t *objheader;
1867 struct sockaddr_in remoteAddr;
1868 char msg[1 + numoid * (sizeof(unsigned short) + sizeof(unsigned int)) + 3 * sizeof(unsigned int)];
1872 unsigned short version;
1873 unsigned int oid,mid;
1874 static unsigned int threadid = 0;
1875 pthread_mutex_t threadnotify = PTHREAD_MUTEX_INITIALIZER; //Lock and condition var for threadjoin and notification
1876 pthread_cond_t threadcond = PTHREAD_COND_INITIALIZER;
1877 notifydata_t *ndata;
1879 //FIXME currently all oids belong to one machine
1881 if((mid = lhashSearch(oid)) == 0) {
1882 printf("Error: %s() No such machine found for oid =%x\n",__func__, oid);
1886 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1887 perror("reqNotify():socket()");
1891 bzero(&remoteAddr, sizeof(remoteAddr));
1892 remoteAddr.sin_family = AF_INET;
1893 remoteAddr.sin_port = htons(LISTEN_PORT);
1894 remoteAddr.sin_addr.s_addr = htonl(mid);
1896 /* Generate unique threadid */
1899 /* Save threadid, numoid, oidarray, versionarray, pthread_cond_variable for later processing */
1900 if((ndata = calloc(1, sizeof(notifydata_t))) == NULL) {
1901 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
1904 ndata->numoid = numoid;
1905 ndata->threadid = threadid;
1906 ndata->oidarry = oidarry;
1907 ndata->versionarry = versionarry;
1908 ndata->threadcond = threadcond;
1909 ndata->threadnotify = threadnotify;
1910 if((status = notifyhashInsert(threadid, ndata)) != 0) {
1911 printf("reqNotify(): Insert into notify hash table not successful %s, %d\n", __FILE__, __LINE__);
1916 /* Send number of oids, oidarry, version array, machine id and threadid */
1917 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1918 printf("reqNotify():error %d connecting to %s:%d\n", errno,
1919 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1923 msg[0] = THREAD_NOTIFY_REQUEST;
1924 *((unsigned int *)(&msg[1])) = numoid;
1925 /* Send array of oids */
1926 size = sizeof(unsigned int);
1931 *((unsigned int *)(&msg[1] + size)) = oid;
1932 size += sizeof(unsigned int);
1937 /* Send array of version */
1941 version = versionarry[i];
1942 *((unsigned short *)(&msg[1] + size)) = version;
1943 size += sizeof(unsigned short);
1948 *((unsigned int *)(&msg[1] + size)) = myIpAddr;
1949 size += sizeof(unsigned int);
1950 *((unsigned int *)(&msg[1] + size)) = threadid;
1952 pthread_mutex_lock(&(ndata->threadnotify));
1953 size = 1 + numoid * (sizeof(unsigned int) + sizeof(unsigned short)) + 3 * sizeof(unsigned int);
1954 send_data(sock, msg, size);
1955 pthread_cond_wait(&(ndata->threadcond), &(ndata->threadnotify));
1956 pthread_mutex_unlock(&(ndata->threadnotify));
1959 pthread_cond_destroy(&threadcond);
1960 pthread_mutex_destroy(&threadnotify);
1966 void threadNotify(unsigned int oid, unsigned short version, unsigned int tid) {
1967 notifydata_t *ndata;
1968 int i, objIsFound = 0, index;
1971 //Look up the tid and call the corresponding pthread_cond_signal
1972 if((ndata = notifyhashSearch(tid)) == NULL) {
1973 printf("threadnotify(): No such threadid is present %s, %d\n", __FILE__, __LINE__);
1976 for(i = 0; i < ndata->numoid; i++) {
1977 if(ndata->oidarry[i] == oid){
1982 if(objIsFound == 0){
1983 printf("threadNotify(): Oid not found %s, %d\n", __FILE__, __LINE__);
1986 if(version <= ndata->versionarry[index]){
1987 printf("threadNotify(): New version %d has not changed since last version %s, %d\n", version, __FILE__, __LINE__);
1990 /* Clear from prefetch cache and free thread related data structure */
1991 if((ptr = prehashSearch(oid)) != NULL) {
1994 pthread_cond_signal(&(ndata->threadcond));
2001 int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) {
2004 struct sockaddr_in remoteAddr;
2005 char msg[1 + sizeof(unsigned short) + 2*sizeof(unsigned int)];
2006 int sock, status, size, bytesSent;
2008 while(*head != NULL) {
2011 //create a socket connection to that machine
2012 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
2013 perror("notifyAll():socket()");
2017 bzero(&remoteAddr, sizeof(remoteAddr));
2018 remoteAddr.sin_family = AF_INET;
2019 remoteAddr.sin_port = htons(LISTEN_PORT);
2020 remoteAddr.sin_addr.s_addr = htonl(mid);
2021 //send Thread Notify response and threadid to that machine
2022 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
2023 printf("notifyAll():error %d connecting to %s:%d\n", errno,
2024 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
2027 bzero(msg, (1+sizeof(unsigned short) + 2*sizeof(unsigned int)));
2028 msg[0] = THREAD_NOTIFY_RESPONSE;
2029 *((unsigned int *)&msg[1]) = oid;
2030 size = sizeof(unsigned int);
2031 *((unsigned short *)(&msg[1]+ size)) = version;
2032 size+= sizeof(unsigned short);
2033 *((unsigned int *)(&msg[1]+ size)) = ptr->threadid;
2035 size = 1 + 2*sizeof(unsigned int) + sizeof(unsigned short);
2036 send_data(sock, msg, size);
2047 void transAbort(transrecord_t *trans) {
2048 objstrDelete(trans->cache);
2049 chashDelete(trans->lookupTable);