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
26 #define RECEIVE_BUFFER_SIZE 2048
27 #define NUM_THREADS 10
28 #define PREFETCH_CACHE_SIZE 1048576 //1MB
29 #define CONFIG_FILENAME "dstm.conf"
31 /* Global Variables */
32 extern int classsize[];
33 extern primarypfq_t pqueue; //Shared prefetch queue
34 extern mcpileq_t mcqueue; //Shared queue containing prefetch requests sorted by remote machineids
35 objstr_t *prefetchcache; //Global Prefetch cache
36 pthread_mutex_t prefetchcache_mutex;// Mutex to lock Prefetch Cache
37 pthread_mutexattr_t prefetchcache_mutex_attr; /* Attribute for lock to make it a recursive lock */
38 extern pthread_mutex_t mainobjstore_mutex;// Mutex to lock main Object store
39 extern prehashtable_t pflookup; //Global Prefetch cache's lookup table
40 pthread_t wthreads[NUM_THREADS]; //Worker threads for working on the prefetch queue
41 pthread_t tPrefetch; /* Primary Prefetch thread that processes the prefetch queue */
42 extern objstr_t *mainobjstore;
43 unsigned int myIpAddr;
44 unsigned int *hostIpAddrs;
47 int myIndexInHostArray;
48 unsigned int oidsPerBlock;
52 pthread_mutex_t mlock = PTHREAD_MUTEX_INITIALIZER;
54 void printhex(unsigned char *, int);
55 plistnode_t *createPiles(transrecord_t *);
57 void printhex(unsigned char *ptr, int numBytes)
60 for (i = 0; i < numBytes; i++)
63 printf("0%x ", ptr[i]);
65 printf("%x ", ptr[i]);
71 inline int arrayLength(int *array) {
73 for(i=0 ;array[i] != -1; i++)
77 inline int findmax(int *array, int arraylength) {
80 for(i = 0; i < arraylength; i++){
87 /* This function is a prefetch call generated by the compiler that
88 * populates the shared primary prefetch queue*/
89 void prefetch(int ntuples, unsigned int *oids, unsigned short *endoffsets, short *arrayfields) {
94 /* Allocate for the queue node*/
97 qnodesize = sizeof(prefetchqelem_t) + sizeof(int) + ntuples * (sizeof(unsigned short) + sizeof(unsigned int)) + endoffsets[ntuples - 1] * sizeof(unsigned short);
98 if((node = calloc(1, qnodesize)) == NULL) {
99 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
102 /* Set queue node values */
103 len = sizeof(prefetchqelem_t);
104 memcpy(node + len, &ntuples, sizeof(int));
106 memcpy(node + len, oids, ntuples*sizeof(unsigned int));
107 len += ntuples * sizeof(unsigned int);
108 memcpy(node + len, endoffsets, ntuples*sizeof(unsigned short));
109 len += ntuples * sizeof(unsigned short);
110 memcpy(node + len, arrayfields, endoffsets[ntuples-1]*sizeof(unsigned short));
111 /* Lock and insert into primary prefetch queue */
112 pthread_mutex_lock(&pqueue.qlock);
113 pre_enqueue((prefetchqelem_t *)node);
114 pthread_cond_signal(&pqueue.qcond);
115 pthread_mutex_unlock(&pqueue.qlock);
119 /* This function starts up the transaction runtime. */
120 int dstmStartup(const char * option) {
121 pthread_t thread_Listen;
123 int master=option!=NULL && strcmp(option, "master")==0;
125 if (processConfigFile() != 0)
126 return 0; //TODO: return error value, cause main program to exit
136 pthread_attr_init(&attr);
137 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
138 pthread_create(&thread_Listen, &attr, dstmListen, NULL);
147 //TODO Use this later
148 void *pCacheAlloc(objstr_t *store, unsigned int size) {
154 while(ptr->next != NULL) {
155 /* check if store is empty */
156 if(((unsigned int)ptr->top - (unsigned int)ptr - sizeof(objstr_t) + size) <= ptr->size) {
171 /* This function initiates the prefetch thread
172 * A queue is shared between the main thread of execution
173 * and the prefetch thread to process the prefetch call
174 * Call from compiler populates the shared queue with prefetch requests while prefetch thread
175 * processes the prefetch requests */
179 //Create and initialize prefetch cache structure
180 prefetchcache = objstrCreate(PREFETCH_CACHE_SIZE);
181 //prefetchcache->next = objstrCreate(PREFETCH_CACHE_SIZE);
182 //prefetchcache->next->next = objstrCreate(PREFETCH_CACHE_SIZE);
184 /* Initialize attributes for mutex */
185 pthread_mutexattr_init(&prefetchcache_mutex_attr);
186 pthread_mutexattr_settype(&prefetchcache_mutex_attr, PTHREAD_MUTEX_RECURSIVE_NP);
188 pthread_mutex_init(&prefetchcache_mutex, &prefetchcache_mutex_attr);
190 //Create prefetch cache lookup table
191 if(prehashCreate(HASH_SIZE, LOADFACTOR))
193 //Initialize primary shared queue
195 //Initialize machine pile w/prefetch oids and offsets shared queue
198 //Create the primary prefetch thread
200 retval=pthread_create(&tPrefetch, NULL, transPrefetch, NULL);
202 pthread_detach(tPrefetch);
204 //Create and Initialize a pool of threads
205 /* Threads are active for the entire period runtime is running */
206 for(t = 0; t< NUM_THREADS; t++) {
208 rc = pthread_create(&wthreads[t], NULL, mcqProcess, (void *)t);
210 pthread_detach(wthreads[t]);
214 /* This function stops the threads spawned */
217 pthread_cancel(tPrefetch);
218 for(t = 0; t < NUM_THREADS; t++)
219 pthread_cancel(wthreads[t]);
224 /* This functions inserts randowm wait delays in the order of msec
225 * Mostly used when transaction commits retry*/
233 req.tv_nsec = (long)(1000000 + (t%10000000)); //1-11 msec
234 nanosleep(&req, NULL);
238 /* This function initializes things required in the transaction start*/
239 transrecord_t *transStart()
241 transrecord_t *tmp = calloc(1, sizeof(transrecord_t));
242 tmp->cache = objstrCreate(1048576);
243 tmp->lookupTable = chashCreate(HASH_SIZE, LOADFACTOR);
245 tmp->revertlist=NULL;
250 /* This function finds the location of the objects involved in a transaction
251 * and returns the pointer to the object if found in a remote location */
252 objheader_t *transRead(transrecord_t *record, unsigned int oid) {
253 unsigned int machinenumber;
254 objheader_t *tmp, *objheader;
255 objheader_t *objcopy;
256 int size, rc, found = 0;
265 rc = gettimeofday(&tp, NULL);
269 if (tp.tv_usec >= 1000000)
271 tp.tv_usec -= 1000000;
274 /* Convert from timeval to timespec */
275 ts.tv_sec = tp.tv_sec;
276 ts.tv_nsec = tp.tv_usec * 1000;
278 /* Search local transaction cache */
279 if((objheader = (objheader_t *)chashSearch(record->lookupTable, oid)) != NULL){
281 return &objheader[1];
285 } else if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
286 /* Look up in machine lookup table and copy into cache*/
287 GETSIZE(size, objheader);
288 size += sizeof(objheader_t);
289 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
290 memcpy(objcopy, objheader, size);
291 /* Insert into cache's lookup table */
292 chashInsert(record->lookupTable, OID(objheader), objcopy);
298 } else if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) { /* Look up in prefetch cache */
300 size+=sizeof(objheader_t);
301 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
302 memcpy(objcopy, tmp, size);
303 /* Insert into cache's lookup table */
304 chashInsert(record->lookupTable, OID(tmp), objcopy);
311 /*If object not found in prefetch cache then block until object appears in the prefetch cache */
312 pthread_mutex_lock(&pflookup.lock);
314 rc = pthread_cond_timedwait(&pflookup.cond, &pflookup.lock, &ts);
315 /* Check Prefetch cache again */
316 if((tmp =(objheader_t *) prehashSearch(oid)) != NULL) {
319 size+=sizeof(objheader_t);
320 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
321 memcpy(objcopy, tmp, size);
322 chashInsert(record->lookupTable, OID(tmp), objcopy);
323 pthread_mutex_unlock(&pflookup.lock);
329 } else if (rc == ETIMEDOUT) {
330 pthread_mutex_unlock(&pflookup.lock);
335 /* Get the object from the remote location */
336 if((machinenumber = lhashSearch(oid)) == 0) {
337 printf("Error: %s() No machine found for oid =% %s,%dx\n",__func__, machinenumber, __FILE__, __LINE__);
341 objcopy = getRemoteObj(record, machinenumber, oid);
342 if(objcopy == NULL) {
343 printf("Error: Object not found in Remote location %s, %d\n", __FILE__, __LINE__);
355 /* This function creates objects in the transaction record */
356 objheader_t *transCreateObj(transrecord_t *record, unsigned int size)
358 objheader_t *tmp = (objheader_t *) objstrAlloc(record->cache, (sizeof(objheader_t) + size));
359 tmp->notifylist = NULL;
360 OID(tmp) = getNewOID();
364 chashInsert(record->lookupTable, OID(tmp), tmp);
367 return &tmp[1]; //want space after object header
373 /* This function creates machine piles based on all machines involved in a
374 * transaction commit request */
375 plistnode_t *createPiles(transrecord_t *record) {
377 unsigned int size;/* Represents number of bins in the chash table */
378 chashlistnode_t *curr, *ptr, *next;
379 plistnode_t *pile = NULL;
380 unsigned int machinenum;
381 void *localmachinenum;
382 objheader_t *headeraddr;
384 ptr = record->lookupTable->table;
385 size = record->lookupTable->size;
387 for(i = 0; i < size ; i++) {
389 /* Inner loop to traverse the linked list of the cache lookupTable */
390 while(curr != NULL) {
391 //if the first bin in hash table is empty
397 if ((headeraddr = chashSearch(record->lookupTable, curr->key)) == NULL) {
398 printf("Error: No such oid %s, %d\n", __FILE__, __LINE__);
402 //Get machine location for object id (and whether local or not)
403 if (STATUS(headeraddr) & NEW || (mhashSearch(curr->key) != NULL)) {
404 machinenum = myIpAddr;
405 } else if ((machinenum = lhashSearch(curr->key)) == 0) {
406 printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
410 //Make machine groups
411 if ((pile = pInsert(pile, headeraddr, machinenum, record->lookupTable->numelements)) == NULL) {
412 printf("pInsert error %s, %d\n", __FILE__, __LINE__);
422 /* This function initiates the transaction commit process
423 * Spawns threads for each of the new connections with Participants
424 * and creates new piles by calling the createPiles(),
425 * Sends a transrequest() to each remote machines for objects found remotely
426 * and calls handleLocalReq() to process objects found locally */
427 int transCommit(transrecord_t *record) {
428 unsigned int tot_bytes_mod, *listmid;
429 plistnode_t *pile, *pile_ptr;
431 int pilecount, offset, threadnum = 0, trecvcount = 0;
432 char buffer[RECEIVE_BUFFER_SIZE],control;
433 char transid[TID_LEN];
434 trans_req_data_t *tosend;
435 trans_commit_data_t transinfo;
436 static int newtid = 0;
437 char treplyctrl = 0, treplyretry = 0; /* keeps track of the common response that needs to be sent */
442 /* Look through all the objects in the transaction record and make piles
443 * for each machine involved in the transaction*/
444 pile_ptr = pile = createPiles(record);
446 /* Create the packet to be sent in TRANS_REQUEST */
448 /* Count the number of participants */
449 pilecount = pCount(pile);
451 /* Create a list of machine ids(Participants) involved in transaction */
452 if((listmid = calloc(pilecount, sizeof(unsigned int))) == NULL) {
453 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
456 pListMid(pile, listmid);
459 /* Initialize thread variables,
460 * Spawn a thread for each Participant involved in a transaction */
461 pthread_t thread[pilecount];
463 pthread_cond_t tcond;
464 pthread_mutex_t tlock;
465 pthread_mutex_t tlshrd;
467 thread_data_array_t *thread_data_array;
468 if((thread_data_array = (thread_data_array_t *) calloc(pilecount, sizeof(thread_data_array_t))) == NULL) {
469 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
470 pthread_cond_destroy(&tcond);
471 pthread_mutex_destroy(&tlock);
477 local_thread_data_array_t *ltdata;
478 if((ltdata = calloc(1, sizeof(local_thread_data_array_t))) == NULL) {
479 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
480 pthread_cond_destroy(&tcond);
481 pthread_mutex_destroy(&tlock);
484 free(thread_data_array);
488 thread_response_t rcvd_control_msg[pilecount]; /* Shared thread array that keeps track of responses of participants */
490 /* Initialize and set thread detach attribute */
491 pthread_attr_init(&attr);
492 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
493 pthread_mutex_init(&tlock, NULL);
494 pthread_cond_init(&tcond, NULL);
496 /* Process each machine pile */
497 while(pile != NULL) {
498 //Create transaction id
500 if ((tosend = calloc(1, sizeof(trans_req_data_t))) == NULL) {
501 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
502 pthread_cond_destroy(&tcond);
503 pthread_mutex_destroy(&tlock);
506 free(thread_data_array);
510 tosend->f.control = TRANS_REQUEST;
511 sprintf(tosend->f.trans_id, "%x_%d", pile->mid, newtid);
512 tosend->f.mcount = pilecount;
513 tosend->f.numread = pile->numread;
514 tosend->f.nummod = pile->nummod;
515 tosend->f.numcreated = pile->numcreated;
516 tosend->f.sum_bytes = pile->sum_bytes;
517 tosend->listmid = listmid;
518 tosend->objread = pile->objread;
519 tosend->oidmod = pile->oidmod;
520 tosend->oidcreated = pile->oidcreated;
521 thread_data_array[threadnum].thread_id = threadnum;
522 thread_data_array[threadnum].mid = pile->mid;
523 thread_data_array[threadnum].buffer = tosend;
524 thread_data_array[threadnum].recvmsg = rcvd_control_msg;
525 thread_data_array[threadnum].threshold = &tcond;
526 thread_data_array[threadnum].lock = &tlock;
527 thread_data_array[threadnum].count = &trecvcount;
528 thread_data_array[threadnum].replyctrl = &treplyctrl;
529 thread_data_array[threadnum].replyretry = &treplyretry;
530 thread_data_array[threadnum].rec = record;
531 /* If local do not create any extra connection */
532 if(pile->mid != myIpAddr) { /* Not local */
534 rc = pthread_create(&thread[threadnum], &attr, transRequest, (void *) &thread_data_array[threadnum]);
537 perror("Error in pthread create\n");
538 pthread_cond_destroy(&tcond);
539 pthread_mutex_destroy(&tlock);
542 for (i = 0; i < threadnum; i++)
543 free(thread_data_array[i].buffer);
544 free(thread_data_array);
549 ltdata->tdata = &thread_data_array[threadnum];
550 ltdata->transinfo = &transinfo;
552 val = pthread_create(&thread[threadnum], &attr, handleLocalReq, (void *) ltdata);
555 perror("Error in pthread create\n");
556 pthread_cond_destroy(&tcond);
557 pthread_mutex_destroy(&tlock);
560 for (i = 0; i < threadnum; i++)
561 free(thread_data_array[i].buffer);
562 free(thread_data_array);
572 /* Free attribute and wait for the other threads */
573 pthread_attr_destroy(&attr);
575 for (i = 0; i < threadnum; i++) {
576 rc = pthread_join(thread[i], NULL);
579 printf("Error: return code from pthread_join() is %d\n", rc);
580 pthread_cond_destroy(&tcond);
581 pthread_mutex_destroy(&tlock);
584 for (j = i; j < threadnum; j++) {
585 free(thread_data_array[j].buffer);
589 free(thread_data_array[i].buffer);
593 pthread_cond_destroy(&tcond);
594 pthread_mutex_destroy(&tlock);
599 if(treplyctrl == TRANS_ABORT) {
601 objstrDelete(record->cache);
602 chashDelete(record->lookupTable);
604 free(thread_data_array);
607 } else if(treplyctrl == TRANS_COMMIT) {
609 objstrDelete(record->cache);
610 chashDelete(record->lookupTable);
612 free(thread_data_array);
616 //TODO Add other cases
617 printf("DEBUG-> THIS SHOULD NOT HAPPEN.....EXIT PROGRAM\n");
624 /* This function sends information involved in the transaction request
625 * to participants and accepts a response from particpants.
626 * It calls decideresponse() to decide on what control message
627 * to send next to participants and sends the message using sendResponse()*/
628 void *transRequest(void *threadarg) {
630 struct sockaddr_in serv_addr;
631 thread_data_array_t *tdata;
632 objheader_t *headeraddr;
633 char buffer[RECEIVE_BUFFER_SIZE], control, recvcontrol;
634 char machineip[16], retval;
636 tdata = (thread_data_array_t *) threadarg;
638 /* Send Trans Request */
639 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
640 perror("Error in socket for TRANS_REQUEST\n");
643 bzero((char*) &serv_addr, sizeof(serv_addr));
644 serv_addr.sin_family = AF_INET;
645 serv_addr.sin_port = htons(LISTEN_PORT);
646 midtoIP(tdata->mid,machineip);
647 machineip[15] = '\0';
648 serv_addr.sin_addr.s_addr = inet_addr(machineip);
649 /* Open Connection */
650 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
651 perror("Error in connect for TRANS_REQUEST\n");
656 /* Send bytes of data with TRANS_REQUEST control message */
657 if (send(sd, &(tdata->buffer->f), sizeof(fixed_data_t),MSG_NOSIGNAL) < sizeof(fixed_data_t)) {
658 perror("Error sending fixed bytes for thread\n");
663 /* Send list of machines involved in the transaction */
665 int size=sizeof(unsigned int)*tdata->buffer->f.mcount;
666 if (send(sd, tdata->buffer->listmid, size, MSG_NOSIGNAL) < size) {
667 perror("Error sending list of machines for thread\n");
673 /* Send oids and version number tuples for objects that are read */
675 int size=(sizeof(unsigned int)+sizeof(short))*tdata->buffer->f.numread;
677 if (send(sd, tdata->buffer->objread, size, MSG_NOSIGNAL) < size) {
678 perror("Error sending tuples for thread\n");
684 /* Send objects that are modified */
685 for(i = 0; i < tdata->buffer->f.nummod ; i++) {
687 headeraddr = chashSearch(tdata->rec->lookupTable, tdata->buffer->oidmod[i]);
688 GETSIZE(size,headeraddr);
689 size+=sizeof(objheader_t);
690 if (send(sd, headeraddr, size, MSG_NOSIGNAL) < size) {
691 perror("Error sending obj modified for thread\n");
697 /* Read control message from Participant */
698 if((n = read(sd, &control, sizeof(char))) <= 0) {
699 perror("Error in reading control message from Participant\n");
704 recvcontrol = control;
706 /* Update common data structure and increment count */
707 tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol;
709 /* Lock and update count */
710 /* Thread sleeps until all messages from pariticipants are received by coordinator */
711 pthread_mutex_lock(tdata->lock);
713 (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */
715 /* Wake up the threads and invoke decideResponse (once) */
716 if(*(tdata->count) == tdata->buffer->f.mcount) {
717 decideResponse(tdata);
718 pthread_cond_broadcast(tdata->threshold);
720 pthread_cond_wait(tdata->threshold, tdata->lock);
722 pthread_mutex_unlock(tdata->lock);
724 /* Send the final response such as TRANS_COMMIT or TRANS_ABORT t
725 * to all participants in their respective socket */
726 if (sendResponse(tdata, sd) == 0) {
727 printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__);
733 retval = recv((int)sd, &control, sizeof(char), 0);
734 } while (retval < sizeof(char));
736 if(control == TRANS_UNSUCESSFUL) {
737 //printf("DEBUG-> TRANS_ABORTED\n");
738 } else if(control == TRANS_SUCESSFUL) {
739 //printf("DEBUG-> TRANS_SUCCESSFUL\n");
741 //printf("DEBUG-> Error: Incorrect Transaction End Message %d\n", control);
744 /* Close connection */
749 /* This function decides the reponse that needs to be sent to
750 * all Participant machines after the TRANS_REQUEST protocol */
751 void decideResponse(thread_data_array_t *tdata) {
753 int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
756 for (i = 0 ; i < tdata->buffer->f.mcount; i++) {
757 control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses
758 written onto the shared array */
761 printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
762 /* treat as disagree, pass thru */
771 case TRANS_SOFT_ABORT:
777 if(transdisagree > 0) {
779 *(tdata->replyctrl) = TRANS_ABORT;
780 *(tdata->replyretry) = 0;
781 /* clear objects from prefetch cache */
782 for (i = 0; i < tdata->buffer->f.numread; i++)
783 prehashRemove(*((unsigned int *)(((char *)tdata->buffer->objread) + (sizeof(unsigned int) + sizeof(unsigned short))*i)));
784 for (i = 0; i < tdata->buffer->f.nummod; i++)
785 prehashRemove(tdata->buffer->oidmod[i]);
786 } else if(transagree == tdata->buffer->f.mcount){
788 *(tdata->replyctrl) = TRANS_COMMIT;
789 *(tdata->replyretry) = 0;
791 /* Send Abort in soft abort case followed by retry commiting transaction again*/
792 *(tdata->replyctrl) = TRANS_ABORT;
793 *(tdata->replyretry) = 1;
798 /* This function sends the final response to remote machines per thread in their respective socket id
799 * It returns a char that is only needed to check the correctness of execution of this function inside
801 char sendResponse(thread_data_array_t *tdata, int sd) {
802 int n, N, sum, oidcount = 0, control;
803 char *ptr, retval = 0;
804 unsigned int *oidnotfound;
806 control = *(tdata->replyctrl);
807 if (send(sd, &control, sizeof(char), MSG_NOSIGNAL) < sizeof(char)) {
808 perror("Error sending ctrl message for participant\n");
812 //FIXME read missing objects
813 /* If the decided response is due to a soft abort and missing objects at the Participant's side */
815 if(tdata->recvmsg[tdata->thread_id].rcv_status == TRANS_SOFT_ABORT) {
816 // Read list of objects missing
817 if((read(sd, &oidcount, sizeof(int)) != 0) && (oidcount != 0)) {
818 N = oidcount * sizeof(unsigned int);
819 if((oidnotfound = calloc(oidcount, sizeof(unsigned int))) == NULL) {
820 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
823 ptr = (char *) oidnotfound;
825 n = read(sd, ptr+sum, N-sum);
827 } while(sum < N && n !=0);
829 retval = TRANS_SOFT_ABORT;
833 /* If the decided response is TRANS_ABORT */
834 if(*(tdata->replyctrl) == TRANS_ABORT) {
835 retval = TRANS_ABORT;
836 } else if(*(tdata->replyctrl) == TRANS_COMMIT) { /* If the decided response is TRANS_COMMIT */
837 retval = TRANS_COMMIT;
843 /* This function opens a connection, places an object read request to the
844 * remote machine, reads the control message and object if available and
845 * copies the object and its header to the local cache.
848 void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
850 struct sockaddr_in serv_addr;
857 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
858 perror("Error in socket\n");
862 bzero((char*) &serv_addr, sizeof(serv_addr));
863 serv_addr.sin_family = AF_INET;
864 serv_addr.sin_port = htons(LISTEN_PORT);
865 midtoIP(mnum,machineip);
866 machineip[15] = '\0';
867 serv_addr.sin_addr.s_addr = inet_addr(machineip);
869 /* Open connection */
870 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
871 perror("getRemoteObj() Error in connect\n");
874 char readrequest[sizeof(char)+sizeof(unsigned int)];
875 readrequest[0] = READ_REQUEST;
876 *((unsigned int *)(&readrequest[1])) = oid;
877 if (send(sd, readrequest, sizeof(readrequest), MSG_NOSIGNAL) < sizeof(readrequest)) {
878 perror("Error sending message\n");
882 /* Read response from the Participant */
883 if((val = read(sd, &control, sizeof(char))) <= 0) {
884 perror("No control response for getRemoteObj sent\n");
888 case OBJECT_NOT_FOUND:
891 /* Read object if found into local cache */
892 if((val = read(sd, &size, sizeof(int))) <= 0) {
893 perror("No size is read from the participant\n");
896 objcopy = objstrAlloc(record->cache, size);
897 if((val = read(sd, (char *)objcopy, size)) <= 0) {
898 perror("No objects are read from the remote participant\n");
901 /* Insert into cache's lookup table */
902 chashInsert(record->lookupTable, oid, objcopy);
905 printf("Error in recv request from participant on a READ_REQUEST %s, %d\n",__FILE__, __LINE__);
908 /* Close connection */
913 /* This function handles the local objects involved in a transaction commiting process.
914 * It also makes a decision if this local machine sends AGREE or DISAGREE or SOFT_ABORT to coordinator.
915 * Note Coordinator = local machine
916 * It wakes up the other threads from remote participants that are waiting for the coordinator's decision and
917 * based on common agreement it either commits or aborts the transaction.
918 * It also frees the memory resources */
919 void *handleLocalReq(void *threadarg) {
920 unsigned int *oidnotfound = NULL, *oidlocked = NULL;
921 local_thread_data_array_t *localtdata;
922 int objnotfound = 0, objlocked = 0;
923 int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
926 unsigned short version;
928 objheader_t *headptr;
930 localtdata = (local_thread_data_array_t *) threadarg;
932 /* Counters and arrays to formulate decision on control message to be sent */
933 oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
934 oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
936 numread = localtdata->tdata->buffer->f.numread;
937 /* Process each oid in the machine pile/ group per thread */
938 for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) {
939 if (i < localtdata->tdata->buffer->f.numread) {
940 int incr = sizeof(unsigned int) + sizeof(short);// Offset that points to next position in the objread array
942 oid = *((unsigned int *)(((char *)localtdata->tdata->buffer->objread) + incr));
943 version = *((short *)(((char *)localtdata->tdata->buffer->objread) + incr + sizeof(unsigned int)));
944 } else { // Objects Modified
946 headptr = (objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidmod[i-numread]);
947 if (headptr == NULL) {
948 printf("Error: handleLocalReq() returning NULL %s, %d\n", __FILE__, __LINE__);
952 version = headptr->version;
954 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
956 /* Save the oids not found and number of oids not found for later use */
957 if ((mobj = mhashSearch(oid)) == NULL) { /* Obj not found */
958 /* Save the oids not found and number of oids not found for later use */
959 oidnotfound[objnotfound] = oid;
961 } else { /* If Obj found in machine (i.e. has not moved) */
962 /* Check if Obj is locked by any previous transaction */
963 if ((STATUS((objheader_t *)mobj) & LOCK) == LOCK) {
964 if (version == ((objheader_t *)mobj)->version) { /* If locked then match versions */
966 } else {/* If versions don't match ...HARD ABORT */
968 /* Send TRANS_DISAGREE to Coordinator */
969 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
971 } else {/* If Obj is not locked then lock object */
972 STATUS(((objheader_t *)mobj)) |= LOCK;
973 /* Save all object oids that are locked on this machine during this transaction request call */
974 oidlocked[objlocked] = OID(((objheader_t *)mobj));
976 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
978 } else { /* If versions don't match ...HARD ABORT */
980 /* Send TRANS_DISAGREE to Coordinator */
981 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
986 /* Condition to send TRANS_AGREE */
987 if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
988 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
990 /* Condition to send TRANS_SOFT_ABORT */
991 if((v_matchlock > 0 && v_nomatch == 0) || (objnotfound > 0 && v_nomatch == 0)) {
992 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
995 /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
996 * if Participant receives a TRANS_COMMIT */
997 localtdata->transinfo->objlocked = oidlocked;
998 localtdata->transinfo->objnotfound = oidnotfound;
999 localtdata->transinfo->modptr = NULL;
1000 localtdata->transinfo->numlocked = objlocked;
1001 localtdata->transinfo->numnotfound = objnotfound;
1002 /* Lock and update count */
1003 //Thread sleeps until all messages from pariticipants are received by coordinator
1004 pthread_mutex_lock(localtdata->tdata->lock);
1005 (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */
1007 /* Wake up the threads and invoke decideResponse (once) */
1008 if(*(localtdata->tdata->count) == localtdata->tdata->buffer->f.mcount) {
1009 decideResponse(localtdata->tdata);
1010 pthread_cond_broadcast(localtdata->tdata->threshold);
1012 pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock);
1014 pthread_mutex_unlock(localtdata->tdata->lock);
1015 if(*(localtdata->tdata->replyctrl) == TRANS_ABORT){
1016 if(transAbortProcess(localtdata) != 0) {
1017 printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
1020 } else if(*(localtdata->tdata->replyctrl) == TRANS_COMMIT) {
1021 if(transComProcess(localtdata) != 0) {
1022 printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
1027 if (localtdata->transinfo->objlocked != NULL) {
1028 free(localtdata->transinfo->objlocked);
1030 if (localtdata->transinfo->objnotfound != NULL) {
1031 free(localtdata->transinfo->objnotfound);
1037 /* This function completes the ABORT process if the transaction is aborting */
1038 int transAbortProcess(local_thread_data_array_t *localtdata) {
1040 unsigned int *objlocked;
1043 numlocked = localtdata->transinfo->numlocked;
1044 objlocked = localtdata->transinfo->objlocked;
1046 for (i = 0; i < numlocked; i++) {
1047 if((header = mhashSearch(objlocked[i])) == NULL) {
1048 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1051 STATUS(((objheader_t *)header)) &= ~(LOCK);
1057 /*This function completes the COMMIT process is the transaction is commiting*/
1058 int transComProcess(local_thread_data_array_t *localtdata) {
1059 objheader_t *header, *tcptr;
1060 int i, nummod, tmpsize, numcreated, numlocked;
1061 unsigned int *oidmod, *oidcreated, *oidlocked;
1064 nummod = localtdata->tdata->buffer->f.nummod;
1065 oidmod = localtdata->tdata->buffer->oidmod;
1066 numcreated = localtdata->tdata->buffer->f.numcreated;
1067 oidcreated = localtdata->tdata->buffer->oidcreated;
1068 numlocked = localtdata->transinfo->numlocked;
1069 oidlocked = localtdata->transinfo->objlocked;
1071 for (i = 0; i < nummod; i++) {
1072 if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
1073 printf("Error: transComProcess() mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1076 /* Copy from transaction cache -> main object store */
1077 if ((tcptr = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidmod[i]))) == NULL) {
1078 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1081 GETSIZE(tmpsize, header);
1082 pthread_mutex_lock(&mainobjstore_mutex);
1083 memcpy((char*)header+sizeof(objheader_t), (char *)tcptr+ sizeof(objheader_t), tmpsize);
1084 header->version += 1;
1085 if(header->notifylist != NULL) {
1086 notifyAll(&header->notifylist, OID(header), header->version);
1088 pthread_mutex_unlock(&mainobjstore_mutex);
1090 /* If object is newly created inside transaction then commit it */
1091 for (i = 0; i < numcreated; i++) {
1092 if ((header = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidcreated[i]))) == NULL) {
1093 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1096 GETSIZE(tmpsize, header);
1097 tmpsize += sizeof(objheader_t);
1098 pthread_mutex_lock(&mainobjstore_mutex);
1099 if ((ptrcreate = objstrAlloc(mainobjstore, tmpsize)) == NULL) {
1100 printf("Error: transComProcess() failed objstrAlloc %s, %d\n", __FILE__, __LINE__);
1101 pthread_mutex_unlock(&mainobjstore_mutex);
1104 pthread_mutex_unlock(&mainobjstore_mutex);
1105 memcpy(ptrcreate, header, tmpsize);
1106 mhashInsert(oidcreated[i], ptrcreate);
1107 lhashInsert(oidcreated[i], myIpAddr);
1109 /* Unlock locked objects */
1110 for(i = 0; i < numlocked; i++) {
1111 if((header = (objheader_t *) mhashSearch(oidlocked[i])) == NULL) {
1112 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1115 STATUS(header) &= ~(LOCK);
1121 /* This function checks if the prefetch oids are same and have same offsets
1122 * for case x.a.b and y.a.b where x and y have same oid's
1123 * or if a.b.c is a subset of x.b.c.d*/
1124 /* check for case where the generated request a.y.z or x.y.z.g then
1125 * prefetch needs to be generated for x.y.z.g if oid of a and x are same*/
1126 void checkPrefetchTuples(prefetchqelem_t *node) {
1127 int i,j, count,k, sindex, index;
1129 int ntuples, slength;
1131 short *endoffsets, *arryfields;
1133 /* Check for the case x.y.z and a.b.c are same oids */
1134 ptr = (char *) node;
1135 ntuples = *(GET_NTUPLES(ptr));
1136 oid = GET_PTR_OID(ptr);
1137 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1138 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1140 /* Find offset length for each tuple */
1141 int numoffset[ntuples];
1142 numoffset[0] = endoffsets[0];
1143 for(i = 1; i<ntuples; i++) {
1144 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1146 /* Check for redundant tuples by comparing oids of each tuple */
1147 for(i = 0; i < ntuples; i++) {
1150 for(j = i+1 ; j < ntuples; j++) {
1153 /*If oids of tuples match */
1154 if (oid[i] == oid[j]) {
1155 /* Find the smallest offset length of two tuples*/
1156 if(numoffset[i] > numoffset[j]){
1157 slength = numoffset[j];
1161 slength = numoffset[i];
1165 /* Compare the offset values based on the current indices
1166 * break if they do not match
1167 * if all offset values match then pick the largest tuple*/
1172 k = endoffsets[i-1];
1174 index = endoffsets[j -1];
1175 for(count = 0; count < slength; count ++) {
1176 if (arryfields[k] != arryfields[index]) {
1182 if(slength == count) {
1189 /* This function makes machine piles to be added into the machine pile queue for each prefetch call */
1190 prefetchpile_t *makePreGroups(prefetchqelem_t *node, int *numoffset) {
1192 int ntuples, i, machinenum, count=0;
1194 short *endoffsets, *arryfields, *offset;
1195 prefetchpile_t *head = NULL, *tmp = NULL;
1197 /* Check for the case x.y.z and a.b.c are same oids */
1198 ptr = (char *) node;
1199 ntuples = *(GET_NTUPLES(ptr));
1200 oid = GET_PTR_OID(ptr);
1201 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1202 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1204 if((head = (prefetchpile_t *) calloc(1, sizeof(prefetchpile_t))) == NULL) {
1205 printf("Calloc error: %s %d\n", __FILE__, __LINE__);
1209 /* Check for redundant tuples by comparing oids of each tuple */
1210 for(i = 0; i < ntuples; i++) {
1212 if(head->next != NULL) {
1213 if((tmp = (prefetchpile_t *) calloc(1, sizeof(prefetchpile_t))) == NULL) {
1214 printf("Calloc error: %s %d\n", __FILE__, __LINE__);
1217 tmp->mid = myIpAddr;
1221 head->mid = myIpAddr;
1225 /* For each tuple make piles */
1226 if ((machinenum = lhashSearch(oid[i])) == 0) {
1227 printf("Error: No such Machine %s, %d\n", __FILE__, __LINE__);
1230 /* Insert into machine pile */
1232 offset = &arryfields[0];
1234 offset = &arryfields[endoffsets[i-1]];
1237 if((head = insertPile(machinenum, oid[i], numoffset[i], offset, head)) == NULL){
1238 printf("Error: Couldn't create a pile %s, %d\n", __FILE__, __LINE__);
1246 prefetchpile_t *foundLocal(prefetchqelem_t *node) {
1247 int ntuples,i, j, k, oidnfound = 0, arryfieldindex,nextarryfieldindex, flag = 0, val;
1249 unsigned int objoid;
1252 objheader_t *objheader;
1253 short *endoffsets, *arryfields;
1254 prefetchpile_t *head = NULL;
1256 ptr = (char *) node;
1257 ntuples = *(GET_NTUPLES(ptr));
1258 oid = GET_PTR_OID(ptr);
1259 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1260 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1262 /* Find offset length for each tuple */
1263 int numoffset[ntuples];//Number of offsets for each tuple
1264 numoffset[0] = endoffsets[0];
1265 for(i = 1; i<ntuples; i++) {
1266 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1268 for(i = 0; i < ntuples; i++) {
1272 nextarryfieldindex = endoffsets[0];
1274 arryfieldindex = endoffsets[i-1];
1275 nextarryfieldindex = endoffsets[i];
1278 endoffsets[0] = val = numoffset[0];
1279 for(k = 1; k < ntuples; k++) {
1280 val = val + numoffset[k];
1281 endoffsets[k] = val;
1284 for(k = 0; k<endoffsets[ntuples-1]; k++) {
1285 arryfields[arryfieldindex+k] = arryfields[nextarryfieldindex+k];
1289 /* If object found locally */
1290 if((objheader = (objheader_t*) mhashSearch(oid[i])) != NULL) {
1291 tmp = (char *) objheader;
1292 int orgnumoffset = numoffset[i];
1296 arryfieldindex = endoffsets[i-1];
1299 for(j = 0; j<orgnumoffset; j++) {
1300 /* Check for arrays */
1301 if(TYPE(objheader) > NUMCLASSES) {
1305 int elementsize = classsize[TYPE(objheader)];
1306 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*arryfields[arryfieldindex])));
1308 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + arryfields[arryfieldindex]));
1310 //Update numoffset array
1311 numoffset[i] = numoffset[i] - 1;
1314 //Update endoffset array
1315 endoffsets[0] = val = numoffset[0];
1316 for(k = 1; k < ntuples; k++) {
1317 val = val + numoffset[k];
1318 endoffsets[k] = val;
1320 //Update arrayfields array
1321 for(k = 0; k < endoffsets[ntuples-1]; k++) {
1322 arryfields[arryfieldindex+k] = arryfields[arryfieldindex+k+1];
1324 if((objheader = (objheader_t*) mhashSearch(oid[i])) == NULL) {
1326 checkPreCache(node, numoffset, oid[i], i);
1329 tmp = (char *) objheader;
1332 /*If all offset oids are found locally,make the prefetch tuple invalid */
1337 /* Look in Prefetch cache */
1338 checkPreCache(node, numoffset, oid[i],i);
1342 /* Make machine groups */
1343 if((head = makePreGroups(node, numoffset)) == NULL) {
1344 printf("Error in makePreGroups() %s %d\n", __FILE__, __LINE__);
1351 void checkPreCache(prefetchqelem_t *node, int *numoffset, unsigned int objoid, int index) {
1353 int ntuples, i, k, flag=0, isArray =0, arryfieldindex, val;
1355 short *endoffsets, *arryfields;
1356 objheader_t *header;
1358 ptr = (char *) node;
1359 ntuples = *(GET_NTUPLES(ptr));
1360 oid = GET_PTR_OID(ptr);
1361 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1362 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1364 if((header = (objheader_t *) prehashSearch(objoid)) == NULL) {
1366 } else { //Found in Prefetch Cache
1367 //TODO Decide if object is too old, if old remove from cache
1368 tmp = (char *) header;
1369 int loopcount = numoffset[index];
1373 arryfieldindex = endoffsets[(index - 1)];
1374 // Check if any of the offset oid is available in the Prefetch cache
1375 for(i = 0; i < loopcount; i++) {
1376 /* Check for arrays */
1377 if(TYPE(header) > NUMCLASSES) {
1381 int elementsize = classsize[TYPE(header)];
1382 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*arryfields[arryfieldindex])));
1384 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + arryfields[arryfieldindex]));
1386 //Update numoffset array
1387 numoffset[index] = numoffset[index] - 1;
1389 oid[index] = objoid;
1390 //Update endoffset array
1391 endoffsets[0] = val = numoffset[0];
1392 for(k = 1; k < ntuples; k++) {
1393 val = val + numoffset[k];
1394 endoffsets[k] = val;
1396 //Update arrayfields array
1397 for(k = 0; k < endoffsets[ntuples-1]; k++) {
1398 arryfields[arryfieldindex+k] = arryfields[arryfieldindex+k+1];
1400 if((header = (objheader_t *)prehashSearch(oid[index])) != NULL) {
1401 tmp = (char *) header;
1409 //Found in the prefetch cache
1410 if(flag == 0 && (numoffset[index] == 0)) {
1417 /* This function is called by the thread calling transPrefetch */
1418 void *transPrefetch(void *t) {
1419 prefetchqelem_t *qnode;
1420 prefetchpile_t *pilehead = NULL;
1421 prefetchpile_t *ptr = NULL, *piletail = NULL;
1424 /* lock mutex of primary prefetch queue */
1425 pthread_mutex_lock(&pqueue.qlock);
1426 /* while primary queue is empty, then wait */
1427 while((pqueue.front == NULL) && (pqueue.rear == NULL)) {
1428 pthread_cond_wait(&pqueue.qcond, &pqueue.qlock);
1431 /* dequeue node to create a machine piles and finally unlock mutex */
1432 if((qnode = pre_dequeue()) == NULL) {
1433 printf("Error: No node returned %s, %d\n", __FILE__, __LINE__);
1434 pthread_mutex_unlock(&pqueue.qlock);
1437 pthread_mutex_unlock(&pqueue.qlock);
1439 /* Reduce redundant prefetch requests */
1440 checkPrefetchTuples(qnode);
1441 /* Check if the tuples are found locally, if yes then reduce them further*/
1442 /* and group requests by remote machine ids by calling the makePreGroups() */
1443 if((pilehead = foundLocal(qnode)) == NULL) {
1444 printf("Error: No node created for serving prefetch request %s %d\n", __FILE__, __LINE__);
1450 while(ptr != NULL) {
1451 if(ptr->next == NULL) {
1457 /* Lock mutex of pool queue */
1458 pthread_mutex_lock(&mcqueue.qlock);
1459 /* Update the pool queue with the new remote machine piles generated per prefetch call */
1460 mcpileenqueue(pilehead, piletail);
1461 /* Broadcast signal on machine pile queue */
1462 pthread_cond_broadcast(&mcqueue.qcond);
1463 /* Unlock mutex of machine pile queue */
1464 pthread_mutex_unlock(&mcqueue.qlock);
1465 /* Deallocate the prefetch queue pile node */
1470 /* Each thread in the pool of threads calls this function to establish connection with
1471 * remote machines, send the prefetch requests and process the reponses from
1472 * the remote machines .
1473 * The thread is active throughout the period of runtime */
1475 void *mcqProcess(void *threadid) {
1477 prefetchpile_t *mcpilenode;
1479 tid = (int) threadid;
1481 /* Lock mutex of mc pile queue */
1482 pthread_mutex_lock(&mcqueue.qlock);
1483 /* When mc pile queue is empty, wait */
1484 while((mcqueue.front == NULL) && (mcqueue.rear == NULL)) {
1485 pthread_cond_wait(&mcqueue.qcond, &mcqueue.qlock);
1487 /* Dequeue node to send remote machine connections*/
1488 if((mcpilenode = mcpiledequeue()) == NULL) {
1489 printf("Dequeue Error: No node returned %s %d\n", __FILE__, __LINE__);
1490 pthread_mutex_unlock(&mcqueue.qlock);
1494 pthread_mutex_unlock(&mcqueue.qlock);
1496 /*Initiate connection to remote host and send request */
1497 /* Process Request */
1498 if(mcpilenode->mid != myIpAddr) {
1499 sendPrefetchReq(mcpilenode);
1502 /* Deallocate the machine queue pile node */
1503 mcdealloc(mcpilenode);
1507 void sendPrefetchReq(prefetchpile_t *mcpilenode) {
1508 int sd, i, off, len, endpair, count = 0;
1509 struct sockaddr_in remoteAddr;
1510 char machineip[16], control;
1514 /* Send Trans Prefetch Request */
1515 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
1516 perror("Error in socket for SEND_PREFETCH_REQUEST\n");
1520 mid = mcpilenode->mid;
1522 bzero(&remoteAddr, sizeof(remoteAddr));
1523 remoteAddr.sin_family = AF_INET;
1524 remoteAddr.sin_port = htons(LISTEN_PORT);
1525 remoteAddr.sin_addr.s_addr = htonl(mid);
1527 /* Open Connection */
1528 if (connect(sd, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0) {
1529 printf("%s():error %d connecting to %s:%d\n", __func__, errno,
1530 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1535 /* Send TRANS_PREFETCH control message */
1536 control = TRANS_PREFETCH;
1537 if(send(sd, &control, sizeof(char), MSG_NOSIGNAL) < sizeof(char)) {
1538 perror("Error in sending prefetch control\n");
1543 /* Send Oids and offsets in pairs */
1544 tmp = mcpilenode->objpiles;
1545 while(tmp != NULL) {
1547 count++; /* Keeps track of the number of oid and offset tuples sent per remote machine */
1548 len = sizeof(int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(unsigned short));
1549 char oidnoffset[len];
1550 bzero(oidnoffset, len);
1551 *((unsigned int*)oidnoffset) = len;
1553 *((unsigned int *)((char *)oidnoffset + off)) = tmp->oid;
1554 off += sizeof(unsigned int);
1555 for(i = 0; i < tmp->numoffset; i++) {
1556 *((unsigned short*)((char *)oidnoffset + off)) = tmp->offset[i];
1557 off+=sizeof(unsigned short);
1560 if (send(sd, oidnoffset, len , MSG_NOSIGNAL) < len) {
1561 perror("Error sending fixed bytes for thread\n");
1569 /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
1571 if (send(sd, &endpair, sizeof(int), MSG_NOSIGNAL) < sizeof(int)) {
1572 perror("Error sending fixed bytes for thread\n");
1577 /* Get Response from the remote machine */
1578 getPrefetchResponse(count,sd);
1583 void getPrefetchResponse(int count, int sd) {
1584 int i = 0, val, n, N, sum, index, objsize;
1585 unsigned int bufsize,oid;
1589 void *modptr, *oldptr;
1591 /* Read prefetch response from the Remote machine */
1592 if((val = read(sd, &control, sizeof(char))) <= 0) {
1593 perror("No control response for Prefetch request sent\n");
1597 if(control == TRANS_PREFETCH_RESPONSE) {
1598 /*For each oid and offset tuple sent as prefetch request to remote machine*/
1599 while(N = recv((int)sd, &bufsize, sizeof(unsigned int), 0) != 0) {
1600 if((buffer = calloc(1, bufsize)) == NULL) {
1601 printf("Calloc Error in %s() at %s, %d\n", __func__, __FILE__, __LINE__);
1607 /* Keep receiving the buffer containing oid info */
1609 n = recv((int)sd, (void *)ptr+sum, bufsize-sum, 0);
1611 } while(sum < bufsize && n != 0);
1613 /* Decode the contents of the buffer */
1614 while(index < bufsize ) {
1615 if(buffer[index] == OBJECT_FOUND) {
1616 /* Increment it to get the object */
1617 index += sizeof(char);
1618 oid = *((unsigned int *)(buffer+index));
1619 index += sizeof(unsigned int);
1620 /* For each object found add to Prefetch Cache */
1621 objsize = *((int *)(buffer+index));
1622 index += sizeof(int);
1623 pthread_mutex_lock(&prefetchcache_mutex);
1624 if ((modptr = objstrAlloc(prefetchcache, objsize)) == NULL) {
1625 printf("Error: objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
1626 pthread_mutex_unlock(&prefetchcache_mutex);
1630 pthread_mutex_unlock(&prefetchcache_mutex);
1631 memcpy(modptr, buffer+index, objsize);
1633 /* Insert the oid and its address into the prefetch hash lookup table */
1634 /* Do a version comparison if the oid exists */
1635 if((oldptr = prehashSearch(oid)) != NULL) {
1636 /* If older version then update with new object ptr */
1637 if(((objheader_t *)oldptr)->version < ((objheader_t *)modptr)->version) {
1639 prehashInsert(oid, modptr);
1640 } else if(((objheader_t *)oldptr)->version == ((objheader_t *)modptr)->version) {
1641 /* Add the new object ptr to hash table */
1643 prehashInsert(oid, modptr);
1644 } else { /* Do nothing: TODO modptr should be reference counted */
1647 } else {/*If doesn't no match found in hashtable, add the object ptr to hash table*/
1648 prehashInsert(oid, modptr);
1650 /* Lock the Prefetch Cache look up table*/
1651 pthread_mutex_lock(&pflookup.lock);
1652 /* Broadcast signal on prefetch cache condition variable */
1653 pthread_cond_broadcast(&pflookup.cond);
1654 /* Unlock the Prefetch Cache look up table*/
1655 pthread_mutex_unlock(&pflookup.lock);
1656 } else if(buffer[index] == OBJECT_NOT_FOUND) {
1657 /* Increment it to get the object */
1658 /* TODO: For each object not found query DHT for new location and retrieve the object */
1659 index += sizeof(char);
1660 oid = *((unsigned int *)(buffer + index));
1661 index += sizeof(unsigned int);
1662 /* Throw an error */
1663 printf("OBJECT NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n");
1666 printf("Error in decoding the index value %d, %s, %d\n",index, __FILE__, __LINE__);
1674 printf("Error in receving response for prefetch request %s, %d\n",__FILE__, __LINE__);
1678 unsigned short getObjType(unsigned int oid)
1680 objheader_t *objheader;
1681 unsigned short numoffset[] ={0};
1682 short fieldoffset[] ={};
1684 if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL)
1686 if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1688 prefetch(1, &oid, numoffset, fieldoffset);
1689 pthread_mutex_lock(&pflookup.lock);
1690 while ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1692 pthread_cond_wait(&pflookup.cond, &pflookup.lock);
1694 pthread_mutex_unlock(&pflookup.lock);
1698 return TYPE(objheader);
1701 int startRemoteThread(unsigned int oid, unsigned int mid)
1704 struct sockaddr_in remoteAddr;
1705 char msg[1 + sizeof(unsigned int)];
1709 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
1711 perror("startRemoteThread():socket()");
1715 bzero(&remoteAddr, sizeof(remoteAddr));
1716 remoteAddr.sin_family = AF_INET;
1717 remoteAddr.sin_port = htons(LISTEN_PORT);
1718 remoteAddr.sin_addr.s_addr = htonl(mid);
1720 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0)
1722 printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
1723 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1728 msg[0] = START_REMOTE_THREAD;
1729 memcpy(&msg[1], &oid, sizeof(unsigned int));
1731 bytesSent = send(sock, msg, 1 + sizeof(unsigned int), 0);
1734 perror("startRemoteThread():send()");
1737 else if (bytesSent != 1 + sizeof(unsigned int))
1739 printf("startRemoteThread(): error, sent %d bytes\n", bytesSent);
1752 //TODO: when reusing oids, make sure they are not already in use!
1753 unsigned int getNewOID(void) {
1754 static unsigned int id = 0xFFFFFFFF;
1757 if (id > oidMax || id < oidMin)
1764 int processConfigFile()
1767 const int maxLineLength = 200;
1768 char lineBuffer[maxLineLength];
1770 const char *delimiters = " \t\n";
1774 configFile = fopen(CONFIG_FILENAME, "r");
1775 if (configFile == NULL)
1777 printf("error opening %s:\n", CONFIG_FILENAME);
1782 numHostsInSystem = 0;
1783 sizeOfHostArray = 8;
1784 hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
1786 while(fgets(lineBuffer, maxLineLength, configFile) != NULL)
1788 commentBegin = strchr(lineBuffer, '#');
1789 if (commentBegin != NULL)
1790 *commentBegin = '\0';
1791 token = strtok(lineBuffer, delimiters);
1792 while (token != NULL)
1794 tmpAddr = inet_addr(token);
1795 if ((int)tmpAddr == -1)
1797 printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
1802 addHost(htonl(tmpAddr));
1803 token = strtok(NULL, delimiters);
1809 if (numHostsInSystem < 1)
1811 printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
1815 myIpAddr = getMyIpAddr("en1");
1817 myIpAddr = getMyIpAddr("eth0");
1819 myIndexInHostArray = findHost(myIpAddr);
1820 if (myIndexInHostArray == -1)
1822 printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
1825 oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
1826 oidMin = oidsPerBlock * myIndexInHostArray;
1827 if (myIndexInHostArray == numHostsInSystem - 1)
1828 oidMax = 0xFFFFFFFF;
1830 oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
1835 void addHost(unsigned int hostIp)
1837 unsigned int *tmpArray;
1839 if (findHost(hostIp) != -1)
1842 if (numHostsInSystem == sizeOfHostArray)
1844 tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
1845 memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
1847 hostIpAddrs = tmpArray;
1850 hostIpAddrs[numHostsInSystem++] = hostIp;
1855 int findHost(unsigned int hostIp)
1858 for (i = 0; i < numHostsInSystem; i++)
1859 if (hostIpAddrs[i] == hostIp)
1866 /* This function sends notification request per thread waiting on object(s) whose version
1868 int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int numoid) {
1870 objheader_t *objheader;
1871 struct sockaddr_in remoteAddr;
1872 char msg[1 + numoid * (sizeof(short) + sizeof(unsigned int)) + 3 * sizeof(unsigned int)];
1876 unsigned short version;
1877 unsigned int oid,mid;
1878 static unsigned int threadid = 0;
1879 pthread_mutex_t threadnotify = PTHREAD_MUTEX_INITIALIZER; //Lock and condition var for threadjoin and notification
1880 pthread_cond_t threadcond = PTHREAD_COND_INITIALIZER;
1881 notifydata_t *ndata;
1883 //FIXME currently all oids belong to one machine
1885 if((mid = lhashSearch(oid)) == 0) {
1886 printf("Error: %s() No such machine found for oid =%x\n",__func__, oid);
1890 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1891 perror("reqNotify():socket()");
1895 bzero(&remoteAddr, sizeof(remoteAddr));
1896 remoteAddr.sin_family = AF_INET;
1897 remoteAddr.sin_port = htons(LISTEN_PORT);
1898 remoteAddr.sin_addr.s_addr = htonl(mid);
1900 /* Generate unique threadid */
1903 /* Save threadid, numoid, oidarray, versionarray, pthread_cond_variable for later processing */
1904 if((ndata = calloc(1, sizeof(notifydata_t))) == NULL) {
1905 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
1908 ndata->numoid = numoid;
1909 ndata->threadid = threadid;
1910 ndata->oidarry = oidarry;
1911 ndata->versionarry = versionarry;
1912 ndata->threadcond = threadcond;
1913 ndata->threadnotify = threadnotify;
1914 if((status = notifyhashInsert(threadid, ndata)) != 0) {
1915 printf("reqNotify(): Insert into notify hash table not successful %s, %d\n", __FILE__, __LINE__);
1920 /* Send number of oids, oidarry, version array, machine id and threadid */
1921 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1922 printf("reqNotify():error %d connecting to %s:%d\n", errno,
1923 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1927 msg[0] = THREAD_NOTIFY_REQUEST;
1928 *((unsigned int *)(&msg[1])) = numoid;
1929 /* Send array of oids */
1930 size = sizeof(unsigned int);
1935 *((unsigned int *)(&msg[1] + size)) = oid;
1936 size += sizeof(unsigned int);
1941 /* Send array of version */
1945 version = versionarry[i];
1946 *((unsigned short *)(&msg[1] + size)) = version;
1947 size += sizeof(unsigned short);
1952 *((unsigned int *)(&msg[1] + size)) = myIpAddr;
1953 size += sizeof(unsigned int);
1954 *((unsigned int *)(&msg[1] + size)) = threadid;
1956 pthread_mutex_lock(&(ndata->threadnotify));
1957 bytesSent = send(sock, msg, 1 + numoid * (sizeof(unsigned int) + sizeof(unsigned short)) + 3 * sizeof(unsigned int) , 0);
1959 perror("reqNotify():send()");
1961 } else if (bytesSent != 1 + numoid*(sizeof(unsigned int) + sizeof(unsigned short)) + 3 * sizeof(unsigned int)){
1962 printf("reNotify(): error, sent %d bytes %s, %d\n", bytesSent, __FILE__, __LINE__);
1968 pthread_cond_wait(&(ndata->threadcond), &(ndata->threadnotify));
1969 pthread_mutex_unlock(&(ndata->threadnotify));
1972 pthread_cond_destroy(&threadcond);
1973 pthread_mutex_destroy(&threadnotify);
1979 void threadNotify(unsigned int oid, unsigned short version, unsigned int tid) {
1980 notifydata_t *ndata;
1981 int i, objIsFound = 0, index;
1984 //Look up the tid and call the corresponding pthread_cond_signal
1985 if((ndata = notifyhashSearch(tid)) == NULL) {
1986 printf("threadnotify(): No such threadid is present %s, %d\n", __FILE__, __LINE__);
1989 for(i = 0; i < ndata->numoid; i++) {
1990 if(ndata->oidarry[i] == oid){
1995 if(objIsFound == 0){
1996 printf("threadNotify(): Oid not found %s, %d\n", __FILE__, __LINE__);
1999 if(version <= ndata->versionarry[index]){
2000 printf("threadNotify(): New version %d has not changed since last version %s, %d\n", version, __FILE__, __LINE__);
2003 /* Clear from prefetch cache and free thread related data structure */
2004 if((ptr = prehashSearch(oid)) != NULL) {
2007 pthread_cond_signal(&(ndata->threadcond));
2014 int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) {
2017 struct sockaddr_in remoteAddr;
2018 char msg[1 + sizeof(unsigned short) + 2*sizeof(unsigned int)];
2019 int sock, status, size, bytesSent;
2021 while(*head != NULL) {
2024 //create a socket connection to that machine
2025 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
2026 perror("notifyAll():socket()");
2030 bzero(&remoteAddr, sizeof(remoteAddr));
2031 remoteAddr.sin_family = AF_INET;
2032 remoteAddr.sin_port = htons(LISTEN_PORT);
2033 remoteAddr.sin_addr.s_addr = htonl(mid);
2034 //send Thread Notify response and threadid to that machine
2035 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
2036 printf("notifyAll():error %d connecting to %s:%d\n", errno,
2037 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
2040 bzero(msg, (1+sizeof(unsigned short) + 2*sizeof(unsigned int)));
2041 msg[0] = THREAD_NOTIFY_RESPONSE;
2042 *((unsigned int *)&msg[1]) = oid;
2043 size = sizeof(unsigned int);
2044 *((unsigned short *)(&msg[1]+ size)) = version;
2045 size+= sizeof(unsigned short);
2046 *((unsigned int *)(&msg[1]+ size)) = ptr->threadid;
2048 bytesSent = send(sock, msg, (1 + 2*sizeof(unsigned int) + sizeof(unsigned short)), 0);
2050 perror("notifyAll():send()");
2052 } else if (bytesSent != 1 + 2*sizeof(unsigned int) + sizeof(unsigned short)){
2053 printf("notifyAll(): error, sent %d bytes %s, %d\n",
2054 bytesSent, __FILE__, __LINE__);
2069 void transAbort(transrecord_t *trans) {
2070 objstrDelete(trans->cache);
2071 chashDelete(trans->lookupTable);