4 #include "machinepile.h"
11 #include <sys/types.h>
12 #include <sys/socket.h>
14 #include <netinet/in.h>
15 #include <sys/types.h>
22 #define LISTEN_PORT 2156
23 #define RECEIVE_BUFFER_SIZE 2048
24 #define NUM_THREADS 10
25 #define PREFETCH_CACHE_SIZE 1048576 //1MB
26 #define CONFIG_FILENAME "dstm.conf"
28 /* Global Variables */
29 extern int classsize[];
30 extern primarypfq_t pqueue; //Shared prefetch queue
31 extern mcpileq_t mcqueue; //Shared queue containing prefetch requests sorted by remote machineids
32 objstr_t *prefetchcache; //Global Prefetch cache
33 pthread_mutex_t prefetchcache_mutex;// Mutex to lock Prefetch Cache
34 pthread_mutexattr_t prefetchcache_mutex_attr; /* Attribute for lock to make it a recursive lock */
35 extern pthread_mutex_t mainobjstore_mutex;// Mutex to lock main Object store
36 extern prehashtable_t pflookup; //Global Prefetch cache's lookup table
37 pthread_t wthreads[NUM_THREADS]; //Worker threads for working on the prefetch queue
38 pthread_t tPrefetch; /* Primary Prefetch thread that processes the prefetch queue */
39 extern objstr_t *mainobjstore;
40 unsigned int myIpAddr;
41 unsigned int *hostIpAddrs;
44 int myIndexInHostArray;
45 unsigned int oidsPerBlock;
49 plistnode_t *createPiles(transrecord_t *);
50 inline int arrayLength(int *array) {
52 for(i=0 ;array[i] != -1; i++)
56 inline int findmax(int *array, int arraylength) {
59 for(i = 0; i < arraylength; i++){
66 /* This function is a prefetch call generated by the compiler that
67 * populates the shared primary prefetch queue*/
68 void prefetch(int ntuples, unsigned int *oids, unsigned short *endoffsets, short *arrayfields) {
72 /* Allocate for the queue node*/
74 qnodesize = sizeof(prefetchqelem_t) + sizeof(int) + ntuples * (sizeof(short) + sizeof(unsigned int)) + endoffsets[ntuples - 1] * sizeof(short);
75 if((node = calloc(1, qnodesize)) == NULL) {
76 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
79 /* Set queue node values */
80 len = sizeof(prefetchqelem_t);
81 memcpy(node + len, &ntuples, sizeof(int));
83 memcpy(node + len, oids, ntuples*sizeof(unsigned int));
84 len += ntuples * sizeof(unsigned int);
85 memcpy(node + len, endoffsets, ntuples*sizeof(short));
86 len += ntuples * sizeof(short);
87 memcpy(node + len, arrayfields, endoffsets[ntuples-1]*sizeof(short));
88 /* Lock and insert into primary prefetch queue */
89 pthread_mutex_lock(&pqueue.qlock);
90 pre_enqueue((prefetchqelem_t *)node);
91 pthread_cond_signal(&pqueue.qcond);
92 pthread_mutex_unlock(&pqueue.qlock);
95 /* This function starts up the transaction runtime. */
96 int dstmStartup(const char * option) {
97 pthread_t thread_Listen;
99 int master=option!=NULL && strcmp(option, "master")==0;
101 if (processConfigFile() != 0)
102 return 0; //TODO: return error value, cause main program to exit
108 pthread_attr_init(&attr);
109 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
110 pthread_create(&thread_Listen, &attr, dstmListen, NULL);
120 /* This function initiates the prefetch thread
121 * A queue is shared between the main thread of execution
122 * and the prefetch thread to process the prefetch call
123 * Call from compiler populates the shared queue with prefetch requests while prefetch thread
124 * processes the prefetch requests */
128 //Create and initialize prefetch cache structure
129 prefetchcache = objstrCreate(PREFETCH_CACHE_SIZE);
131 /* Initialize attributes for mutex */
132 pthread_mutexattr_init(&prefetchcache_mutex_attr);
133 pthread_mutexattr_settype(&prefetchcache_mutex_attr, PTHREAD_MUTEX_RECURSIVE_NP);
135 pthread_mutex_init(&prefetchcache_mutex, &prefetchcache_mutex_attr);
137 //Create prefetch cache lookup table
138 if(prehashCreate(HASH_SIZE, LOADFACTOR))
140 //Initialize primary shared queue
142 //Initialize machine pile w/prefetch oids and offsets shared queue
144 //Create the primary prefetch thread
147 retval=pthread_create(&tPrefetch, NULL, transPrefetch, NULL);
149 pthread_detach(tPrefetch);
151 //Create and Initialize a pool of threads
152 /* Threads are active for the entire period runtime is running */
153 for(t = 0; t< NUM_THREADS; t++) {
155 rc = pthread_create(&wthreads[t], NULL, mcqProcess, (void *)t);
157 pthread_detach(wthreads[t]);
161 /* This function stops the threads spawned */
164 pthread_cancel(tPrefetch);
165 for(t = 0; t < NUM_THREADS; t++)
166 pthread_cancel(wthreads[t]);
171 /* This functions inserts randowm wait delays in the order of msec
172 * Mostly used when transaction commits retry*/
173 void randomdelay(void)
175 struct timespec req, rem;
180 req.tv_nsec = (long)(1000000 + (t%10000000)); //1-11 msec
181 //nanosleep(&req, &rem);
182 nanosleep(&req, NULL);
186 /* This function initializes things required in the transaction start*/
187 transrecord_t *transStart()
189 printf("Starting transaction\n");
190 transrecord_t *tmp = malloc(sizeof(transrecord_t));
191 tmp->cache = objstrCreate(1048576);
192 tmp->lookupTable = chashCreate(HASH_SIZE, LOADFACTOR);
194 tmp->revertlist=NULL;
199 /* This function finds the location of the objects involved in a transaction
200 * and returns the pointer to the object if found in a remote location */
201 objheader_t *transRead(transrecord_t *record, unsigned int oid) {
202 unsigned int machinenumber;
203 objheader_t *tmp, *objheader;
204 objheader_t *objcopy;
205 int size, rc, found = 0;
210 rc = gettimeofday(&tp, NULL);
212 /* Convert from timeval to timespec */
213 ts.tv_nsec = tp.tv_usec * 1000;
215 /* Search local transaction cache */
216 if((objheader = (objheader_t *)chashSearch(record->lookupTable, oid)) != NULL){
218 return &objheader[1];
222 } else if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
223 /* Look up in machine lookup table and copy into cache*/
224 GETSIZE(size, objheader);
225 size += sizeof(objheader_t);
226 //TODO:Lock the local trans cache while copying the object here
227 objcopy = objstrAlloc(record->cache, size);
228 memcpy(objcopy, (void *)objheader, size);
229 /* Insert into cache's lookup table */
230 chashInsert(record->lookupTable, OID(objheader), objcopy);
236 } else if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) { /* Look up in prefetch cache */
239 size+=sizeof(objheader_t);
240 //TODO:Lock the local trans cache while copying the object here
241 objcopy = objstrAlloc(record->cache, size);
242 memcpy(objcopy, (void *)tmp, size);
243 /* Insert into cache's lookup table */
244 chashInsert(record->lookupTable, OID(tmp), objcopy);
251 /*If object not found in prefetch cache then block until object appears in the prefetch cache */
252 pthread_mutex_lock(&pflookup.lock);
254 rc = pthread_cond_timedwait(&pflookup.cond, &pflookup.lock, &ts);
255 if(rc == ETIMEDOUT) {
256 printf("Wait timed out\n");
257 /* Check Prefetch cache again */
258 if((tmp =(objheader_t *) prehashSearch(oid)) != NULL) {
261 size+=sizeof(objheader_t);
262 objcopy = objstrAlloc(record->cache, size);
263 memcpy(objcopy, (void *)tmp, size);
264 chashInsert(record->lookupTable, OID(tmp), objcopy);
265 pthread_mutex_unlock(&pflookup.lock);
272 pthread_mutex_unlock(&pflookup.lock);
278 /* Get the object from the remote location */
279 machinenumber = lhashSearch(oid);
280 objcopy = getRemoteObj(record, machinenumber, oid);
281 if(objcopy == NULL) {
282 printf("Object not found in Remote location %s, %d\n", __FILE__, __LINE__);
294 /* This function creates objects in the transaction record */
295 objheader_t *transCreateObj(transrecord_t *record, unsigned int size)
297 objheader_t *tmp = (objheader_t *) objstrAlloc(record->cache, (sizeof(objheader_t) + size));
298 OID(tmp) = getNewOID();
302 chashInsert(record->lookupTable, OID(tmp), tmp);
304 return &tmp[1]; //want space after object header
310 /* This function creates machine piles based on all machines involved in a
311 * transaction commit request */
312 plistnode_t *createPiles(transrecord_t *record) {
314 unsigned int size;/* Represents number of bins in the chash table */
315 chashlistnode_t *curr, *ptr, *next;
316 plistnode_t *pile = NULL;
317 unsigned int machinenum;
318 void *localmachinenum;
319 objheader_t *headeraddr;
321 ptr = record->lookupTable->table;
322 size = record->lookupTable->size;
324 for(i = 0; i < size ; i++) {
326 /* Inner loop to traverse the linked list of the cache lookupTable */
327 while(curr != NULL) {
328 //if the first bin in hash table is empty
334 if ((headeraddr = chashSearch(record->lookupTable, curr->key)) == NULL) {
335 printf("Error: No such oid %s, %d\n", __FILE__, __LINE__);
339 //Get machine location for object id (and whether local or not)
340 if (STATUS(headeraddr) & NEW || mhashSearch(curr->key) != NULL) {
341 machinenum = myIpAddr;
342 } else if ((machinenum = lhashSearch(curr->key)) == 0) {
343 printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
347 //Make machine groups
348 if ((pile = pInsert(pile, headeraddr, machinenum, record->lookupTable->numelements)) == NULL) {
349 printf("pInsert error %s, %d\n", __FILE__, __LINE__);
359 /* This function initiates the transaction commit process
360 * Spawns threads for each of the new connections with Participants
361 * and creates new piles by calling the createPiles(),
362 * Sends a transrequest() to each remote machines for objects found remotely
363 * and calls handleLocalReq() to process objects found locally */
364 int transCommit(transrecord_t *record) {
365 unsigned int tot_bytes_mod, *listmid;
366 plistnode_t *pile, *pile_ptr;
368 int pilecount, offset, threadnum, trecvcount;
369 char buffer[RECEIVE_BUFFER_SIZE],control;
370 char transid[TID_LEN];
371 trans_req_data_t *tosend;
372 trans_commit_data_t transinfo;
373 static int newtid = 0;
374 char treplyctrl = 0, treplyretry = 0; /* keeps track of the common response that needs to be sent */
381 /* Look through all the objects in the transaction record and make piles
382 * for each machine involved in the transaction*/
383 pile_ptr = pile = createPiles(record);
385 /* Create the packet to be sent in TRANS_REQUEST */
387 /* Count the number of participants */
388 pilecount = pCount(pile);
390 /* Create a list of machine ids(Participants) involved in transaction */
391 if((listmid = calloc(pilecount, sizeof(unsigned int))) == NULL) {
392 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
396 pListMid(pile, listmid);
399 /* Initialize thread variables,
400 * Spawn a thread for each Participant involved in a transaction */
401 pthread_t thread[pilecount];
403 pthread_cond_t tcond;
404 pthread_mutex_t tlock;
405 pthread_mutex_t tlshrd;
407 thread_data_array_t *thread_data_array;
408 if((thread_data_array = (thread_data_array_t *) malloc(sizeof(thread_data_array_t)*pilecount)) == NULL) {
409 printf("Malloc error %s, %d\n", __FILE__, __LINE__);
410 pthread_cond_destroy(&tcond);
411 pthread_mutex_destroy(&tlock);
418 local_thread_data_array_t *ltdata;
419 if((ltdata = calloc(1, sizeof(local_thread_data_array_t))) == NULL) {
420 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
421 pthread_cond_destroy(&tcond);
422 pthread_mutex_destroy(&tlock);
425 free(thread_data_array);
430 thread_response_t rcvd_control_msg[pilecount]; /* Shared thread array that keeps track of responses of participants */
432 /* Initialize and set thread detach attribute */
433 pthread_attr_init(&attr);
434 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
435 pthread_mutex_init(&tlock, NULL);
436 pthread_cond_init(&tcond, NULL);
438 /* Process each machine pile */
439 while(pile != NULL) {
440 //Create transaction id
442 if ((tosend = calloc(1, sizeof(trans_req_data_t))) == NULL) {
443 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
444 pthread_cond_destroy(&tcond);
445 pthread_mutex_destroy(&tlock);
448 free(thread_data_array);
453 tosend->f.control = TRANS_REQUEST;
454 sprintf(tosend->f.trans_id, "%x_%d", pile->mid, newtid);
455 tosend->f.mcount = pilecount;
456 tosend->f.numread = pile->numread;
457 tosend->f.nummod = pile->nummod;
458 tosend->f.numcreated = pile->numcreated;
459 tosend->f.sum_bytes = pile->sum_bytes;
460 tosend->listmid = listmid;
461 tosend->objread = pile->objread;
462 tosend->oidmod = pile->oidmod;
463 tosend->oidcreated = pile->oidcreated;
464 thread_data_array[threadnum].thread_id = threadnum;
465 thread_data_array[threadnum].mid = pile->mid;
466 thread_data_array[threadnum].buffer = tosend;
467 thread_data_array[threadnum].recvmsg = rcvd_control_msg;
468 thread_data_array[threadnum].threshold = &tcond;
469 thread_data_array[threadnum].lock = &tlock;
470 thread_data_array[threadnum].count = &trecvcount;
471 thread_data_array[threadnum].replyctrl = &treplyctrl;
472 thread_data_array[threadnum].replyretry = &treplyretry;
473 thread_data_array[threadnum].rec = record;
474 /* If local do not create any extra connection */
475 if(pile->mid != myIpAddr) { /* Not local */
477 rc = pthread_create(&thread[threadnum], &attr, transRequest, (void *) &thread_data_array[threadnum]);
480 perror("Error in pthread create\n");
481 pthread_cond_destroy(&tcond);
482 pthread_mutex_destroy(&tlock);
485 for (i = 0; i < threadnum; i++)
486 free(thread_data_array[i].buffer);
487 free(thread_data_array);
493 ltdata->tdata = &thread_data_array[threadnum];
494 ltdata->transinfo = &transinfo;
496 val = pthread_create(&thread[threadnum], &attr, handleLocalReq, (void *) ltdata);
499 perror("Error in pthread create\n");
500 pthread_cond_destroy(&tcond);
501 pthread_mutex_destroy(&tlock);
504 for (i = 0; i < threadnum; i++)
505 free(thread_data_array[i].buffer);
506 free(thread_data_array);
517 /* Free attribute and wait for the other threads */
518 pthread_attr_destroy(&attr);
520 for (i = 0; i < pilecount; i++) {
521 rc = pthread_join(thread[i], NULL);
524 printf("ERROR return code from pthread_join() is %d\n", rc);
525 pthread_cond_destroy(&tcond);
526 pthread_mutex_destroy(&tlock);
529 for (j = i; j < pilecount; j++)
530 free(thread_data_array[j].buffer);
531 free(thread_data_array);
536 free(thread_data_array[i].buffer);
541 pthread_cond_destroy(&tcond);
542 pthread_mutex_destroy(&tlock);
545 free(thread_data_array);
548 /* wait a random amount of time */
549 if (treplyretry == 1)
552 /* Retry trans commit procedure if not sucessful in the first try */
553 } while (treplyretry == 1);
556 objstrDelete(record->cache);
557 chashDelete(record->lookupTable);
562 /* This function sends information involved in the transaction request
563 * to participants and accepts a response from particpants.
564 * It calls decideresponse() to decide on what control message
565 * to send next to participants and sends the message using sendResponse()*/
566 void *transRequest(void *threadarg) {
568 struct sockaddr_in serv_addr;
569 struct hostent *server;
570 thread_data_array_t *tdata;
571 objheader_t *headeraddr;
572 char buffer[RECEIVE_BUFFER_SIZE], control, recvcontrol;
573 char machineip[16], retval;
575 tdata = (thread_data_array_t *) threadarg;
577 /* Send Trans Request */
578 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
579 perror("Error in socket for TRANS_REQUEST\n");
582 bzero((char*) &serv_addr, sizeof(serv_addr));
583 serv_addr.sin_family = AF_INET;
584 serv_addr.sin_port = htons(LISTEN_PORT);
585 midtoIP(tdata->mid,machineip);
586 machineip[15] = '\0';
587 serv_addr.sin_addr.s_addr = inet_addr(machineip);
588 /* Open Connection */
589 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
590 perror("Error in connect for TRANS_REQUEST\n");
595 /* Send bytes of data with TRANS_REQUEST control message */
596 if (send(sd, &(tdata->buffer->f), sizeof(fixed_data_t),MSG_NOSIGNAL) < sizeof(fixed_data_t)) {
597 perror("Error sending fixed bytes for thread\n");
601 /* Send list of machines involved in the transaction */
603 int size=sizeof(unsigned int)*tdata->buffer->f.mcount;
604 if (send(sd, tdata->buffer->listmid, size, MSG_NOSIGNAL) < size) {
605 perror("Error sending list of machines for thread\n");
610 /* Send oids and version number tuples for objects that are read */
612 int size=(sizeof(unsigned int)+sizeof(short))*tdata->buffer->f.numread;
613 if (send(sd, tdata->buffer->objread, size, MSG_NOSIGNAL) < size) {
614 perror("Error sending tuples for thread\n");
619 /* Send objects that are modified */
620 for(i = 0; i < tdata->buffer->f.nummod ; i++) {
622 headeraddr = chashSearch(tdata->rec->lookupTable, tdata->buffer->oidmod[i]);
623 GETSIZE(size,headeraddr);
624 size+=sizeof(objheader_t);
625 if (send(sd, headeraddr, size, MSG_NOSIGNAL) < size) {
626 perror("Error sending obj modified for thread\n");
632 /* Read control message from Participant */
633 if((n = read(sd, &control, sizeof(char))) <= 0) {
634 perror("Error in reading control message from Participant\n");
638 recvcontrol = control;
640 /* Update common data structure and increment count */
641 tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol;
643 /* Lock and update count */
644 /* Thread sleeps until all messages from pariticipants are received by coordinator */
645 pthread_mutex_lock(tdata->lock);
647 (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */
649 /* Wake up the threads and invoke decideResponse (once) */
650 if(*(tdata->count) == tdata->buffer->f.mcount) {
651 decideResponse(tdata);
652 pthread_cond_broadcast(tdata->threshold);
654 pthread_cond_wait(tdata->threshold, tdata->lock);
656 pthread_mutex_unlock(tdata->lock);
658 /* Send the final response such as TRANS_COMMIT or TRANS_ABORT t
659 * to all participants in their respective socket */
660 if (sendResponse(tdata, sd) == 0) {
661 printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__);
666 /* Close connection */
671 /* This function decides the reponse that needs to be sent to
672 * all Participant machines after the TRANS_REQUEST protocol */
673 void decideResponse(thread_data_array_t *tdata) {
675 int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
678 for (i = 0 ; i < tdata->buffer->f.mcount; i++) {
679 control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses
680 written onto the shared array */
683 printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
684 /* treat as disagree, pass thru */
693 case TRANS_SOFT_ABORT:
699 if(transdisagree > 0) {
701 *(tdata->replyctrl) = TRANS_ABORT;
702 } else if(transagree == tdata->buffer->f.mcount){
704 *(tdata->replyctrl) = TRANS_COMMIT;
706 /* Send Abort in soft abort case followed by retry commiting transaction again*/
707 *(tdata->replyctrl) = TRANS_ABORT;
708 *(tdata->replyretry) = 1;
713 /* This function sends the final response to remote machines per thread in their respective socket id
714 * It returns a char that is only needed to check the correctness of execution of this function inside
716 char sendResponse(thread_data_array_t *tdata, int sd) {
717 int n, N, sum, oidcount = 0;
718 char *ptr, retval = 0;
719 unsigned int *oidnotfound;
721 /* If the decided response is due to a soft abort and missing objects at the Participant's side */
722 if(tdata->recvmsg[tdata->thread_id].rcv_status == TRANS_SOFT_ABORT) {
723 /* Read list of objects missing */
724 if((read(sd, &oidcount, sizeof(int)) != 0) && (oidcount != 0)) {
725 N = oidcount * sizeof(unsigned int);
726 if((oidnotfound = calloc(oidcount, sizeof(unsigned int))) == NULL) {
727 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
730 ptr = (char *) oidnotfound;
732 n = read(sd, ptr+sum, N-sum);
734 } while(sum < N && n !=0);
736 retval = TRANS_SOFT_ABORT;
738 /* If the decided response is TRANS_ABORT */
739 if(*(tdata->replyctrl) == TRANS_ABORT) {
740 retval = TRANS_ABORT;
741 } else if(*(tdata->replyctrl) == TRANS_COMMIT) { /* If the decided response is TRANS_COMMIT */
742 retval = TRANS_COMMIT;
745 if (send(sd, tdata->replyctrl, sizeof(char),MSG_NOSIGNAL) < sizeof(char)) {
746 perror("Error sending ctrl message for participant\n");
752 /* This function opens a connection, places an object read request to the
753 * remote machine, reads the control message and object if available and
754 * copies the object and its header to the local cache.
755 * TODO replace mnum and midtoIP() with MACHINE_IP address later */
757 void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
759 struct sockaddr_in serv_addr;
760 struct hostent *server;
766 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
767 perror("Error in socket\n");
770 bzero((char*) &serv_addr, sizeof(serv_addr));
771 serv_addr.sin_family = AF_INET;
772 serv_addr.sin_port = htons(LISTEN_PORT);
773 //serv_addr.sin_addr.s_addr = inet_addr(MACHINE_IP);
774 midtoIP(mnum,machineip);
775 machineip[15] = '\0';
776 serv_addr.sin_addr.s_addr = inet_addr(machineip);
777 /* Open connection */
778 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
779 perror("Error in connect\n");
782 char readrequest[sizeof(char)+sizeof(unsigned int)];
783 readrequest[0] = READ_REQUEST;
784 *((unsigned int *)(&readrequest[1])) = oid;
785 if (send(sd, &readrequest, sizeof(readrequest), MSG_NOSIGNAL) < sizeof(readrequest)) {
786 perror("Error sending message\n");
791 printf("DEBUG -> ready to rcv ...\n");
793 /* Read response from the Participant */
794 if((val = read(sd, &control, sizeof(char))) <= 0) {
795 perror("No control response for getRemoteObj sent\n");
799 case OBJECT_NOT_FOUND:
802 /* Read object if found into local cache */
803 if((val = read(sd, &size, sizeof(int))) <= 0) {
804 perror("No size is read from the participant\n");
807 objcopy = objstrAlloc(record->cache, size);
808 if((val = read(sd, objcopy, size)) <= 0) {
809 perror("No objects are read from the remote participant\n");
812 /* Insert into cache's lookup table */
813 chashInsert(record->lookupTable, oid, objcopy);
816 printf("Error in recv request from participant on a READ_REQUEST %s, %d\n",__FILE__, __LINE__);
819 /* Close connection */
824 /* This function handles the local objects involved in a transaction commiting process.
825 * It also makes a decision if this local machine sends AGREE or DISAGREE or SOFT_ABORT to coordinator.
826 * Note Coordinator = local machine
827 * It wakes up the other threads from remote participants that are waiting for the coordinator's decision and
828 * based on common agreement it either commits or aborts the transaction.
829 * It also frees the memory resources */
830 void *handleLocalReq(void *threadarg) {
831 int val, i = 0, size, offset = 0;
833 char control = 0, *ptr;
835 unsigned int *oidnotfound = NULL, *oidlocked = NULL;
837 objheader_t *headptr, *headeraddr;
838 local_thread_data_array_t *localtdata;
840 localtdata = (local_thread_data_array_t *) threadarg;
842 /* Counters and arrays to formulate decision on control message to be sent */
843 oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
844 oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
845 int objnotfound = 0, objlocked = 0;
846 int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
848 /* modptr points to the beginning of the object store
849 * created at the Pariticipant */
850 pthread_mutex_lock(&mainobjstore_mutex);
851 if ((modptr = objstrAlloc(mainobjstore, localtdata->tdata->buffer->f.sum_bytes)) == NULL) {
852 printf("objstrAlloc error for modified objects %s, %d\n", __FILE__, __LINE__);
853 pthread_mutex_unlock(&mainobjstore_mutex);
856 pthread_mutex_unlock(&mainobjstore_mutex);
857 /* Write modified objects into the mainobject store */
858 for(i = 0; i< localtdata->tdata->buffer->f.nummod; i++) {
859 headeraddr = chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidmod[i]);
860 GETSIZE(size,headeraddr);
861 size+=sizeof(objheader_t);
862 memcpy((char *)modptr+offset, headeraddr, size);
865 /* Write new objects into the mainobject store */
866 for(i = 0; i< localtdata->tdata->buffer->f.numcreated; i++) {
867 headeraddr = chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidcreated[i]);
868 GETSIZE(size, headeraddr);
869 size+=sizeof(objheader_t);
870 memcpy((char *)modptr+offset, headeraddr, size);
877 /* Process each oid in the machine pile/ group per thread */
878 for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) {
879 if (i < localtdata->tdata->buffer->f.numread) {//Objs only read and not modified
880 int incr = sizeof(unsigned int) + sizeof(short);// Offset that points to next position in the objread array
882 oid = *((unsigned int *)(localtdata->tdata->buffer->objread + incr));
883 incr += sizeof(unsigned int);
884 version = *((short *)(localtdata->tdata->buffer->objread + incr));
885 } else {//Objs modified
887 headptr = (objheader_t *)ptr;
889 version = headptr->version;
890 GETSIZE(tmpsize, headptr);
891 ptr += sizeof(objheader_t) + tmpsize;
894 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
896 /* Save the oids not found and number of oids not found for later use */
897 if ((mobj = mhashSearch(oid)) == NULL) {/* Obj not found */
898 /* Save the oids not found and number of oids not found for later use */
899 oidnotfound[objnotfound] = oid;
901 } else { /* If Obj found in machine (i.e. has not moved) */
902 /* Check if Obj is locked by any previous transaction */
903 if (STATUS(((objheader_t *)mobj)) & LOCK) {
904 if (version == ((objheader_t *)mobj)->version) { /* If not locked then match versions */
906 } else {/* If versions don't match ...HARD ABORT */
908 /* Send TRANS_DISAGREE to Coordinator */
909 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
911 } else {/* If Obj is not locked then lock object */
912 STATUS(((objheader_t *)mobj)) |= LOCK;
913 //TODO Remove this for Testing
914 //randomdelay(); -- Why is this here. BCD
916 /* Save all object oids that are locked on this machine during this transaction request call */
917 oidlocked[objlocked] = OID(((objheader_t *)mobj));
919 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
921 } else { /* If versions don't match ...HARD ABORT */
923 /* Send TRANS_DISAGREE to Coordinator */
924 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
930 /* Condition to send TRANS_AGREE */
931 if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
932 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
934 /* Condition to send TRANS_SOFT_ABORT */
935 if((v_matchlock > 0 && v_nomatch == 0) || (objnotfound > 0 && v_nomatch == 0)) {
936 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
937 //TODO currently the only soft abort case that is supported is when object locked by previous
938 //transaction => v_matchlock > 0
939 //The other case for SOFT ABORT i.e. when object is not found but versions match is not supported
940 /* Send number of oids not found and the missing oids if objects are missing in the machine */
941 /* TODO Remember to store the oidnotfound for later use
942 if(objnotfound != 0) {
943 int size = sizeof(unsigned int)* objnotfound;
948 /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
949 * if Participant receives a TRANS_COMMIT */
950 localtdata->transinfo->objlocked = oidlocked;
951 localtdata->transinfo->objnotfound = oidnotfound;
952 localtdata->transinfo->modptr = modptr;
953 localtdata->transinfo->numlocked = objlocked;
954 localtdata->transinfo->numnotfound = objnotfound;
956 /* Lock and update count */
957 //Thread sleeps until all messages from pariticipants are received by coordinator
958 pthread_mutex_lock(localtdata->tdata->lock);
959 (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */
961 /* Wake up the threads and invoke decideResponse (once) */
962 if(*(localtdata->tdata->count) == localtdata->tdata->buffer->f.mcount) {
963 decideResponse(localtdata->tdata);
964 pthread_cond_broadcast(localtdata->tdata->threshold);
966 pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock);
968 pthread_mutex_unlock(localtdata->tdata->lock);
970 /*Based on DecideResponse(), Either COMMIT or ABORT the operation*/
971 if(*(localtdata->tdata->replyctrl) == TRANS_ABORT){
972 if(transAbortProcess(modptr,oidlocked, localtdata->transinfo->numlocked, localtdata->tdata->buffer->f.nummod) != 0) {
973 printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
976 }else if(*(localtdata->tdata->replyctrl) == TRANS_COMMIT){
977 if(transComProcess(modptr, localtdata->tdata->buffer->oidmod, localtdata->tdata->buffer->oidcreated, oidlocked, localtdata->tdata->buffer->f.nummod, localtdata->tdata->buffer->f.numcreated, localtdata->transinfo->numlocked) != 0) {
978 printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
984 if (localtdata->transinfo->objlocked != NULL) {
985 free(localtdata->transinfo->objlocked);
986 localtdata->transinfo->objlocked = NULL;
988 if (localtdata->transinfo->objnotfound != NULL) {
989 free(localtdata->transinfo->objnotfound);
990 localtdata->transinfo->objnotfound = NULL;
995 /* This function completes the ABORT process if the transaction is aborting
997 int transAbortProcess(void *modptr, unsigned int *objlocked, int numlocked, int nummod) {
1000 objheader_t *tmp_header;
1003 /* Set all ref counts as 1 and do garbage collection */
1005 for(i = 0; i< nummod; i++) {
1007 tmp_header = (objheader_t *)ptr;
1008 tmp_header->rcount = 0;
1009 GETSIZE(tmpsize, tmp_header);
1010 ptr += sizeof(objheader_t) + tmpsize;
1012 /* Unlock objects that was locked due to this transaction */
1013 for(i = 0; i< numlocked; i++) {
1014 if((header = mhashSearch(objlocked[i])) == NULL) {
1015 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1018 STATUS(((objheader_t *)header)) &= ~(LOCK);
1021 /* Send ack to Coordinator */
1023 /*Free the pointer */
1028 /*This function completes the COMMIT process is the transaction is commiting
1030 int transComProcess(void *modptr, unsigned int *oidmod, unsigned int *oidcreated, unsigned int *objlocked, int nummod, int numcreated, int numlocked) {
1031 objheader_t *header;
1032 int i = 0, offset = 0;
1035 /* Process each modified object saved in the mainobject store */
1036 for(i = 0; i < nummod; i++) {
1038 if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
1039 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1042 /* Change reference count of older address and free space in objstr ?? */
1045 /* Change ptr address in mhash table */
1046 mhashRemove(oidmod[i]); //TODO: this shouldn't be necessary
1047 mhashInsert(oidmod[i], (((char *)modptr) + offset));
1048 GETSIZE(tmpsize, header);
1049 offset += sizeof(objheader_t) + tmpsize;
1051 /* Update object version number */
1052 header = (objheader_t *) mhashSearch(oidmod[i]);
1053 header->version += 1;
1056 /*If object is in prefetch cache then update it in prefetch cache */
1059 /* If object is newly created inside transaction then commit it */
1060 for (i = 0; i < numcreated; i++)
1063 header = (objheader_t *)(((char *)modptr) + offset);
1064 mhashInsert(oidcreated[i], (((char *)modptr) + offset));
1065 GETSIZE(tmpsize, header);
1066 offset += sizeof(objheader_t) + tmpsize;
1067 lhashInsert(oidcreated[i], myIpAddr);
1070 /* Unlock locked objects */
1071 for(i = 0; i < numlocked; i++) {
1072 if((header = (objheader_t *) mhashSearch(objlocked[i])) == NULL) {
1073 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1076 STATUS(header) &= ~(LOCK);
1079 //TODO Update location lookup table
1081 /* Send ack to Coordinator */
1082 printf("TRANS_SUCCESSFUL\n");
1086 /* This function checks if the prefetch oids are same and have same offsets
1087 * for case x.a.b and y.a.b where x and y have same oid's
1088 * or if a.b.c is a subset of x.b.c.d*/
1089 /* check for case where the generated request a.y.z or x.y.z.g then
1090 * prefetch needs to be generated for x.y.z.g if oid of a and x are same*/
1091 void checkPrefetchTuples(prefetchqelem_t *node) {
1092 int i,j, count,k, sindex, index;
1094 int ntuples, slength;
1096 short *endoffsets, *arryfields;
1098 /* Check for the case x.y.z and a.b.c are same oids */
1099 ptr = (char *) node;
1100 ntuples = *(GET_NTUPLES(ptr));
1101 oid = GET_PTR_OID(ptr);
1102 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1103 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1104 /* Find offset length for each tuple */
1105 int numoffset[ntuples];
1106 numoffset[0] = endoffsets[0];
1107 for(i = 1; i<ntuples; i++) {
1108 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1110 /* Check for redundant tuples by comparing oids of each tuple */
1111 for(i = 0; i < ntuples; i++) {
1114 for(j = i+1 ; j < ntuples; j++) {
1117 /*If oids of tuples match */
1118 if (oid[i] == oid[j]) {
1119 /* Find the smallest offset length of two tuples*/
1120 if(numoffset[i] > numoffset[j]){
1121 slength = numoffset[j];
1125 slength = numoffset[i];
1129 /* Compare the offset values based on the current indices
1130 * break if they do not match
1131 * if all offset values match then pick the largest tuple*/
1135 index = endoffsets[j -1];
1136 for(count = 0; count < slength; count ++) {
1137 if (arryfields[k] != arryfields[index]) {
1144 k = endoffsets[i-1];
1145 index = endoffsets[j-1];
1146 printf("Value of slength = %d\n", slength);
1147 for(count = 0; count < slength; count++) {
1148 if(arryfields[k] != arryfields[index]) {
1156 if(slength == count) {
1164 void checkPreCache(prefetchqelem_t *node, int *numoffset, int counter, int loopcount, unsigned int objoid, int index, int iter, int oidnfound) {
1166 int ntuples, i, k, flag;
1168 short *endoffsets, *arryfields;
1169 objheader_t *header;
1171 ptr = (char *) node;
1172 ntuples = *(GET_NTUPLES(ptr));
1173 oid = GET_PTR_OID(ptr);
1174 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1175 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1177 if(oidnfound == 1) {
1178 if((header = (objheader_t *) prehashSearch(objoid)) == NULL) {
1180 } else { //Found in Prefetch Cache
1181 //TODO Decide if object is too old, if old remove from cache
1182 tmp = (char *) header;
1183 /* Check if any of the offset oid is available in the Prefetch cache */
1184 for(i = counter; i < loopcount; i++) {
1185 objoid = *(tmp + sizeof(objheader_t) + arryfields[counter]);
1186 if((header = (objheader_t *)prehashSearch(objoid)) != NULL) {
1195 for(i = counter; i<loopcount; i++) {
1196 if((header = (objheader_t *)prehashSearch(objoid)) != NULL) {
1197 tmp = (char *) header;
1198 objoid = *(tmp + sizeof(objheader_t) + arryfields[index]);
1208 /* If oid not found locally or in prefetch cache then
1209 * assign the latest oid found as the new oid
1210 * and copy left over offsets into the arrayoffsetfieldarray*/
1212 numoffset[iter] = numoffset[iter] - (i+1);
1213 for(k = 0; k < numoffset[iter] ; k++) {
1214 arryfields[endoffsets[counter]+k] = arryfields[endoffsets[counter]+k+1];
1219 numoffset[iter] = 0;
1223 /* This function makes machine piles to be added into the machine pile queue for each prefetch call */
1224 prefetchpile_t *makePreGroups(prefetchqelem_t *node, int *numoffset) {
1226 int ntuples, slength, i, machinenum;
1229 short *endoffsets, *arryfields, *offset;
1230 prefetchpile_t *head = NULL;
1232 /* Check for the case x.y.z and a.b.c are same oids */
1233 ptr = (char *) node;
1234 ntuples = *(GET_NTUPLES(ptr));
1235 oid = GET_PTR_OID(ptr);
1236 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1237 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1239 /* Check for redundant tuples by comparing oids of each tuple */
1240 for(i = 0; i < ntuples; i++) {
1243 /* For each tuple make piles */
1244 if ((machinenum = lhashSearch(oid[i])) == 0) {
1245 printf("Error: No such Machine %s, %d\n", __FILE__, __LINE__);
1248 /* Insert into machine pile */
1249 offset = &arryfields[endoffsets[i-1]];
1250 insertPile(machinenum, oid[i], numoffset[i], offset, &head);
1256 /* This function checks if the oids within the prefetch tuples are available locally.
1257 * If yes then makes the tuple invalid. If no then rearranges oid and offset values in
1258 * the prefetchqelem_t node to represent a new prefetch tuple */
1259 prefetchpile_t *foundLocal(prefetchqelem_t *node) {
1260 int ntuples,i, j, k, oidnfound = 0, index, flag;
1262 unsigned int objoid;
1264 objheader_t *objheader;
1265 short *endoffsets, *arryfields;
1266 prefetchpile_t *head = NULL;
1268 ptr = (char *) node;
1269 ntuples = *(GET_NTUPLES(ptr));
1270 oid = GET_PTR_OID(ptr);
1271 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1272 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1273 /* Find offset length for each tuple */
1274 int numoffset[ntuples];//Number of offsets for each tuple
1275 numoffset[0] = endoffsets[0];
1276 for(i = 1; i<ntuples; i++) {
1277 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1279 for(i = 0; i < ntuples; i++) {
1282 /* If object found locally */
1283 if((objheader = (objheader_t*) mhashSearch(oid[i])) != NULL) {
1285 tmp = (char *) objheader;
1286 /* Find the oid of its offset value */
1290 index = endoffsets[i - 1];
1291 for(j = 0 ; j < numoffset[i] ; j++) {
1292 objoid = *(tmp + sizeof(objheader_t) + arryfields[index]);
1293 /*If oid found locally then
1294 *assign the latest oid found as the new oid
1295 *and copy left over offsets into the arrayoffsetfieldarray*/
1297 numoffset[i] = numoffset[i] - (j+1);
1298 for(k = 0; k < numoffset[i]; k++)
1299 arryfields[endoffsets[j]+ k] = arryfields[endoffsets[j]+k+1];
1301 /*New offset oid not found */
1302 if((objheader = (objheader_t*) mhashSearch(objoid)) == NULL) {
1304 checkPreCache(node, numoffset, j, numoffset[i], objoid, index, i, oidnfound);
1310 /*If all offset oids are found locally,make the prefetch tuple invalid */
1317 /* Look in Prefetch cache */
1318 checkPreCache(node, numoffset, 0, numoffset[i], oid[i], 0, i, oidnfound);
1322 /* Make machine groups */
1323 head = makePreGroups(node, numoffset);
1327 /* This function is called by the thread calling transPrefetch */
1328 void *transPrefetch(void *t) {
1329 prefetchqelem_t *qnode;
1330 prefetchpile_t *pilehead = NULL;
1333 /* lock mutex of primary prefetch queue */
1334 pthread_mutex_lock(&pqueue.qlock);
1335 /* while primary queue is empty, then wait */
1336 while((pqueue.front == NULL) && (pqueue.rear == NULL)) {
1337 pthread_cond_wait(&pqueue.qcond, &pqueue.qlock);
1340 /* dequeue node to create a machine piles and finally unlock mutex */
1341 if((qnode = pre_dequeue()) == NULL) {
1342 printf("Error: No node returned %s, %d\n", __FILE__, __LINE__);
1343 pthread_mutex_unlock(&pqueue.qlock);
1346 pthread_mutex_unlock(&pqueue.qlock);
1347 /* Reduce redundant prefetch requests */
1348 checkPrefetchTuples(qnode);
1349 /* Check if the tuples are found locally, if yes then reduce them further*/
1350 /* and group requests by remote machine ids by calling the makePreGroups() */
1351 pilehead = foundLocal(qnode);
1353 /* Lock mutex of pool queue */
1354 pthread_mutex_lock(&mcqueue.qlock);
1355 /* Update the pool queue with the new remote machine piles generated per prefetch call */
1356 mcpileenqueue(pilehead);
1357 /* Broadcast signal on machine pile queue */
1358 pthread_cond_broadcast(&mcqueue.qcond);
1359 /* Unlock mutex of machine pile queue */
1360 pthread_mutex_unlock(&mcqueue.qlock);
1361 /* Deallocate the prefetch queue pile node */
1367 /* Each thread in the pool of threads calls this function to establish connection with
1368 * remote machines, send the prefetch requests and process the reponses from
1369 * the remote machines .
1370 * The thread is active throughout the period of runtime */
1372 void *mcqProcess(void *threadid) {
1374 prefetchpile_t *mcpilenode;
1376 tid = (int) threadid;
1378 /* Lock mutex of mc pile queue */
1379 pthread_mutex_lock(&mcqueue.qlock);
1380 /* When mc pile queue is empty, wait */
1381 while((mcqueue.front == NULL) && (mcqueue.rear == NULL)) {
1382 pthread_cond_wait(&mcqueue.qcond, &mcqueue.qlock);
1384 /* Dequeue node to send remote machine connections*/
1385 if((mcpilenode = mcpiledequeue()) == NULL) {
1386 printf("Dequeue Error: No node returned %s %d\n", __FILE__, __LINE__);
1387 pthread_mutex_unlock(&mcqueue.qlock);
1391 pthread_mutex_unlock(&mcqueue.qlock);
1393 /*Initiate connection to remote host and send request */
1394 /* Process Request */
1395 sendPrefetchReq(mcpilenode, tid);
1397 /* Deallocate the machine queue pile node */
1398 mcdealloc(mcpilenode);
1402 void sendPrefetchReq(prefetchpile_t *mcpilenode, int threadid) {
1403 int sd, i, offset, off, len, endpair, count = 0;
1404 struct sockaddr_in serv_addr;
1405 struct hostent *server;
1406 char machineip[16], control;
1410 /* Send Trans Prefetch Request */
1411 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
1412 perror("Error in socket for TRANS_REQUEST\n");
1415 bzero((char*) &serv_addr, sizeof(serv_addr));
1416 serv_addr.sin_family = AF_INET;
1417 serv_addr.sin_port = htons(LISTEN_PORT);
1418 //serv_addr.sin_addr.s_addr = inet_addr(MACHINE_IP);
1419 midtoIP(mcpilenode->mid ,machineip);
1420 machineip[15] = '\0';
1421 serv_addr.sin_addr.s_addr = inet_addr(machineip);
1423 /* Open Connection */
1424 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
1425 perror("Error in connect for TRANS_REQUEST\n");
1430 /* Send TRANS_PREFETCH control message */
1431 control = TRANS_PREFETCH;
1432 if(send(sd, &control, sizeof(char), MSG_NOSIGNAL) < sizeof(char)) {
1433 perror("Error in sending prefetch control\n");
1438 /* Send Oids and offsets in pairs */
1439 tmp = mcpilenode->objpiles;
1440 while(tmp != NULL) {
1442 count++; /* Keeps track of the number of oid and offset tuples sent per remote machine */
1443 len = sizeof(int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1444 char oidnoffset[len];
1445 memcpy(oidnoffset, &len, sizeof(int));
1447 memcpy(oidnoffset + off, &tmp->oid, sizeof(unsigned int));
1448 off += sizeof(unsigned int);
1449 for(i = 0; i < tmp->numoffset; i++) {
1450 memcpy(oidnoffset + off, &tmp->offset[i], sizeof(short));
1453 if (send(sd, &oidnoffset, sizeof(oidnoffset),MSG_NOSIGNAL) < sizeof(oidnoffset)) {
1454 perror("Error sending fixed bytes for thread\n");
1461 /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
1463 if (send(sd, &endpair, sizeof(int), MSG_NOSIGNAL) < sizeof(int)) {
1464 perror("Error sending fixed bytes for thread\n");
1469 /* Get Response from the remote machine */
1470 getPrefetchResponse(count,sd);
1475 void getPrefetchResponse(int count, int sd) {
1476 int i = 0, val, n, N, sum, index, objsize;
1477 unsigned int bufsize,oid;
1478 char buffer[RECEIVE_BUFFER_SIZE], control;
1480 void *modptr, *oldptr;
1482 /* Read prefetch response from the Remote machine */
1483 if((val = read(sd, &control, sizeof(char))) <= 0) {
1484 perror("No control response for Prefetch request sent\n");
1488 if(control == TRANS_PREFETCH_RESPONSE) {
1489 /*For each oid and offset tuple sent as prefetch request to remote machine*/
1493 /* Read the size of buffer to be received */
1494 if((N = read(sd, buffer, sizeof(unsigned int))) <= 0) {
1495 perror("Size of buffer not recv\n");
1498 memcpy(&bufsize, buffer, sizeof(unsigned int));
1499 ptr = buffer + sizeof(unsigned int);
1500 /* Keep receiving the buffer containing oid info */
1502 n = recv((int)sd, (void *)ptr+sum, bufsize-sum, 0);
1504 } while(sum < bufsize && n != 0);
1505 /* Decode the contents of the buffer */
1506 index = sizeof(unsigned int);
1507 while(index < (bufsize - sizeof(unsigned int))) {
1508 if(buffer[index] == OBJECT_FOUND) {
1509 /* Increment it to get the object */
1510 index += sizeof(char);
1511 memcpy(&oid, buffer + index, sizeof(unsigned int));
1512 index += sizeof(unsigned int);
1513 /* For each object found add to Prefetch Cache */
1514 memcpy(&objsize, buffer + index, sizeof(int));
1516 pthread_mutex_lock(&prefetchcache_mutex);
1517 if ((modptr = objstrAlloc(prefetchcache, objsize)) == NULL) {
1518 printf("objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
1519 pthread_mutex_unlock(&prefetchcache_mutex);
1522 pthread_mutex_unlock(&prefetchcache_mutex);
1523 memcpy(modptr, buffer+index, objsize);
1525 /* Insert the oid and its address into the prefetch hash lookup table */
1526 /* Do a version comparison if the oid exists */
1527 if((oldptr = prehashSearch(oid)) != NULL) {
1528 /* If older version then update with new object ptr */
1529 if(((objheader_t *)oldptr)->version < ((objheader_t *)modptr)->version) {
1531 prehashInsert(oid, modptr);
1532 } else if(((objheader_t *)oldptr)->version == ((objheader_t *)modptr)->version) {
1533 /* Add the new object ptr to hash table */
1535 prehashInsert(oid, modptr);
1536 } else { /* Do nothing: TODO modptr should be reference counted */
1539 } else {/*If doesn't no match found in hashtable, add the object ptr to hash table*/
1540 prehashInsert(oid, modptr);
1542 /* Lock the Prefetch Cache look up table*/
1543 //pthread_mutex_lock(&pflookup.lock);
1544 /* Broadcast signal on prefetch cache condition variable */
1545 pthread_cond_broadcast(&pflookup.cond);
1546 /* Unlock the Prefetch Cache look up table*/
1547 //pthread_mutex_unlock(&pflookup.lock);
1548 } else if(buffer[index] == OBJECT_NOT_FOUND) {
1549 /* Increment it to get the object */
1550 /* TODO: For each object not found query DHT for new location and retrieve the object */
1551 index += sizeof(char);
1552 memcpy(&oid, buffer + index, sizeof(unsigned int));
1553 index += sizeof(unsigned int);
1554 /* Throw an error */
1555 printf("OBJECT NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n");
1558 printf("Error in decoding the index value %s, %d\n",__FILE__, __LINE__);
1566 printf("Error in receving response for prefetch request %s, %d\n",__FILE__, __LINE__);
1570 unsigned short getObjType(unsigned int oid)
1572 objheader_t *objheader;
1573 unsigned short numoffsets = 0;
1575 if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL)
1577 if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1579 prefetch(1, &oid, &numoffsets, NULL);
1580 pthread_mutex_lock(&pflookup.lock);
1581 while ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1583 pthread_cond_wait(&pflookup.cond, &pflookup.lock);
1585 pthread_mutex_unlock(&pflookup.lock);
1589 return TYPE(objheader);
1592 int startRemoteThread(unsigned int oid, unsigned int mid)
1595 struct sockaddr_in remoteAddr;
1596 char msg[1 + sizeof(unsigned int)];
1600 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
1602 perror("startRemoteThread():socket()");
1606 bzero(&remoteAddr, sizeof(remoteAddr));
1607 remoteAddr.sin_family = AF_INET;
1608 remoteAddr.sin_port = htons(LISTEN_PORT);
1609 remoteAddr.sin_addr.s_addr = htonl(mid);
1611 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0)
1613 printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
1614 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1619 msg[0] = START_REMOTE_THREAD;
1620 memcpy(&msg[1], &oid, sizeof(unsigned int));
1622 bytesSent = send(sock, msg, 1 + sizeof(unsigned int), 0);
1625 perror("startRemoteThread():send()");
1628 else if (bytesSent != 1 + sizeof(unsigned int))
1630 printf("startRemoteThread(): error, sent %d bytes\n", bytesSent);
1643 //TODO: when reusing oids, make sure they are not already in use!
1644 unsigned int getNewOID(void) {
1645 static unsigned int id = 0xFFFFFFFF;
1648 if (id > oidMax || id < oidMin)
1655 int processConfigFile()
1658 const int maxLineLength = 200;
1659 char lineBuffer[maxLineLength];
1661 const char *delimiters = " \t\n";
1665 configFile = fopen(CONFIG_FILENAME, "r");
1666 if (configFile == NULL)
1668 printf("error opening %s:\n", CONFIG_FILENAME);
1673 numHostsInSystem = 0;
1674 sizeOfHostArray = 8;
1675 hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
1677 while(fgets(lineBuffer, maxLineLength, configFile) != NULL)
1679 commentBegin = strchr(lineBuffer, '#');
1680 if (commentBegin != NULL)
1681 *commentBegin = '\0';
1682 token = strtok(lineBuffer, delimiters);
1683 while (token != NULL)
1685 tmpAddr = inet_addr(token);
1686 if ((int)tmpAddr == -1)
1688 printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
1693 addHost(htonl(tmpAddr));
1694 token = strtok(NULL, delimiters);
1700 if (numHostsInSystem < 1)
1702 printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
1706 myIpAddr = getMyIpAddr("en1");
1708 myIpAddr = getMyIpAddr("eth0");
1710 myIndexInHostArray = findHost(myIpAddr);
1711 if (myIndexInHostArray == -1)
1713 printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
1716 oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
1717 oidMin = oidsPerBlock * myIndexInHostArray;
1718 if (myIndexInHostArray == numHostsInSystem - 1)
1719 oidMax = 0xFFFFFFFF;
1721 oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
1726 void addHost(unsigned int hostIp)
1728 unsigned int *tmpArray;
1730 if (findHost(hostIp) != -1)
1733 if (numHostsInSystem == sizeOfHostArray)
1735 tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
1736 memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
1738 hostIpAddrs = tmpArray;
1741 hostIpAddrs[numHostsInSystem++] = hostIp;
1746 int findHost(unsigned int hostIp)
1749 for (i = 0; i < numHostsInSystem; i++)
1750 if (hostIpAddrs[i] == hostIp)