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) {
95 // rc=pthread_create(&tPrefetch, NULL, transPrefetch, NULL);
98 /* Allocate for the queue node*/
101 qnodesize = sizeof(prefetchqelem_t) + sizeof(int) + ntuples * (sizeof(unsigned short) + sizeof(unsigned int)) + endoffsets[ntuples - 1] * sizeof(unsigned short);
102 if((node = calloc(1, qnodesize)) == NULL) {
103 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
106 /* Set queue node values */
107 len = sizeof(prefetchqelem_t);
108 memcpy(node + len, &ntuples, sizeof(int));
110 memcpy(node + len, oids, ntuples*sizeof(unsigned int));
111 len += ntuples * sizeof(unsigned int);
112 memcpy(node + len, endoffsets, ntuples*sizeof(unsigned short));
113 len += ntuples * sizeof(unsigned short);
114 memcpy(node + len, arrayfields, endoffsets[ntuples-1]*sizeof(unsigned short));
115 /* Lock and insert into primary prefetch queue */
116 pthread_mutex_lock(&pqueue.qlock);
117 pre_enqueue((prefetchqelem_t *)node);
118 pthread_cond_signal(&pqueue.qcond);
119 pthread_mutex_unlock(&pqueue.qlock);
123 /* This function starts up the transaction runtime. */
124 int dstmStartup(const char * option) {
125 pthread_t thread_Listen;
127 int master=option!=NULL && strcmp(option, "master")==0;
129 if (processConfigFile() != 0)
130 return 0; //TODO: return error value, cause main program to exit
140 pthread_attr_init(&attr);
141 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
142 pthread_create(&thread_Listen, &attr, dstmListen, NULL);
151 //TODO Use this later
152 void *pCacheAlloc(objstr_t *store, unsigned int size) {
158 while(ptr->next != NULL) {
159 /* check if store is empty */
160 if(((unsigned int)ptr->top - (unsigned int)ptr - sizeof(objstr_t) + size) <= ptr->size) {
175 /* This function initiates the prefetch thread
176 * A queue is shared between the main thread of execution
177 * and the prefetch thread to process the prefetch call
178 * Call from compiler populates the shared queue with prefetch requests while prefetch thread
179 * processes the prefetch requests */
183 //Create and initialize prefetch cache structure
184 prefetchcache = objstrCreate(PREFETCH_CACHE_SIZE);
185 //prefetchcache->next = objstrCreate(PREFETCH_CACHE_SIZE);
186 //prefetchcache->next->next = objstrCreate(PREFETCH_CACHE_SIZE);
188 /* Initialize attributes for mutex */
189 pthread_mutexattr_init(&prefetchcache_mutex_attr);
190 pthread_mutexattr_settype(&prefetchcache_mutex_attr, PTHREAD_MUTEX_RECURSIVE_NP);
192 pthread_mutex_init(&prefetchcache_mutex, &prefetchcache_mutex_attr);
194 //Create prefetch cache lookup table
195 if(prehashCreate(HASH_SIZE, LOADFACTOR))
197 //Initialize primary shared queue
199 //Initialize machine pile w/prefetch oids and offsets shared queue
202 //Create the primary prefetch thread
204 retval=pthread_create(&tPrefetch, NULL, transPrefetch, NULL);
206 pthread_detach(tPrefetch);
208 //Create and Initialize a pool of threads
209 /* Threads are active for the entire period runtime is running */
210 for(t = 0; t< NUM_THREADS; t++) {
212 rc = pthread_create(&wthreads[t], NULL, mcqProcess, (void *)t);
214 pthread_detach(wthreads[t]);
218 /* This function stops the threads spawned */
221 pthread_cancel(tPrefetch);
222 for(t = 0; t < NUM_THREADS; t++)
223 pthread_cancel(wthreads[t]);
228 /* This functions inserts randowm wait delays in the order of msec
229 * Mostly used when transaction commits retry*/
237 req.tv_nsec = (long)(1000000 + (t%10000000)); //1-11 msec
238 nanosleep(&req, NULL);
242 /* This function initializes things required in the transaction start*/
243 transrecord_t *transStart()
245 transrecord_t *tmp = calloc(1, sizeof(transrecord_t));
246 tmp->cache = objstrCreate(1048576);
247 tmp->lookupTable = chashCreate(HASH_SIZE, LOADFACTOR);
249 tmp->revertlist=NULL;
254 /* This function finds the location of the objects involved in a transaction
255 * and returns the pointer to the object if found in a remote location */
256 objheader_t *transRead(transrecord_t *record, unsigned int oid) {
257 unsigned int machinenumber;
258 objheader_t *tmp, *objheader;
259 objheader_t *objcopy;
260 int size, rc, found = 0;
269 rc = gettimeofday(&tp, NULL);
273 if (tp.tv_usec >= 1000000)
275 tp.tv_usec -= 1000000;
278 /* Convert from timeval to timespec */
279 ts.tv_sec = tp.tv_sec;
280 ts.tv_nsec = tp.tv_usec * 1000;
282 /* Search local transaction cache */
283 if((objheader = (objheader_t *)chashSearch(record->lookupTable, oid)) != NULL){
285 return &objheader[1];
289 } else if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
290 /* Look up in machine lookup table and copy into cache*/
291 GETSIZE(size, objheader);
292 size += sizeof(objheader_t);
293 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
294 memcpy(objcopy, objheader, size);
295 /* Insert into cache's lookup table */
296 chashInsert(record->lookupTable, OID(objheader), objcopy);
302 } else if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) { /* Look up in prefetch cache */
304 size+=sizeof(objheader_t);
305 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
306 memcpy(objcopy, tmp, size);
307 /* Insert into cache's lookup table */
308 chashInsert(record->lookupTable, OID(tmp), objcopy);
315 /*If object not found in prefetch cache then block until object appears in the prefetch cache */
316 pthread_mutex_lock(&pflookup.lock);
318 rc = pthread_cond_timedwait(&pflookup.cond, &pflookup.lock, &ts);
319 /* Check Prefetch cache again */
320 if((tmp =(objheader_t *) prehashSearch(oid)) != NULL) {
323 size+=sizeof(objheader_t);
324 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
325 memcpy(objcopy, tmp, size);
326 chashInsert(record->lookupTable, OID(tmp), objcopy);
327 pthread_mutex_unlock(&pflookup.lock);
333 } else if (rc == ETIMEDOUT) {
334 pthread_mutex_unlock(&pflookup.lock);
339 /* Get the object from the remote location */
340 machinenumber = lhashSearch(oid);
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 */
440 /* Look through all the objects in the transaction record and make piles
441 * for each machine involved in the transaction*/
442 pile_ptr = pile = createPiles(record);
444 /* Create the packet to be sent in TRANS_REQUEST */
446 /* Count the number of participants */
447 pilecount = pCount(pile);
449 /* Create a list of machine ids(Participants) involved in transaction */
450 if((listmid = calloc(pilecount, sizeof(unsigned int))) == NULL) {
451 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
454 pListMid(pile, listmid);
457 /* Initialize thread variables,
458 * Spawn a thread for each Participant involved in a transaction */
459 pthread_t thread[pilecount];
461 pthread_cond_t tcond;
462 pthread_mutex_t tlock;
463 pthread_mutex_t tlshrd;
465 thread_data_array_t *thread_data_array;
466 if((thread_data_array = (thread_data_array_t *) calloc(pilecount, sizeof(thread_data_array_t))) == NULL) {
467 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
468 pthread_cond_destroy(&tcond);
469 pthread_mutex_destroy(&tlock);
475 local_thread_data_array_t *ltdata;
476 if((ltdata = calloc(1, sizeof(local_thread_data_array_t))) == NULL) {
477 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
478 pthread_cond_destroy(&tcond);
479 pthread_mutex_destroy(&tlock);
482 free(thread_data_array);
486 thread_response_t rcvd_control_msg[pilecount]; /* Shared thread array that keeps track of responses of participants */
488 /* Initialize and set thread detach attribute */
489 pthread_attr_init(&attr);
490 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
491 pthread_mutex_init(&tlock, NULL);
492 pthread_cond_init(&tcond, NULL);
494 /* Process each machine pile */
495 while(pile != NULL) {
496 //Create transaction id
498 if ((tosend = calloc(1, sizeof(trans_req_data_t))) == NULL) {
499 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
500 pthread_cond_destroy(&tcond);
501 pthread_mutex_destroy(&tlock);
504 free(thread_data_array);
508 tosend->f.control = TRANS_REQUEST;
509 sprintf(tosend->f.trans_id, "%x_%d", pile->mid, newtid);
510 tosend->f.mcount = pilecount;
511 tosend->f.numread = pile->numread;
512 tosend->f.nummod = pile->nummod;
513 tosend->f.numcreated = pile->numcreated;
514 tosend->f.sum_bytes = pile->sum_bytes;
515 tosend->listmid = listmid;
516 tosend->objread = pile->objread;
517 tosend->oidmod = pile->oidmod;
518 tosend->oidcreated = pile->oidcreated;
519 thread_data_array[threadnum].thread_id = threadnum;
520 thread_data_array[threadnum].mid = pile->mid;
521 thread_data_array[threadnum].buffer = tosend;
522 thread_data_array[threadnum].recvmsg = rcvd_control_msg;
523 thread_data_array[threadnum].threshold = &tcond;
524 thread_data_array[threadnum].lock = &tlock;
525 thread_data_array[threadnum].count = &trecvcount;
526 thread_data_array[threadnum].replyctrl = &treplyctrl;
527 thread_data_array[threadnum].replyretry = &treplyretry;
528 thread_data_array[threadnum].rec = record;
529 /* If local do not create any extra connection */
530 if(pile->mid != myIpAddr) { /* Not local */
532 rc = pthread_create(&thread[threadnum], &attr, transRequest, (void *) &thread_data_array[threadnum]);
535 perror("Error in pthread create\n");
536 pthread_cond_destroy(&tcond);
537 pthread_mutex_destroy(&tlock);
540 for (i = 0; i < threadnum; i++)
541 free(thread_data_array[i].buffer);
542 free(thread_data_array);
547 ltdata->tdata = &thread_data_array[threadnum];
548 ltdata->transinfo = &transinfo;
550 val = pthread_create(&thread[threadnum], &attr, handleLocalReq, (void *) ltdata);
553 perror("Error in pthread create\n");
554 pthread_cond_destroy(&tcond);
555 pthread_mutex_destroy(&tlock);
558 for (i = 0; i < threadnum; i++)
559 free(thread_data_array[i].buffer);
560 free(thread_data_array);
570 /* Free attribute and wait for the other threads */
571 pthread_attr_destroy(&attr);
573 for (i = 0; i < threadnum; i++) {
574 rc = pthread_join(thread[i], NULL);
577 printf("Error: return code from pthread_join() is %d\n", rc);
578 pthread_cond_destroy(&tcond);
579 pthread_mutex_destroy(&tlock);
582 for (j = i; j < threadnum; j++) {
583 free(thread_data_array[j].buffer);
587 free(thread_data_array[i].buffer);
591 pthread_cond_destroy(&tcond);
592 pthread_mutex_destroy(&tlock);
597 if(treplyctrl == TRANS_ABORT) {
599 objstrDelete(record->cache);
600 chashDelete(record->lookupTable);
602 free(thread_data_array);
605 } else if(treplyctrl == TRANS_COMMIT) {
607 objstrDelete(record->cache);
608 chashDelete(record->lookupTable);
610 free(thread_data_array);
614 //TODO Add other cases
615 printf("DEBUG-> THIS SHOULD NOT HAPPEN.....EXIT PROGRAM\n");
622 /* This function sends information involved in the transaction request
623 * to participants and accepts a response from particpants.
624 * It calls decideresponse() to decide on what control message
625 * to send next to participants and sends the message using sendResponse()*/
626 void *transRequest(void *threadarg) {
628 struct sockaddr_in serv_addr;
629 struct hostent *server;
630 thread_data_array_t *tdata;
631 objheader_t *headeraddr;
632 char buffer[RECEIVE_BUFFER_SIZE], control, recvcontrol;
633 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");
662 /* Send list of machines involved in the transaction */
664 int size=sizeof(unsigned int)*tdata->buffer->f.mcount;
665 if (send(sd, tdata->buffer->listmid, size, MSG_NOSIGNAL) < size) {
666 perror("Error sending list of machines for thread\n");
671 /* Send oids and version number tuples for objects that are read */
673 int size=(sizeof(unsigned int)+sizeof(short))*tdata->buffer->f.numread;
674 if (send(sd, tdata->buffer->objread, size, MSG_NOSIGNAL) < size) {
675 perror("Error sending tuples for thread\n");
680 /* Send objects that are modified */
681 for(i = 0; i < tdata->buffer->f.nummod ; i++) {
683 headeraddr = chashSearch(tdata->rec->lookupTable, tdata->buffer->oidmod[i]);
684 GETSIZE(size,headeraddr);
685 size+=sizeof(objheader_t);
686 if (send(sd, headeraddr, size, MSG_NOSIGNAL) < size) {
687 perror("Error sending obj modified for thread\n");
693 /* Read control message from Participant */
694 if((n = read(sd, &control, sizeof(char))) <= 0) {
695 perror("Error in reading control message from Participant\n");
700 recvcontrol = control;
702 /* Update common data structure and increment count */
703 tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol;
705 /* Lock and update count */
706 /* Thread sleeps until all messages from pariticipants are received by coordinator */
707 pthread_mutex_lock(tdata->lock);
709 (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */
711 /* Wake up the threads and invoke decideResponse (once) */
712 if(*(tdata->count) == tdata->buffer->f.mcount) {
713 decideResponse(tdata);
714 pthread_cond_broadcast(tdata->threshold);
716 pthread_cond_wait(tdata->threshold, tdata->lock);
718 pthread_mutex_unlock(tdata->lock);
720 /* Send the final response such as TRANS_COMMIT or TRANS_ABORT t
721 * to all participants in their respective socket */
722 if (sendResponse(tdata, sd) == 0) {
723 printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__);
728 if ((retval = recv((int)sd, &control, sizeof(char), 0))<= 0) {
729 printf("Error: In receiving control %s,%d\n", __FILE__, __LINE__);
734 if(control == TRANS_UNSUCESSFUL) {
735 //printf("DEBUG-> TRANS_ABORTED\n");
736 } else if(control == TRANS_SUCESSFUL) {
737 //printf("DEBUG-> TRANS_SUCCESSFUL\n");
739 //printf("DEBUG-> Error: Incorrect Transaction End Message %d\n", control);
742 /* Close connection */
747 /* This function decides the reponse that needs to be sent to
748 * all Participant machines after the TRANS_REQUEST protocol */
749 void decideResponse(thread_data_array_t *tdata) {
751 int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
754 for (i = 0 ; i < tdata->buffer->f.mcount; i++) {
755 control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses
756 written onto the shared array */
759 printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
760 /* treat as disagree, pass thru */
769 case TRANS_SOFT_ABORT:
775 if(transdisagree > 0) {
777 *(tdata->replyctrl) = TRANS_ABORT;
778 *(tdata->replyretry) = 0;
779 /* clear objects from prefetch cache */
780 for (i = 0; i < tdata->buffer->f.numread; i++)
781 prehashRemove(*((unsigned int *)(((char *)tdata->buffer->objread) + (sizeof(unsigned int) + sizeof(unsigned short))*i)));
782 for (i = 0; i < tdata->buffer->f.nummod; i++)
783 prehashRemove(tdata->buffer->oidmod[i]);
784 } else if(transagree == tdata->buffer->f.mcount){
786 *(tdata->replyctrl) = TRANS_COMMIT;
787 *(tdata->replyretry) = 0;
789 /* Send Abort in soft abort case followed by retry commiting transaction again*/
790 *(tdata->replyctrl) = TRANS_ABORT;
791 *(tdata->replyretry) = 1;
796 /* This function sends the final response to remote machines per thread in their respective socket id
797 * It returns a char that is only needed to check the correctness of execution of this function inside
799 char sendResponse(thread_data_array_t *tdata, int sd) {
800 int n, N, sum, oidcount = 0, control;
801 char *ptr, retval = 0;
802 unsigned int *oidnotfound;
804 /* If the decided response is due to a soft abort and missing objects at the Participant's side */
805 if(tdata->recvmsg[tdata->thread_id].rcv_status == TRANS_SOFT_ABORT) {
806 /* Read list of objects missing */
807 if((read(sd, &oidcount, sizeof(int)) != 0) && (oidcount != 0)) {
808 N = oidcount * sizeof(unsigned int);
809 if((oidnotfound = calloc(oidcount, sizeof(unsigned int))) == NULL) {
810 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
813 ptr = (char *) oidnotfound;
815 n = read(sd, ptr+sum, N-sum);
817 } while(sum < N && n !=0);
819 retval = TRANS_SOFT_ABORT;
821 /* If the decided response is TRANS_ABORT */
822 if(*(tdata->replyctrl) == TRANS_ABORT) {
823 retval = TRANS_ABORT;
824 } else if(*(tdata->replyctrl) == TRANS_COMMIT) { /* If the decided response is TRANS_COMMIT */
825 retval = TRANS_COMMIT;
828 if (send(sd, tdata->replyctrl, sizeof(char),MSG_NOSIGNAL) < sizeof(char)) {
829 perror("Error sending ctrl message for participant\n");
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;
844 struct hostent *server;
851 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
852 perror("Error in socket\n");
856 bzero((char*) &serv_addr, sizeof(serv_addr));
857 serv_addr.sin_family = AF_INET;
858 serv_addr.sin_port = htons(LISTEN_PORT);
859 midtoIP(mnum,machineip);
860 machineip[15] = '\0';
861 serv_addr.sin_addr.s_addr = inet_addr(machineip);
863 /* Open connection */
864 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
865 perror("Error in connect\n");
868 char readrequest[sizeof(char)+sizeof(unsigned int)];
869 readrequest[0] = READ_REQUEST;
870 *((unsigned int *)(&readrequest[1])) = oid;
871 if (send(sd, readrequest, sizeof(readrequest), MSG_NOSIGNAL) < sizeof(readrequest)) {
872 perror("Error sending message\n");
876 /* Read response from the Participant */
877 if((val = read(sd, &control, sizeof(char))) <= 0) {
878 perror("No control response for getRemoteObj sent\n");
882 case OBJECT_NOT_FOUND:
885 /* Read object if found into local cache */
886 if((val = read(sd, &size, sizeof(int))) <= 0) {
887 perror("No size is read from the participant\n");
890 objcopy = objstrAlloc(record->cache, size);
891 if((val = read(sd, (char *)objcopy, size)) <= 0) {
892 perror("No objects are read from the remote participant\n");
895 /* Insert into cache's lookup table */
896 chashInsert(record->lookupTable, oid, objcopy);
899 printf("Error in recv request from participant on a READ_REQUEST %s, %d\n",__FILE__, __LINE__);
902 /* Close connection */
907 /* This function handles the local objects involved in a transaction commiting process.
908 * It also makes a decision if this local machine sends AGREE or DISAGREE or SOFT_ABORT to coordinator.
909 * Note Coordinator = local machine
910 * It wakes up the other threads from remote participants that are waiting for the coordinator's decision and
911 * based on common agreement it either commits or aborts the transaction.
912 * It also frees the memory resources */
913 void *handleLocalReq(void *threadarg) {
914 unsigned int *oidnotfound = NULL, *oidlocked = NULL;
915 local_thread_data_array_t *localtdata;
916 int objnotfound = 0, objlocked = 0;
917 int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
920 unsigned short version;
922 objheader_t *headptr;
924 localtdata = (local_thread_data_array_t *) threadarg;
926 /* Counters and arrays to formulate decision on control message to be sent */
927 oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
928 oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
930 numread = localtdata->tdata->buffer->f.numread;
931 /* Process each oid in the machine pile/ group per thread */
932 for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) {
933 if (i < localtdata->tdata->buffer->f.numread) {
934 int incr = sizeof(unsigned int) + sizeof(short);// Offset that points to next position in the objread array
936 oid = *((unsigned int *)(((char *)localtdata->tdata->buffer->objread) + incr));
937 version = *((short *)(((char *)localtdata->tdata->buffer->objread) + incr + sizeof(unsigned int)));
938 } else { // Objects Modified
940 headptr = (objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidmod[i-numread]);
941 if (headptr == NULL) {
942 printf("Error: handleLocalReq() returning NULL %s, %d\n", __FILE__, __LINE__);
946 version = headptr->version;
948 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
950 /* Save the oids not found and number of oids not found for later use */
951 if ((mobj = mhashSearch(oid)) == NULL) { /* Obj not found */
952 /* Save the oids not found and number of oids not found for later use */
953 oidnotfound[objnotfound] = oid;
955 } else { /* If Obj found in machine (i.e. has not moved) */
956 /* Check if Obj is locked by any previous transaction */
957 if ((STATUS((objheader_t *)mobj) & LOCK) == LOCK) {
958 if (version == ((objheader_t *)mobj)->version) { /* If locked then match versions */
960 } else {/* If versions don't match ...HARD ABORT */
962 /* Send TRANS_DISAGREE to Coordinator */
963 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
965 } else {/* If Obj is not locked then lock object */
966 STATUS(((objheader_t *)mobj)) |= LOCK;
967 /* Save all object oids that are locked on this machine during this transaction request call */
968 oidlocked[objlocked] = OID(((objheader_t *)mobj));
970 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
972 } else { /* If versions don't match ...HARD ABORT */
974 /* Send TRANS_DISAGREE to Coordinator */
975 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
980 /* Condition to send TRANS_AGREE */
981 if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
982 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
984 /* Condition to send TRANS_SOFT_ABORT */
985 if((v_matchlock > 0 && v_nomatch == 0) || (objnotfound > 0 && v_nomatch == 0)) {
986 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
989 /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
990 * if Participant receives a TRANS_COMMIT */
991 localtdata->transinfo->objlocked = oidlocked;
992 localtdata->transinfo->objnotfound = oidnotfound;
993 localtdata->transinfo->modptr = NULL;
994 localtdata->transinfo->numlocked = objlocked;
995 localtdata->transinfo->numnotfound = objnotfound;
996 /* Lock and update count */
997 //Thread sleeps until all messages from pariticipants are received by coordinator
998 pthread_mutex_lock(localtdata->tdata->lock);
999 (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */
1001 /* Wake up the threads and invoke decideResponse (once) */
1002 if(*(localtdata->tdata->count) == localtdata->tdata->buffer->f.mcount) {
1003 decideResponse(localtdata->tdata);
1004 pthread_cond_broadcast(localtdata->tdata->threshold);
1006 pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock);
1008 pthread_mutex_unlock(localtdata->tdata->lock);
1009 if(*(localtdata->tdata->replyctrl) == TRANS_ABORT){
1010 if(transAbortProcess(localtdata) != 0) {
1011 printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
1014 } else if(*(localtdata->tdata->replyctrl) == TRANS_COMMIT) {
1015 if(transComProcess(localtdata) != 0) {
1016 printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
1021 if (localtdata->transinfo->objlocked != NULL) {
1022 free(localtdata->transinfo->objlocked);
1024 if (localtdata->transinfo->objnotfound != NULL) {
1025 free(localtdata->transinfo->objnotfound);
1031 /* This function completes the ABORT process if the transaction is aborting */
1032 int transAbortProcess(local_thread_data_array_t *localtdata) {
1034 unsigned int *objlocked;
1037 numlocked = localtdata->transinfo->numlocked;
1038 objlocked = localtdata->transinfo->objlocked;
1040 for (i = 0; i < numlocked; i++) {
1041 if((header = mhashSearch(objlocked[i])) == NULL) {
1042 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1045 STATUS(((objheader_t *)header)) &= ~(LOCK);
1051 /*This function completes the COMMIT process is the transaction is commiting*/
1052 int transComProcess(local_thread_data_array_t *localtdata) {
1053 objheader_t *header, *tcptr;
1054 int i, nummod, tmpsize, numcreated, numlocked;
1055 unsigned int *oidmod, *oidcreated, *oidlocked;
1058 nummod = localtdata->tdata->buffer->f.nummod;
1059 oidmod = localtdata->tdata->buffer->oidmod;
1060 numcreated = localtdata->tdata->buffer->f.numcreated;
1061 oidcreated = localtdata->tdata->buffer->oidcreated;
1062 numlocked = localtdata->transinfo->numlocked;
1063 oidlocked = localtdata->transinfo->objlocked;
1065 for (i = 0; i < nummod; i++) {
1066 if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
1067 printf("Error: transComProcess() mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1070 /* Copy from transaction cache -> main object store */
1071 if ((tcptr = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidmod[i]))) == NULL) {
1072 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1075 GETSIZE(tmpsize, header);
1076 pthread_mutex_lock(&mainobjstore_mutex);
1077 memcpy((char*)header+sizeof(objheader_t), (char *)tcptr+ sizeof(objheader_t), tmpsize);
1078 header->version += 1;
1079 if(header->notifylist != NULL) {
1080 notifyAll(&header->notifylist, OID(header), header->version);
1082 pthread_mutex_unlock(&mainobjstore_mutex);
1084 /* If object is newly created inside transaction then commit it */
1085 for (i = 0; i < numcreated; i++) {
1086 if ((header = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidcreated[i]))) == NULL) {
1087 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1090 GETSIZE(tmpsize, header);
1091 tmpsize += sizeof(objheader_t);
1092 pthread_mutex_lock(&mainobjstore_mutex);
1093 if ((ptrcreate = objstrAlloc(mainobjstore, tmpsize)) == NULL) {
1094 printf("Error: transComProcess() failed objstrAlloc %s, %d\n", __FILE__, __LINE__);
1095 pthread_mutex_unlock(&mainobjstore_mutex);
1098 pthread_mutex_unlock(&mainobjstore_mutex);
1099 memcpy(ptrcreate, header, tmpsize);
1100 mhashInsert(oidcreated[i], ptrcreate);
1101 lhashInsert(oidcreated[i], myIpAddr);
1103 /* Unlock locked objects */
1104 for(i = 0; i < numlocked; i++) {
1105 if((header = (objheader_t *) mhashSearch(oidlocked[i])) == NULL) {
1106 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1109 STATUS(header) &= ~(LOCK);
1115 /* This function checks if the prefetch oids are same and have same offsets
1116 * for case x.a.b and y.a.b where x and y have same oid's
1117 * or if a.b.c is a subset of x.b.c.d*/
1118 /* check for case where the generated request a.y.z or x.y.z.g then
1119 * prefetch needs to be generated for x.y.z.g if oid of a and x are same*/
1120 void checkPrefetchTuples(prefetchqelem_t *node) {
1121 int i,j, count,k, sindex, index;
1123 int ntuples, slength;
1125 short *endoffsets, *arryfields;
1127 /* Check for the case x.y.z and a.b.c are same oids */
1128 ptr = (char *) node;
1129 ntuples = *(GET_NTUPLES(ptr));
1130 oid = GET_PTR_OID(ptr);
1131 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1132 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1134 /* Find offset length for each tuple */
1135 int numoffset[ntuples];
1136 numoffset[0] = endoffsets[0];
1137 for(i = 1; i<ntuples; i++) {
1138 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1140 /* Check for redundant tuples by comparing oids of each tuple */
1141 for(i = 0; i < ntuples; i++) {
1144 for(j = i+1 ; j < ntuples; j++) {
1147 /*If oids of tuples match */
1148 if (oid[i] == oid[j]) {
1149 /* Find the smallest offset length of two tuples*/
1150 if(numoffset[i] > numoffset[j]){
1151 slength = numoffset[j];
1155 slength = numoffset[i];
1159 /* Compare the offset values based on the current indices
1160 * break if they do not match
1161 * if all offset values match then pick the largest tuple*/
1166 k = endoffsets[i-1];
1168 index = endoffsets[j -1];
1169 for(count = 0; count < slength; count ++) {
1170 if (arryfields[k] != arryfields[index]) {
1176 if(slength == count) {
1183 /* This function makes machine piles to be added into the machine pile queue for each prefetch call */
1184 prefetchpile_t *makePreGroups(prefetchqelem_t *node, int *numoffset) {
1186 int ntuples, i, machinenum, count=0;
1188 short *endoffsets, *arryfields, *offset;
1189 prefetchpile_t *head = NULL, *tmp = NULL;
1191 /* Check for the case x.y.z and a.b.c are same oids */
1192 ptr = (char *) node;
1193 ntuples = *(GET_NTUPLES(ptr));
1194 oid = GET_PTR_OID(ptr);
1195 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1196 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1198 if((head = (prefetchpile_t *) calloc(1, sizeof(prefetchpile_t))) == NULL) {
1199 printf("Calloc error: %s %d\n", __FILE__, __LINE__);
1203 /* Check for redundant tuples by comparing oids of each tuple */
1204 for(i = 0; i < ntuples; i++) {
1206 if(head->next != NULL) {
1207 if((tmp = (prefetchpile_t *) calloc(1, sizeof(prefetchpile_t))) == NULL) {
1208 printf("Calloc error: %s %d\n", __FILE__, __LINE__);
1211 tmp->mid = myIpAddr;
1215 head->mid = myIpAddr;
1219 /* For each tuple make piles */
1220 if ((machinenum = lhashSearch(oid[i])) == 0) {
1221 printf("Error: No such Machine %s, %d\n", __FILE__, __LINE__);
1224 /* Insert into machine pile */
1226 offset = &arryfields[0];
1228 offset = &arryfields[endoffsets[i-1]];
1231 if((head = insertPile(machinenum, oid[i], numoffset[i], offset, head)) == NULL){
1232 printf("Error: Couldn't create a pile %s, %d\n", __FILE__, __LINE__);
1240 prefetchpile_t *foundLocal(prefetchqelem_t *node) {
1241 int ntuples,i, j, k, oidnfound = 0, arryfieldindex,nextarryfieldindex, flag = 0, val;
1243 unsigned int objoid;
1246 objheader_t *objheader;
1247 short *endoffsets, *arryfields;
1248 prefetchpile_t *head = NULL;
1250 ptr = (char *) node;
1251 ntuples = *(GET_NTUPLES(ptr));
1252 oid = GET_PTR_OID(ptr);
1253 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1254 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1256 /* Find offset length for each tuple */
1257 int numoffset[ntuples];//Number of offsets for each tuple
1258 numoffset[0] = endoffsets[0];
1259 for(i = 1; i<ntuples; i++) {
1260 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1262 for(i = 0; i < ntuples; i++) {
1266 nextarryfieldindex = endoffsets[0];
1268 arryfieldindex = endoffsets[i-1];
1269 nextarryfieldindex = endoffsets[i];
1272 endoffsets[0] = val = numoffset[0];
1273 for(k = 1; k < ntuples; k++) {
1274 val = val + numoffset[k];
1275 endoffsets[k] = val;
1278 for(k = 0; k<endoffsets[ntuples-1]; k++) {
1279 arryfields[arryfieldindex+k] = arryfields[nextarryfieldindex+k];
1283 /* If object found locally */
1284 if((objheader = (objheader_t*) mhashSearch(oid[i])) != NULL) {
1285 tmp = (char *) objheader;
1286 int orgnumoffset = numoffset[i];
1290 arryfieldindex = endoffsets[i-1];
1293 for(j = 0; j<orgnumoffset; j++) {
1294 /* Check for arrays */
1295 if(TYPE(objheader) > NUMCLASSES) {
1299 int elementsize = classsize[TYPE(objheader)];
1300 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*arryfields[arryfieldindex])));
1302 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + arryfields[arryfieldindex]));
1304 //Update numoffset array
1305 numoffset[i] = numoffset[i] - 1;
1308 //Update endoffset array
1309 endoffsets[0] = val = numoffset[0];
1310 for(k = 1; k < ntuples; k++) {
1311 val = val + numoffset[k];
1312 endoffsets[k] = val;
1314 //Update arrayfields array
1315 for(k = 0; k < endoffsets[ntuples-1]; k++) {
1316 arryfields[arryfieldindex+k] = arryfields[arryfieldindex+k+1];
1318 if((objheader = (objheader_t*) mhashSearch(oid[i])) == NULL) {
1320 checkPreCache(node, numoffset, oid[i], i);
1323 tmp = (char *) objheader;
1326 /*If all offset oids are found locally,make the prefetch tuple invalid */
1331 /* Look in Prefetch cache */
1332 checkPreCache(node, numoffset, oid[i],i);
1336 /* Make machine groups */
1337 if((head = makePreGroups(node, numoffset)) == NULL) {
1338 printf("Error in makePreGroups() %s %d\n", __FILE__, __LINE__);
1345 void checkPreCache(prefetchqelem_t *node, int *numoffset, unsigned int objoid, int index) {
1347 int ntuples, i, k, flag=0, isArray =0, arryfieldindex, val;
1349 short *endoffsets, *arryfields;
1350 objheader_t *header;
1352 ptr = (char *) node;
1353 ntuples = *(GET_NTUPLES(ptr));
1354 oid = GET_PTR_OID(ptr);
1355 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1356 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1358 if((header = (objheader_t *) prehashSearch(objoid)) == NULL) {
1360 } else { //Found in Prefetch Cache
1361 //TODO Decide if object is too old, if old remove from cache
1362 tmp = (char *) header;
1363 int loopcount = numoffset[index];
1367 arryfieldindex = endoffsets[(index - 1)];
1368 // Check if any of the offset oid is available in the Prefetch cache
1369 for(i = 0; i < loopcount; i++) {
1370 /* Check for arrays */
1371 if(TYPE(header) > NUMCLASSES) {
1375 int elementsize = classsize[TYPE(header)];
1376 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*arryfields[arryfieldindex])));
1378 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + arryfields[arryfieldindex]));
1380 //Update numoffset array
1381 numoffset[index] = numoffset[index] - 1;
1383 oid[index] = objoid;
1384 //Update endoffset array
1385 endoffsets[0] = val = numoffset[0];
1386 for(k = 1; k < ntuples; k++) {
1387 val = val + numoffset[k];
1388 endoffsets[k] = val;
1390 //Update arrayfields array
1391 for(k = 0; k < endoffsets[ntuples-1]; k++) {
1392 arryfields[arryfieldindex+k] = arryfields[arryfieldindex+k+1];
1394 if((header = (objheader_t *)prehashSearch(oid[index])) != NULL) {
1395 tmp = (char *) header;
1403 //Found in the prefetch cache
1404 if(flag == 0 && (numoffset[index] == 0)) {
1411 /* This function is called by the thread calling transPrefetch */
1412 void *transPrefetch(void *t) {
1413 prefetchqelem_t *qnode;
1414 prefetchpile_t *pilehead = NULL;
1415 prefetchpile_t *ptr = NULL, *piletail = NULL;
1418 /* lock mutex of primary prefetch queue */
1419 pthread_mutex_lock(&pqueue.qlock);
1420 /* while primary queue is empty, then wait */
1421 while((pqueue.front == NULL) && (pqueue.rear == NULL)) {
1422 pthread_cond_wait(&pqueue.qcond, &pqueue.qlock);
1425 /* dequeue node to create a machine piles and finally unlock mutex */
1426 if((qnode = pre_dequeue()) == NULL) {
1427 printf("Error: No node returned %s, %d\n", __FILE__, __LINE__);
1428 pthread_mutex_unlock(&pqueue.qlock);
1431 pthread_mutex_unlock(&pqueue.qlock);
1433 /* Reduce redundant prefetch requests */
1434 checkPrefetchTuples(qnode);
1435 /* Check if the tuples are found locally, if yes then reduce them further*/
1436 /* and group requests by remote machine ids by calling the makePreGroups() */
1437 if((pilehead = foundLocal(qnode)) == NULL) {
1438 printf("Error: No node created for serving prefetch request %s %d\n", __FILE__, __LINE__);
1443 while(ptr != NULL) {
1444 if(ptr->next == NULL) {
1450 /* Lock mutex of pool queue */
1451 pthread_mutex_lock(&mcqueue.qlock);
1452 /* Update the pool queue with the new remote machine piles generated per prefetch call */
1453 mcpileenqueue(pilehead, piletail);
1454 /* Broadcast signal on machine pile queue */
1455 pthread_cond_broadcast(&mcqueue.qcond);
1456 /* Unlock mutex of machine pile queue */
1457 pthread_mutex_unlock(&mcqueue.qlock);
1458 /* Deallocate the prefetch queue pile node */
1463 /* Each thread in the pool of threads calls this function to establish connection with
1464 * remote machines, send the prefetch requests and process the reponses from
1465 * the remote machines .
1466 * The thread is active throughout the period of runtime */
1468 void *mcqProcess(void *threadid) {
1470 prefetchpile_t *mcpilenode;
1472 tid = (int) threadid;
1474 /* Lock mutex of mc pile queue */
1475 pthread_mutex_lock(&mcqueue.qlock);
1476 /* When mc pile queue is empty, wait */
1477 while((mcqueue.front == NULL) && (mcqueue.rear == NULL)) {
1478 pthread_cond_wait(&mcqueue.qcond, &mcqueue.qlock);
1480 /* Dequeue node to send remote machine connections*/
1481 if((mcpilenode = mcpiledequeue()) == NULL) {
1482 printf("Dequeue Error: No node returned %s %d\n", __FILE__, __LINE__);
1483 pthread_mutex_unlock(&mcqueue.qlock);
1487 pthread_mutex_unlock(&mcqueue.qlock);
1489 /*Initiate connection to remote host and send request */
1490 /* Process Request */
1491 if(mcpilenode->mid != myIpAddr)
1492 sendPrefetchReq(mcpilenode);
1494 /* Deallocate the machine queue pile node */
1495 mcdealloc(mcpilenode);
1499 void sendPrefetchReq(prefetchpile_t *mcpilenode) {
1500 int sd, i, off, len, endpair, count = 0;
1501 struct sockaddr_in serv_addr;
1502 struct hostent *server;
1503 char machineip[16], control;
1506 /* Send Trans Prefetch Request */
1507 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
1508 perror("Error in socket for SEND_PREFETCH_REQUEST\n");
1512 bzero((char*) &serv_addr, sizeof(serv_addr));
1513 serv_addr.sin_family = AF_INET;
1514 serv_addr.sin_port = htons(LISTEN_PORT);
1515 midtoIP(mcpilenode->mid ,machineip);
1516 machineip[15] = '\0';
1517 serv_addr.sin_addr.s_addr = inet_addr(machineip);
1519 /* Open Connection */
1520 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
1521 perror("Error in connect for SEND_PREFETCH_REQUEST\n");
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;
1543 //memcpy(oidnoffset, &len, sizeof(int));
1545 *((unsigned int *)((char *)oidnoffset + off)) = tmp->oid;
1546 //memcpy(oidnoffset + off, &tmp->oid, sizeof(unsigned int));
1547 off += sizeof(unsigned int);
1548 for(i = 0; i < tmp->numoffset; i++) {
1549 *((unsigned short*)((char *)oidnoffset + off)) = tmp->offset[i];
1550 //memcpy(oidnoffset + off, &(tmp->offset[i]), sizeof(short));
1551 off+=sizeof(unsigned short);
1554 if (send(sd, oidnoffset, len , MSG_NOSIGNAL) < len) {
1555 perror("Error sending fixed bytes for thread\n");
1563 /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
1565 if (send(sd, &endpair, sizeof(int), MSG_NOSIGNAL) < sizeof(int)) {
1566 perror("Error sending fixed bytes for thread\n");
1571 /* Get Response from the remote machine */
1572 getPrefetchResponse(count,sd);
1577 void getPrefetchResponse(int count, int sd) {
1578 int i = 0, val, n, N, sum, index, objsize;
1579 unsigned int bufsize,oid;
1580 char buffer[RECEIVE_BUFFER_SIZE], control;
1582 void *modptr, *oldptr;
1584 /* Read prefetch response from the Remote machine */
1585 if((val = read(sd, &control, sizeof(char))) <= 0) {
1586 perror("No control response for Prefetch request sent\n");
1590 if(control == TRANS_PREFETCH_RESPONSE) {
1591 /*For each oid and offset tuple sent as prefetch request to remote machine*/
1595 /* Read the size of buffer to be received */
1596 if((N = read(sd, buffer, sizeof(unsigned int))) <= 0) {
1597 perror("Size of buffer not recv\n");
1600 bufsize = *((unsigned int *) buffer);
1601 ptr = buffer + sizeof(unsigned int);
1602 /* Keep receiving the buffer containing oid info */
1604 n = recv((int)sd, (void *)ptr+sum, bufsize-sum, 0);
1606 } while(sum < bufsize && n != 0);
1608 /* Decode the contents of the buffer */
1609 index = sizeof(unsigned int);
1610 while(index < (bufsize - sizeof(unsigned int))) {
1611 if(buffer[index] == OBJECT_FOUND) {
1612 /* Increment it to get the object */
1613 index += sizeof(char);
1614 oid = *((unsigned int *)(buffer+index));
1615 index += sizeof(unsigned int);
1616 /* For each object found add to Prefetch Cache */
1617 objsize = *((int *)(buffer+index));
1619 pthread_mutex_lock(&prefetchcache_mutex);
1620 if ((modptr = objstrAlloc(prefetchcache, objsize)) == NULL) {
1621 printf("Error: objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
1622 pthread_mutex_unlock(&prefetchcache_mutex);
1625 pthread_mutex_unlock(&prefetchcache_mutex);
1626 memcpy(modptr, buffer+index, objsize);
1628 /* Insert the oid and its address into the prefetch hash lookup table */
1629 /* Do a version comparison if the oid exists */
1630 if((oldptr = prehashSearch(oid)) != NULL) {
1631 /* If older version then update with new object ptr */
1632 if(((objheader_t *)oldptr)->version < ((objheader_t *)modptr)->version) {
1634 prehashInsert(oid, modptr);
1635 } else if(((objheader_t *)oldptr)->version == ((objheader_t *)modptr)->version) {
1636 /* Add the new object ptr to hash table */
1638 prehashInsert(oid, modptr);
1639 } else { /* Do nothing: TODO modptr should be reference counted */
1642 } else {/*If doesn't no match found in hashtable, add the object ptr to hash table*/
1643 prehashInsert(oid, modptr);
1645 /* Lock the Prefetch Cache look up table*/
1646 pthread_mutex_lock(&pflookup.lock);
1647 /* Broadcast signal on prefetch cache condition variable */
1648 pthread_cond_broadcast(&pflookup.cond);
1649 /* Unlock the Prefetch Cache look up table*/
1650 pthread_mutex_unlock(&pflookup.lock);
1651 } else if(buffer[index] == OBJECT_NOT_FOUND) {
1652 /* Increment it to get the object */
1653 /* TODO: For each object not found query DHT for new location and retrieve the object */
1654 index += sizeof(char);
1655 oid = *((unsigned int *)(buffer + index));
1656 index += sizeof(unsigned int);
1657 /* Throw an error */
1658 printf("OBJECT NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n");
1661 printf("Error in decoding the index value %s, %d\n",__FILE__, __LINE__);
1669 printf("Error in receving response for prefetch request %s, %d\n",__FILE__, __LINE__);
1673 unsigned short getObjType(unsigned int oid)
1675 objheader_t *objheader;
1676 unsigned short numoffset[] ={0};
1677 short fieldoffset[] ={};
1679 if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL)
1681 if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1683 prefetch(1, &oid, numoffset, fieldoffset);
1684 pthread_mutex_lock(&pflookup.lock);
1685 while ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1687 pthread_cond_wait(&pflookup.cond, &pflookup.lock);
1689 pthread_mutex_unlock(&pflookup.lock);
1693 return TYPE(objheader);
1696 int startRemoteThread(unsigned int oid, unsigned int mid)
1699 struct sockaddr_in remoteAddr;
1700 char msg[1 + sizeof(unsigned int)];
1704 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
1706 perror("startRemoteThread():socket()");
1710 bzero(&remoteAddr, sizeof(remoteAddr));
1711 remoteAddr.sin_family = AF_INET;
1712 remoteAddr.sin_port = htons(LISTEN_PORT);
1713 remoteAddr.sin_addr.s_addr = htonl(mid);
1715 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0)
1717 printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
1718 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1723 msg[0] = START_REMOTE_THREAD;
1724 memcpy(&msg[1], &oid, sizeof(unsigned int));
1726 bytesSent = send(sock, msg, 1 + sizeof(unsigned int), 0);
1729 perror("startRemoteThread():send()");
1732 else if (bytesSent != 1 + sizeof(unsigned int))
1734 printf("startRemoteThread(): error, sent %d bytes\n", bytesSent);
1747 //TODO: when reusing oids, make sure they are not already in use!
1748 unsigned int getNewOID(void) {
1749 static unsigned int id = 0xFFFFFFFF;
1752 if (id > oidMax || id < oidMin)
1759 int processConfigFile()
1762 const int maxLineLength = 200;
1763 char lineBuffer[maxLineLength];
1765 const char *delimiters = " \t\n";
1769 configFile = fopen(CONFIG_FILENAME, "r");
1770 if (configFile == NULL)
1772 printf("error opening %s:\n", CONFIG_FILENAME);
1777 numHostsInSystem = 0;
1778 sizeOfHostArray = 8;
1779 hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
1781 while(fgets(lineBuffer, maxLineLength, configFile) != NULL)
1783 commentBegin = strchr(lineBuffer, '#');
1784 if (commentBegin != NULL)
1785 *commentBegin = '\0';
1786 token = strtok(lineBuffer, delimiters);
1787 while (token != NULL)
1789 tmpAddr = inet_addr(token);
1790 if ((int)tmpAddr == -1)
1792 printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
1797 addHost(htonl(tmpAddr));
1798 token = strtok(NULL, delimiters);
1804 if (numHostsInSystem < 1)
1806 printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
1810 myIpAddr = getMyIpAddr("en1");
1812 myIpAddr = getMyIpAddr("eth0");
1814 myIndexInHostArray = findHost(myIpAddr);
1815 if (myIndexInHostArray == -1)
1817 printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
1820 oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
1821 oidMin = oidsPerBlock * myIndexInHostArray;
1822 if (myIndexInHostArray == numHostsInSystem - 1)
1823 oidMax = 0xFFFFFFFF;
1825 oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
1830 void addHost(unsigned int hostIp)
1832 unsigned int *tmpArray;
1834 if (findHost(hostIp) != -1)
1837 if (numHostsInSystem == sizeOfHostArray)
1839 tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
1840 memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
1842 hostIpAddrs = tmpArray;
1845 hostIpAddrs[numHostsInSystem++] = hostIp;
1850 int findHost(unsigned int hostIp)
1853 for (i = 0; i < numHostsInSystem; i++)
1854 if (hostIpAddrs[i] == hostIp)
1861 /* This function sends notification request per thread waiting on object(s) whose version
1863 int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int numoid) {
1865 objheader_t *objheader;
1866 struct sockaddr_in remoteAddr;
1867 char msg[1 + numoid * (sizeof(short) + sizeof(unsigned int)) + 3 * sizeof(unsigned int)];
1871 unsigned short version;
1872 unsigned int oid,mid;
1873 static unsigned int threadid = 0;
1874 pthread_mutex_t threadnotify = PTHREAD_MUTEX_INITIALIZER; //Lock and condition var for threadjoin and notification
1875 pthread_cond_t threadcond = PTHREAD_COND_INITIALIZER;
1876 notifydata_t *ndata;
1878 //FIXME currently all oids belong to one machine
1880 mid = lhashSearch(oid);
1882 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1883 perror("reqNotify():socket()");
1887 bzero(&remoteAddr, sizeof(remoteAddr));
1888 remoteAddr.sin_family = AF_INET;
1889 remoteAddr.sin_port = htons(LISTEN_PORT);
1890 remoteAddr.sin_addr.s_addr = htonl(mid);
1892 /* Generate unique threadid */
1895 /* Save threadid, numoid, oidarray, versionarray, pthread_cond_variable for later processing */
1896 if((ndata = calloc(1, sizeof(notifydata_t))) == NULL) {
1897 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
1900 ndata->numoid = numoid;
1901 ndata->threadid = threadid;
1902 ndata->oidarry = oidarry;
1903 ndata->versionarry = versionarry;
1904 ndata->threadcond = threadcond;
1905 ndata->threadnotify = threadnotify;
1906 if((status = notifyhashInsert(threadid, ndata)) != 0) {
1907 printf("reqNotify(): Insert into notify hash table not successful %s, %d\n", __FILE__, __LINE__);
1912 /* Send number of oids, oidarry, version array, machine id and threadid */
1913 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1914 printf("reqNotify():error %d connecting to %s:%d\n", errno,
1915 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1919 msg[0] = THREAD_NOTIFY_REQUEST;
1920 *((unsigned int *)(&msg[1])) = numoid;
1921 /* Send array of oids */
1922 size = sizeof(unsigned int);
1927 *((unsigned int *)(&msg[1] + size)) = oid;
1928 size += sizeof(unsigned int);
1933 /* Send array of version */
1937 version = versionarry[i];
1938 *((unsigned short *)(&msg[1] + size)) = version;
1939 size += sizeof(unsigned short);
1944 *((unsigned int *)(&msg[1] + size)) = myIpAddr;
1945 size += sizeof(unsigned int);
1946 *((unsigned int *)(&msg[1] + size)) = threadid;
1948 pthread_mutex_lock(&(ndata->threadnotify));
1949 bytesSent = send(sock, msg, 1 + numoid * (sizeof(unsigned int) + sizeof(unsigned short)) + 3 * sizeof(unsigned int) , 0);
1951 perror("reqNotify():send()");
1953 } else if (bytesSent != 1 + numoid*(sizeof(unsigned int) + sizeof(unsigned short)) + 3 * sizeof(unsigned int)){
1954 printf("reNotify(): error, sent %d bytes %s, %d\n", bytesSent, __FILE__, __LINE__);
1960 pthread_cond_wait(&(ndata->threadcond), &(ndata->threadnotify));
1961 pthread_mutex_unlock(&(ndata->threadnotify));
1964 pthread_cond_destroy(&threadcond);
1965 pthread_mutex_destroy(&threadnotify);
1971 void threadNotify(unsigned int oid, unsigned short version, unsigned int tid) {
1972 notifydata_t *ndata;
1973 int i, objIsFound = 0, index;
1976 //Look up the tid and call the corresponding pthread_cond_signal
1977 if((ndata = notifyhashSearch(tid)) == NULL) {
1978 printf("threadnotify(): No such threadid is present %s, %d\n", __FILE__, __LINE__);
1981 for(i = 0; i < ndata->numoid; i++) {
1982 if(ndata->oidarry[i] == oid){
1987 if(objIsFound == 0){
1988 printf("threadNotify(): Oid not found %s, %d\n", __FILE__, __LINE__);
1991 if(version <= ndata->versionarry[index]){
1992 printf("threadNotify(): New version %d has not changed since last version %s, %d\n", version, __FILE__, __LINE__);
1995 /* Clear from prefetch cache and free thread related data structure */
1996 if((ptr = prehashSearch(oid)) != NULL) {
1999 pthread_cond_signal(&(ndata->threadcond));
2006 int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) {
2009 struct sockaddr_in remoteAddr;
2010 char msg[1 + sizeof(unsigned short) + 2*sizeof(unsigned int)];
2011 int sock, status, size, bytesSent;
2013 while(*head != NULL) {
2016 //create a socket connection to that machine
2017 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
2018 perror("notifyAll():socket()");
2022 bzero(&remoteAddr, sizeof(remoteAddr));
2023 remoteAddr.sin_family = AF_INET;
2024 remoteAddr.sin_port = htons(LISTEN_PORT);
2025 remoteAddr.sin_addr.s_addr = htonl(mid);
2026 //send Thread Notify response and threadid to that machine
2027 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
2028 printf("notifyAll():error %d connecting to %s:%d\n", errno,
2029 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
2032 bzero(msg, (1+sizeof(unsigned short) + 2*sizeof(unsigned int)));
2033 msg[0] = THREAD_NOTIFY_RESPONSE;
2034 *((unsigned int *)&msg[1]) = oid;
2035 size = sizeof(unsigned int);
2036 *((unsigned short *)(&msg[1]+ size)) = version;
2037 size+= sizeof(unsigned short);
2038 *((unsigned int *)(&msg[1]+ size)) = ptr->threadid;
2040 bytesSent = send(sock, msg, (1 + 2*sizeof(unsigned int) + sizeof(unsigned short)), 0);
2042 perror("notifyAll():send()");
2044 } else if (bytesSent != 1 + 2*sizeof(unsigned int) + sizeof(unsigned short)){
2045 printf("notifyAll(): error, sent %d bytes %s, %d\n",
2046 bytesSent, __FILE__, __LINE__);
2061 void transAbort(transrecord_t *trans) {
2062 objstrDelete(trans->cache);
2063 chashDelete(trans->lookupTable);