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 */
441 /* Look through all the objects in the transaction record and make piles
442 * for each machine involved in the transaction*/
443 pile_ptr = pile = createPiles(record);
445 /* Create the packet to be sent in TRANS_REQUEST */
447 /* Count the number of participants */
448 pilecount = pCount(pile);
450 /* Create a list of machine ids(Participants) involved in transaction */
451 if((listmid = calloc(pilecount, sizeof(unsigned int))) == NULL) {
452 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
455 pListMid(pile, listmid);
458 /* Initialize thread variables,
459 * Spawn a thread for each Participant involved in a transaction */
460 pthread_t thread[pilecount];
462 pthread_cond_t tcond;
463 pthread_mutex_t tlock;
464 pthread_mutex_t tlshrd;
466 thread_data_array_t *thread_data_array;
467 if((thread_data_array = (thread_data_array_t *) calloc(pilecount, sizeof(thread_data_array_t))) == NULL) {
468 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
469 pthread_cond_destroy(&tcond);
470 pthread_mutex_destroy(&tlock);
476 local_thread_data_array_t *ltdata;
477 if((ltdata = calloc(1, sizeof(local_thread_data_array_t))) == NULL) {
478 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
479 pthread_cond_destroy(&tcond);
480 pthread_mutex_destroy(&tlock);
483 free(thread_data_array);
487 thread_response_t rcvd_control_msg[pilecount]; /* Shared thread array that keeps track of responses of participants */
489 /* Initialize and set thread detach attribute */
490 pthread_attr_init(&attr);
491 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
492 pthread_mutex_init(&tlock, NULL);
493 pthread_cond_init(&tcond, NULL);
495 /* Process each machine pile */
496 while(pile != NULL) {
497 //Create transaction id
499 if ((tosend = calloc(1, sizeof(trans_req_data_t))) == NULL) {
500 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
501 pthread_cond_destroy(&tcond);
502 pthread_mutex_destroy(&tlock);
505 free(thread_data_array);
509 tosend->f.control = TRANS_REQUEST;
510 sprintf(tosend->f.trans_id, "%x_%d", pile->mid, newtid);
511 tosend->f.mcount = pilecount;
512 tosend->f.numread = pile->numread;
513 tosend->f.nummod = pile->nummod;
514 tosend->f.numcreated = pile->numcreated;
515 tosend->f.sum_bytes = pile->sum_bytes;
516 tosend->listmid = listmid;
517 tosend->objread = pile->objread;
518 tosend->oidmod = pile->oidmod;
519 tosend->oidcreated = pile->oidcreated;
520 thread_data_array[threadnum].thread_id = threadnum;
521 thread_data_array[threadnum].mid = pile->mid;
522 thread_data_array[threadnum].buffer = tosend;
523 thread_data_array[threadnum].recvmsg = rcvd_control_msg;
524 thread_data_array[threadnum].threshold = &tcond;
525 thread_data_array[threadnum].lock = &tlock;
526 thread_data_array[threadnum].count = &trecvcount;
527 thread_data_array[threadnum].replyctrl = &treplyctrl;
528 thread_data_array[threadnum].replyretry = &treplyretry;
529 thread_data_array[threadnum].rec = record;
530 /* If local do not create any extra connection */
531 if(pile->mid != myIpAddr) { /* Not local */
533 rc = pthread_create(&thread[threadnum], &attr, transRequest, (void *) &thread_data_array[threadnum]);
536 perror("Error in pthread create\n");
537 pthread_cond_destroy(&tcond);
538 pthread_mutex_destroy(&tlock);
541 for (i = 0; i < threadnum; i++)
542 free(thread_data_array[i].buffer);
543 free(thread_data_array);
548 ltdata->tdata = &thread_data_array[threadnum];
549 ltdata->transinfo = &transinfo;
551 val = pthread_create(&thread[threadnum], &attr, handleLocalReq, (void *) ltdata);
554 perror("Error in pthread create\n");
555 pthread_cond_destroy(&tcond);
556 pthread_mutex_destroy(&tlock);
559 for (i = 0; i < threadnum; i++)
560 free(thread_data_array[i].buffer);
561 free(thread_data_array);
571 /* Free attribute and wait for the other threads */
572 pthread_attr_destroy(&attr);
574 for (i = 0; i < threadnum; i++) {
575 rc = pthread_join(thread[i], NULL);
578 printf("Error: return code from pthread_join() is %d\n", rc);
579 pthread_cond_destroy(&tcond);
580 pthread_mutex_destroy(&tlock);
583 for (j = i; j < threadnum; j++) {
584 free(thread_data_array[j].buffer);
588 free(thread_data_array[i].buffer);
592 pthread_cond_destroy(&tcond);
593 pthread_mutex_destroy(&tlock);
598 if(treplyctrl == TRANS_ABORT) {
600 objstrDelete(record->cache);
601 chashDelete(record->lookupTable);
603 free(thread_data_array);
606 } else if(treplyctrl == TRANS_COMMIT) {
608 objstrDelete(record->cache);
609 chashDelete(record->lookupTable);
611 free(thread_data_array);
615 //TODO Add other cases
616 printf("DEBUG-> THIS SHOULD NOT HAPPEN.....EXIT PROGRAM\n");
623 /* This function sends information involved in the transaction request
624 * to participants and accepts a response from particpants.
625 * It calls decideresponse() to decide on what control message
626 * to send next to participants and sends the message using sendResponse()*/
627 void *transRequest(void *threadarg) {
629 struct sockaddr_in serv_addr;
630 struct hostent *server;
631 thread_data_array_t *tdata;
632 objheader_t *headeraddr;
633 char buffer[RECEIVE_BUFFER_SIZE], control, recvcontrol;
634 char machineip[16], retval;
637 tdata = (thread_data_array_t *) threadarg;
639 /* Send Trans Request */
640 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
641 perror("Error in socket for TRANS_REQUEST\n");
644 bzero((char*) &serv_addr, sizeof(serv_addr));
645 serv_addr.sin_family = AF_INET;
646 serv_addr.sin_port = htons(LISTEN_PORT);
647 midtoIP(tdata->mid,machineip);
648 machineip[15] = '\0';
649 serv_addr.sin_addr.s_addr = inet_addr(machineip);
650 /* Open Connection */
651 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
652 perror("Error in connect for TRANS_REQUEST\n");
657 /* Send bytes of data with TRANS_REQUEST control message */
658 if (send(sd, &(tdata->buffer->f), sizeof(fixed_data_t),MSG_NOSIGNAL) < sizeof(fixed_data_t)) {
659 perror("Error sending fixed bytes for thread\n");
663 /* Send list of machines involved in the transaction */
665 int size=sizeof(unsigned int)*tdata->buffer->f.mcount;
666 if (send(sd, tdata->buffer->listmid, size, MSG_NOSIGNAL) < size) {
667 perror("Error sending list of machines for thread\n");
672 /* Send oids and version number tuples for objects that are read */
674 int size=(sizeof(unsigned int)+sizeof(short))*tdata->buffer->f.numread;
675 if (send(sd, tdata->buffer->objread, size, MSG_NOSIGNAL) < size) {
676 perror("Error sending tuples for thread\n");
681 /* Send objects that are modified */
682 for(i = 0; i < tdata->buffer->f.nummod ; i++) {
684 headeraddr = chashSearch(tdata->rec->lookupTable, tdata->buffer->oidmod[i]);
685 GETSIZE(size,headeraddr);
686 size+=sizeof(objheader_t);
687 if (send(sd, headeraddr, size, MSG_NOSIGNAL) < size) {
688 perror("Error sending obj modified for thread\n");
694 /* Read control message from Participant */
695 if((n = read(sd, &control, sizeof(char))) <= 0) {
696 perror("Error in reading control message from Participant\n");
701 recvcontrol = control;
703 /* Update common data structure and increment count */
704 tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol;
706 /* Lock and update count */
707 /* Thread sleeps until all messages from pariticipants are received by coordinator */
708 pthread_mutex_lock(tdata->lock);
710 (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */
712 /* Wake up the threads and invoke decideResponse (once) */
713 if(*(tdata->count) == tdata->buffer->f.mcount) {
714 decideResponse(tdata);
715 pthread_cond_broadcast(tdata->threshold);
717 pthread_cond_wait(tdata->threshold, tdata->lock);
719 pthread_mutex_unlock(tdata->lock);
721 /* Send the final response such as TRANS_COMMIT or TRANS_ABORT t
722 * to all participants in their respective socket */
723 if (sendResponse(tdata, sd) == 0) {
724 printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__);
729 if ((retval = recv((int)sd, &control, sizeof(char), 0))<= 0) {
730 printf("Error: In receiving control %s,%d\n", __FILE__, __LINE__);
735 if(control == TRANS_UNSUCESSFUL) {
736 //printf("DEBUG-> TRANS_ABORTED\n");
737 } else if(control == TRANS_SUCESSFUL) {
738 //printf("DEBUG-> TRANS_SUCCESSFUL\n");
740 //printf("DEBUG-> Error: Incorrect Transaction End Message %d\n", control);
743 /* Close connection */
748 /* This function decides the reponse that needs to be sent to
749 * all Participant machines after the TRANS_REQUEST protocol */
750 void decideResponse(thread_data_array_t *tdata) {
752 int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
755 for (i = 0 ; i < tdata->buffer->f.mcount; i++) {
756 control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses
757 written onto the shared array */
760 printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
761 /* treat as disagree, pass thru */
770 case TRANS_SOFT_ABORT:
776 if(transdisagree > 0) {
778 *(tdata->replyctrl) = TRANS_ABORT;
779 *(tdata->replyretry) = 0;
780 /* clear objects from prefetch cache */
781 for (i = 0; i < tdata->buffer->f.numread; i++)
782 prehashRemove(*((unsigned int *)(((char *)tdata->buffer->objread) + (sizeof(unsigned int) + sizeof(unsigned short))*i)));
783 for (i = 0; i < tdata->buffer->f.nummod; i++)
784 prehashRemove(tdata->buffer->oidmod[i]);
785 } else if(transagree == tdata->buffer->f.mcount){
787 *(tdata->replyctrl) = TRANS_COMMIT;
788 *(tdata->replyretry) = 0;
790 /* Send Abort in soft abort case followed by retry commiting transaction again*/
791 *(tdata->replyctrl) = TRANS_ABORT;
792 *(tdata->replyretry) = 1;
797 /* This function sends the final response to remote machines per thread in their respective socket id
798 * It returns a char that is only needed to check the correctness of execution of this function inside
800 char sendResponse(thread_data_array_t *tdata, int sd) {
801 int n, N, sum, oidcount = 0, control;
802 char *ptr, retval = 0;
803 unsigned int *oidnotfound;
805 /* If the decided response is due to a soft abort and missing objects at the Participant's side */
806 if(tdata->recvmsg[tdata->thread_id].rcv_status == TRANS_SOFT_ABORT) {
807 /* Read list of objects missing */
808 if((read(sd, &oidcount, sizeof(int)) != 0) && (oidcount != 0)) {
809 N = oidcount * sizeof(unsigned int);
810 if((oidnotfound = calloc(oidcount, sizeof(unsigned int))) == NULL) {
811 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
814 ptr = (char *) oidnotfound;
816 n = read(sd, ptr+sum, N-sum);
818 } while(sum < N && n !=0);
820 retval = TRANS_SOFT_ABORT;
822 /* If the decided response is TRANS_ABORT */
823 if(*(tdata->replyctrl) == TRANS_ABORT) {
824 retval = TRANS_ABORT;
825 } else if(*(tdata->replyctrl) == TRANS_COMMIT) { /* If the decided response is TRANS_COMMIT */
826 retval = TRANS_COMMIT;
829 if (send(sd, tdata->replyctrl, sizeof(char),MSG_NOSIGNAL) < sizeof(char)) {
830 perror("Error sending ctrl message for participant\n");
837 /* This function opens a connection, places an object read request to the
838 * remote machine, reads the control message and object if available and
839 * copies the object and its header to the local cache.
842 void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
844 struct sockaddr_in serv_addr;
845 struct hostent *server;
852 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
853 perror("Error in socket\n");
857 bzero((char*) &serv_addr, sizeof(serv_addr));
858 serv_addr.sin_family = AF_INET;
859 serv_addr.sin_port = htons(LISTEN_PORT);
860 midtoIP(mnum,machineip);
861 machineip[15] = '\0';
862 serv_addr.sin_addr.s_addr = inet_addr(machineip);
864 /* Open connection */
865 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
866 perror("getRemoteObj() Error in connect\n");
869 char readrequest[sizeof(char)+sizeof(unsigned int)];
870 readrequest[0] = READ_REQUEST;
871 *((unsigned int *)(&readrequest[1])) = oid;
872 if (send(sd, readrequest, sizeof(readrequest), MSG_NOSIGNAL) < sizeof(readrequest)) {
873 perror("Error sending message\n");
877 /* Read response from the Participant */
878 if((val = read(sd, &control, sizeof(char))) <= 0) {
879 perror("No control response for getRemoteObj sent\n");
883 case OBJECT_NOT_FOUND:
886 /* Read object if found into local cache */
887 if((val = read(sd, &size, sizeof(int))) <= 0) {
888 perror("No size is read from the participant\n");
891 objcopy = objstrAlloc(record->cache, size);
892 if((val = read(sd, (char *)objcopy, size)) <= 0) {
893 perror("No objects are read from the remote participant\n");
896 /* Insert into cache's lookup table */
897 chashInsert(record->lookupTable, oid, objcopy);
900 printf("Error in recv request from participant on a READ_REQUEST %s, %d\n",__FILE__, __LINE__);
903 /* Close connection */
908 /* This function handles the local objects involved in a transaction commiting process.
909 * It also makes a decision if this local machine sends AGREE or DISAGREE or SOFT_ABORT to coordinator.
910 * Note Coordinator = local machine
911 * It wakes up the other threads from remote participants that are waiting for the coordinator's decision and
912 * based on common agreement it either commits or aborts the transaction.
913 * It also frees the memory resources */
914 void *handleLocalReq(void *threadarg) {
915 unsigned int *oidnotfound = NULL, *oidlocked = NULL;
916 local_thread_data_array_t *localtdata;
917 int objnotfound = 0, objlocked = 0;
918 int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
921 unsigned short version;
923 objheader_t *headptr;
925 localtdata = (local_thread_data_array_t *) threadarg;
927 /* Counters and arrays to formulate decision on control message to be sent */
928 oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
929 oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
931 numread = localtdata->tdata->buffer->f.numread;
932 /* Process each oid in the machine pile/ group per thread */
933 for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) {
934 if (i < localtdata->tdata->buffer->f.numread) {
935 int incr = sizeof(unsigned int) + sizeof(short);// Offset that points to next position in the objread array
937 oid = *((unsigned int *)(((char *)localtdata->tdata->buffer->objread) + incr));
938 version = *((short *)(((char *)localtdata->tdata->buffer->objread) + incr + sizeof(unsigned int)));
939 } else { // Objects Modified
941 headptr = (objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidmod[i-numread]);
942 if (headptr == NULL) {
943 printf("Error: handleLocalReq() returning NULL %s, %d\n", __FILE__, __LINE__);
947 version = headptr->version;
949 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
951 /* Save the oids not found and number of oids not found for later use */
952 if ((mobj = mhashSearch(oid)) == NULL) { /* Obj not found */
953 /* Save the oids not found and number of oids not found for later use */
954 oidnotfound[objnotfound] = oid;
956 } else { /* If Obj found in machine (i.e. has not moved) */
957 /* Check if Obj is locked by any previous transaction */
958 if ((STATUS((objheader_t *)mobj) & LOCK) == LOCK) {
959 if (version == ((objheader_t *)mobj)->version) { /* If locked then match versions */
961 } else {/* If versions don't match ...HARD ABORT */
963 /* Send TRANS_DISAGREE to Coordinator */
964 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
966 } else {/* If Obj is not locked then lock object */
967 STATUS(((objheader_t *)mobj)) |= LOCK;
968 /* Save all object oids that are locked on this machine during this transaction request call */
969 oidlocked[objlocked] = OID(((objheader_t *)mobj));
971 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
973 } else { /* If versions don't match ...HARD ABORT */
975 /* Send TRANS_DISAGREE to Coordinator */
976 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
981 /* Condition to send TRANS_AGREE */
982 if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
983 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
985 /* Condition to send TRANS_SOFT_ABORT */
986 if((v_matchlock > 0 && v_nomatch == 0) || (objnotfound > 0 && v_nomatch == 0)) {
987 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
990 /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
991 * if Participant receives a TRANS_COMMIT */
992 localtdata->transinfo->objlocked = oidlocked;
993 localtdata->transinfo->objnotfound = oidnotfound;
994 localtdata->transinfo->modptr = NULL;
995 localtdata->transinfo->numlocked = objlocked;
996 localtdata->transinfo->numnotfound = objnotfound;
997 /* Lock and update count */
998 //Thread sleeps until all messages from pariticipants are received by coordinator
999 pthread_mutex_lock(localtdata->tdata->lock);
1000 (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */
1002 /* Wake up the threads and invoke decideResponse (once) */
1003 if(*(localtdata->tdata->count) == localtdata->tdata->buffer->f.mcount) {
1004 decideResponse(localtdata->tdata);
1005 pthread_cond_broadcast(localtdata->tdata->threshold);
1007 pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock);
1009 pthread_mutex_unlock(localtdata->tdata->lock);
1010 if(*(localtdata->tdata->replyctrl) == TRANS_ABORT){
1011 if(transAbortProcess(localtdata) != 0) {
1012 printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
1015 } else if(*(localtdata->tdata->replyctrl) == TRANS_COMMIT) {
1016 if(transComProcess(localtdata) != 0) {
1017 printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
1022 if (localtdata->transinfo->objlocked != NULL) {
1023 free(localtdata->transinfo->objlocked);
1025 if (localtdata->transinfo->objnotfound != NULL) {
1026 free(localtdata->transinfo->objnotfound);
1032 /* This function completes the ABORT process if the transaction is aborting */
1033 int transAbortProcess(local_thread_data_array_t *localtdata) {
1035 unsigned int *objlocked;
1038 numlocked = localtdata->transinfo->numlocked;
1039 objlocked = localtdata->transinfo->objlocked;
1041 for (i = 0; i < numlocked; i++) {
1042 if((header = mhashSearch(objlocked[i])) == NULL) {
1043 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1046 STATUS(((objheader_t *)header)) &= ~(LOCK);
1052 /*This function completes the COMMIT process is the transaction is commiting*/
1053 int transComProcess(local_thread_data_array_t *localtdata) {
1054 objheader_t *header, *tcptr;
1055 int i, nummod, tmpsize, numcreated, numlocked;
1056 unsigned int *oidmod, *oidcreated, *oidlocked;
1059 nummod = localtdata->tdata->buffer->f.nummod;
1060 oidmod = localtdata->tdata->buffer->oidmod;
1061 numcreated = localtdata->tdata->buffer->f.numcreated;
1062 oidcreated = localtdata->tdata->buffer->oidcreated;
1063 numlocked = localtdata->transinfo->numlocked;
1064 oidlocked = localtdata->transinfo->objlocked;
1066 for (i = 0; i < nummod; i++) {
1067 if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
1068 printf("Error: transComProcess() mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1071 /* Copy from transaction cache -> main object store */
1072 if ((tcptr = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidmod[i]))) == NULL) {
1073 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1076 GETSIZE(tmpsize, header);
1077 pthread_mutex_lock(&mainobjstore_mutex);
1078 memcpy((char*)header+sizeof(objheader_t), (char *)tcptr+ sizeof(objheader_t), tmpsize);
1079 header->version += 1;
1080 if(header->notifylist != NULL) {
1081 notifyAll(&header->notifylist, OID(header), header->version);
1083 pthread_mutex_unlock(&mainobjstore_mutex);
1085 /* If object is newly created inside transaction then commit it */
1086 for (i = 0; i < numcreated; i++) {
1087 if ((header = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidcreated[i]))) == NULL) {
1088 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1091 GETSIZE(tmpsize, header);
1092 tmpsize += sizeof(objheader_t);
1093 pthread_mutex_lock(&mainobjstore_mutex);
1094 if ((ptrcreate = objstrAlloc(mainobjstore, tmpsize)) == NULL) {
1095 printf("Error: transComProcess() failed objstrAlloc %s, %d\n", __FILE__, __LINE__);
1096 pthread_mutex_unlock(&mainobjstore_mutex);
1099 pthread_mutex_unlock(&mainobjstore_mutex);
1100 memcpy(ptrcreate, header, tmpsize);
1101 mhashInsert(oidcreated[i], ptrcreate);
1102 lhashInsert(oidcreated[i], myIpAddr);
1104 /* Unlock locked objects */
1105 for(i = 0; i < numlocked; i++) {
1106 if((header = (objheader_t *) mhashSearch(oidlocked[i])) == NULL) {
1107 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1110 STATUS(header) &= ~(LOCK);
1116 /* This function checks if the prefetch oids are same and have same offsets
1117 * for case x.a.b and y.a.b where x and y have same oid's
1118 * or if a.b.c is a subset of x.b.c.d*/
1119 /* check for case where the generated request a.y.z or x.y.z.g then
1120 * prefetch needs to be generated for x.y.z.g if oid of a and x are same*/
1121 void checkPrefetchTuples(prefetchqelem_t *node) {
1122 int i,j, count,k, sindex, index;
1124 int ntuples, slength;
1126 short *endoffsets, *arryfields;
1128 /* Check for the case x.y.z and a.b.c are same oids */
1129 ptr = (char *) node;
1130 ntuples = *(GET_NTUPLES(ptr));
1131 oid = GET_PTR_OID(ptr);
1132 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1133 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1135 /* Find offset length for each tuple */
1136 int numoffset[ntuples];
1137 numoffset[0] = endoffsets[0];
1138 for(i = 1; i<ntuples; i++) {
1139 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1141 /* Check for redundant tuples by comparing oids of each tuple */
1142 for(i = 0; i < ntuples; i++) {
1145 for(j = i+1 ; j < ntuples; j++) {
1148 /*If oids of tuples match */
1149 if (oid[i] == oid[j]) {
1150 /* Find the smallest offset length of two tuples*/
1151 if(numoffset[i] > numoffset[j]){
1152 slength = numoffset[j];
1156 slength = numoffset[i];
1160 /* Compare the offset values based on the current indices
1161 * break if they do not match
1162 * if all offset values match then pick the largest tuple*/
1167 k = endoffsets[i-1];
1169 index = endoffsets[j -1];
1170 for(count = 0; count < slength; count ++) {
1171 if (arryfields[k] != arryfields[index]) {
1177 if(slength == count) {
1184 /* This function makes machine piles to be added into the machine pile queue for each prefetch call */
1185 prefetchpile_t *makePreGroups(prefetchqelem_t *node, int *numoffset) {
1187 int ntuples, i, machinenum, count=0;
1189 short *endoffsets, *arryfields, *offset;
1190 prefetchpile_t *head = NULL, *tmp = NULL;
1192 /* Check for the case x.y.z and a.b.c are same oids */
1193 ptr = (char *) node;
1194 ntuples = *(GET_NTUPLES(ptr));
1195 oid = GET_PTR_OID(ptr);
1196 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1197 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1199 if((head = (prefetchpile_t *) calloc(1, sizeof(prefetchpile_t))) == NULL) {
1200 printf("Calloc error: %s %d\n", __FILE__, __LINE__);
1204 /* Check for redundant tuples by comparing oids of each tuple */
1205 for(i = 0; i < ntuples; i++) {
1207 if(head->next != NULL) {
1208 if((tmp = (prefetchpile_t *) calloc(1, sizeof(prefetchpile_t))) == NULL) {
1209 printf("Calloc error: %s %d\n", __FILE__, __LINE__);
1212 tmp->mid = myIpAddr;
1216 head->mid = myIpAddr;
1220 /* For each tuple make piles */
1221 if ((machinenum = lhashSearch(oid[i])) == 0) {
1222 printf("Error: No such Machine %s, %d\n", __FILE__, __LINE__);
1225 /* Insert into machine pile */
1227 offset = &arryfields[0];
1229 offset = &arryfields[endoffsets[i-1]];
1232 if((head = insertPile(machinenum, oid[i], numoffset[i], offset, head)) == NULL){
1233 printf("Error: Couldn't create a pile %s, %d\n", __FILE__, __LINE__);
1241 prefetchpile_t *foundLocal(prefetchqelem_t *node) {
1242 int ntuples,i, j, k, oidnfound = 0, arryfieldindex,nextarryfieldindex, flag = 0, val;
1244 unsigned int objoid;
1247 objheader_t *objheader;
1248 short *endoffsets, *arryfields;
1249 prefetchpile_t *head = NULL;
1251 ptr = (char *) node;
1252 ntuples = *(GET_NTUPLES(ptr));
1253 oid = GET_PTR_OID(ptr);
1254 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1255 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1257 /* Find offset length for each tuple */
1258 int numoffset[ntuples];//Number of offsets for each tuple
1259 numoffset[0] = endoffsets[0];
1260 for(i = 1; i<ntuples; i++) {
1261 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1263 for(i = 0; i < ntuples; i++) {
1267 nextarryfieldindex = endoffsets[0];
1269 arryfieldindex = endoffsets[i-1];
1270 nextarryfieldindex = endoffsets[i];
1273 endoffsets[0] = val = numoffset[0];
1274 for(k = 1; k < ntuples; k++) {
1275 val = val + numoffset[k];
1276 endoffsets[k] = val;
1279 for(k = 0; k<endoffsets[ntuples-1]; k++) {
1280 arryfields[arryfieldindex+k] = arryfields[nextarryfieldindex+k];
1284 /* If object found locally */
1285 if((objheader = (objheader_t*) mhashSearch(oid[i])) != NULL) {
1286 tmp = (char *) objheader;
1287 int orgnumoffset = numoffset[i];
1291 arryfieldindex = endoffsets[i-1];
1294 for(j = 0; j<orgnumoffset; j++) {
1295 /* Check for arrays */
1296 if(TYPE(objheader) > NUMCLASSES) {
1300 int elementsize = classsize[TYPE(objheader)];
1301 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*arryfields[arryfieldindex])));
1303 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + arryfields[arryfieldindex]));
1305 //Update numoffset array
1306 numoffset[i] = numoffset[i] - 1;
1309 //Update endoffset array
1310 endoffsets[0] = val = numoffset[0];
1311 for(k = 1; k < ntuples; k++) {
1312 val = val + numoffset[k];
1313 endoffsets[k] = val;
1315 //Update arrayfields array
1316 for(k = 0; k < endoffsets[ntuples-1]; k++) {
1317 arryfields[arryfieldindex+k] = arryfields[arryfieldindex+k+1];
1319 if((objheader = (objheader_t*) mhashSearch(oid[i])) == NULL) {
1321 checkPreCache(node, numoffset, oid[i], i);
1324 tmp = (char *) objheader;
1327 /*If all offset oids are found locally,make the prefetch tuple invalid */
1332 /* Look in Prefetch cache */
1333 checkPreCache(node, numoffset, oid[i],i);
1337 /* Make machine groups */
1338 if((head = makePreGroups(node, numoffset)) == NULL) {
1339 printf("Error in makePreGroups() %s %d\n", __FILE__, __LINE__);
1346 void checkPreCache(prefetchqelem_t *node, int *numoffset, unsigned int objoid, int index) {
1348 int ntuples, i, k, flag=0, isArray =0, arryfieldindex, val;
1350 short *endoffsets, *arryfields;
1351 objheader_t *header;
1353 ptr = (char *) node;
1354 ntuples = *(GET_NTUPLES(ptr));
1355 oid = GET_PTR_OID(ptr);
1356 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1357 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1359 if((header = (objheader_t *) prehashSearch(objoid)) == NULL) {
1361 } else { //Found in Prefetch Cache
1362 //TODO Decide if object is too old, if old remove from cache
1363 tmp = (char *) header;
1364 int loopcount = numoffset[index];
1368 arryfieldindex = endoffsets[(index - 1)];
1369 // Check if any of the offset oid is available in the Prefetch cache
1370 for(i = 0; i < loopcount; i++) {
1371 /* Check for arrays */
1372 if(TYPE(header) > NUMCLASSES) {
1376 int elementsize = classsize[TYPE(header)];
1377 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*arryfields[arryfieldindex])));
1379 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + arryfields[arryfieldindex]));
1381 //Update numoffset array
1382 numoffset[index] = numoffset[index] - 1;
1384 oid[index] = objoid;
1385 //Update endoffset array
1386 endoffsets[0] = val = numoffset[0];
1387 for(k = 1; k < ntuples; k++) {
1388 val = val + numoffset[k];
1389 endoffsets[k] = val;
1391 //Update arrayfields array
1392 for(k = 0; k < endoffsets[ntuples-1]; k++) {
1393 arryfields[arryfieldindex+k] = arryfields[arryfieldindex+k+1];
1395 if((header = (objheader_t *)prehashSearch(oid[index])) != NULL) {
1396 tmp = (char *) header;
1404 //Found in the prefetch cache
1405 if(flag == 0 && (numoffset[index] == 0)) {
1412 /* This function is called by the thread calling transPrefetch */
1413 void *transPrefetch(void *t) {
1414 prefetchqelem_t *qnode;
1415 prefetchpile_t *pilehead = NULL;
1416 prefetchpile_t *ptr = NULL, *piletail = NULL;
1419 /* lock mutex of primary prefetch queue */
1420 pthread_mutex_lock(&pqueue.qlock);
1421 /* while primary queue is empty, then wait */
1422 while((pqueue.front == NULL) && (pqueue.rear == NULL)) {
1423 pthread_cond_wait(&pqueue.qcond, &pqueue.qlock);
1426 /* dequeue node to create a machine piles and finally unlock mutex */
1427 if((qnode = pre_dequeue()) == NULL) {
1428 printf("Error: No node returned %s, %d\n", __FILE__, __LINE__);
1429 pthread_mutex_unlock(&pqueue.qlock);
1432 pthread_mutex_unlock(&pqueue.qlock);
1434 /* Reduce redundant prefetch requests */
1435 checkPrefetchTuples(qnode);
1436 /* Check if the tuples are found locally, if yes then reduce them further*/
1437 /* and group requests by remote machine ids by calling the makePreGroups() */
1438 if((pilehead = foundLocal(qnode)) == NULL) {
1439 printf("Error: No node created for serving prefetch request %s %d\n", __FILE__, __LINE__);
1444 while(ptr != NULL) {
1445 if(ptr->next == NULL) {
1451 /* Lock mutex of pool queue */
1452 pthread_mutex_lock(&mcqueue.qlock);
1453 /* Update the pool queue with the new remote machine piles generated per prefetch call */
1454 mcpileenqueue(pilehead, piletail);
1455 /* Broadcast signal on machine pile queue */
1456 pthread_cond_broadcast(&mcqueue.qcond);
1457 /* Unlock mutex of machine pile queue */
1458 pthread_mutex_unlock(&mcqueue.qlock);
1459 /* Deallocate the prefetch queue pile node */
1464 /* Each thread in the pool of threads calls this function to establish connection with
1465 * remote machines, send the prefetch requests and process the reponses from
1466 * the remote machines .
1467 * The thread is active throughout the period of runtime */
1469 void *mcqProcess(void *threadid) {
1471 prefetchpile_t *mcpilenode;
1473 tid = (int) threadid;
1475 /* Lock mutex of mc pile queue */
1476 pthread_mutex_lock(&mcqueue.qlock);
1477 /* When mc pile queue is empty, wait */
1478 while((mcqueue.front == NULL) && (mcqueue.rear == NULL)) {
1479 pthread_cond_wait(&mcqueue.qcond, &mcqueue.qlock);
1481 /* Dequeue node to send remote machine connections*/
1482 if((mcpilenode = mcpiledequeue()) == NULL) {
1483 printf("Dequeue Error: No node returned %s %d\n", __FILE__, __LINE__);
1484 pthread_mutex_unlock(&mcqueue.qlock);
1488 pthread_mutex_unlock(&mcqueue.qlock);
1490 /*Initiate connection to remote host and send request */
1491 /* Process Request */
1492 if(mcpilenode->mid != myIpAddr)
1493 sendPrefetchReq(mcpilenode);
1495 /* Deallocate the machine queue pile node */
1496 mcdealloc(mcpilenode);
1500 void sendPrefetchReq(prefetchpile_t *mcpilenode) {
1501 int sd, i, off, len, endpair, count = 0;
1502 struct sockaddr_in serv_addr;
1503 struct hostent *server;
1504 char machineip[16], control;
1507 /* Send Trans Prefetch Request */
1508 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
1509 perror("Error in socket for SEND_PREFETCH_REQUEST\n");
1513 bzero((char*) &serv_addr, sizeof(serv_addr));
1514 serv_addr.sin_family = AF_INET;
1515 serv_addr.sin_port = htons(LISTEN_PORT);
1516 midtoIP(mcpilenode->mid ,machineip);
1517 machineip[15] = '\0';
1518 serv_addr.sin_addr.s_addr = inet_addr(machineip);
1520 /* Open Connection */
1521 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
1522 perror("Error in connect for SEND_PREFETCH_REQUEST\n");
1527 /* Send TRANS_PREFETCH control message */
1528 control = TRANS_PREFETCH;
1529 if(send(sd, &control, sizeof(char), MSG_NOSIGNAL) < sizeof(char)) {
1530 perror("Error in sending prefetch control\n");
1535 /* Send Oids and offsets in pairs */
1536 tmp = mcpilenode->objpiles;
1537 while(tmp != NULL) {
1539 count++; /* Keeps track of the number of oid and offset tuples sent per remote machine */
1540 len = sizeof(int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(unsigned short));
1541 char oidnoffset[len];
1542 bzero(oidnoffset, len);
1543 *((unsigned int*)oidnoffset) = len;
1544 //memcpy(oidnoffset, &len, sizeof(int));
1546 *((unsigned int *)((char *)oidnoffset + off)) = tmp->oid;
1547 //memcpy(oidnoffset + off, &tmp->oid, sizeof(unsigned int));
1548 off += sizeof(unsigned int);
1549 for(i = 0; i < tmp->numoffset; i++) {
1550 *((unsigned short*)((char *)oidnoffset + off)) = tmp->offset[i];
1551 //memcpy(oidnoffset + off, &(tmp->offset[i]), sizeof(short));
1552 off+=sizeof(unsigned short);
1555 if (send(sd, oidnoffset, len , MSG_NOSIGNAL) < len) {
1556 perror("Error sending fixed bytes for thread\n");
1564 /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
1566 if (send(sd, &endpair, sizeof(int), MSG_NOSIGNAL) < sizeof(int)) {
1567 perror("Error sending fixed bytes for thread\n");
1572 /* Get Response from the remote machine */
1573 getPrefetchResponse(count,sd);
1578 void getPrefetchResponse(int count, int sd) {
1579 int i = 0, val, n, N, sum, index, objsize;
1580 unsigned int bufsize,oid;
1581 char buffer[RECEIVE_BUFFER_SIZE], control;
1583 void *modptr, *oldptr;
1585 /* Read prefetch response from the Remote machine */
1586 if((val = read(sd, &control, sizeof(char))) <= 0) {
1587 perror("No control response for Prefetch request sent\n");
1591 if(control == TRANS_PREFETCH_RESPONSE) {
1592 /*For each oid and offset tuple sent as prefetch request to remote machine*/
1596 /* Read the size of buffer to be received */
1597 if((N = read(sd, buffer, sizeof(unsigned int))) <= 0) {
1598 perror("Size of buffer not recv\n");
1601 bufsize = *((unsigned int *) buffer);
1602 ptr = buffer + sizeof(unsigned int);
1603 /* Keep receiving the buffer containing oid info */
1605 n = recv((int)sd, (void *)ptr+sum, bufsize-sum, 0);
1607 } while(sum < bufsize && n != 0);
1609 /* Decode the contents of the buffer */
1610 index = sizeof(unsigned int);
1611 while(index < (bufsize - sizeof(unsigned int))) {
1612 if(buffer[index] == OBJECT_FOUND) {
1613 /* Increment it to get the object */
1614 index += sizeof(char);
1615 oid = *((unsigned int *)(buffer+index));
1616 index += sizeof(unsigned int);
1617 /* For each object found add to Prefetch Cache */
1618 objsize = *((int *)(buffer+index));
1620 pthread_mutex_lock(&prefetchcache_mutex);
1621 if ((modptr = objstrAlloc(prefetchcache, objsize)) == NULL) {
1622 printf("Error: objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
1623 pthread_mutex_unlock(&prefetchcache_mutex);
1626 pthread_mutex_unlock(&prefetchcache_mutex);
1627 memcpy(modptr, buffer+index, objsize);
1629 /* Insert the oid and its address into the prefetch hash lookup table */
1630 /* Do a version comparison if the oid exists */
1631 if((oldptr = prehashSearch(oid)) != NULL) {
1632 /* If older version then update with new object ptr */
1633 if(((objheader_t *)oldptr)->version < ((objheader_t *)modptr)->version) {
1635 prehashInsert(oid, modptr);
1636 } else if(((objheader_t *)oldptr)->version == ((objheader_t *)modptr)->version) {
1637 /* Add the new object ptr to hash table */
1639 prehashInsert(oid, modptr);
1640 } else { /* Do nothing: TODO modptr should be reference counted */
1643 } else {/*If doesn't no match found in hashtable, add the object ptr to hash table*/
1644 prehashInsert(oid, modptr);
1646 /* Lock the Prefetch Cache look up table*/
1647 pthread_mutex_lock(&pflookup.lock);
1648 /* Broadcast signal on prefetch cache condition variable */
1649 pthread_cond_broadcast(&pflookup.cond);
1650 /* Unlock the Prefetch Cache look up table*/
1651 pthread_mutex_unlock(&pflookup.lock);
1652 } else if(buffer[index] == OBJECT_NOT_FOUND) {
1653 /* Increment it to get the object */
1654 /* TODO: For each object not found query DHT for new location and retrieve the object */
1655 index += sizeof(char);
1656 oid = *((unsigned int *)(buffer + index));
1657 index += sizeof(unsigned int);
1658 /* Throw an error */
1659 printf("OBJECT NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n");
1662 printf("Error in decoding the index value %s, %d\n",__FILE__, __LINE__);
1670 printf("Error in receving response for prefetch request %s, %d\n",__FILE__, __LINE__);
1674 unsigned short getObjType(unsigned int oid)
1676 objheader_t *objheader;
1677 unsigned short numoffset[] ={0};
1678 short fieldoffset[] ={};
1680 if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL)
1682 if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1684 prefetch(1, &oid, numoffset, fieldoffset);
1685 pthread_mutex_lock(&pflookup.lock);
1686 while ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1688 pthread_cond_wait(&pflookup.cond, &pflookup.lock);
1690 pthread_mutex_unlock(&pflookup.lock);
1694 return TYPE(objheader);
1697 int startRemoteThread(unsigned int oid, unsigned int mid)
1700 struct sockaddr_in remoteAddr;
1701 char msg[1 + sizeof(unsigned int)];
1705 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
1707 perror("startRemoteThread():socket()");
1711 bzero(&remoteAddr, sizeof(remoteAddr));
1712 remoteAddr.sin_family = AF_INET;
1713 remoteAddr.sin_port = htons(LISTEN_PORT);
1714 remoteAddr.sin_addr.s_addr = htonl(mid);
1716 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0)
1718 printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
1719 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1724 msg[0] = START_REMOTE_THREAD;
1725 memcpy(&msg[1], &oid, sizeof(unsigned int));
1727 bytesSent = send(sock, msg, 1 + sizeof(unsigned int), 0);
1730 perror("startRemoteThread():send()");
1733 else if (bytesSent != 1 + sizeof(unsigned int))
1735 printf("startRemoteThread(): error, sent %d bytes\n", bytesSent);
1748 //TODO: when reusing oids, make sure they are not already in use!
1749 unsigned int getNewOID(void) {
1750 static unsigned int id = 0xFFFFFFFF;
1753 if (id > oidMax || id < oidMin)
1760 int processConfigFile()
1763 const int maxLineLength = 200;
1764 char lineBuffer[maxLineLength];
1766 const char *delimiters = " \t\n";
1770 configFile = fopen(CONFIG_FILENAME, "r");
1771 if (configFile == NULL)
1773 printf("error opening %s:\n", CONFIG_FILENAME);
1778 numHostsInSystem = 0;
1779 sizeOfHostArray = 8;
1780 hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
1782 while(fgets(lineBuffer, maxLineLength, configFile) != NULL)
1784 commentBegin = strchr(lineBuffer, '#');
1785 if (commentBegin != NULL)
1786 *commentBegin = '\0';
1787 token = strtok(lineBuffer, delimiters);
1788 while (token != NULL)
1790 tmpAddr = inet_addr(token);
1791 if ((int)tmpAddr == -1)
1793 printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
1798 addHost(htonl(tmpAddr));
1799 token = strtok(NULL, delimiters);
1805 if (numHostsInSystem < 1)
1807 printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
1811 myIpAddr = getMyIpAddr("en1");
1813 myIpAddr = getMyIpAddr("eth0");
1815 myIndexInHostArray = findHost(myIpAddr);
1816 if (myIndexInHostArray == -1)
1818 printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
1821 oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
1822 oidMin = oidsPerBlock * myIndexInHostArray;
1823 if (myIndexInHostArray == numHostsInSystem - 1)
1824 oidMax = 0xFFFFFFFF;
1826 oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
1831 void addHost(unsigned int hostIp)
1833 unsigned int *tmpArray;
1835 if (findHost(hostIp) != -1)
1838 if (numHostsInSystem == sizeOfHostArray)
1840 tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
1841 memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
1843 hostIpAddrs = tmpArray;
1846 hostIpAddrs[numHostsInSystem++] = hostIp;
1851 int findHost(unsigned int hostIp)
1854 for (i = 0; i < numHostsInSystem; i++)
1855 if (hostIpAddrs[i] == hostIp)
1862 /* This function sends notification request per thread waiting on object(s) whose version
1864 int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int numoid) {
1866 objheader_t *objheader;
1867 struct sockaddr_in remoteAddr;
1868 char msg[1 + numoid * (sizeof(short) + sizeof(unsigned int)) + 3 * sizeof(unsigned int)];
1872 unsigned short version;
1873 unsigned int oid,mid;
1874 static unsigned int threadid = 0;
1875 pthread_mutex_t threadnotify = PTHREAD_MUTEX_INITIALIZER; //Lock and condition var for threadjoin and notification
1876 pthread_cond_t threadcond = PTHREAD_COND_INITIALIZER;
1877 notifydata_t *ndata;
1879 //FIXME currently all oids belong to one machine
1881 mid = lhashSearch(oid);
1883 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1884 perror("reqNotify():socket()");
1888 bzero(&remoteAddr, sizeof(remoteAddr));
1889 remoteAddr.sin_family = AF_INET;
1890 remoteAddr.sin_port = htons(LISTEN_PORT);
1891 remoteAddr.sin_addr.s_addr = htonl(mid);
1893 /* Generate unique threadid */
1896 /* Save threadid, numoid, oidarray, versionarray, pthread_cond_variable for later processing */
1897 if((ndata = calloc(1, sizeof(notifydata_t))) == NULL) {
1898 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
1901 ndata->numoid = numoid;
1902 ndata->threadid = threadid;
1903 ndata->oidarry = oidarry;
1904 ndata->versionarry = versionarry;
1905 ndata->threadcond = threadcond;
1906 ndata->threadnotify = threadnotify;
1907 if((status = notifyhashInsert(threadid, ndata)) != 0) {
1908 printf("reqNotify(): Insert into notify hash table not successful %s, %d\n", __FILE__, __LINE__);
1913 /* Send number of oids, oidarry, version array, machine id and threadid */
1914 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1915 printf("reqNotify():error %d connecting to %s:%d\n", errno,
1916 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1920 msg[0] = THREAD_NOTIFY_REQUEST;
1921 *((unsigned int *)(&msg[1])) = numoid;
1922 /* Send array of oids */
1923 size = sizeof(unsigned int);
1928 *((unsigned int *)(&msg[1] + size)) = oid;
1929 size += sizeof(unsigned int);
1934 /* Send array of version */
1938 version = versionarry[i];
1939 *((unsigned short *)(&msg[1] + size)) = version;
1940 size += sizeof(unsigned short);
1945 *((unsigned int *)(&msg[1] + size)) = myIpAddr;
1946 size += sizeof(unsigned int);
1947 *((unsigned int *)(&msg[1] + size)) = threadid;
1949 pthread_mutex_lock(&(ndata->threadnotify));
1950 bytesSent = send(sock, msg, 1 + numoid * (sizeof(unsigned int) + sizeof(unsigned short)) + 3 * sizeof(unsigned int) , 0);
1952 perror("reqNotify():send()");
1954 } else if (bytesSent != 1 + numoid*(sizeof(unsigned int) + sizeof(unsigned short)) + 3 * sizeof(unsigned int)){
1955 printf("reNotify(): error, sent %d bytes %s, %d\n", bytesSent, __FILE__, __LINE__);
1961 pthread_cond_wait(&(ndata->threadcond), &(ndata->threadnotify));
1962 pthread_mutex_unlock(&(ndata->threadnotify));
1965 pthread_cond_destroy(&threadcond);
1966 pthread_mutex_destroy(&threadnotify);
1972 void threadNotify(unsigned int oid, unsigned short version, unsigned int tid) {
1973 notifydata_t *ndata;
1974 int i, objIsFound = 0, index;
1977 //Look up the tid and call the corresponding pthread_cond_signal
1978 if((ndata = notifyhashSearch(tid)) == NULL) {
1979 printf("threadnotify(): No such threadid is present %s, %d\n", __FILE__, __LINE__);
1982 for(i = 0; i < ndata->numoid; i++) {
1983 if(ndata->oidarry[i] == oid){
1988 if(objIsFound == 0){
1989 printf("threadNotify(): Oid not found %s, %d\n", __FILE__, __LINE__);
1992 if(version <= ndata->versionarry[index]){
1993 printf("threadNotify(): New version %d has not changed since last version %s, %d\n", version, __FILE__, __LINE__);
1996 /* Clear from prefetch cache and free thread related data structure */
1997 if((ptr = prehashSearch(oid)) != NULL) {
2000 pthread_cond_signal(&(ndata->threadcond));
2007 int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) {
2010 struct sockaddr_in remoteAddr;
2011 char msg[1 + sizeof(unsigned short) + 2*sizeof(unsigned int)];
2012 int sock, status, size, bytesSent;
2014 while(*head != NULL) {
2017 //create a socket connection to that machine
2018 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
2019 perror("notifyAll():socket()");
2023 bzero(&remoteAddr, sizeof(remoteAddr));
2024 remoteAddr.sin_family = AF_INET;
2025 remoteAddr.sin_port = htons(LISTEN_PORT);
2026 remoteAddr.sin_addr.s_addr = htonl(mid);
2027 //send Thread Notify response and threadid to that machine
2028 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
2029 printf("notifyAll():error %d connecting to %s:%d\n", errno,
2030 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
2033 bzero(msg, (1+sizeof(unsigned short) + 2*sizeof(unsigned int)));
2034 msg[0] = THREAD_NOTIFY_RESPONSE;
2035 *((unsigned int *)&msg[1]) = oid;
2036 size = sizeof(unsigned int);
2037 *((unsigned short *)(&msg[1]+ size)) = version;
2038 size+= sizeof(unsigned short);
2039 *((unsigned int *)(&msg[1]+ size)) = ptr->threadid;
2041 bytesSent = send(sock, msg, (1 + 2*sizeof(unsigned int) + sizeof(unsigned short)), 0);
2043 perror("notifyAll():send()");
2045 } else if (bytesSent != 1 + 2*sizeof(unsigned int) + sizeof(unsigned short)){
2046 printf("notifyAll(): error, sent %d bytes %s, %d\n",
2047 bytesSent, __FILE__, __LINE__);
2062 void transAbort(transrecord_t *trans) {
2063 objstrDelete(trans->cache);
2064 chashDelete(trans->lookupTable);