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, offset, threadnum, trecvcount;
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 */
368 /* Look through all the objects in the transaction record and make piles
369 * for each machine involved in the transaction*/
370 pile_ptr = pile = createPiles(record);
372 /* Create the packet to be sent in TRANS_REQUEST */
374 /* Count the number of participants */
375 pilecount = pCount(pile);
377 /* Create a list of machine ids(Participants) involved in transaction */
378 if((listmid = calloc(pilecount, sizeof(unsigned int))) == NULL) {
379 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
383 pListMid(pile, listmid);
386 /* Initialize thread variables,
387 * Spawn a thread for each Participant involved in a transaction */
388 pthread_t thread[pilecount];
390 pthread_cond_t tcond;
391 pthread_mutex_t tlock;
392 pthread_mutex_t tlshrd;
394 thread_data_array_t *thread_data_array;
395 if((thread_data_array = (thread_data_array_t *) malloc(sizeof(thread_data_array_t)*pilecount)) == NULL) {
396 printf("Malloc error %s, %d\n", __FILE__, __LINE__);
397 pthread_cond_destroy(&tcond);
398 pthread_mutex_destroy(&tlock);
405 local_thread_data_array_t *ltdata;
406 if((ltdata = calloc(1, sizeof(local_thread_data_array_t))) == NULL) {
407 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
408 pthread_cond_destroy(&tcond);
409 pthread_mutex_destroy(&tlock);
412 free(thread_data_array);
417 thread_response_t rcvd_control_msg[pilecount]; /* Shared thread array that keeps track of responses of participants */
419 /* Initialize and set thread detach attribute */
420 pthread_attr_init(&attr);
421 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
422 pthread_mutex_init(&tlock, NULL);
423 pthread_cond_init(&tcond, NULL);
425 /* Process each machine pile */
426 while(pile != NULL) {
427 //Create transaction id
429 if ((tosend = calloc(1, sizeof(trans_req_data_t))) == NULL) {
430 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
431 pthread_cond_destroy(&tcond);
432 pthread_mutex_destroy(&tlock);
435 free(thread_data_array);
440 tosend->f.control = TRANS_REQUEST;
441 sprintf(tosend->f.trans_id, "%x_%d", pile->mid, newtid);
442 tosend->f.mcount = pilecount;
443 tosend->f.numread = pile->numread;
444 tosend->f.nummod = pile->nummod;
445 tosend->f.numcreated = pile->numcreated;
446 tosend->f.sum_bytes = pile->sum_bytes;
447 tosend->listmid = listmid;
448 tosend->objread = pile->objread;
449 tosend->oidmod = pile->oidmod;
450 tosend->oidcreated = pile->oidcreated;
451 thread_data_array[threadnum].thread_id = threadnum;
452 thread_data_array[threadnum].mid = pile->mid;
453 thread_data_array[threadnum].buffer = tosend;
454 thread_data_array[threadnum].recvmsg = rcvd_control_msg;
455 thread_data_array[threadnum].threshold = &tcond;
456 thread_data_array[threadnum].lock = &tlock;
457 thread_data_array[threadnum].count = &trecvcount;
458 thread_data_array[threadnum].replyctrl = &treplyctrl;
459 thread_data_array[threadnum].replyretry = &treplyretry;
460 thread_data_array[threadnum].rec = record;
461 /* If local do not create any extra connection */
462 if(pile->mid != myIpAddr) { /* Not local */
463 rc = pthread_create(&thread[threadnum], &attr, transRequest, (void *) &thread_data_array[threadnum]);
465 perror("Error in pthread create\n");
466 pthread_cond_destroy(&tcond);
467 pthread_mutex_destroy(&tlock);
470 for (i = 0; i < threadnum; i++)
471 free(thread_data_array[i].buffer);
472 free(thread_data_array);
478 ltdata->tdata = &thread_data_array[threadnum];
479 ltdata->transinfo = &transinfo;
480 val = pthread_create(&thread[threadnum], &attr, handleLocalReq, (void *) ltdata);
482 perror("Error in pthread create\n");
483 pthread_cond_destroy(&tcond);
484 pthread_mutex_destroy(&tlock);
487 for (i = 0; i < threadnum; i++)
488 free(thread_data_array[i].buffer);
489 free(thread_data_array);
500 /* Free attribute and wait for the other threads */
501 pthread_attr_destroy(&attr);
503 for (i = 0; i < pilecount; i++) {
504 rc = pthread_join(thread[i], NULL);
507 printf("ERROR return code from pthread_join() is %d\n", rc);
508 pthread_cond_destroy(&tcond);
509 pthread_mutex_destroy(&tlock);
512 for (j = i; j < pilecount; j++)
513 free(thread_data_array[j].buffer);
514 free(thread_data_array);
519 free(thread_data_array[i].buffer);
524 pthread_cond_destroy(&tcond);
525 pthread_mutex_destroy(&tlock);
528 free(thread_data_array);
531 /* wait a random amount of time */
532 if (treplyretry == 1)
535 /* Retry trans commit procedure if not sucessful in the first try */
536 } while (treplyretry == 1);
542 /* This function sends information involved in the transaction request
543 * to participants and accepts a response from particpants.
544 * It calls decideresponse() to decide on what control message
545 * to send next to participants and sends the message using sendResponse()*/
546 void *transRequest(void *threadarg) {
548 struct sockaddr_in serv_addr;
549 struct hostent *server;
550 thread_data_array_t *tdata;
551 objheader_t *headeraddr;
552 char buffer[RECEIVE_BUFFER_SIZE], control, recvcontrol;
553 char machineip[16], retval;
555 tdata = (thread_data_array_t *) threadarg;
557 /* Send Trans Request */
558 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
559 perror("Error in socket for TRANS_REQUEST\n");
562 bzero((char*) &serv_addr, sizeof(serv_addr));
563 serv_addr.sin_family = AF_INET;
564 serv_addr.sin_port = htons(LISTEN_PORT);
565 midtoIP(tdata->mid,machineip);
566 machineip[15] = '\0';
567 serv_addr.sin_addr.s_addr = inet_addr(machineip);
568 /* Open Connection */
569 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
570 perror("Error in connect for TRANS_REQUEST\n");
575 printf("DEBUG-> trans.c Sending TRANS_REQUEST to mid %s\n", machineip);
576 /* Send bytes of data with TRANS_REQUEST control message */
577 if (send(sd, &(tdata->buffer->f), sizeof(fixed_data_t),MSG_NOSIGNAL) < sizeof(fixed_data_t)) {
578 perror("Error sending fixed bytes for thread\n");
582 /* Send list of machines involved in the transaction */
584 int size=sizeof(unsigned int)*tdata->buffer->f.mcount;
585 if (send(sd, tdata->buffer->listmid, size, MSG_NOSIGNAL) < size) {
586 perror("Error sending list of machines for thread\n");
591 /* Send oids and version number tuples for objects that are read */
593 int size=(sizeof(unsigned int)+sizeof(short))*tdata->buffer->f.numread;
594 if (send(sd, tdata->buffer->objread, size, MSG_NOSIGNAL) < size) {
595 perror("Error sending tuples for thread\n");
600 /* Send objects that are modified */
601 for(i = 0; i < tdata->buffer->f.nummod ; i++) {
603 headeraddr = chashSearch(tdata->rec->lookupTable, tdata->buffer->oidmod[i]);
604 GETSIZE(size,headeraddr);
605 size+=sizeof(objheader_t);
606 if (send(sd, headeraddr, size, MSG_NOSIGNAL) < size) {
607 perror("Error sending obj modified for thread\n");
613 /* Read control message from Participant */
614 if((n = read(sd, &control, sizeof(char))) <= 0) {
615 perror("Error in reading control message from Participant\n");
619 recvcontrol = control;
621 /* Update common data structure and increment count */
622 tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol;
624 /* Lock and update count */
625 /* Thread sleeps until all messages from pariticipants are received by coordinator */
626 pthread_mutex_lock(tdata->lock);
628 (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */
630 /* Wake up the threads and invoke decideResponse (once) */
631 if(*(tdata->count) == tdata->buffer->f.mcount) {
632 decideResponse(tdata);
633 pthread_cond_broadcast(tdata->threshold);
635 pthread_cond_wait(tdata->threshold, tdata->lock);
637 pthread_mutex_unlock(tdata->lock);
639 /* Send the final response such as TRANS_COMMIT or TRANS_ABORT t
640 * to all participants in their respective socket */
641 if (sendResponse(tdata, sd) == 0) {
642 printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__);
647 /* Close connection */
652 /* This function decides the reponse that needs to be sent to
653 * all Participant machines after the TRANS_REQUEST protocol */
654 void decideResponse(thread_data_array_t *tdata) {
656 int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
659 for (i = 0 ; i < tdata->buffer->f.mcount; i++) {
660 control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses
661 written onto the shared array */
664 printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
665 /* treat as disagree, pass thru */
674 case TRANS_SOFT_ABORT:
681 if(transdisagree > 0) {
682 *(tdata->replyctrl) = TRANS_ABORT;
684 objstrDelete(tdata->rec->cache);
685 chashDelete(tdata->rec->lookupTable);
686 } else if(transagree == tdata->buffer->f.mcount){
688 *(tdata->replyctrl) = TRANS_COMMIT;
690 objstrDelete(tdata->rec->cache);
691 chashDelete(tdata->rec->lookupTable);
692 } else { /* (transsoftabort > 0 && transdisagree == 0) */
693 /* Send Abort in soft abort case followed by retry commiting transaction again*/
694 *(tdata->replyctrl) = TRANS_ABORT;
695 *(tdata->replyretry) = 1;
700 /* This function sends the final response to remote machines per thread in their respective socket id */
701 char sendResponse(thread_data_array_t *tdata, int sd) {
702 int n, N, sum, oidcount = 0;
703 char *ptr, retval = 0;
704 unsigned int *oidnotfound;
706 /* If the decided response is due to a soft abort and missing objects at the Participant's side */
707 if(tdata->recvmsg[tdata->thread_id].rcv_status == TRANS_SOFT_ABORT) {
708 /* Read list of objects missing */
709 if((read(sd, &oidcount, sizeof(int)) != 0) && (oidcount != 0)) {
710 N = oidcount * sizeof(unsigned int);
711 if((oidnotfound = calloc(oidcount, sizeof(unsigned int))) == NULL) {
712 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
715 ptr = (char *) oidnotfound;
717 n = read(sd, ptr+sum, N-sum);
719 } while(sum < N && n !=0);
721 retval = TRANS_SOFT_ABORT;
723 /* If the decided response is TRANS_ABORT */
724 if(*(tdata->replyctrl) == TRANS_ABORT) {
725 retval = TRANS_ABORT;
726 } else if(*(tdata->replyctrl) == TRANS_COMMIT) { /* If the decided response is TRANS_COMMIT */
727 retval = TRANS_COMMIT;
730 if (send(sd, tdata->replyctrl, sizeof(char),MSG_NOSIGNAL) < sizeof(char)) {
731 perror("Error sending ctrl message for participant\n");
737 /* This function opens a connection, places an object read request to the
738 * remote machine, reads the control message and object if available and
739 * copies the object and its header to the local cache.
740 * TODO replace mnum and midtoIP() with MACHINE_IP address later */
742 void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
744 struct sockaddr_in serv_addr;
745 struct hostent *server;
751 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
752 perror("Error in socket\n");
755 bzero((char*) &serv_addr, sizeof(serv_addr));
756 serv_addr.sin_family = AF_INET;
757 serv_addr.sin_port = htons(LISTEN_PORT);
758 //serv_addr.sin_addr.s_addr = inet_addr(MACHINE_IP);
759 midtoIP(mnum,machineip);
760 machineip[15] = '\0';
761 serv_addr.sin_addr.s_addr = inet_addr(machineip);
762 /* Open connection */
763 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
764 perror("Error in connect\n");
767 char readrequest[sizeof(char)+sizeof(unsigned int)];
768 readrequest[0] = READ_REQUEST;
769 *((unsigned int *)(&readrequest[1])) = oid;
770 if (send(sd, &readrequest, sizeof(readrequest), MSG_NOSIGNAL) < sizeof(readrequest)) {
771 perror("Error sending message\n");
776 printf("DEBUG -> ready to rcv ...\n");
778 /* Read response from the Participant */
779 if((val = read(sd, &control, sizeof(char))) <= 0) {
780 perror("No control response for getRemoteObj sent\n");
784 case OBJECT_NOT_FOUND:
787 /* Read object if found into local cache */
788 if((val = read(sd, &size, sizeof(int))) <= 0) {
789 perror("No size is read from the participant\n");
792 objcopy = objstrAlloc(record->cache, size);
793 if((val = read(sd, objcopy, size)) <= 0) {
794 perror("No objects are read from the remote participant\n");
797 /* Insert into cache's lookup table */
798 chashInsert(record->lookupTable, oid, objcopy);
801 printf("Error in recv request from participant on a READ_REQUEST %s, %d\n",__FILE__, __LINE__);
804 /* Close connection */
809 /* This function handles the local objects involved in a transaction commiting process.
810 * It also makes a decision if this local machine sends AGREE or DISAGREE or SOFT_ABORT to coordinator.
811 * Note Coordinator = local machine
812 * It wakes up the other threads from remote participants that are waiting for the coordinator's decision and
813 * based on common agreement it either commits or aborts the transaction.
814 * It also frees the memory resources */
815 void *handleLocalReq(void *threadarg) {
816 int val, i = 0, size, offset = 0;
818 char control = 0, *ptr;
820 unsigned int *oidnotfound = NULL, *oidlocked = NULL;
822 objheader_t *headptr, *headeraddr;
823 local_thread_data_array_t *localtdata;
825 localtdata = (local_thread_data_array_t *) threadarg;
827 /* Counters and arrays to formulate decision on control message to be sent */
828 oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
829 oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
830 int objnotfound = 0, objlocked = 0;
831 int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
833 /* modptr points to the beginning of the object store
834 * created at the Pariticipant */
835 pthread_mutex_lock(&mainobjstore_mutex);
836 if ((modptr = objstrAlloc(mainobjstore, localtdata->tdata->buffer->f.sum_bytes)) == NULL) {
837 printf("objstrAlloc error for modified objects %s, %d\n", __FILE__, __LINE__);
838 pthread_mutex_unlock(&mainobjstore_mutex);
841 pthread_mutex_unlock(&mainobjstore_mutex);
842 /* Write modified objects into the mainobject store */
843 for(i = 0; i< localtdata->tdata->buffer->f.nummod; i++) {
844 headeraddr = chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidmod[i]);
845 GETSIZE(size,headeraddr);
846 size+=sizeof(objheader_t);
847 memcpy((char *)modptr+offset, headeraddr, size);
850 /* Write new objects into the mainobject store */
851 for(i = 0; i< localtdata->tdata->buffer->f.numcreated; i++) {
852 headeraddr = chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidcreated[i]);
853 GETSIZE(size, headeraddr);
854 size+=sizeof(objheader_t);
855 memcpy((char *)modptr+offset, headeraddr, size);
862 /* Process each oid in the machine pile/ group per thread */
863 for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) {
864 if (i < localtdata->tdata->buffer->f.numread) {//Objs only read and not modified
865 int incr = sizeof(unsigned int) + sizeof(short);// Offset that points to next position in the objread array
867 oid = *((unsigned int *)(localtdata->tdata->buffer->objread + incr));
868 incr += sizeof(unsigned int);
869 version = *((short *)(localtdata->tdata->buffer->objread + incr));
870 } else {//Objs modified
872 headptr = (objheader_t *)ptr;
874 version = headptr->version;
875 GETSIZE(tmpsize, headptr);
876 ptr += sizeof(objheader_t) + tmpsize;
879 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
881 /* Save the oids not found and number of oids not found for later use */
882 if ((mobj = mhashSearch(oid)) == NULL) {/* Obj not found */
883 /* Save the oids not found and number of oids not found for later use */
884 oidnotfound[objnotfound] = oid;
886 } else { /* If Obj found in machine (i.e. has not moved) */
887 /* Check if Obj is locked by any previous transaction */
888 if (STATUS(((objheader_t *)mobj)) & LOCK) {
889 if (version == ((objheader_t *)mobj)->version) { /* If not locked then match versions */
891 } else {/* If versions don't match ...HARD ABORT */
893 /* Send TRANS_DISAGREE to Coordinator */
894 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
896 } else {/* If Obj is not locked then lock object */
897 STATUS(((objheader_t *)mobj)) |= LOCK;
898 //TODO Remove this for Testing
899 //randomdelay(); -- Why is this here. BCD
901 /* Save all object oids that are locked on this machine during this transaction request call */
902 oidlocked[objlocked] = OID(((objheader_t *)mobj));
904 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
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;
915 /* Condition to send TRANS_AGREE */
916 if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
917 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
919 /* Condition to send TRANS_SOFT_ABORT */
920 if((v_matchlock > 0 && v_nomatch == 0) || (objnotfound > 0 && v_nomatch == 0)) {
921 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
922 //TODO currently the only soft abort case that is supported is when object locked by previous
923 //transaction => v_matchlock > 0
924 //The other case for SOFT ABORT i.e. when object is not found but versions match is not supported
925 /* Send number of oids not found and the missing oids if objects are missing in the machine */
926 /* TODO Remember to store the oidnotfound for later use
927 if(objnotfound != 0) {
928 int size = sizeof(unsigned int)* objnotfound;
933 /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
934 * if Participant receives a TRANS_COMMIT */
935 localtdata->transinfo->objlocked = oidlocked;
936 localtdata->transinfo->objnotfound = oidnotfound;
937 localtdata->transinfo->modptr = modptr;
938 localtdata->transinfo->numlocked = objlocked;
939 localtdata->transinfo->numnotfound = objnotfound;
941 /* Lock and update count */
942 //Thread sleeps until all messages from pariticipants are received by coordinator
943 pthread_mutex_lock(localtdata->tdata->lock);
944 (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */
946 /* Wake up the threads and invoke decideResponse (once) */
947 if(*(localtdata->tdata->count) == localtdata->tdata->buffer->f.mcount) {
948 decideResponse(localtdata->tdata);
949 pthread_cond_broadcast(localtdata->tdata->threshold);
951 pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock);
953 pthread_mutex_unlock(localtdata->tdata->lock);
955 /*Based on DecideResponse(), Either COMMIT or ABORT the operation*/
956 if(*(localtdata->tdata->replyctrl) == TRANS_ABORT){
957 if(transAbortProcess(modptr,oidlocked, localtdata->transinfo->numlocked, localtdata->tdata->buffer->f.nummod) != 0) {
958 printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
961 }else if(*(localtdata->tdata->replyctrl) == TRANS_COMMIT){
962 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) {
963 printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
969 if (localtdata->transinfo->objlocked != NULL) {
970 free(localtdata->transinfo->objlocked);
971 localtdata->transinfo->objlocked = NULL;
973 if (localtdata->transinfo->objnotfound != NULL) {
974 free(localtdata->transinfo->objnotfound);
975 localtdata->transinfo->objnotfound = NULL;
980 /* This function completes the ABORT process if the transaction is aborting
982 int transAbortProcess(void *modptr, unsigned int *objlocked, int numlocked, int nummod) {
985 objheader_t *tmp_header;
988 /* Set all ref counts as 1 and do garbage collection */
990 for(i = 0; i< nummod; i++) {
992 tmp_header = (objheader_t *)ptr;
993 tmp_header->rcount = 0;
994 GETSIZE(tmpsize, tmp_header);
995 ptr += sizeof(objheader_t) + tmpsize;
997 /* Unlock objects that was locked due to this transaction */
998 for(i = 0; i< numlocked; i++) {
999 if((header = mhashSearch(objlocked[i])) == NULL) {
1000 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1003 STATUS(((objheader_t *)header)) &= ~(LOCK);
1006 /* Send ack to Coordinator */
1007 printf("TRANS_SUCCESSFUL\n");
1009 /*Free the pointer */
1014 /*This function completes the COMMIT process is the transaction is commiting
1016 int transComProcess(void *modptr, unsigned int *oidmod, unsigned int *oidcreated, unsigned int *objlocked, int nummod, int numcreated, int numlocked) {
1017 objheader_t *header;
1018 int i = 0, offset = 0;
1021 /* Process each modified object saved in the mainobject store */
1022 for(i = 0; i < nummod; i++) {
1024 if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
1025 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1028 /* Change reference count of older address and free space in objstr ?? */
1031 /* Change ptr address in mhash table */
1032 mhashRemove(oidmod[i]); //TODO: this shouldn't be necessary
1033 mhashInsert(oidmod[i], (((char *)modptr) + offset));
1034 GETSIZE(tmpsize, header);
1035 offset += sizeof(objheader_t) + tmpsize;
1037 /* Update object version number */
1038 header = (objheader_t *) mhashSearch(oidmod[i]);
1039 header->version += 1;
1042 for (i = 0; i < numcreated; i++)
1045 header = (objheader_t *)(((char *)modptr) + offset);
1046 mhashInsert(oidcreated[i], (((char *)modptr) + offset));
1047 GETSIZE(tmpsize, header);
1048 offset += sizeof(objheader_t) + tmpsize;
1050 lhashInsert(oidcreated[i], myIpAddr);
1053 /* Unlock locked objects */
1054 for(i = 0; i < numlocked; i++) {
1055 if((header = (objheader_t *) mhashSearch(objlocked[i])) == NULL) {
1056 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1059 STATUS(header) &= ~(LOCK);
1062 //TODO Update location lookup table
1064 /* Send ack to Coordinator */
1065 printf("TRANS_SUCCESSFUL\n");
1069 /* This function checks if the prefetch oids are same and have same offsets
1070 * for case x.a.b and y.a.b where x and y have same oid's
1071 * or if a.b.c is a subset of x.b.c.d*/
1072 /* check for case where the generated request a.y.z or x.y.z.g then
1073 * prefetch needs to be generated for x.y.z.g if oid of a and x are same*/
1074 void checkPrefetchTuples(prefetchqelem_t *node) {
1075 int i,j, count,k, sindex, index;
1077 int ntuples, slength;
1079 short *endoffsets, *arryfields;
1081 /* Check for the case x.y.z and a.b.c are same oids */
1082 ptr = (char *) node;
1083 ntuples = *(GET_NTUPLES(ptr));
1084 oid = GET_PTR_OID(ptr);
1085 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1086 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1087 /* Find offset length for each tuple */
1088 int numoffset[ntuples];
1089 numoffset[0] = endoffsets[0];
1090 for(i = 1; i<ntuples; i++) {
1091 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1093 /* Check for redundant tuples by comparing oids of each tuple */
1094 for(i = 0; i < ntuples; i++) {
1097 for(j = i+1 ; j < ntuples; j++) {
1100 /*If oids of tuples match */
1101 if (oid[i] == oid[j]) {
1102 /* Find the smallest offset length of two tuples*/
1103 if(numoffset[i] > numoffset[j]){
1104 slength = numoffset[j];
1108 slength = numoffset[i];
1112 /* Compare the offset values based on the current indices
1113 * break if they do not match
1114 * if all offset values match then pick the largest tuple*/
1118 index = endoffsets[j -1];
1119 for(count = 0; count < slength; count ++) {
1120 if (arryfields[k] != arryfields[index]) {
1127 k = endoffsets[i-1];
1128 index = endoffsets[j-1];
1129 printf("Value of slength = %d\n", slength);
1130 for(count = 0; count < slength; count++) {
1131 if(arryfields[k] != arryfields[index]) {
1139 if(slength == count) {
1147 void checkPreCache(prefetchqelem_t *node, int *numoffset, int counter, int loopcount, unsigned int objoid, int index, int iter, int oidnfound) {
1149 int ntuples, i, k, flag;
1151 short *endoffsets, *arryfields;
1152 objheader_t *header;
1154 ptr = (char *) node;
1155 ntuples = *(GET_NTUPLES(ptr));
1156 oid = GET_PTR_OID(ptr);
1157 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1158 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1160 if(oidnfound == 1) {
1161 if((header = (objheader_t *) prehashSearch(objoid)) == NULL) {
1163 } else { //Found in Prefetch Cache
1164 //TODO Decide if object is too old, if old remove from cache
1165 tmp = (char *) header;
1166 /* Check if any of the offset oid is available in the Prefetch cache */
1167 for(i = counter; i < loopcount; i++) {
1168 objoid = *(tmp + sizeof(objheader_t) + arryfields[counter]);
1169 if((header = (objheader_t *)prehashSearch(objoid)) != NULL) {
1178 for(i = counter; i<loopcount; i++) {
1179 if((header = (objheader_t *)prehashSearch(objoid)) != NULL) {
1180 tmp = (char *) header;
1181 objoid = *(tmp + sizeof(objheader_t) + arryfields[index]);
1191 /* If oid not found locally or in prefetch cache then
1192 * assign the latest oid found as the new oid
1193 * and copy left over offsets into the arrayoffsetfieldarray*/
1195 numoffset[iter] = numoffset[iter] - (i+1);
1196 for(k = 0; k < numoffset[iter] ; k++) {
1197 arryfields[endoffsets[counter]+k] = arryfields[endoffsets[counter]+k+1];
1202 numoffset[iter] = 0;
1206 /* This function makes machine piles to be added into the machine pile queue for each prefetch call */
1207 prefetchpile_t *makePreGroups(prefetchqelem_t *node, int *numoffset) {
1209 int ntuples, slength, i, machinenum;
1212 short *endoffsets, *arryfields, *offset;
1213 prefetchpile_t *head = NULL;
1215 /* Check for the case x.y.z and a.b.c are same oids */
1216 ptr = (char *) node;
1217 ntuples = *(GET_NTUPLES(ptr));
1218 oid = GET_PTR_OID(ptr);
1219 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1220 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1222 /* Check for redundant tuples by comparing oids of each tuple */
1223 for(i = 0; i < ntuples; i++) {
1226 /* For each tuple make piles */
1227 if ((machinenum = lhashSearch(oid[i])) == 0) {
1228 printf("Error: No such Machine %s, %d\n", __FILE__, __LINE__);
1231 /* Insert into machine pile */
1232 offset = &arryfields[endoffsets[i-1]];
1233 insertPile(machinenum, oid[i], numoffset[i], offset, &head);
1239 /* This function checks if the oids within the prefetch tuples are available locally.
1240 * If yes then makes the tuple invalid. If no then rearranges oid and offset values in
1241 * the prefetchqelem_t node to represent a new prefetch tuple */
1242 prefetchpile_t *foundLocal(prefetchqelem_t *node) {
1243 int ntuples,i, j, k, oidnfound = 0, index, flag;
1245 unsigned int objoid;
1247 objheader_t *objheader;
1248 short *endoffsets, *arryfields;
1249 prefetchpile_t *head = NULL;
1251 ptr = (char *) node;
1252 ntuples = *(GET_NTUPLES(ptr));
1253 oid = GET_PTR_OID(ptr);
1254 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1255 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1256 /* Find offset length for each tuple */
1257 int numoffset[ntuples];//Number of offsets for each tuple
1258 numoffset[0] = endoffsets[0];
1259 for(i = 1; i<ntuples; i++) {
1260 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1262 for(i = 0; i < ntuples; i++) {
1265 /* If object found locally */
1266 if((objheader = (objheader_t*) mhashSearch(oid[i])) != NULL) {
1268 tmp = (char *) objheader;
1269 /* Find the oid of its offset value */
1273 index = endoffsets[i - 1];
1274 for(j = 0 ; j < numoffset[i] ; j++) {
1275 objoid = *(tmp + sizeof(objheader_t) + arryfields[index]);
1276 /*If oid found locally then
1277 *assign the latest oid found as the new oid
1278 *and copy left over offsets into the arrayoffsetfieldarray*/
1280 numoffset[i] = numoffset[i] - (j+1);
1281 for(k = 0; k < numoffset[i]; k++)
1282 arryfields[endoffsets[j]+ k] = arryfields[endoffsets[j]+k+1];
1284 /*New offset oid not found */
1285 if((objheader = (objheader_t*) mhashSearch(objoid)) == NULL) {
1287 checkPreCache(node, numoffset, j, numoffset[i], objoid, index, i, oidnfound);
1293 /*If all offset oids are found locally,make the prefetch tuple invalid */
1300 /* Look in Prefetch cache */
1301 checkPreCache(node, numoffset, 0, numoffset[i], oid[i], 0, i, oidnfound);
1305 /* Make machine groups */
1306 head = makePreGroups(node, numoffset);
1310 /* This function is called by the thread calling transPrefetch */
1311 void *transPrefetch(void *t) {
1312 prefetchqelem_t *qnode;
1313 prefetchpile_t *pilehead = NULL;
1316 /* lock mutex of primary prefetch queue */
1317 pthread_mutex_lock(&pqueue.qlock);
1318 /* while primary queue is empty, then wait */
1319 while((pqueue.front == NULL) && (pqueue.rear == NULL)) {
1320 pthread_cond_wait(&pqueue.qcond, &pqueue.qlock);
1323 /* dequeue node to create a machine piles and finally unlock mutex */
1324 if((qnode = pre_dequeue()) == NULL) {
1325 printf("Error: No node returned %s, %d\n", __FILE__, __LINE__);
1328 pthread_mutex_unlock(&pqueue.qlock);
1329 /* Reduce redundant prefetch requests */
1330 checkPrefetchTuples(qnode);
1331 /* Check if the tuples are found locally, if yes then reduce them further*/
1332 /* and group requests by remote machine ids by calling the makePreGroups() */
1333 pilehead = foundLocal(qnode);
1335 /* Lock mutex of pool queue */
1336 pthread_mutex_lock(&mcqueue.qlock);
1337 /* Update the pool queue with the new remote machine piles generated per prefetch call */
1338 mcpileenqueue(pilehead);
1339 /* Broadcast signal on machine pile queue */
1340 pthread_cond_broadcast(&mcqueue.qcond);
1341 /* Unlock mutex of machine pile queue */
1342 pthread_mutex_unlock(&mcqueue.qlock);
1343 /* Deallocate the prefetch queue pile node */
1349 /* Each thread in the pool of threads calls this function to establish connection with
1350 * remote machines, send the prefetch requests and process the reponses from
1351 * the remote machines .
1352 * The thread is active throughout the period of runtime */
1354 void *mcqProcess(void *threadid) {
1356 prefetchpile_t *mcpilenode;
1358 tid = (int) threadid;
1360 /* Lock mutex of mc pile queue */
1361 pthread_mutex_lock(&mcqueue.qlock);
1362 /* When mc pile queue is empty, wait */
1363 while((mcqueue.front == NULL) && (mcqueue.rear == NULL)) {
1364 pthread_cond_wait(&mcqueue.qcond, &mcqueue.qlock);
1366 /* Dequeue node to send remote machine connections*/
1367 if((mcpilenode = mcpiledequeue()) == NULL) {
1368 printf("Dequeue Error: No node returned %s %d\n", __FILE__, __LINE__);
1372 pthread_mutex_unlock(&mcqueue.qlock);
1374 /*Initiate connection to remote host and send request */
1375 /* Process Request */
1376 sendPrefetchReq(mcpilenode, tid);
1378 /* Deallocate the machine queue pile node */
1379 mcdealloc(mcpilenode);
1383 void sendPrefetchReq(prefetchpile_t *mcpilenode, int threadid) {
1384 int sd, i, offset, off, len, endpair, count = 0;
1385 struct sockaddr_in serv_addr;
1386 struct hostent *server;
1387 char machineip[16], control;
1391 /* Send Trans Prefetch Request */
1392 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
1393 perror("Error in socket for TRANS_REQUEST\n");
1396 bzero((char*) &serv_addr, sizeof(serv_addr));
1397 serv_addr.sin_family = AF_INET;
1398 serv_addr.sin_port = htons(LISTEN_PORT);
1399 //serv_addr.sin_addr.s_addr = inet_addr(MACHINE_IP);
1400 midtoIP(mcpilenode->mid ,machineip);
1401 machineip[15] = '\0';
1402 serv_addr.sin_addr.s_addr = inet_addr(machineip);
1404 /* Open Connection */
1405 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
1406 perror("Error in connect for TRANS_REQUEST\n");
1411 /* Send TRANS_PREFETCH control message */
1412 control = TRANS_PREFETCH;
1413 if(send(sd, &control, sizeof(char), MSG_NOSIGNAL) < sizeof(char)) {
1414 perror("Error in sending prefetch control\n");
1419 /* Send Oids and offsets in pairs */
1420 tmp = mcpilenode->objpiles;
1421 while(tmp != NULL) {
1423 count++; /* Keeps track of the number of oid and offset tuples sent per remote machine */
1424 len = sizeof(int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1425 char oidnoffset[len];
1426 memcpy(oidnoffset, &len, sizeof(int));
1428 memcpy(oidnoffset + off, &tmp->oid, sizeof(unsigned int));
1429 off += sizeof(unsigned int);
1430 for(i = 0; i < tmp->numoffset; i++) {
1431 memcpy(oidnoffset + off, &tmp->offset[i], sizeof(short));
1434 if (send(sd, &oidnoffset, sizeof(oidnoffset),MSG_NOSIGNAL) < sizeof(oidnoffset)) {
1435 perror("Error sending fixed bytes for thread\n");
1442 /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
1444 if (send(sd, &endpair, sizeof(int), MSG_NOSIGNAL) < sizeof(int)) {
1445 perror("Error sending fixed bytes for thread\n");
1450 /* Get Response from the remote machine */
1451 getPrefetchResponse(count,sd);
1456 void getPrefetchResponse(int count, int sd) {
1457 int i = 0, val, n, N, sum, index, objsize;
1458 unsigned int bufsize,oid;
1459 char buffer[RECEIVE_BUFFER_SIZE], control;
1461 void *modptr, *oldptr;
1463 /* Read prefetch response from the Remote machine */
1464 if((val = read(sd, &control, sizeof(char))) <= 0) {
1465 perror("No control response for Prefetch request sent\n");
1469 if(control == TRANS_PREFETCH_RESPONSE) {
1470 /*For each oid and offset tuple sent as prefetch request to remote machine*/
1474 /* Read the size of buffer to be received */
1475 if((N = read(sd, buffer, sizeof(unsigned int))) <= 0) {
1476 perror("Size of buffer not recv\n");
1479 memcpy(&bufsize, buffer, sizeof(unsigned int));
1480 ptr = buffer + sizeof(unsigned int);
1481 /* Keep receiving the buffer containing oid info */
1483 n = recv((int)sd, (void *)ptr+sum, bufsize-sum, 0);
1485 } while(sum < bufsize && n != 0);
1486 /* Decode the contents of the buffer */
1487 index = sizeof(unsigned int);
1488 while(index < (bufsize - sizeof(unsigned int))) {
1489 if(buffer[index] == OBJECT_FOUND) {
1490 /* Increment it to get the object */
1491 index += sizeof(char);
1492 memcpy(&oid, buffer + index, sizeof(unsigned int));
1493 index += sizeof(unsigned int);
1494 /* For each object found add to Prefetch Cache */
1495 memcpy(&objsize, buffer + index, sizeof(int));
1497 pthread_mutex_lock(&prefetchcache_mutex);
1498 if ((modptr = objstrAlloc(prefetchcache, objsize)) == NULL) {
1499 printf("objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
1500 pthread_mutex_unlock(&prefetchcache_mutex);
1503 pthread_mutex_unlock(&prefetchcache_mutex);
1504 memcpy(modptr, buffer+index, objsize);
1506 /* Insert the oid and its address into the prefetch hash lookup table */
1507 /* Do a version comparison if the oid exists */
1508 if((oldptr = prehashSearch(oid)) != NULL) {
1509 /* If older version then update with new object ptr */
1510 if(((objheader_t *)oldptr)->version < ((objheader_t *)modptr)->version) {
1512 prehashInsert(oid, modptr);
1513 } else if(((objheader_t *)oldptr)->version == ((objheader_t *)modptr)->version) {
1514 /* Add the new object ptr to hash table */
1515 prehashInsert(oid, modptr);
1516 } else { /* Do nothing */
1519 } else {/*If doesn't no match found in hashtable, add the object ptr to hash table*/
1520 prehashInsert(oid, modptr);
1522 /* Lock the Prefetch Cache look up table*/
1523 pthread_mutex_lock(&pflookup.lock);
1524 /* Broadcast signal on prefetch cache condition variable */
1525 pthread_cond_broadcast(&pflookup.cond);
1526 /* Unlock the Prefetch Cache look up table*/
1527 pthread_mutex_unlock(&pflookup.lock);
1528 } else if(buffer[index] == OBJECT_NOT_FOUND) {
1529 /* Increment it to get the object */
1530 /* TODO: For each object not found query DHT for new location and retrieve the object */
1531 index += sizeof(char);
1532 memcpy(&oid, buffer + index, sizeof(unsigned int));
1533 index += sizeof(unsigned int);
1534 /* Throw an error */
1535 printf("OBJECT NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n");
1538 printf("Error in decoding the index value %s, %d\n",__FILE__, __LINE__);
1546 printf("Error in receving response for prefetch request %s, %d\n",__FILE__, __LINE__);
1550 unsigned short getObjType(unsigned int oid)
1552 objheader_t *objheader;
1553 unsigned short numoffsets = 0;
1555 if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL)
1557 if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1559 prefetch(1, &oid, &numoffsets, NULL);
1560 pthread_mutex_lock(&pflookup.lock);
1561 while ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1563 pthread_cond_wait(&pflookup.cond, &pflookup.lock);
1565 pthread_mutex_unlock(&pflookup.lock);
1569 return TYPE(objheader);
1572 int startRemoteThread(unsigned int oid, unsigned int mid)
1575 struct sockaddr_in remoteAddr;
1576 char msg[1 + sizeof(unsigned int)];
1580 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
1582 perror("startRemoteThread():socket()");
1586 bzero(&remoteAddr, sizeof(remoteAddr));
1587 remoteAddr.sin_family = AF_INET;
1588 remoteAddr.sin_port = htons(LISTEN_PORT);
1589 remoteAddr.sin_addr.s_addr = htonl(mid);
1591 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0)
1593 printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
1594 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1599 msg[0] = START_REMOTE_THREAD;
1600 memcpy(&msg[1], &oid, sizeof(unsigned int));
1602 bytesSent = send(sock, msg, 1 + sizeof(unsigned int), 0);
1605 perror("startRemoteThread():send()");
1608 else if (bytesSent != 1 + sizeof(unsigned int))
1610 printf("startRemoteThread(): error, sent %d bytes\n", bytesSent);
1623 //TODO: when reusing oids, make sure they are not already in use!
1624 unsigned int getNewOID(void) {
1625 static unsigned int id = 0xFFFFFFFF;
1628 if (id > oidMax || id < oidMin)
1635 int processConfigFile()
1638 const int maxLineLength = 200;
1639 char lineBuffer[maxLineLength];
1641 const char *delimiters = " \t\n";
1645 configFile = fopen(CONFIG_FILENAME, "r");
1646 if (configFile == NULL)
1648 printf("error opening %s:\n", CONFIG_FILENAME);
1653 numHostsInSystem = 0;
1654 sizeOfHostArray = 8;
1655 hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
1657 while(fgets(lineBuffer, maxLineLength, configFile) != NULL)
1659 commentBegin = strchr(lineBuffer, '#');
1660 if (commentBegin != NULL)
1661 *commentBegin = '\0';
1662 token = strtok(lineBuffer, delimiters);
1663 while (token != NULL)
1665 tmpAddr = inet_addr(token);
1666 if ((int)tmpAddr == -1)
1668 printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
1673 addHost(htonl(tmpAddr));
1674 token = strtok(NULL, delimiters);
1680 if (numHostsInSystem < 1)
1682 printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
1686 myIpAddr = getMyIpAddr("en1");
1688 myIpAddr = getMyIpAddr("eth0");
1690 myIndexInHostArray = findHost(myIpAddr);
1691 if (myIndexInHostArray == -1)
1693 printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
1696 oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
1697 oidMin = oidsPerBlock * myIndexInHostArray;
1698 if (myIndexInHostArray == numHostsInSystem - 1)
1699 oidMax = 0xFFFFFFFF;
1701 oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
1706 void addHost(unsigned int hostIp)
1708 unsigned int *tmpArray;
1710 if (findHost(hostIp) != -1)
1713 if (numHostsInSystem == sizeOfHostArray)
1715 tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
1716 memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
1718 hostIpAddrs = tmpArray;
1721 hostIpAddrs[numHostsInSystem++] = hostIp;
1726 int findHost(unsigned int hostIp)
1729 for (i = 0; i < numHostsInSystem; i++)
1730 if (hostIpAddrs[i] == hostIp)