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 machinenumber = lhashSearch(oid);
337 objcopy = getRemoteObj(record, machinenumber, oid);
338 if(objcopy == NULL) {
339 printf("Error: Object not found in Remote location %s, %d\n", __FILE__, __LINE__);
351 /* This function creates objects in the transaction record */
352 objheader_t *transCreateObj(transrecord_t *record, unsigned int size)
354 objheader_t *tmp = (objheader_t *) objstrAlloc(record->cache, (sizeof(objheader_t) + size));
355 tmp->notifylist = NULL;
356 OID(tmp) = getNewOID();
360 chashInsert(record->lookupTable, OID(tmp), tmp);
363 return &tmp[1]; //want space after object header
369 /* This function creates machine piles based on all machines involved in a
370 * transaction commit request */
371 plistnode_t *createPiles(transrecord_t *record) {
373 unsigned int size;/* Represents number of bins in the chash table */
374 chashlistnode_t *curr, *ptr, *next;
375 plistnode_t *pile = NULL;
376 unsigned int machinenum;
377 void *localmachinenum;
378 objheader_t *headeraddr;
380 ptr = record->lookupTable->table;
381 size = record->lookupTable->size;
383 for(i = 0; i < size ; i++) {
385 /* Inner loop to traverse the linked list of the cache lookupTable */
386 while(curr != NULL) {
387 //if the first bin in hash table is empty
393 if ((headeraddr = chashSearch(record->lookupTable, curr->key)) == NULL) {
394 printf("Error: No such oid %s, %d\n", __FILE__, __LINE__);
398 //Get machine location for object id (and whether local or not)
399 if (STATUS(headeraddr) & NEW || (mhashSearch(curr->key) != NULL)) {
400 machinenum = myIpAddr;
401 } else if ((machinenum = lhashSearch(curr->key)) == 0) {
402 printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
406 //Make machine groups
407 if ((pile = pInsert(pile, headeraddr, machinenum, record->lookupTable->numelements)) == NULL) {
408 printf("pInsert error %s, %d\n", __FILE__, __LINE__);
418 /* This function initiates the transaction commit process
419 * Spawns threads for each of the new connections with Participants
420 * and creates new piles by calling the createPiles(),
421 * Sends a transrequest() to each remote machines for objects found remotely
422 * and calls handleLocalReq() to process objects found locally */
423 int transCommit(transrecord_t *record) {
424 unsigned int tot_bytes_mod, *listmid;
425 plistnode_t *pile, *pile_ptr;
427 int pilecount, offset, threadnum = 0, trecvcount = 0;
428 char buffer[RECEIVE_BUFFER_SIZE],control;
429 char transid[TID_LEN];
430 trans_req_data_t *tosend;
431 trans_commit_data_t transinfo;
432 static int newtid = 0;
433 char treplyctrl = 0, treplyretry = 0; /* keeps track of the common response that needs to be sent */
438 /* Look through all the objects in the transaction record and make piles
439 * for each machine involved in the transaction*/
440 pile_ptr = pile = createPiles(record);
442 /* Create the packet to be sent in TRANS_REQUEST */
444 /* Count the number of participants */
445 pilecount = pCount(pile);
447 /* Create a list of machine ids(Participants) involved in transaction */
448 if((listmid = calloc(pilecount, sizeof(unsigned int))) == NULL) {
449 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
452 pListMid(pile, listmid);
455 /* Initialize thread variables,
456 * Spawn a thread for each Participant involved in a transaction */
457 pthread_t thread[pilecount];
459 pthread_cond_t tcond;
460 pthread_mutex_t tlock;
461 pthread_mutex_t tlshrd;
463 thread_data_array_t *thread_data_array;
464 if((thread_data_array = (thread_data_array_t *) calloc(pilecount, sizeof(thread_data_array_t))) == NULL) {
465 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
466 pthread_cond_destroy(&tcond);
467 pthread_mutex_destroy(&tlock);
473 local_thread_data_array_t *ltdata;
474 if((ltdata = calloc(1, sizeof(local_thread_data_array_t))) == NULL) {
475 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
476 pthread_cond_destroy(&tcond);
477 pthread_mutex_destroy(&tlock);
480 free(thread_data_array);
484 thread_response_t rcvd_control_msg[pilecount]; /* Shared thread array that keeps track of responses of participants */
486 /* Initialize and set thread detach attribute */
487 pthread_attr_init(&attr);
488 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
489 pthread_mutex_init(&tlock, NULL);
490 pthread_cond_init(&tcond, NULL);
492 /* Process each machine pile */
493 while(pile != NULL) {
494 //Create transaction id
496 if ((tosend = calloc(1, sizeof(trans_req_data_t))) == NULL) {
497 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
498 pthread_cond_destroy(&tcond);
499 pthread_mutex_destroy(&tlock);
502 free(thread_data_array);
506 tosend->f.control = TRANS_REQUEST;
507 sprintf(tosend->f.trans_id, "%x_%d", pile->mid, newtid);
508 tosend->f.mcount = pilecount;
509 tosend->f.numread = pile->numread;
510 tosend->f.nummod = pile->nummod;
511 tosend->f.numcreated = pile->numcreated;
512 tosend->f.sum_bytes = pile->sum_bytes;
513 tosend->listmid = listmid;
514 tosend->objread = pile->objread;
515 tosend->oidmod = pile->oidmod;
516 tosend->oidcreated = pile->oidcreated;
517 thread_data_array[threadnum].thread_id = threadnum;
518 thread_data_array[threadnum].mid = pile->mid;
519 thread_data_array[threadnum].buffer = tosend;
520 thread_data_array[threadnum].recvmsg = rcvd_control_msg;
521 thread_data_array[threadnum].threshold = &tcond;
522 thread_data_array[threadnum].lock = &tlock;
523 thread_data_array[threadnum].count = &trecvcount;
524 thread_data_array[threadnum].replyctrl = &treplyctrl;
525 thread_data_array[threadnum].replyretry = &treplyretry;
526 thread_data_array[threadnum].rec = record;
527 /* If local do not create any extra connection */
528 if(pile->mid != myIpAddr) { /* Not local */
530 rc = pthread_create(&thread[threadnum], &attr, transRequest, (void *) &thread_data_array[threadnum]);
533 perror("Error in pthread create\n");
534 pthread_cond_destroy(&tcond);
535 pthread_mutex_destroy(&tlock);
538 for (i = 0; i < threadnum; i++)
539 free(thread_data_array[i].buffer);
540 free(thread_data_array);
545 ltdata->tdata = &thread_data_array[threadnum];
546 ltdata->transinfo = &transinfo;
548 val = pthread_create(&thread[threadnum], &attr, handleLocalReq, (void *) ltdata);
551 perror("Error in pthread create\n");
552 pthread_cond_destroy(&tcond);
553 pthread_mutex_destroy(&tlock);
556 for (i = 0; i < threadnum; i++)
557 free(thread_data_array[i].buffer);
558 free(thread_data_array);
568 /* Free attribute and wait for the other threads */
569 pthread_attr_destroy(&attr);
571 for (i = 0; i < threadnum; i++) {
572 rc = pthread_join(thread[i], NULL);
575 printf("Error: return code from pthread_join() is %d\n", rc);
576 pthread_cond_destroy(&tcond);
577 pthread_mutex_destroy(&tlock);
580 for (j = i; j < threadnum; j++) {
581 free(thread_data_array[j].buffer);
585 free(thread_data_array[i].buffer);
589 pthread_cond_destroy(&tcond);
590 pthread_mutex_destroy(&tlock);
595 if(treplyctrl == TRANS_ABORT) {
597 objstrDelete(record->cache);
598 chashDelete(record->lookupTable);
600 free(thread_data_array);
603 } else if(treplyctrl == TRANS_COMMIT) {
605 objstrDelete(record->cache);
606 chashDelete(record->lookupTable);
608 free(thread_data_array);
612 //TODO Add other cases
613 printf("DEBUG-> THIS SHOULD NOT HAPPEN.....EXIT PROGRAM\n");
620 /* This function sends information involved in the transaction request
621 * to participants and accepts a response from particpants.
622 * It calls decideresponse() to decide on what control message
623 * to send next to participants and sends the message using sendResponse()*/
624 void *transRequest(void *threadarg) {
626 struct sockaddr_in serv_addr;
627 thread_data_array_t *tdata;
628 objheader_t *headeraddr;
629 char buffer[RECEIVE_BUFFER_SIZE], control, recvcontrol;
630 char machineip[16], retval;
633 tdata = (thread_data_array_t *) threadarg;
635 /* Send Trans Request */
636 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
637 perror("Error in socket for TRANS_REQUEST\n");
640 bzero((char*) &serv_addr, sizeof(serv_addr));
641 serv_addr.sin_family = AF_INET;
642 serv_addr.sin_port = htons(LISTEN_PORT);
643 midtoIP(tdata->mid,machineip);
644 machineip[15] = '\0';
645 serv_addr.sin_addr.s_addr = inet_addr(machineip);
646 /* Open Connection */
647 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
648 perror("Error in connect for TRANS_REQUEST\n");
653 /* Send bytes of data with TRANS_REQUEST control message */
654 if (send(sd, &(tdata->buffer->f), sizeof(fixed_data_t),MSG_NOSIGNAL) < sizeof(fixed_data_t)) {
655 perror("Error sending fixed bytes for thread\n");
659 /* Send list of machines involved in the transaction */
661 int size=sizeof(unsigned int)*tdata->buffer->f.mcount;
662 if (send(sd, tdata->buffer->listmid, size, MSG_NOSIGNAL) < size) {
663 perror("Error sending list of machines for thread\n");
668 /* Send oids and version number tuples for objects that are read */
670 int size=(sizeof(unsigned int)+sizeof(short))*tdata->buffer->f.numread;
671 if (send(sd, tdata->buffer->objread, size, MSG_NOSIGNAL) < size) {
672 perror("Error sending tuples for thread\n");
677 /* Send objects that are modified */
678 for(i = 0; i < tdata->buffer->f.nummod ; i++) {
680 headeraddr = chashSearch(tdata->rec->lookupTable, tdata->buffer->oidmod[i]);
681 GETSIZE(size,headeraddr);
682 size+=sizeof(objheader_t);
683 if (send(sd, headeraddr, size, MSG_NOSIGNAL) < size) {
684 perror("Error sending obj modified for thread\n");
690 /* Read control message from Participant */
691 if((n = read(sd, &control, sizeof(char))) <= 0) {
692 perror("Error in reading control message from Participant\n");
697 recvcontrol = control;
699 /* Update common data structure and increment count */
700 tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol;
702 /* Lock and update count */
703 /* Thread sleeps until all messages from pariticipants are received by coordinator */
704 pthread_mutex_lock(tdata->lock);
706 (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */
708 /* Wake up the threads and invoke decideResponse (once) */
709 if(*(tdata->count) == tdata->buffer->f.mcount) {
710 decideResponse(tdata);
711 pthread_cond_broadcast(tdata->threshold);
713 pthread_cond_wait(tdata->threshold, tdata->lock);
715 pthread_mutex_unlock(tdata->lock);
717 /* Send the final response such as TRANS_COMMIT or TRANS_ABORT t
718 * to all participants in their respective socket */
719 if (sendResponse(tdata, sd) == 0) {
720 printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__);
726 retval = recv((int)sd, &control, sizeof(char), 0);
727 } while (retval < sizeof(char));
729 if(control == TRANS_UNSUCESSFUL) {
730 //printf("DEBUG-> TRANS_ABORTED\n");
731 } else if(control == TRANS_SUCESSFUL) {
732 //printf("DEBUG-> TRANS_SUCCESSFUL\n");
734 //printf("DEBUG-> Error: Incorrect Transaction End Message %d\n", control);
737 /* Close connection */
742 /* This function decides the reponse that needs to be sent to
743 * all Participant machines after the TRANS_REQUEST protocol */
744 void decideResponse(thread_data_array_t *tdata) {
746 int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
749 for (i = 0 ; i < tdata->buffer->f.mcount; i++) {
750 control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses
751 written onto the shared array */
754 printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
755 /* treat as disagree, pass thru */
764 case TRANS_SOFT_ABORT:
770 if(transdisagree > 0) {
772 *(tdata->replyctrl) = TRANS_ABORT;
773 *(tdata->replyretry) = 0;
774 /* clear objects from prefetch cache */
775 for (i = 0; i < tdata->buffer->f.numread; i++)
776 prehashRemove(*((unsigned int *)(((char *)tdata->buffer->objread) + (sizeof(unsigned int) + sizeof(unsigned short))*i)));
777 for (i = 0; i < tdata->buffer->f.nummod; i++)
778 prehashRemove(tdata->buffer->oidmod[i]);
779 } else if(transagree == tdata->buffer->f.mcount){
781 *(tdata->replyctrl) = TRANS_COMMIT;
782 *(tdata->replyretry) = 0;
784 /* Send Abort in soft abort case followed by retry commiting transaction again*/
785 *(tdata->replyctrl) = TRANS_ABORT;
786 *(tdata->replyretry) = 1;
791 /* This function sends the final response to remote machines per thread in their respective socket id
792 * It returns a char that is only needed to check the correctness of execution of this function inside
794 char sendResponse(thread_data_array_t *tdata, int sd) {
795 int n, N, sum, oidcount = 0, control;
796 char *ptr, retval = 0;
797 unsigned int *oidnotfound;
799 control = *(tdata->replyctrl);
800 if (send(sd, &control, sizeof(char), MSG_NOSIGNAL) < sizeof(char)) {
801 perror("Error sending ctrl message for participant\n");
805 //FIXME read missing objects
806 /* If the decided response is due to a soft abort and missing objects at the Participant's side */
808 if(tdata->recvmsg[tdata->thread_id].rcv_status == TRANS_SOFT_ABORT) {
809 // Read list of objects missing
810 if((read(sd, &oidcount, sizeof(int)) != 0) && (oidcount != 0)) {
811 N = oidcount * sizeof(unsigned int);
812 if((oidnotfound = calloc(oidcount, sizeof(unsigned int))) == NULL) {
813 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
816 ptr = (char *) oidnotfound;
818 n = read(sd, ptr+sum, N-sum);
820 } while(sum < N && n !=0);
822 retval = TRANS_SOFT_ABORT;
826 /* If the decided response is TRANS_ABORT */
827 if(*(tdata->replyctrl) == TRANS_ABORT) {
828 retval = TRANS_ABORT;
829 } else if(*(tdata->replyctrl) == TRANS_COMMIT) { /* If the decided response is TRANS_COMMIT */
830 retval = TRANS_COMMIT;
836 /* This function opens a connection, places an object read request to the
837 * remote machine, reads the control message and object if available and
838 * copies the object and its header to the local cache.
841 void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
843 struct sockaddr_in serv_addr;
850 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
851 perror("Error in socket\n");
855 bzero((char*) &serv_addr, sizeof(serv_addr));
856 serv_addr.sin_family = AF_INET;
857 serv_addr.sin_port = htons(LISTEN_PORT);
858 midtoIP(mnum,machineip);
859 machineip[15] = '\0';
860 serv_addr.sin_addr.s_addr = inet_addr(machineip);
862 /* Open connection */
863 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
864 perror("getRemoteObj() Error in connect\n");
867 char readrequest[sizeof(char)+sizeof(unsigned int)];
868 readrequest[0] = READ_REQUEST;
869 *((unsigned int *)(&readrequest[1])) = oid;
870 if (send(sd, readrequest, sizeof(readrequest), MSG_NOSIGNAL) < sizeof(readrequest)) {
871 perror("Error sending message\n");
875 /* Read response from the Participant */
876 if((val = read(sd, &control, sizeof(char))) <= 0) {
877 perror("No control response for getRemoteObj sent\n");
881 case OBJECT_NOT_FOUND:
884 /* Read object if found into local cache */
885 if((val = read(sd, &size, sizeof(int))) <= 0) {
886 perror("No size is read from the participant\n");
889 objcopy = objstrAlloc(record->cache, size);
890 if((val = read(sd, (char *)objcopy, size)) <= 0) {
891 perror("No objects are read from the remote participant\n");
894 /* Insert into cache's lookup table */
895 chashInsert(record->lookupTable, oid, objcopy);
898 printf("Error in recv request from participant on a READ_REQUEST %s, %d\n",__FILE__, __LINE__);
901 /* Close connection */
906 /* This function handles the local objects involved in a transaction commiting process.
907 * It also makes a decision if this local machine sends AGREE or DISAGREE or SOFT_ABORT to coordinator.
908 * Note Coordinator = local machine
909 * It wakes up the other threads from remote participants that are waiting for the coordinator's decision and
910 * based on common agreement it either commits or aborts the transaction.
911 * It also frees the memory resources */
912 void *handleLocalReq(void *threadarg) {
913 unsigned int *oidnotfound = NULL, *oidlocked = NULL;
914 local_thread_data_array_t *localtdata;
915 int objnotfound = 0, objlocked = 0;
916 int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
919 unsigned short version;
921 objheader_t *headptr;
923 localtdata = (local_thread_data_array_t *) threadarg;
925 /* Counters and arrays to formulate decision on control message to be sent */
926 oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
927 oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
929 numread = localtdata->tdata->buffer->f.numread;
930 /* Process each oid in the machine pile/ group per thread */
931 for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) {
932 if (i < localtdata->tdata->buffer->f.numread) {
933 int incr = sizeof(unsigned int) + sizeof(short);// Offset that points to next position in the objread array
935 oid = *((unsigned int *)(((char *)localtdata->tdata->buffer->objread) + incr));
936 version = *((short *)(((char *)localtdata->tdata->buffer->objread) + incr + sizeof(unsigned int)));
937 } else { // Objects Modified
939 headptr = (objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidmod[i-numread]);
940 if (headptr == NULL) {
941 printf("Error: handleLocalReq() returning NULL %s, %d\n", __FILE__, __LINE__);
945 version = headptr->version;
947 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
949 /* Save the oids not found and number of oids not found for later use */
950 if ((mobj = mhashSearch(oid)) == NULL) { /* Obj not found */
951 /* Save the oids not found and number of oids not found for later use */
952 oidnotfound[objnotfound] = oid;
954 } else { /* If Obj found in machine (i.e. has not moved) */
955 /* Check if Obj is locked by any previous transaction */
956 if ((STATUS((objheader_t *)mobj) & LOCK) == LOCK) {
957 if (version == ((objheader_t *)mobj)->version) { /* If locked then match versions */
959 } else {/* If versions don't match ...HARD ABORT */
961 /* Send TRANS_DISAGREE to Coordinator */
962 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
964 } else {/* If Obj is not locked then lock object */
965 STATUS(((objheader_t *)mobj)) |= LOCK;
966 /* Save all object oids that are locked on this machine during this transaction request call */
967 oidlocked[objlocked] = OID(((objheader_t *)mobj));
969 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
971 } else { /* If versions don't match ...HARD ABORT */
973 /* Send TRANS_DISAGREE to Coordinator */
974 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
979 /* Condition to send TRANS_AGREE */
980 if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
981 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
983 /* Condition to send TRANS_SOFT_ABORT */
984 if((v_matchlock > 0 && v_nomatch == 0) || (objnotfound > 0 && v_nomatch == 0)) {
985 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
988 /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
989 * if Participant receives a TRANS_COMMIT */
990 localtdata->transinfo->objlocked = oidlocked;
991 localtdata->transinfo->objnotfound = oidnotfound;
992 localtdata->transinfo->modptr = NULL;
993 localtdata->transinfo->numlocked = objlocked;
994 localtdata->transinfo->numnotfound = objnotfound;
995 /* Lock and update count */
996 //Thread sleeps until all messages from pariticipants are received by coordinator
997 pthread_mutex_lock(localtdata->tdata->lock);
998 (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */
1000 /* Wake up the threads and invoke decideResponse (once) */
1001 if(*(localtdata->tdata->count) == localtdata->tdata->buffer->f.mcount) {
1002 decideResponse(localtdata->tdata);
1003 pthread_cond_broadcast(localtdata->tdata->threshold);
1005 pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock);
1007 pthread_mutex_unlock(localtdata->tdata->lock);
1008 if(*(localtdata->tdata->replyctrl) == TRANS_ABORT){
1009 if(transAbortProcess(localtdata) != 0) {
1010 printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
1013 } else if(*(localtdata->tdata->replyctrl) == TRANS_COMMIT) {
1014 if(transComProcess(localtdata) != 0) {
1015 printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
1020 if (localtdata->transinfo->objlocked != NULL) {
1021 free(localtdata->transinfo->objlocked);
1023 if (localtdata->transinfo->objnotfound != NULL) {
1024 free(localtdata->transinfo->objnotfound);
1030 /* This function completes the ABORT process if the transaction is aborting */
1031 int transAbortProcess(local_thread_data_array_t *localtdata) {
1033 unsigned int *objlocked;
1036 numlocked = localtdata->transinfo->numlocked;
1037 objlocked = localtdata->transinfo->objlocked;
1039 for (i = 0; i < numlocked; i++) {
1040 if((header = mhashSearch(objlocked[i])) == NULL) {
1041 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1044 STATUS(((objheader_t *)header)) &= ~(LOCK);
1050 /*This function completes the COMMIT process is the transaction is commiting*/
1051 int transComProcess(local_thread_data_array_t *localtdata) {
1052 objheader_t *header, *tcptr;
1053 int i, nummod, tmpsize, numcreated, numlocked;
1054 unsigned int *oidmod, *oidcreated, *oidlocked;
1057 nummod = localtdata->tdata->buffer->f.nummod;
1058 oidmod = localtdata->tdata->buffer->oidmod;
1059 numcreated = localtdata->tdata->buffer->f.numcreated;
1060 oidcreated = localtdata->tdata->buffer->oidcreated;
1061 numlocked = localtdata->transinfo->numlocked;
1062 oidlocked = localtdata->transinfo->objlocked;
1064 for (i = 0; i < nummod; i++) {
1065 if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
1066 printf("Error: transComProcess() mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1069 /* Copy from transaction cache -> main object store */
1070 if ((tcptr = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidmod[i]))) == NULL) {
1071 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1074 GETSIZE(tmpsize, header);
1075 pthread_mutex_lock(&mainobjstore_mutex);
1076 memcpy((char*)header+sizeof(objheader_t), (char *)tcptr+ sizeof(objheader_t), tmpsize);
1077 header->version += 1;
1078 if(header->notifylist != NULL) {
1079 notifyAll(&header->notifylist, OID(header), header->version);
1081 pthread_mutex_unlock(&mainobjstore_mutex);
1083 /* If object is newly created inside transaction then commit it */
1084 for (i = 0; i < numcreated; i++) {
1085 if ((header = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidcreated[i]))) == NULL) {
1086 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1089 GETSIZE(tmpsize, header);
1090 tmpsize += sizeof(objheader_t);
1091 pthread_mutex_lock(&mainobjstore_mutex);
1092 if ((ptrcreate = objstrAlloc(mainobjstore, tmpsize)) == NULL) {
1093 printf("Error: transComProcess() failed objstrAlloc %s, %d\n", __FILE__, __LINE__);
1094 pthread_mutex_unlock(&mainobjstore_mutex);
1097 pthread_mutex_unlock(&mainobjstore_mutex);
1098 memcpy(ptrcreate, header, tmpsize);
1099 mhashInsert(oidcreated[i], ptrcreate);
1100 lhashInsert(oidcreated[i], myIpAddr);
1102 /* Unlock locked objects */
1103 for(i = 0; i < numlocked; i++) {
1104 if((header = (objheader_t *) mhashSearch(oidlocked[i])) == NULL) {
1105 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1108 STATUS(header) &= ~(LOCK);
1114 /* This function checks if the prefetch oids are same and have same offsets
1115 * for case x.a.b and y.a.b where x and y have same oid's
1116 * or if a.b.c is a subset of x.b.c.d*/
1117 /* check for case where the generated request a.y.z or x.y.z.g then
1118 * prefetch needs to be generated for x.y.z.g if oid of a and x are same*/
1119 void checkPrefetchTuples(prefetchqelem_t *node) {
1120 int i,j, count,k, sindex, index;
1122 int ntuples, slength;
1124 short *endoffsets, *arryfields;
1126 /* Check for the case x.y.z and a.b.c are same oids */
1127 ptr = (char *) node;
1128 ntuples = *(GET_NTUPLES(ptr));
1129 oid = GET_PTR_OID(ptr);
1130 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1131 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1133 /* Find offset length for each tuple */
1134 int numoffset[ntuples];
1135 numoffset[0] = endoffsets[0];
1136 for(i = 1; i<ntuples; i++) {
1137 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1139 /* Check for redundant tuples by comparing oids of each tuple */
1140 for(i = 0; i < ntuples; i++) {
1143 for(j = i+1 ; j < ntuples; j++) {
1146 /*If oids of tuples match */
1147 if (oid[i] == oid[j]) {
1148 /* Find the smallest offset length of two tuples*/
1149 if(numoffset[i] > numoffset[j]){
1150 slength = numoffset[j];
1154 slength = numoffset[i];
1158 /* Compare the offset values based on the current indices
1159 * break if they do not match
1160 * if all offset values match then pick the largest tuple*/
1165 k = endoffsets[i-1];
1167 index = endoffsets[j -1];
1168 for(count = 0; count < slength; count ++) {
1169 if (arryfields[k] != arryfields[index]) {
1175 if(slength == count) {
1182 /* This function makes machine piles to be added into the machine pile queue for each prefetch call */
1183 prefetchpile_t *makePreGroups(prefetchqelem_t *node, int *numoffset) {
1185 int ntuples, i, machinenum, count=0;
1187 short *endoffsets, *arryfields, *offset;
1188 prefetchpile_t *head = NULL, *tmp = NULL;
1190 /* Check for the case x.y.z and a.b.c are same oids */
1191 ptr = (char *) node;
1192 ntuples = *(GET_NTUPLES(ptr));
1193 oid = GET_PTR_OID(ptr);
1194 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1195 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1197 if((head = (prefetchpile_t *) calloc(1, sizeof(prefetchpile_t))) == NULL) {
1198 printf("Calloc error: %s %d\n", __FILE__, __LINE__);
1202 /* Check for redundant tuples by comparing oids of each tuple */
1203 for(i = 0; i < ntuples; i++) {
1205 if(head->next != NULL) {
1206 if((tmp = (prefetchpile_t *) calloc(1, sizeof(prefetchpile_t))) == NULL) {
1207 printf("Calloc error: %s %d\n", __FILE__, __LINE__);
1210 tmp->mid = myIpAddr;
1214 head->mid = myIpAddr;
1218 /* For each tuple make piles */
1219 if ((machinenum = lhashSearch(oid[i])) == 0) {
1220 printf("Error: No such Machine %s, %d\n", __FILE__, __LINE__);
1223 /* Insert into machine pile */
1225 offset = &arryfields[0];
1227 offset = &arryfields[endoffsets[i-1]];
1230 if((head = insertPile(machinenum, oid[i], numoffset[i], offset, head)) == NULL){
1231 printf("Error: Couldn't create a pile %s, %d\n", __FILE__, __LINE__);
1239 prefetchpile_t *foundLocal(prefetchqelem_t *node) {
1240 int ntuples,i, j, k, oidnfound = 0, arryfieldindex,nextarryfieldindex, flag = 0, val;
1242 unsigned int objoid;
1245 objheader_t *objheader;
1246 short *endoffsets, *arryfields;
1247 prefetchpile_t *head = NULL;
1249 ptr = (char *) node;
1250 ntuples = *(GET_NTUPLES(ptr));
1251 oid = GET_PTR_OID(ptr);
1252 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1253 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1255 /* Find offset length for each tuple */
1256 int numoffset[ntuples];//Number of offsets for each tuple
1257 numoffset[0] = endoffsets[0];
1258 for(i = 1; i<ntuples; i++) {
1259 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1261 for(i = 0; i < ntuples; i++) {
1265 nextarryfieldindex = endoffsets[0];
1267 arryfieldindex = endoffsets[i-1];
1268 nextarryfieldindex = endoffsets[i];
1271 endoffsets[0] = val = numoffset[0];
1272 for(k = 1; k < ntuples; k++) {
1273 val = val + numoffset[k];
1274 endoffsets[k] = val;
1277 for(k = 0; k<endoffsets[ntuples-1]; k++) {
1278 arryfields[arryfieldindex+k] = arryfields[nextarryfieldindex+k];
1282 /* If object found locally */
1283 if((objheader = (objheader_t*) mhashSearch(oid[i])) != NULL) {
1284 tmp = (char *) objheader;
1285 int orgnumoffset = numoffset[i];
1289 arryfieldindex = endoffsets[i-1];
1292 for(j = 0; j<orgnumoffset; j++) {
1293 /* Check for arrays */
1294 if(TYPE(objheader) > NUMCLASSES) {
1298 int elementsize = classsize[TYPE(objheader)];
1299 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*arryfields[arryfieldindex])));
1301 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + arryfields[arryfieldindex]));
1303 //Update numoffset array
1304 numoffset[i] = numoffset[i] - 1;
1307 //Update endoffset array
1308 endoffsets[0] = val = numoffset[0];
1309 for(k = 1; k < ntuples; k++) {
1310 val = val + numoffset[k];
1311 endoffsets[k] = val;
1313 //Update arrayfields array
1314 for(k = 0; k < endoffsets[ntuples-1]; k++) {
1315 arryfields[arryfieldindex+k] = arryfields[arryfieldindex+k+1];
1317 if((objheader = (objheader_t*) mhashSearch(oid[i])) == NULL) {
1319 checkPreCache(node, numoffset, oid[i], i);
1322 tmp = (char *) objheader;
1325 /*If all offset oids are found locally,make the prefetch tuple invalid */
1330 /* Look in Prefetch cache */
1331 checkPreCache(node, numoffset, oid[i],i);
1335 /* Make machine groups */
1336 if((head = makePreGroups(node, numoffset)) == NULL) {
1337 printf("Error in makePreGroups() %s %d\n", __FILE__, __LINE__);
1344 void checkPreCache(prefetchqelem_t *node, int *numoffset, unsigned int objoid, int index) {
1346 int ntuples, i, k, flag=0, isArray =0, arryfieldindex, val;
1348 short *endoffsets, *arryfields;
1349 objheader_t *header;
1351 ptr = (char *) node;
1352 ntuples = *(GET_NTUPLES(ptr));
1353 oid = GET_PTR_OID(ptr);
1354 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1355 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1357 if((header = (objheader_t *) prehashSearch(objoid)) == NULL) {
1359 } else { //Found in Prefetch Cache
1360 //TODO Decide if object is too old, if old remove from cache
1361 tmp = (char *) header;
1362 int loopcount = numoffset[index];
1366 arryfieldindex = endoffsets[(index - 1)];
1367 // Check if any of the offset oid is available in the Prefetch cache
1368 for(i = 0; i < loopcount; i++) {
1369 /* Check for arrays */
1370 if(TYPE(header) > NUMCLASSES) {
1374 int elementsize = classsize[TYPE(header)];
1375 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*arryfields[arryfieldindex])));
1377 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + arryfields[arryfieldindex]));
1379 //Update numoffset array
1380 numoffset[index] = numoffset[index] - 1;
1382 oid[index] = objoid;
1383 //Update endoffset array
1384 endoffsets[0] = val = numoffset[0];
1385 for(k = 1; k < ntuples; k++) {
1386 val = val + numoffset[k];
1387 endoffsets[k] = val;
1389 //Update arrayfields array
1390 for(k = 0; k < endoffsets[ntuples-1]; k++) {
1391 arryfields[arryfieldindex+k] = arryfields[arryfieldindex+k+1];
1393 if((header = (objheader_t *)prehashSearch(oid[index])) != NULL) {
1394 tmp = (char *) header;
1402 //Found in the prefetch cache
1403 if(flag == 0 && (numoffset[index] == 0)) {
1410 /* This function is called by the thread calling transPrefetch */
1411 void *transPrefetch(void *t) {
1412 prefetchqelem_t *qnode;
1413 prefetchpile_t *pilehead = NULL;
1414 prefetchpile_t *ptr = NULL, *piletail = NULL;
1417 /* lock mutex of primary prefetch queue */
1418 pthread_mutex_lock(&pqueue.qlock);
1419 /* while primary queue is empty, then wait */
1420 while((pqueue.front == NULL) && (pqueue.rear == NULL)) {
1421 pthread_cond_wait(&pqueue.qcond, &pqueue.qlock);
1424 /* dequeue node to create a machine piles and finally unlock mutex */
1425 if((qnode = pre_dequeue()) == NULL) {
1426 printf("Error: No node returned %s, %d\n", __FILE__, __LINE__);
1427 pthread_mutex_unlock(&pqueue.qlock);
1430 pthread_mutex_unlock(&pqueue.qlock);
1432 /* Reduce redundant prefetch requests */
1433 checkPrefetchTuples(qnode);
1434 /* Check if the tuples are found locally, if yes then reduce them further*/
1435 /* and group requests by remote machine ids by calling the makePreGroups() */
1436 if((pilehead = foundLocal(qnode)) == NULL) {
1437 printf("Error: No node created for serving prefetch request %s %d\n", __FILE__, __LINE__);
1442 while(ptr != NULL) {
1443 if(ptr->next == NULL) {
1449 /* Lock mutex of pool queue */
1450 pthread_mutex_lock(&mcqueue.qlock);
1451 /* Update the pool queue with the new remote machine piles generated per prefetch call */
1452 mcpileenqueue(pilehead, piletail);
1453 /* Broadcast signal on machine pile queue */
1454 pthread_cond_broadcast(&mcqueue.qcond);
1455 /* Unlock mutex of machine pile queue */
1456 pthread_mutex_unlock(&mcqueue.qlock);
1457 /* Deallocate the prefetch queue pile node */
1462 /* Each thread in the pool of threads calls this function to establish connection with
1463 * remote machines, send the prefetch requests and process the reponses from
1464 * the remote machines .
1465 * The thread is active throughout the period of runtime */
1467 void *mcqProcess(void *threadid) {
1469 prefetchpile_t *mcpilenode;
1471 tid = (int) threadid;
1473 /* Lock mutex of mc pile queue */
1474 pthread_mutex_lock(&mcqueue.qlock);
1475 /* When mc pile queue is empty, wait */
1476 while((mcqueue.front == NULL) && (mcqueue.rear == NULL)) {
1477 pthread_cond_wait(&mcqueue.qcond, &mcqueue.qlock);
1479 /* Dequeue node to send remote machine connections*/
1480 if((mcpilenode = mcpiledequeue()) == NULL) {
1481 printf("Dequeue Error: No node returned %s %d\n", __FILE__, __LINE__);
1482 pthread_mutex_unlock(&mcqueue.qlock);
1486 pthread_mutex_unlock(&mcqueue.qlock);
1488 /*Initiate connection to remote host and send request */
1489 /* Process Request */
1490 if(mcpilenode->mid != myIpAddr)
1491 sendPrefetchReq(mcpilenode);
1493 /* Deallocate the machine queue pile node */
1494 mcdealloc(mcpilenode);
1498 void sendPrefetchReq(prefetchpile_t *mcpilenode) {
1499 int sd, i, off, len, endpair, count = 0;
1500 struct sockaddr_in remoteAddr;
1501 char machineip[16], control;
1505 /* Send Trans Prefetch Request */
1506 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
1507 perror("Error in socket for SEND_PREFETCH_REQUEST\n");
1511 mid = mcpilenode->mid;
1513 bzero(&remoteAddr, sizeof(remoteAddr));
1514 remoteAddr.sin_family = AF_INET;
1515 remoteAddr.sin_port = htons(LISTEN_PORT);
1516 remoteAddr.sin_addr.s_addr = htonl(mid);
1518 /* Open Connection */
1519 if (connect(sd, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0) {
1520 printf("%s():error %d connecting to %s:%d\n", __func__, errno,
1521 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1526 /* Send TRANS_PREFETCH control message */
1527 control = TRANS_PREFETCH;
1528 if(send(sd, &control, sizeof(char), MSG_NOSIGNAL) < sizeof(char)) {
1529 perror("Error in sending prefetch control\n");
1534 /* Send Oids and offsets in pairs */
1535 tmp = mcpilenode->objpiles;
1536 while(tmp != NULL) {
1538 count++; /* Keeps track of the number of oid and offset tuples sent per remote machine */
1539 len = sizeof(int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(unsigned short));
1540 char oidnoffset[len];
1541 bzero(oidnoffset, len);
1542 *((unsigned int*)oidnoffset) = len;
1544 *((unsigned int *)((char *)oidnoffset + off)) = tmp->oid;
1545 off += sizeof(unsigned int);
1546 for(i = 0; i < tmp->numoffset; i++) {
1547 *((unsigned short*)((char *)oidnoffset + off)) = tmp->offset[i];
1548 off+=sizeof(unsigned short);
1551 if (send(sd, oidnoffset, len , MSG_NOSIGNAL) < len) {
1552 perror("Error sending fixed bytes for thread\n");
1560 /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
1562 if (send(sd, &endpair, sizeof(int), MSG_NOSIGNAL) < sizeof(int)) {
1563 perror("Error sending fixed bytes for thread\n");
1568 /* Get Response from the remote machine */
1569 getPrefetchResponse(count,sd);
1574 void getPrefetchResponse(int count, int sd) {
1575 int i = 0, val, n, N, sum, index, objsize;
1576 unsigned int bufsize,oid;
1580 void *modptr, *oldptr;
1582 /* Read prefetch response from the Remote machine */
1583 if((val = read(sd, &control, sizeof(char))) <= 0) {
1584 perror("No control response for Prefetch request sent\n");
1588 if(control == TRANS_PREFETCH_RESPONSE) {
1589 /*For each oid and offset tuple sent as prefetch request to remote machine*/
1590 while(N = recv((int)sd, &bufsize, sizeof(unsigned int), 0) != 0) {
1591 if((buffer = calloc(1, bufsize)) == NULL) {
1592 printf("Calloc Error in %s() at %s, %d\n", __func__, __FILE__, __LINE__);
1598 /* Keep receiving the buffer containing oid info */
1600 n = recv((int)sd, (void *)ptr+sum, bufsize-sum, 0);
1602 } while(sum < bufsize && n != 0);
1604 /* Decode the contents of the buffer */
1605 while(index < bufsize ) {
1606 if(buffer[index] == OBJECT_FOUND) {
1607 /* Increment it to get the object */
1608 index += sizeof(char);
1609 oid = *((unsigned int *)(buffer+index));
1610 index += sizeof(unsigned int);
1611 /* For each object found add to Prefetch Cache */
1612 objsize = *((int *)(buffer+index));
1614 pthread_mutex_lock(&prefetchcache_mutex);
1615 if ((modptr = objstrAlloc(prefetchcache, objsize)) == NULL) {
1616 printf("Error: objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
1617 pthread_mutex_unlock(&prefetchcache_mutex);
1621 pthread_mutex_unlock(&prefetchcache_mutex);
1622 memcpy(modptr, buffer+index, objsize);
1624 /* Insert the oid and its address into the prefetch hash lookup table */
1625 /* Do a version comparison if the oid exists */
1626 if((oldptr = prehashSearch(oid)) != NULL) {
1627 /* If older version then update with new object ptr */
1628 if(((objheader_t *)oldptr)->version < ((objheader_t *)modptr)->version) {
1630 prehashInsert(oid, modptr);
1631 } else if(((objheader_t *)oldptr)->version == ((objheader_t *)modptr)->version) {
1632 /* Add the new object ptr to hash table */
1634 prehashInsert(oid, modptr);
1635 } else { /* Do nothing: TODO modptr should be reference counted */
1638 } else {/*If doesn't no match found in hashtable, add the object ptr to hash table*/
1639 prehashInsert(oid, modptr);
1641 /* Lock the Prefetch Cache look up table*/
1642 pthread_mutex_lock(&pflookup.lock);
1643 /* Broadcast signal on prefetch cache condition variable */
1644 pthread_cond_broadcast(&pflookup.cond);
1645 /* Unlock the Prefetch Cache look up table*/
1646 pthread_mutex_unlock(&pflookup.lock);
1647 } else if(buffer[index] == OBJECT_NOT_FOUND) {
1648 /* Increment it to get the object */
1649 /* TODO: For each object not found query DHT for new location and retrieve the object */
1650 index += sizeof(char);
1651 oid = *((unsigned int *)(buffer + index));
1652 index += sizeof(unsigned int);
1653 /* Throw an error */
1654 printf("OBJECT NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n");
1657 printf("Error in decoding the index value %d, %s, %d\n",index, __FILE__, __LINE__);
1665 printf("Error in receving response for prefetch request %s, %d\n",__FILE__, __LINE__);
1669 unsigned short getObjType(unsigned int oid)
1671 objheader_t *objheader;
1672 unsigned short numoffset[] ={0};
1673 short fieldoffset[] ={};
1675 if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL)
1677 if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1679 prefetch(1, &oid, numoffset, fieldoffset);
1680 pthread_mutex_lock(&pflookup.lock);
1681 while ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1683 pthread_cond_wait(&pflookup.cond, &pflookup.lock);
1685 pthread_mutex_unlock(&pflookup.lock);
1689 return TYPE(objheader);
1692 int startRemoteThread(unsigned int oid, unsigned int mid)
1695 struct sockaddr_in remoteAddr;
1696 char msg[1 + sizeof(unsigned int)];
1700 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
1702 perror("startRemoteThread():socket()");
1706 bzero(&remoteAddr, sizeof(remoteAddr));
1707 remoteAddr.sin_family = AF_INET;
1708 remoteAddr.sin_port = htons(LISTEN_PORT);
1709 remoteAddr.sin_addr.s_addr = htonl(mid);
1711 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0)
1713 printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
1714 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1719 msg[0] = START_REMOTE_THREAD;
1720 memcpy(&msg[1], &oid, sizeof(unsigned int));
1722 bytesSent = send(sock, msg, 1 + sizeof(unsigned int), 0);
1725 perror("startRemoteThread():send()");
1728 else if (bytesSent != 1 + sizeof(unsigned int))
1730 printf("startRemoteThread(): error, sent %d bytes\n", bytesSent);
1743 //TODO: when reusing oids, make sure they are not already in use!
1744 unsigned int getNewOID(void) {
1745 static unsigned int id = 0xFFFFFFFF;
1748 if (id > oidMax || id < oidMin)
1755 int processConfigFile()
1758 const int maxLineLength = 200;
1759 char lineBuffer[maxLineLength];
1761 const char *delimiters = " \t\n";
1765 configFile = fopen(CONFIG_FILENAME, "r");
1766 if (configFile == NULL)
1768 printf("error opening %s:\n", CONFIG_FILENAME);
1773 numHostsInSystem = 0;
1774 sizeOfHostArray = 8;
1775 hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
1777 while(fgets(lineBuffer, maxLineLength, configFile) != NULL)
1779 commentBegin = strchr(lineBuffer, '#');
1780 if (commentBegin != NULL)
1781 *commentBegin = '\0';
1782 token = strtok(lineBuffer, delimiters);
1783 while (token != NULL)
1785 tmpAddr = inet_addr(token);
1786 if ((int)tmpAddr == -1)
1788 printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
1793 addHost(htonl(tmpAddr));
1794 token = strtok(NULL, delimiters);
1800 if (numHostsInSystem < 1)
1802 printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
1806 myIpAddr = getMyIpAddr("en1");
1808 myIpAddr = getMyIpAddr("eth0");
1810 myIndexInHostArray = findHost(myIpAddr);
1811 if (myIndexInHostArray == -1)
1813 printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
1816 oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
1817 oidMin = oidsPerBlock * myIndexInHostArray;
1818 if (myIndexInHostArray == numHostsInSystem - 1)
1819 oidMax = 0xFFFFFFFF;
1821 oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
1826 void addHost(unsigned int hostIp)
1828 unsigned int *tmpArray;
1830 if (findHost(hostIp) != -1)
1833 if (numHostsInSystem == sizeOfHostArray)
1835 tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
1836 memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
1838 hostIpAddrs = tmpArray;
1841 hostIpAddrs[numHostsInSystem++] = hostIp;
1846 int findHost(unsigned int hostIp)
1849 for (i = 0; i < numHostsInSystem; i++)
1850 if (hostIpAddrs[i] == hostIp)
1857 /* This function sends notification request per thread waiting on object(s) whose version
1859 int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int numoid) {
1861 objheader_t *objheader;
1862 struct sockaddr_in remoteAddr;
1863 char msg[1 + numoid * (sizeof(short) + sizeof(unsigned int)) + 3 * sizeof(unsigned int)];
1867 unsigned short version;
1868 unsigned int oid,mid;
1869 static unsigned int threadid = 0;
1870 pthread_mutex_t threadnotify = PTHREAD_MUTEX_INITIALIZER; //Lock and condition var for threadjoin and notification
1871 pthread_cond_t threadcond = PTHREAD_COND_INITIALIZER;
1872 notifydata_t *ndata;
1874 //FIXME currently all oids belong to one machine
1876 mid = lhashSearch(oid);
1878 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1879 perror("reqNotify():socket()");
1883 bzero(&remoteAddr, sizeof(remoteAddr));
1884 remoteAddr.sin_family = AF_INET;
1885 remoteAddr.sin_port = htons(LISTEN_PORT);
1886 remoteAddr.sin_addr.s_addr = htonl(mid);
1888 /* Generate unique threadid */
1891 /* Save threadid, numoid, oidarray, versionarray, pthread_cond_variable for later processing */
1892 if((ndata = calloc(1, sizeof(notifydata_t))) == NULL) {
1893 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
1896 ndata->numoid = numoid;
1897 ndata->threadid = threadid;
1898 ndata->oidarry = oidarry;
1899 ndata->versionarry = versionarry;
1900 ndata->threadcond = threadcond;
1901 ndata->threadnotify = threadnotify;
1902 if((status = notifyhashInsert(threadid, ndata)) != 0) {
1903 printf("reqNotify(): Insert into notify hash table not successful %s, %d\n", __FILE__, __LINE__);
1908 /* Send number of oids, oidarry, version array, machine id and threadid */
1909 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1910 printf("reqNotify():error %d connecting to %s:%d\n", errno,
1911 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1915 msg[0] = THREAD_NOTIFY_REQUEST;
1916 *((unsigned int *)(&msg[1])) = numoid;
1917 /* Send array of oids */
1918 size = sizeof(unsigned int);
1923 *((unsigned int *)(&msg[1] + size)) = oid;
1924 size += sizeof(unsigned int);
1929 /* Send array of version */
1933 version = versionarry[i];
1934 *((unsigned short *)(&msg[1] + size)) = version;
1935 size += sizeof(unsigned short);
1940 *((unsigned int *)(&msg[1] + size)) = myIpAddr;
1941 size += sizeof(unsigned int);
1942 *((unsigned int *)(&msg[1] + size)) = threadid;
1944 pthread_mutex_lock(&(ndata->threadnotify));
1945 bytesSent = send(sock, msg, 1 + numoid * (sizeof(unsigned int) + sizeof(unsigned short)) + 3 * sizeof(unsigned int) , 0);
1947 perror("reqNotify():send()");
1949 } else if (bytesSent != 1 + numoid*(sizeof(unsigned int) + sizeof(unsigned short)) + 3 * sizeof(unsigned int)){
1950 printf("reNotify(): error, sent %d bytes %s, %d\n", bytesSent, __FILE__, __LINE__);
1956 pthread_cond_wait(&(ndata->threadcond), &(ndata->threadnotify));
1957 pthread_mutex_unlock(&(ndata->threadnotify));
1960 pthread_cond_destroy(&threadcond);
1961 pthread_mutex_destroy(&threadnotify);
1967 void threadNotify(unsigned int oid, unsigned short version, unsigned int tid) {
1968 notifydata_t *ndata;
1969 int i, objIsFound = 0, index;
1972 //Look up the tid and call the corresponding pthread_cond_signal
1973 if((ndata = notifyhashSearch(tid)) == NULL) {
1974 printf("threadnotify(): No such threadid is present %s, %d\n", __FILE__, __LINE__);
1977 for(i = 0; i < ndata->numoid; i++) {
1978 if(ndata->oidarry[i] == oid){
1983 if(objIsFound == 0){
1984 printf("threadNotify(): Oid not found %s, %d\n", __FILE__, __LINE__);
1987 if(version <= ndata->versionarry[index]){
1988 printf("threadNotify(): New version %d has not changed since last version %s, %d\n", version, __FILE__, __LINE__);
1991 /* Clear from prefetch cache and free thread related data structure */
1992 if((ptr = prehashSearch(oid)) != NULL) {
1995 pthread_cond_signal(&(ndata->threadcond));
2002 int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) {
2005 struct sockaddr_in remoteAddr;
2006 char msg[1 + sizeof(unsigned short) + 2*sizeof(unsigned int)];
2007 int sock, status, size, bytesSent;
2009 while(*head != NULL) {
2012 //create a socket connection to that machine
2013 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
2014 perror("notifyAll():socket()");
2018 bzero(&remoteAddr, sizeof(remoteAddr));
2019 remoteAddr.sin_family = AF_INET;
2020 remoteAddr.sin_port = htons(LISTEN_PORT);
2021 remoteAddr.sin_addr.s_addr = htonl(mid);
2022 //send Thread Notify response and threadid to that machine
2023 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
2024 printf("notifyAll():error %d connecting to %s:%d\n", errno,
2025 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
2028 bzero(msg, (1+sizeof(unsigned short) + 2*sizeof(unsigned int)));
2029 msg[0] = THREAD_NOTIFY_RESPONSE;
2030 *((unsigned int *)&msg[1]) = oid;
2031 size = sizeof(unsigned int);
2032 *((unsigned short *)(&msg[1]+ size)) = version;
2033 size+= sizeof(unsigned short);
2034 *((unsigned int *)(&msg[1]+ size)) = ptr->threadid;
2036 bytesSent = send(sock, msg, (1 + 2*sizeof(unsigned int) + sizeof(unsigned short)), 0);
2038 perror("notifyAll():send()");
2040 } else if (bytesSent != 1 + 2*sizeof(unsigned int) + sizeof(unsigned short)){
2041 printf("notifyAll(): error, sent %d bytes %s, %d\n",
2042 bytesSent, __FILE__, __LINE__);
2057 void transAbort(transrecord_t *trans) {
2058 objstrDelete(trans->cache);
2059 chashDelete(trans->lookupTable);