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 extern pthread_mutex_t mainobjstore_mutex;// Mutex to lock main Object store
35 extern prehashtable_t pflookup; //Global Prefetch cache's lookup table
36 pthread_t wthreads[NUM_THREADS]; //Worker threads for working on the prefetch queue
37 pthread_t tPrefetch; /* Primary Prefetch thread that processes the prefetch queue */
38 extern objstr_t *mainobjstore;
39 unsigned int myIpAddr;
40 unsigned int *hostIpAddrs;
43 int myIndexInHostArray;
44 unsigned int oidsPerBlock;
48 plistnode_t *createPiles(transrecord_t *);
49 inline int arrayLength(int *array) {
51 for(i=0 ;array[i] != -1; i++)
55 inline int findmax(int *array, int arraylength) {
58 for(i = 0; i < arraylength; i++){
65 /* This function is a prefetch call generated by the compiler that
66 * populates the shared primary prefetch queue*/
67 void prefetch(int ntuples, unsigned int *oids, unsigned short *endoffsets, short *arrayfields) {
71 /* Allocate for the queue node*/
73 qnodesize = sizeof(prefetchqelem_t) + sizeof(int) + ntuples * (sizeof(short) + sizeof(unsigned int)) + endoffsets[ntuples - 1] * sizeof(short);
74 if((node = calloc(1, qnodesize)) == NULL) {
75 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
78 /* Set queue node values */
79 len = sizeof(prefetchqelem_t);
80 memcpy(node + len, &ntuples, sizeof(int));
82 memcpy(node + len, oids, ntuples*sizeof(unsigned int));
83 len += ntuples * sizeof(unsigned int);
84 memcpy(node + len, endoffsets, ntuples*sizeof(short));
85 len += ntuples * sizeof(short);
86 memcpy(node + len, arrayfields, endoffsets[ntuples-1]*sizeof(short));
87 /* Lock and insert into primary prefetch queue */
88 pthread_mutex_lock(&pqueue.qlock);
89 pre_enqueue((prefetchqelem_t *)node);
90 pthread_cond_signal(&pqueue.qcond);
91 pthread_mutex_unlock(&pqueue.qlock);
94 /* This function starts up the transaction runtime. */
95 int dstmStartup(const char * option) {
96 pthread_t thread_Listen;
98 int master=option!=NULL && strcmp(option, "master")==0;
100 if (processConfigFile() != 0)
101 return 0; //TODO: return error value, cause main program to exit
107 pthread_attr_init(&attr);
108 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
109 pthread_create(&thread_Listen, &attr, dstmListen, NULL);
119 /* This function initiates the prefetch thread
120 * A queue is shared between the main thread of execution
121 * and the prefetch thread to process the prefetch call
122 * Call from compiler populates the shared queue with prefetch requests while prefetch thread
123 * processes the prefetch requests */
126 //Create and initialize prefetch cache structure
127 prefetchcache = objstrCreate(PREFETCH_CACHE_SIZE);
128 pthread_mutex_init(&prefetchcache_mutex, NULL);
129 //Create prefetch cache lookup table
130 if(prehashCreate(HASH_SIZE, LOADFACTOR))
132 //Initialize primary shared queue
134 //Initialize machine pile w/prefetch oids and offsets shared queue
136 //Create the primary prefetch thread
137 pthread_create(&tPrefetch, NULL, transPrefetch, NULL);
138 //Create and Initialize a pool of threads
139 /* Threads are active for the entire period runtime is running */
140 for(t = 0; t< NUM_THREADS; t++) {
141 rc = pthread_create(&wthreads[t], NULL, mcqProcess, (void *)t);
143 printf("Thread create error %s, %d\n", __FILE__, __LINE__);
149 /* This function stops the threads spawned */
152 pthread_cancel(tPrefetch);
153 for(t = 0; t < NUM_THREADS; t++)
154 pthread_cancel(wthreads[t]);
159 /* This functions inserts randowm wait delays in the order of msec
160 * Mostly used when transaction commits retry*/
161 void randomdelay(void)
163 struct timespec req, rem;
168 req.tv_nsec = (long)(1000000 + (t%10000000)); //1-11 msec
169 nanosleep(&req, &rem);
173 /* This function initializes things required in the transaction start*/
174 transrecord_t *transStart()
176 transrecord_t *tmp = malloc(sizeof(transrecord_t));
177 tmp->cache = objstrCreate(1048576);
178 tmp->lookupTable = chashCreate(HASH_SIZE, LOADFACTOR);
180 tmp->revertlist=NULL;
185 /* This function finds the location of the objects involved in a transaction
186 * and returns the pointer to the object if found in a remote location */
187 objheader_t *transRead(transrecord_t *record, unsigned int oid) {
188 unsigned int machinenumber;
189 objheader_t *tmp, *objheader;
190 objheader_t *objcopy;
191 int size, rc, found = 0;
196 rc = gettimeofday(&tp, NULL);
198 /* Convert from timeval to timespec */
199 ts.tv_nsec = tp.tv_usec * 10;
201 /* Search local transaction cache */
202 if((objheader = (objheader_t *)chashSearch(record->lookupTable, oid)) != NULL){
204 return &objheader[1];
208 } else if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
209 /* Look up in machine lookup table and copy into cache*/
210 tmp = mhashSearch(oid);
212 size += sizeof(objheader_t);
213 //TODO:Lock the local trans cache while copying the object here
214 objcopy = objstrAlloc(record->cache, size);
215 memcpy(objcopy, (void *)objheader, size);
216 /* Insert into cache's lookup table */
217 chashInsert(record->lookupTable, OID(objheader), objcopy);
223 } else if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) { /* Look up in prefetch cache */
226 size+=sizeof(objheader_t);
227 //TODO:Lock the local trans cache while copying the object here
228 objcopy = objstrAlloc(record->cache, size);
229 memcpy(objcopy, (void *)tmp, size);
230 /* Insert into cache's lookup table */
231 chashInsert(record->lookupTable, OID(tmp), objcopy);
238 /*If object not found in prefetch cache then block until object appears in the prefetch cache */
239 pthread_mutex_lock(&prefetchcache_mutex);
241 rc = pthread_cond_timedwait(&pflookup.cond, &pflookup.lock, &ts);
242 if(rc == ETIMEDOUT) {
243 printf("Wait timed out\n");
244 /* Check Prefetch cache again */
245 if((tmp =(objheader_t *) prehashSearch(oid)) != NULL) {
248 size+=sizeof(objheader_t);
249 objcopy = objstrAlloc(record->cache, size);
250 memcpy(objcopy, (void *)tmp, size);
251 chashInsert(record->lookupTable, OID(tmp), objcopy);
252 pthread_mutex_unlock(&prefetchcache_mutex);
259 pthread_mutex_unlock(&prefetchcache_mutex);
265 /* Get the object from the remote location */
266 machinenumber = lhashSearch(oid);
267 objcopy = getRemoteObj(record, machinenumber, oid);
268 if(objcopy == NULL) {
269 printf("Object not found in Remote location %s, %d\n", __FILE__, __LINE__);
281 /* This function creates objects in the transaction record */
282 objheader_t *transCreateObj(transrecord_t *record, unsigned int size)
284 objheader_t *tmp = (objheader_t *) objstrAlloc(record->cache, (sizeof(objheader_t) + size));
285 OID(tmp) = getNewOID();
289 chashInsert(record->lookupTable, OID(tmp), tmp);
291 return &tmp[1]; //want space after object header
297 /* This function creates machine piles based on all machines involved in a
298 * transaction commit request */
299 plistnode_t *createPiles(transrecord_t *record) {
301 unsigned int size;/* Represents number of bins in the chash table */
302 chashlistnode_t *curr, *ptr, *next;
303 plistnode_t *pile = NULL;
304 unsigned int machinenum;
305 void *localmachinenum;
306 objheader_t *headeraddr;
308 ptr = record->lookupTable->table;
309 size = record->lookupTable->size;
311 for(i = 0; i < size ; i++) {
313 /* Inner loop to traverse the linked list of the cache lookupTable */
314 while(curr != NULL) {
315 //if the first bin in hash table is empty
321 if ((headeraddr = chashSearch(record->lookupTable, curr->key)) == NULL) {
322 printf("Error: No such oid %s, %d\n", __FILE__, __LINE__);
326 //Get machine location for object id (and whether local or not)
327 if (STATUS(headeraddr) & NEW || mhashSearch(curr->key) != NULL) {
328 machinenum = myIpAddr;
329 } else if ((machinenum = lhashSearch(curr->key)) == 0) {
330 printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
334 //Make machine groups
335 if ((pile = pInsert(pile, headeraddr, machinenum, record->lookupTable->numelements)) == NULL) {
336 printf("pInsert error %s, %d\n", __FILE__, __LINE__);
346 /* This function initiates the transaction commit process
347 * Spawns threads for each of the new connections with Participants
348 * and creates new piles by calling the createPiles(),
349 * Sends a transrequest() to each remote machines for objects found remotely
350 * and calls handleLocalReq() to process objects found locally */
351 int transCommit(transrecord_t *record) {
352 unsigned int tot_bytes_mod, *listmid;
353 plistnode_t *pile, *pile_ptr;
355 int pilecount = 0, offset, threadnum = 0, trecvcount = 0, tmachcount = 0;
356 char buffer[RECEIVE_BUFFER_SIZE],control;
357 char transid[TID_LEN];
358 trans_req_data_t *tosend;
359 trans_commit_data_t transinfo;
360 static int newtid = 0;
361 char treplyctrl = 0, treplyretry = 0; /* keeps track of the common response that needs to be sent */
366 /* Look through all the objects in the transaction record and make piles
367 * for each machine involved in the transaction*/
368 pile_ptr = pile = createPiles(record);
370 /* Create the packet to be sent in TRANS_REQUEST */
372 /* Count the number of participants */
373 pilecount = pCount(pile);
375 /* Create a list of machine ids(Participants) involved in transaction */
376 if((listmid = calloc(pilecount, sizeof(unsigned int))) == NULL) {
377 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
380 pListMid(pile, listmid);
383 /* Initialize thread variables,
384 * Spawn a thread for each Participant involved in a transaction */
385 pthread_t thread[pilecount];
387 pthread_cond_t tcond;
388 pthread_mutex_t tlock;
389 pthread_mutex_t tlshrd;
391 thread_data_array_t *thread_data_array;
392 if((thread_data_array = (thread_data_array_t *) malloc(sizeof(thread_data_array_t)*pilecount)) == NULL) {
393 printf("Malloc error %s, %d\n", __FILE__, __LINE__);
394 pthread_cond_destroy(&tcond);
395 pthread_mutex_destroy(&tlock);
401 local_thread_data_array_t *ltdata;
402 if((ltdata = calloc(1, sizeof(local_thread_data_array_t))) == NULL) {
403 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
404 pthread_cond_destroy(&tcond);
405 pthread_mutex_destroy(&tlock);
408 free(thread_data_array);
412 thread_response_t rcvd_control_msg[pilecount]; /* Shared thread array that keeps track of responses of participants */
414 /* Initialize and set thread detach attribute */
415 pthread_attr_init(&attr);
416 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
417 pthread_mutex_init(&tlock, NULL);
418 pthread_cond_init(&tcond, NULL);
420 /* Process each machine pile */
421 while(pile != NULL) {
422 //Create transaction id
424 if ((tosend = calloc(1, sizeof(trans_req_data_t))) == NULL) {
425 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
426 pthread_cond_destroy(&tcond);
427 pthread_mutex_destroy(&tlock);
430 free(thread_data_array);
434 tosend->f.control = TRANS_REQUEST;
435 sprintf(tosend->f.trans_id, "%x_%d", pile->mid, newtid);
436 tosend->f.mcount = pilecount;
437 tosend->f.numread = pile->numread;
438 tosend->f.nummod = pile->nummod;
439 tosend->f.numcreated = pile->numcreated;
440 tosend->f.sum_bytes = pile->sum_bytes;
441 tosend->listmid = listmid;
442 tosend->objread = pile->objread;
443 tosend->oidmod = pile->oidmod;
444 tosend->oidcreated = pile->oidcreated;
445 thread_data_array[threadnum].thread_id = threadnum;
446 thread_data_array[threadnum].mid = pile->mid;
447 thread_data_array[threadnum].buffer = tosend;
448 thread_data_array[threadnum].recvmsg = rcvd_control_msg;
449 thread_data_array[threadnum].threshold = &tcond;
450 thread_data_array[threadnum].lock = &tlock;
451 thread_data_array[threadnum].count = &trecvcount;
452 thread_data_array[threadnum].replyctrl = &treplyctrl;
453 thread_data_array[threadnum].replyretry = &treplyretry;
454 thread_data_array[threadnum].rec = record;
455 /* If local do not create any extra connection */
456 if(pile->mid != myIpAddr) { /* Not local */
457 rc = pthread_create(&thread[threadnum], NULL, transRequest, (void *) &thread_data_array[threadnum]);
459 perror("Error in pthread create\n");
460 pthread_cond_destroy(&tcond);
461 pthread_mutex_destroy(&tlock);
464 free(thread_data_array);
470 ltdata->tdata = &thread_data_array[threadnum];
471 ltdata->transinfo = &transinfo;
472 val = pthread_create(&thread[threadnum], NULL, handleLocalReq, (void *) ltdata);
474 perror("Error in pthread create\n");
475 pthread_cond_destroy(&tcond);
476 pthread_mutex_destroy(&tlock);
479 free(thread_data_array);
490 /* Free attribute and wait for the other threads */
491 pthread_attr_destroy(&attr);
493 for (i = 0; i < pilecount; i++) {
494 rc = pthread_join(thread[i], NULL);
497 printf("ERROR return code from pthread_join() is %d\n", rc);
498 pthread_cond_destroy(&tcond);
499 pthread_mutex_destroy(&tlock);
502 free(thread_data_array);
507 free(thread_data_array[i].buffer);
512 pthread_cond_destroy(&tcond);
513 pthread_mutex_destroy(&tlock);
517 if(thread_data_array != NULL)
518 free(thread_data_array);
522 /* wait a random amount of time */
523 if (treplyretry == 1)
526 /* Retry trans commit procedure if not sucessful in the first try */
527 } while (treplyretry == 1);
532 /* This function sends information involved in the transaction request
533 * to participants and accepts a response from particpants.
534 * It calls decideresponse() to decide on what control message
535 * to send next to participants and sends the message using sendResponse()*/
536 void *transRequest(void *threadarg) {
538 struct sockaddr_in serv_addr;
539 struct hostent *server;
540 thread_data_array_t *tdata;
541 objheader_t *headeraddr;
542 char buffer[RECEIVE_BUFFER_SIZE], control, recvcontrol;
543 char machineip[16], retval;
545 tdata = (thread_data_array_t *) threadarg;
547 /* Send Trans Request */
548 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
549 perror("Error in socket for TRANS_REQUEST\n");
553 bzero((char*) &serv_addr, sizeof(serv_addr));
554 serv_addr.sin_family = AF_INET;
555 serv_addr.sin_port = htons(LISTEN_PORT);
556 midtoIP(tdata->mid,machineip);
557 machineip[15] = '\0';
558 serv_addr.sin_addr.s_addr = inet_addr(machineip);
559 /* Open Connection */
560 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
561 perror("Error in connect for TRANS_REQUEST\n");
566 printf("DEBUG-> trans.c Sending TRANS_REQUEST to mid %s\n", machineip);
567 /* Send bytes of data with TRANS_REQUEST control message */
568 if (send(sd, &(tdata->buffer->f), sizeof(fixed_data_t),MSG_NOSIGNAL) < sizeof(fixed_data_t)) {
569 perror("Error sending fixed bytes for thread\n");
573 /* Send list of machines involved in the transaction */
575 int size=sizeof(unsigned int)*tdata->buffer->f.mcount;
576 if (send(sd, tdata->buffer->listmid, size, MSG_NOSIGNAL) < size) {
577 perror("Error sending list of machines for thread\n");
582 /* Send oids and version number tuples for objects that are read */
584 int size=(sizeof(unsigned int)+sizeof(short))*tdata->buffer->f.numread;
585 if (send(sd, tdata->buffer->objread, size, MSG_NOSIGNAL) < size) {
586 perror("Error sending tuples for thread\n");
591 /* Send objects that are modified */
592 for(i = 0; i < tdata->buffer->f.nummod ; i++) {
594 headeraddr = chashSearch(tdata->rec->lookupTable, tdata->buffer->oidmod[i]);
595 GETSIZE(size,headeraddr);
596 size+=sizeof(objheader_t);
597 if (send(sd, headeraddr, size, MSG_NOSIGNAL) < size) {
598 perror("Error sending obj modified for thread\n");
604 /* Read control message from Participant */
605 if((n = read(sd, &control, sizeof(char))) <= 0) {
606 perror("Error in reading control message from Participant\n");
610 recvcontrol = control;
612 /* Update common data structure and increment count */
613 tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol;
615 /* Lock and update count */
616 /* Thread sleeps until all messages from pariticipants are received by coordinator */
617 pthread_mutex_lock(tdata->lock);
619 (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */
621 /* Wake up the threads and invoke decideResponse (once) */
622 if(*(tdata->count) == tdata->buffer->f.mcount) {
623 if (decideResponse(tdata) != 0) {
624 printf("decideResponse returned error %s,%d\n", __FILE__, __LINE__);
625 pthread_mutex_unlock(tdata->lock);
629 pthread_cond_broadcast(tdata->threshold);
631 pthread_cond_wait(tdata->threshold, tdata->lock);
633 pthread_mutex_unlock(tdata->lock);
635 /* Send the final response such as TRANS_COMMIT or TRANS_ABORT t
636 * to all participants in their respective socket */
637 if (sendResponse(tdata, sd) == 0) {
638 printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__);
639 pthread_mutex_unlock(tdata->lock);
644 /* Close connection */
649 /* This function decides the reponse that needs to be sent to
650 * all Participant machines after the TRANS_REQUEST protocol */
651 int decideResponse(thread_data_array_t *tdata) {
653 int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
656 for (i = 0 ; i < tdata->buffer->f.mcount; i++) {
657 control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses
658 written onto the shared array */
668 case TRANS_SOFT_ABORT:
672 printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
678 if(transdisagree > 0) {
679 *(tdata->replyctrl) = TRANS_ABORT;
681 objstrDelete(tdata->rec->cache);
682 chashDelete(tdata->rec->lookupTable);
684 } else if(transagree == tdata->buffer->f.mcount){
686 *(tdata->replyctrl) = TRANS_COMMIT;
688 objstrDelete(tdata->rec->cache);
689 chashDelete(tdata->rec->lookupTable);
691 } else if(transsoftabort > 0 && transdisagree == 0) {
692 /* Send Abort in soft abort case followed by retry commiting transaction again*/
693 *(tdata->replyctrl) = TRANS_ABORT;
694 *(tdata->replyretry) = 1;
701 /* This function sends the final response to remote machines per thread in their respective socket id */
702 char sendResponse(thread_data_array_t *tdata, int sd) {
703 int n, N, sum, oidcount = 0;
704 char *ptr, retval = 0;
705 unsigned int *oidnotfound;
707 /* If the decided response is due to a soft abort and missing objects at the Participant's side */
708 if(tdata->recvmsg[tdata->thread_id].rcv_status == TRANS_SOFT_ABORT) {
709 /* Read list of objects missing */
710 if((read(sd, &oidcount, sizeof(int)) != 0) && (oidcount != 0)) {
711 N = oidcount * sizeof(unsigned int);
712 if((oidnotfound = calloc(oidcount, sizeof(unsigned int))) == NULL) {
713 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
716 ptr = (char *) oidnotfound;
718 n = read(sd, ptr+sum, N-sum);
720 } while(sum < N && n !=0);
722 retval = TRANS_SOFT_ABORT;
724 /* If the decided response is TRANS_ABORT */
725 if(*(tdata->replyctrl) == TRANS_ABORT) {
726 retval = TRANS_ABORT;
727 } else if(*(tdata->replyctrl) == TRANS_COMMIT) { /* If the decided response is TRANS_COMMIT */
728 retval = TRANS_COMMIT;
731 if (send(sd, tdata->replyctrl, sizeof(char),MSG_NOSIGNAL) < sizeof(char)) {
732 perror("Error sending ctrl message for participant\n");
738 /* This function opens a connection, places an object read request to the
739 * remote machine, reads the control message and object if available and
740 * copies the object and its header to the local cache.
741 * TODO replace mnum and midtoIP() with MACHINE_IP address later */
743 void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
745 struct sockaddr_in serv_addr;
746 struct hostent *server;
752 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
753 perror("Error in socket\n");
756 bzero((char*) &serv_addr, sizeof(serv_addr));
757 serv_addr.sin_family = AF_INET;
758 serv_addr.sin_port = htons(LISTEN_PORT);
759 //serv_addr.sin_addr.s_addr = inet_addr(MACHINE_IP);
760 midtoIP(mnum,machineip);
761 machineip[15] = '\0';
762 serv_addr.sin_addr.s_addr = inet_addr(machineip);
763 /* Open connection */
764 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
765 perror("Error in connect\n");
768 char readrequest[sizeof(char)+sizeof(unsigned int)];
769 readrequest[0] = READ_REQUEST;
770 *((unsigned int *)(&readrequest[1])) = oid;
771 if (send(sd, &readrequest, sizeof(readrequest), MSG_NOSIGNAL) < sizeof(readrequest)) {
772 perror("Error sending message\n");
777 printf("DEBUG -> ready to rcv ...\n");
779 /* Read response from the Participant */
780 if((val = read(sd, &control, sizeof(char))) <= 0) {
781 perror("No control response for getRemoteObj sent\n");
785 case OBJECT_NOT_FOUND:
788 /* Read object if found into local cache */
789 if((val = read(sd, &size, sizeof(int))) <= 0) {
790 perror("No size is read from the participant\n");
793 objcopy = objstrAlloc(record->cache, size);
794 if((val = read(sd, objcopy, size)) <= 0) {
795 perror("No objects are read from the remote participant\n");
798 /* Insert into cache's lookup table */
799 chashInsert(record->lookupTable, oid, objcopy);
802 printf("Error in recv request from participant on a READ_REQUEST %s, %d\n",__FILE__, __LINE__);
805 /* Close connection */
810 /* This function handles the local objects involved in a transaction commiting process.
811 * It also makes a decision if this local machine sends AGREE or DISAGREE or SOFT_ABORT to coordinator.
812 * Note Coordinator = local machine
813 * It wakes up the other threads from remote participants that are waiting for the coordinator's decision and
814 * based on common agreement it either commits or aborts the transaction.
815 * It also frees the memory resources */
816 void *handleLocalReq(void *threadarg) {
817 int val, i = 0, size, offset = 0;
819 char control = 0, *ptr;
821 unsigned int *oidnotfound = NULL, *oidlocked = NULL;
823 objheader_t *headptr, *headeraddr;
824 local_thread_data_array_t *localtdata;
826 localtdata = (local_thread_data_array_t *) threadarg;
828 /* Counters and arrays to formulate decision on control message to be sent */
829 oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
830 oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
831 int objnotfound = 0, objlocked = 0;
832 int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
834 /* modptr points to the beginning of the object store
835 * created at the Pariticipant */
836 pthread_mutex_lock(&mainobjstore_mutex);
837 if ((modptr = objstrAlloc(mainobjstore, localtdata->tdata->buffer->f.sum_bytes)) == NULL) {
838 printf("objstrAlloc error for modified objects %s, %d\n", __FILE__, __LINE__);
839 pthread_mutex_unlock(&mainobjstore_mutex);
842 pthread_mutex_unlock(&mainobjstore_mutex);
843 /* Write modified objects into the mainobject store */
844 for(i = 0; i< localtdata->tdata->buffer->f.nummod; i++) {
845 headeraddr = chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidmod[i]);
846 GETSIZE(size,headeraddr);
847 size+=sizeof(objheader_t);
848 memcpy((char *)modptr+offset, headeraddr, size);
851 /* Write new objects into the mainobject store */
852 for(i = 0; i< localtdata->tdata->buffer->f.numcreated; i++) {
853 headeraddr = chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidcreated[i]);
854 GETSIZE(size, headeraddr);
855 size+=sizeof(objheader_t);
856 memcpy((char *)modptr+offset, headeraddr, size);
863 /* Process each oid in the machine pile/ group per thread */
864 for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) {
865 if (i < localtdata->tdata->buffer->f.numread) {//Objs only read and not modified
866 int incr = sizeof(unsigned int) + sizeof(short);// Offset that points to next position in the objread array
868 oid = *((unsigned int *)(localtdata->tdata->buffer->objread + incr));
869 incr += sizeof(unsigned int);
870 version = *((short *)(localtdata->tdata->buffer->objread + incr));
871 } else {//Objs modified
873 headptr = (objheader_t *)ptr;
875 version = headptr->version;
876 GETSIZE(tmpsize, headptr);
877 ptr += sizeof(objheader_t) + tmpsize;
880 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
882 /* Save the oids not found and number of oids not found for later use */
883 if ((mobj = mhashSearch(oid)) == NULL) {/* Obj not found */
884 /* Save the oids not found and number of oids not found for later use */
885 oidnotfound[objnotfound] = oid;
887 } else { /* If Obj found in machine (i.e. has not moved) */
888 /* Check if Obj is locked by any previous transaction */
889 if (STATUS(((objheader_t *)mobj)) & LOCK) {
890 if (version == ((objheader_t *)mobj)->version) { /* If not locked then match versions */
892 } else {/* If versions don't match ...HARD ABORT */
894 /* Send TRANS_DISAGREE to Coordinator */
895 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
897 } else {/* If Obj is not locked then lock object */
898 STATUS(((objheader_t *)mobj)) |= LOCK;
899 //TODO Remove this for Testing
900 //randomdelay(); -- Why is this here. BCD
902 /* Save all object oids that are locked on this machine during this transaction request call */
903 oidlocked[objlocked] = OID(((objheader_t *)mobj));
905 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
907 } else { /* If versions don't match ...HARD ABORT */
909 /* Send TRANS_DISAGREE to Coordinator */
910 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
916 /* Condition to send TRANS_AGREE */
917 if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
918 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
920 /* Condition to send TRANS_SOFT_ABORT */
921 if((v_matchlock > 0 && v_nomatch == 0) || (objnotfound > 0 && v_nomatch == 0)) {
922 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
923 //TODO currently the only soft abort case that is supported is when object locked by previous
924 //transaction => v_matchlock > 0
925 //The other case for SOFT ABORT i.e. when object is not found but versions match is not supported
926 /* Send number of oids not found and the missing oids if objects are missing in the machine */
927 /* TODO Remember to store the oidnotfound for later use
928 if(objnotfound != 0) {
929 int size = sizeof(unsigned int)* objnotfound;
934 /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
935 * if Participant receives a TRANS_COMMIT */
936 localtdata->transinfo->objlocked = oidlocked;
937 localtdata->transinfo->objnotfound = oidnotfound;
938 localtdata->transinfo->modptr = modptr;
939 localtdata->transinfo->numlocked = objlocked;
940 localtdata->transinfo->numnotfound = objnotfound;
942 /* Lock and update count */
943 //Thread sleeps until all messages from pariticipants are received by coordinator
944 pthread_mutex_lock(localtdata->tdata->lock);
945 (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */
947 /* Wake up the threads and invoke decideResponse (once) */
948 if(*(localtdata->tdata->count) == localtdata->tdata->buffer->f.mcount) {
949 if (decideResponse(localtdata->tdata) != 0) {
950 printf("decideResponse returned error %s,%d\n", __FILE__, __LINE__);
951 pthread_mutex_unlock(localtdata->tdata->lock);
954 pthread_cond_broadcast(localtdata->tdata->threshold);
956 pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock);
958 pthread_mutex_unlock(localtdata->tdata->lock);
960 /*Based on DecideResponse(), Either COMMIT or ABORT the operation*/
961 if(*(localtdata->tdata->replyctrl) == TRANS_ABORT){
962 if(transAbortProcess(modptr,oidlocked, localtdata->transinfo->numlocked, localtdata->tdata->buffer->f.nummod) != 0) {
963 printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
966 }else if(*(localtdata->tdata->replyctrl) == TRANS_COMMIT){
967 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) {
968 printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
974 if (localtdata->transinfo->objlocked != NULL) {
975 free(localtdata->transinfo->objlocked);
976 localtdata->transinfo->objlocked = NULL;
978 if (localtdata->transinfo->objnotfound != NULL) {
979 free(localtdata->transinfo->objnotfound);
980 localtdata->transinfo->objnotfound = NULL;
985 /* This function completes the ABORT process if the transaction is aborting
987 int transAbortProcess(void *modptr, unsigned int *objlocked, int numlocked, int nummod) {
990 objheader_t *tmp_header;
993 /* Set all ref counts as 1 and do garbage collection */
995 for(i = 0; i< nummod; i++) {
997 tmp_header = (objheader_t *)ptr;
998 tmp_header->rcount = 0;
999 GETSIZE(tmpsize, tmp_header);
1000 ptr += sizeof(objheader_t) + tmpsize;
1002 /* Unlock objects that was locked due to this transaction */
1003 for(i = 0; i< numlocked; i++) {
1004 if((header = mhashSearch(objlocked[i])) == NULL) {
1005 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1008 STATUS(((objheader_t *)header)) &= ~(LOCK);
1011 /* Send ack to Coordinator */
1012 printf("TRANS_SUCCESSFUL\n");
1014 /*Free the pointer */
1019 /*This function completes the COMMIT process is the transaction is commiting
1021 int transComProcess(void *modptr, unsigned int *oidmod, unsigned int *oidcreated, unsigned int *objlocked, int nummod, int numcreated, int numlocked) {
1022 objheader_t *header;
1023 int i = 0, offset = 0;
1026 /* Process each modified object saved in the mainobject store */
1027 for(i = 0; i < nummod; i++) {
1029 if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
1030 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1033 /* Change reference count of older address and free space in objstr ?? */
1036 /* Change ptr address in mhash table */
1037 mhashRemove(oidmod[i]); //TODO: this shouldn't be necessary
1038 mhashInsert(oidmod[i], (((char *)modptr) + offset));
1039 GETSIZE(tmpsize, header);
1040 offset += sizeof(objheader_t) + tmpsize;
1042 /* Update object version number */
1043 header = (objheader_t *) mhashSearch(oidmod[i]);
1044 header->version += 1;
1047 for (i = 0; i < numcreated; i++)
1050 header = (objheader_t *)(((char *)modptr) + offset);
1051 mhashInsert(oidcreated[i], (((char *)modptr) + offset));
1052 GETSIZE(tmpsize, header);
1053 offset += sizeof(objheader_t) + tmpsize;
1055 lhashInsert(oidcreated[i], myIpAddr);
1058 /* Unlock locked objects */
1059 for(i = 0; i < numlocked; i++) {
1060 if((header = (objheader_t *) mhashSearch(objlocked[i])) == NULL) {
1061 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1064 STATUS(header) &= ~(LOCK);
1067 //TODO Update location lookup table
1069 /* Send ack to Coordinator */
1070 printf("TRANS_SUCCESSFUL\n");
1074 /* This function checks if the prefetch oids are same and have same offsets
1075 * for case x.a.b and y.a.b where x and y have same oid's
1076 * or if a.b.c is a subset of x.b.c.d*/
1077 /* check for case where the generated request a.y.z or x.y.z.g then
1078 * prefetch needs to be generated for x.y.z.g if oid of a and x are same*/
1079 void checkPrefetchTuples(prefetchqelem_t *node) {
1080 int i,j, count,k, sindex, index;
1082 int ntuples, slength;
1084 short *endoffsets, *arryfields;
1086 /* Check for the case x.y.z and a.b.c are same oids */
1087 ptr = (char *) node;
1088 ntuples = *(GET_NTUPLES(ptr));
1089 oid = GET_PTR_OID(ptr);
1090 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1091 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1092 /* Find offset length for each tuple */
1093 int numoffset[ntuples];
1094 numoffset[0] = endoffsets[0];
1095 for(i = 1; i<ntuples; i++) {
1096 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1098 /* Check for redundant tuples by comparing oids of each tuple */
1099 for(i = 0; i < ntuples; i++) {
1102 for(j = i+1 ; j < ntuples; j++) {
1105 /*If oids of tuples match */
1106 if (oid[i] == oid[j]) {
1107 /* Find the smallest offset length of two tuples*/
1108 if(numoffset[i] > numoffset[j]){
1109 slength = numoffset[j];
1113 slength = numoffset[i];
1117 /* Compare the offset values based on the current indices
1118 * break if they do not match
1119 * if all offset values match then pick the largest tuple*/
1123 index = endoffsets[j -1];
1124 for(count = 0; count < slength; count ++) {
1125 if (arryfields[k] != arryfields[index]) {
1132 k = endoffsets[i-1];
1133 index = endoffsets[j-1];
1134 printf("Value of slength = %d\n", slength);
1135 for(count = 0; count < slength; count++) {
1136 if(arryfields[k] != arryfields[index]) {
1144 if(slength == count) {
1152 void checkPreCache(prefetchqelem_t *node, int *numoffset, int counter, int loopcount, unsigned int objoid, int index, int iter, int oidnfound) {
1154 int ntuples, i, k, flag;
1156 short *endoffsets, *arryfields;
1157 objheader_t *header;
1159 ptr = (char *) node;
1160 ntuples = *(GET_NTUPLES(ptr));
1161 oid = GET_PTR_OID(ptr);
1162 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1163 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1165 if(oidnfound == 1) {
1166 if((header = (objheader_t *) prehashSearch(objoid)) == NULL) {
1168 } else { //Found in Prefetch Cache
1169 //TODO Decide if object is too old, if old remove from cache
1170 tmp = (char *) header;
1171 /* Check if any of the offset oid is available in the Prefetch cache */
1172 for(i = counter; i < loopcount; i++) {
1173 objoid = *(tmp + sizeof(objheader_t) + arryfields[counter]);
1174 if((header = (objheader_t *)prehashSearch(objoid)) != NULL) {
1183 for(i = counter; i<loopcount; i++) {
1184 if((header = (objheader_t *)prehashSearch(objoid)) != NULL) {
1185 tmp = (char *) header;
1186 objoid = *(tmp + sizeof(objheader_t) + arryfields[index]);
1196 /* If oid not found locally or in prefetch cache then
1197 * assign the latest oid found as the new oid
1198 * and copy left over offsets into the arrayoffsetfieldarray*/
1200 numoffset[iter] = numoffset[iter] - (i+1);
1201 for(k = 0; k < numoffset[iter] ; k++) {
1202 arryfields[endoffsets[counter]+k] = arryfields[endoffsets[counter]+k+1];
1207 numoffset[iter] = 0;
1211 /* This function makes machine piles to be added into the machine pile queue for each prefetch call */
1212 prefetchpile_t *makePreGroups(prefetchqelem_t *node, int *numoffset) {
1214 int ntuples, slength, i, machinenum;
1217 short *endoffsets, *arryfields, *offset;
1218 prefetchpile_t *head = NULL;
1220 /* Check for the case x.y.z and a.b.c are same oids */
1221 ptr = (char *) node;
1222 ntuples = *(GET_NTUPLES(ptr));
1223 oid = GET_PTR_OID(ptr);
1224 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1225 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1227 /* Check for redundant tuples by comparing oids of each tuple */
1228 for(i = 0; i < ntuples; i++) {
1231 /* For each tuple make piles */
1232 if ((machinenum = lhashSearch(oid[i])) == 0) {
1233 printf("Error: No such Machine %s, %d\n", __FILE__, __LINE__);
1236 /* Insert into machine pile */
1237 offset = &arryfields[endoffsets[i-1]];
1238 insertPile(machinenum, oid[i], numoffset[i], offset, &head);
1244 /* This function checks if the oids within the prefetch tuples are available locally.
1245 * If yes then makes the tuple invalid. If no then rearranges oid and offset values in
1246 * the prefetchqelem_t node to represent a new prefetch tuple */
1247 prefetchpile_t *foundLocal(prefetchqelem_t *node) {
1248 int ntuples,i, j, k, oidnfound = 0, index, flag;
1250 unsigned int objoid;
1252 objheader_t *objheader;
1253 short *endoffsets, *arryfields;
1254 prefetchpile_t *head = NULL;
1256 ptr = (char *) node;
1257 ntuples = *(GET_NTUPLES(ptr));
1258 oid = GET_PTR_OID(ptr);
1259 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1260 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1261 /* Find offset length for each tuple */
1262 int numoffset[ntuples];//Number of offsets for each tuple
1263 numoffset[0] = endoffsets[0];
1264 for(i = 1; i<ntuples; i++) {
1265 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1267 for(i = 0; i < ntuples; i++) {
1270 /* If object found locally */
1271 if((objheader = (objheader_t*) mhashSearch(oid[i])) != NULL) {
1273 tmp = (char *) objheader;
1274 /* Find the oid of its offset value */
1278 index = endoffsets[i - 1];
1279 for(j = 0 ; j < numoffset[i] ; j++) {
1280 objoid = *(tmp + sizeof(objheader_t) + arryfields[index]);
1281 /*If oid found locally then
1282 *assign the latest oid found as the new oid
1283 *and copy left over offsets into the arrayoffsetfieldarray*/
1285 numoffset[i] = numoffset[i] - (j+1);
1286 for(k = 0; k < numoffset[i]; k++)
1287 arryfields[endoffsets[j]+ k] = arryfields[endoffsets[j]+k+1];
1289 /*New offset oid not found */
1290 if((objheader = (objheader_t*) mhashSearch(objoid)) == NULL) {
1292 checkPreCache(node, numoffset, j, numoffset[i], objoid, index, i, oidnfound);
1298 /*If all offset oids are found locally,make the prefetch tuple invalid */
1305 /* Look in Prefetch cache */
1306 checkPreCache(node, numoffset, 0, numoffset[i], oid[i], 0, i, oidnfound);
1310 /* Make machine groups */
1311 head = makePreGroups(node, numoffset);
1315 /* This function is called by the thread calling transPrefetch */
1316 void *transPrefetch(void *t) {
1317 prefetchqelem_t *qnode;
1318 prefetchpile_t *pilehead = NULL;
1321 /* lock mutex of primary prefetch queue */
1322 pthread_mutex_lock(&pqueue.qlock);
1323 /* while primary queue is empty, then wait */
1324 while((pqueue.front == NULL) && (pqueue.rear == NULL)) {
1325 pthread_cond_wait(&pqueue.qcond, &pqueue.qlock);
1328 /* dequeue node to create a machine piles and finally unlock mutex */
1329 if((qnode = pre_dequeue()) == NULL) {
1330 printf("Error: No node returned %s, %d\n", __FILE__, __LINE__);
1333 pthread_mutex_unlock(&pqueue.qlock);
1334 /* Reduce redundant prefetch requests */
1335 checkPrefetchTuples(qnode);
1336 /* Check if the tuples are found locally, if yes then reduce them further*/
1337 /* and group requests by remote machine ids by calling the makePreGroups() */
1338 pilehead = foundLocal(qnode);
1340 /* Lock mutex of pool queue */
1341 pthread_mutex_lock(&mcqueue.qlock);
1342 /* Update the pool queue with the new remote machine piles generated per prefetch call */
1343 mcpileenqueue(pilehead);
1344 /* Broadcast signal on machine pile queue */
1345 pthread_cond_broadcast(&mcqueue.qcond);
1346 /* Unlock mutex of machine pile queue */
1347 pthread_mutex_unlock(&mcqueue.qlock);
1348 /* Deallocate the prefetch queue pile node */
1354 /* Each thread in the pool of threads calls this function to establish connection with
1355 * remote machines, send the prefetch requests and process the reponses from
1356 * the remote machines .
1357 * The thread is active throughout the period of runtime */
1359 void *mcqProcess(void *threadid) {
1361 prefetchpile_t *mcpilenode;
1363 tid = (int) threadid;
1365 /* Lock mutex of mc pile queue */
1366 pthread_mutex_lock(&mcqueue.qlock);
1367 /* When mc pile queue is empty, wait */
1368 while((mcqueue.front == NULL) && (mcqueue.rear == NULL)) {
1369 pthread_cond_wait(&mcqueue.qcond, &mcqueue.qlock);
1371 /* Dequeue node to send remote machine connections*/
1372 if((mcpilenode = mcpiledequeue()) == NULL) {
1373 printf("Dequeue Error: No node returned %s %d\n", __FILE__, __LINE__);
1377 pthread_mutex_unlock(&mcqueue.qlock);
1379 /*Initiate connection to remote host and send request */
1380 /* Process Request */
1381 sendPrefetchReq(mcpilenode, tid);
1383 /* Deallocate the machine queue pile node */
1384 mcdealloc(mcpilenode);
1388 void sendPrefetchReq(prefetchpile_t *mcpilenode, int threadid) {
1389 int sd, i, offset, off, len, endpair, count = 0;
1390 struct sockaddr_in serv_addr;
1391 struct hostent *server;
1392 char machineip[16], control;
1396 /* Send Trans Prefetch Request */
1397 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
1398 perror("Error in socket for TRANS_REQUEST\n");
1401 bzero((char*) &serv_addr, sizeof(serv_addr));
1402 serv_addr.sin_family = AF_INET;
1403 serv_addr.sin_port = htons(LISTEN_PORT);
1404 //serv_addr.sin_addr.s_addr = inet_addr(MACHINE_IP);
1405 midtoIP(mcpilenode->mid ,machineip);
1406 machineip[15] = '\0';
1407 serv_addr.sin_addr.s_addr = inet_addr(machineip);
1409 /* Open Connection */
1410 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
1411 perror("Error in connect for TRANS_REQUEST\n");
1415 /* Send TRANS_PREFETCH control message */
1416 control = TRANS_PREFETCH;
1417 if(send(sd, &control, sizeof(char), MSG_NOSIGNAL) < sizeof(char)) {
1418 perror("Error in sending prefetch control\n");
1422 /* Send Oids and offsets in pairs */
1423 tmp = mcpilenode->objpiles;
1424 while(tmp != NULL) {
1426 count++; /* Keeps track of the number of oid and offset tuples sent per remote machine */
1427 len = sizeof(int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1428 char oidnoffset[len];
1429 memcpy(oidnoffset, &len, sizeof(int));
1431 memcpy(oidnoffset + off, &tmp->oid, sizeof(unsigned int));
1432 off += sizeof(unsigned int);
1433 for(i = 0; i < tmp->numoffset; i++) {
1434 memcpy(oidnoffset + off, &tmp->offset[i], sizeof(short));
1437 if (send(sd, &oidnoffset, sizeof(oidnoffset),MSG_NOSIGNAL) < sizeof(oidnoffset)) {
1438 perror("Error sending fixed bytes for thread\n");
1444 /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
1446 if (send(sd, &endpair, sizeof(int), MSG_NOSIGNAL) < sizeof(int)) {
1447 perror("Error sending fixed bytes for thread\n");
1451 /* Get Response from the remote machine */
1452 getPrefetchResponse(count,sd);
1457 void getPrefetchResponse(int count, int sd) {
1458 int i = 0, val, n, N, sum, index, objsize;
1459 unsigned int bufsize,oid;
1460 char buffer[RECEIVE_BUFFER_SIZE], control;
1462 void *modptr, *oldptr;
1464 /* Read prefetch response from the Remote machine */
1465 if((val = read(sd, &control, sizeof(char))) <= 0) {
1466 perror("No control response for Prefetch request sent\n");
1470 if(control == TRANS_PREFETCH_RESPONSE) {
1471 /*For each oid and offset tuple sent as prefetch request to remote machine*/
1475 /* Read the size of buffer to be received */
1476 if((N = read(sd, buffer, sizeof(unsigned int))) <= 0) {
1477 perror("Size of buffer not recv\n");
1480 memcpy(&bufsize, buffer, sizeof(unsigned int));
1481 ptr = buffer + sizeof(unsigned int);
1482 /* Keep receiving the buffer containing oid info */
1484 n = recv((int)sd, (void *)ptr+sum, bufsize-sum, 0);
1486 } while(sum < bufsize && n != 0);
1487 /* Decode the contents of the buffer */
1488 index = sizeof(unsigned int);
1489 while(index < (bufsize - sizeof(unsigned int))) {
1490 if(buffer[index] == OBJECT_FOUND) {
1491 /* Increment it to get the object */
1492 index += sizeof(char);
1493 memcpy(&oid, buffer + index, sizeof(unsigned int));
1494 index += sizeof(unsigned int);
1495 /* For each object found add to Prefetch Cache */
1496 memcpy(&objsize, buffer + index, sizeof(int));
1498 pthread_mutex_lock(&prefetchcache_mutex);
1499 if ((modptr = objstrAlloc(prefetchcache, objsize)) == NULL) {
1500 printf("objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
1501 pthread_mutex_unlock(&prefetchcache_mutex);
1504 pthread_mutex_unlock(&prefetchcache_mutex);
1505 memcpy(modptr, buffer+index, objsize);
1507 /* Insert the oid and its address into the prefetch hash lookup table */
1508 /* Do a version comparison if the oid exists */
1509 if((oldptr = prehashSearch(oid)) != NULL) {
1510 /* If older version then update with new object ptr */
1511 if(((objheader_t *)oldptr)->version < ((objheader_t *)modptr)->version) {
1513 prehashInsert(oid, modptr);
1514 } else if(((objheader_t *)oldptr)->version == ((objheader_t *)modptr)->version) {
1515 /* Add the new object ptr to hash table */
1516 prehashInsert(oid, modptr);
1517 } else { /* Do nothing */
1520 } else {/*If doesn't no match found in hashtable, add the object ptr to hash table*/
1521 prehashInsert(oid, modptr);
1523 /* Lock the Prefetch Cache look up table*/
1524 pthread_mutex_lock(&pflookup.lock);
1525 /* Broadcast signal on prefetch cache condition variable */
1526 pthread_cond_broadcast(&pflookup.cond);
1527 /* Unlock the Prefetch Cache look up table*/
1528 pthread_mutex_unlock(&pflookup.lock);
1529 } else if(buffer[index] == OBJECT_NOT_FOUND) {
1530 /* Increment it to get the object */
1531 /* TODO: For each object not found query DHT for new location and retrieve the object */
1532 index += sizeof(char);
1533 memcpy(&oid, buffer + index, sizeof(unsigned int));
1534 index += sizeof(unsigned int);
1535 /* Throw an error */
1536 printf("OBJECT NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n");
1539 printf("Error in decoding the index value %s, %d\n",__FILE__, __LINE__);
1547 printf("Error in receving response for prefetch request %s, %d\n",__FILE__, __LINE__);
1551 unsigned short getObjType(unsigned int oid)
1553 objheader_t *objheader;
1554 unsigned short numoffsets = 0;
1556 if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL)
1558 if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1560 prefetch(1, &oid, &numoffsets, NULL);
1561 pthread_mutex_lock(&pflookup.lock);
1562 while ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1564 pthread_cond_wait(&pflookup.cond, &pflookup.lock);
1566 pthread_mutex_unlock(&pflookup.lock);
1570 return TYPE(objheader);
1573 int startRemoteThread(unsigned int oid, unsigned int mid)
1576 struct sockaddr_in remoteAddr;
1577 char msg[1 + sizeof(unsigned int)];
1581 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
1583 perror("startRemoteThread():socket()");
1587 bzero(&remoteAddr, sizeof(remoteAddr));
1588 remoteAddr.sin_family = AF_INET;
1589 remoteAddr.sin_port = htons(LISTEN_PORT);
1590 remoteAddr.sin_addr.s_addr = htonl(mid);
1592 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0)
1594 printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
1595 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1600 msg[0] = START_REMOTE_THREAD;
1601 memcpy(&msg[1], &oid, sizeof(unsigned int));
1603 bytesSent = send(sock, msg, 1 + sizeof(unsigned int), 0);
1606 perror("startRemoteThread():send()");
1609 else if (bytesSent != 1 + sizeof(unsigned int))
1611 printf("startRemoteThread(): error, sent %d bytes\n", bytesSent);
1624 //TODO: when reusing oids, make sure they are not already in use!
1625 unsigned int getNewOID(void) {
1626 static unsigned int id = 0xFFFFFFFF;
1629 if (id > oidMax || id < oidMin)
1636 int processConfigFile()
1639 const int maxLineLength = 200;
1640 char lineBuffer[maxLineLength];
1642 const char *delimiters = " \t\n";
1646 configFile = fopen(CONFIG_FILENAME, "r");
1647 if (configFile == NULL)
1649 printf("error opening %s:\n", CONFIG_FILENAME);
1654 numHostsInSystem = 0;
1655 sizeOfHostArray = 8;
1656 hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
1658 while(fgets(lineBuffer, maxLineLength, configFile) != NULL)
1660 commentBegin = strchr(lineBuffer, '#');
1661 if (commentBegin != NULL)
1662 *commentBegin = '\0';
1663 token = strtok(lineBuffer, delimiters);
1664 while (token != NULL)
1666 tmpAddr = inet_addr(token);
1667 if ((int)tmpAddr == -1)
1669 printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
1674 addHost(htonl(tmpAddr));
1675 token = strtok(NULL, delimiters);
1681 if (numHostsInSystem < 1)
1683 printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
1687 myIpAddr = getMyIpAddr("en1");
1689 myIpAddr = getMyIpAddr("eth0");
1691 myIndexInHostArray = findHost(myIpAddr);
1692 if (myIndexInHostArray == -1)
1694 printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
1697 oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
1698 oidMin = oidsPerBlock * myIndexInHostArray;
1699 if (myIndexInHostArray == numHostsInSystem - 1)
1700 oidMax = 0xFFFFFFFF;
1702 oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
1707 void addHost(unsigned int hostIp)
1709 unsigned int *tmpArray;
1711 if (findHost(hostIp) != -1)
1714 if (numHostsInSystem == sizeOfHostArray)
1716 tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
1717 memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
1719 hostIpAddrs = tmpArray;
1722 hostIpAddrs[numHostsInSystem++] = hostIp;
1727 int findHost(unsigned int hostIp)
1730 for (i = 0; i < numHostsInSystem; i++)
1731 if (hostIpAddrs[i] == hostIp)