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;
34 extern pthread_mutex_t mainobjstore_mutex;
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
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=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 * 1000;
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);
211 size = sizeof(objheader_t)+classsize[TYPE(tmp)];
212 objcopy = objstrAlloc(record->cache, size);
213 memcpy(objcopy, (void *)objheader, size);
214 /* Insert into cache's lookup table */
215 chashInsert(record->lookupTable, OID(objheader), objcopy);
221 } else if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) { /* Look up in prefetch cache */
223 size = sizeof(objheader_t)+classsize[TYPE(tmp)];
224 objcopy = objstrAlloc(record->cache, size);
225 memcpy(objcopy, (void *)tmp, size);
226 /* Insert into cache's lookup table */
227 chashInsert(record->lookupTable, OID(tmp), objcopy);
233 } else { /* If not found anywhere, then block until object appears in prefetch cache */
235 printf("Inside remote machine\n");
236 pthread_mutex_lock(&pflookup.lock);
238 rc = pthread_cond_timedwait(&pflookup.cond, &pflookup.lock, &ts);
239 if(rc == ETIMEDOUT) {
240 printf("Wait timed out\n");
241 /* Check Prefetch cache again */
242 if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) { /* Look up in prefetch cache */
244 size = sizeof(objheader_t)+classsize[TYPE(tmp)];
245 objcopy = objstrAlloc(record->cache, size);
246 memcpy(objcopy, (void *)tmp, size);
247 /* Insert into cache's lookup table */
248 chashInsert(record->lookupTable, OID(tmp), objcopy);
255 pthread_mutex_unlock(&pflookup.lock);
258 pthread_mutex_unlock(&pflookup.lock);
262 /* Get the object from the remote location */
263 machinenumber = lhashSearch(oid);
264 objcopy = getRemoteObj(record, machinenumber, oid);
265 if(objcopy == NULL) {
266 //If object is not found in Remote location
278 /* This function creates objects in the transaction record */
279 objheader_t *transCreateObj(transrecord_t *record, unsigned int size)
281 objheader_t *tmp = (objheader_t *) objstrAlloc(record->cache, (sizeof(objheader_t) + size));
282 OID(tmp) = getNewOID();
286 chashInsert(record->lookupTable, OID(tmp), tmp);
288 return &tmp[1]; //want space after object header
294 /* This function creates machine piles based on all machines involved in a
295 * transaction commit request */
296 plistnode_t *createPiles(transrecord_t *record) {
298 unsigned int size;/* Represents number of bins in the chash table */
299 chashlistnode_t *curr, *ptr, *next;
300 plistnode_t *pile = NULL;
301 unsigned int machinenum;
302 void *localmachinenum;
303 objheader_t *headeraddr;
305 ptr = record->lookupTable->table;
306 size = record->lookupTable->size;
308 for(i = 0; i < size ; i++) {
310 /* Inner loop to traverse the linked list of the cache lookupTable */
311 while(curr != NULL) {
312 //if the first bin in hash table is empty
318 if ((headeraddr = chashSearch(record->lookupTable, curr->key)) == NULL) {
319 printf("Error: No such oid %s, %d\n", __FILE__, __LINE__);
323 //Get machine location for object id (and whether local or not)
324 if (STATUS(headeraddr) & NEW || mhashSearch(curr->key) != NULL) {
325 machinenum = myIpAddr;
326 } else if ((machinenum = lhashSearch(curr->key)) == 0) {
327 printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
331 //Make machine groups
332 if ((pile = pInsert(pile, headeraddr, machinenum, record->lookupTable->numelements)) == NULL) {
333 printf("pInsert error %s, %d\n", __FILE__, __LINE__);
343 /* This function initiates the transaction commit process
344 * Spawns threads for each of the new connections with Participants
345 * and creates new piles by calling the createPiles(),
346 * Sends a transrequest() to each remote machines for objects found remotely
347 * and calls handleLocalReq() to process objects found locally */
348 int transCommit(transrecord_t *record) {
349 unsigned int tot_bytes_mod, *listmid;
350 plistnode_t *pile, *pile_ptr;
352 int pilecount = 0, offset, threadnum = 0, trecvcount = 0, tmachcount = 0;
353 char buffer[RECEIVE_BUFFER_SIZE],control;
354 char transid[TID_LEN];
355 trans_req_data_t *tosend;
356 trans_commit_data_t transinfo;
357 static int newtid = 0;
358 char treplyctrl = 0, treplyretry = 0; /* keeps track of the common response that needs to be sent */
363 /* Look through all the objects in the transaction record and make piles
364 * for each machine involved in the transaction*/
365 pile_ptr = pile = createPiles(record);
367 /* Create the packet to be sent in TRANS_REQUEST */
369 /* Count the number of participants */
370 pilecount = pCount(pile);
372 /* Create a list of machine ids(Participants) involved in transaction */
373 if((listmid = calloc(pilecount, sizeof(unsigned int))) == NULL) {
374 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
377 pListMid(pile, listmid);
380 /* Initialize thread variables,
381 * Spawn a thread for each Participant involved in a transaction */
382 pthread_t thread[pilecount];
384 pthread_cond_t tcond;
385 pthread_mutex_t tlock;
386 pthread_mutex_t tlshrd;
388 thread_data_array_t *thread_data_array;
389 if((thread_data_array = (thread_data_array_t *) malloc(sizeof(thread_data_array_t)*pilecount)) == NULL) {
390 printf("Malloc error %s, %d\n", __FILE__, __LINE__);
391 pthread_cond_destroy(&tcond);
392 pthread_mutex_destroy(&tlock);
398 local_thread_data_array_t *ltdata;
399 if((ltdata = calloc(1, sizeof(local_thread_data_array_t))) == NULL) {
400 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
401 pthread_cond_destroy(&tcond);
402 pthread_mutex_destroy(&tlock);
405 free(thread_data_array);
409 thread_response_t rcvd_control_msg[pilecount]; /* Shared thread array that keeps track of responses of participants */
411 /* Initialize and set thread detach attribute */
412 pthread_attr_init(&attr);
413 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
414 pthread_mutex_init(&tlock, NULL);
415 pthread_cond_init(&tcond, NULL);
417 /* Process each machine pile */
418 while(pile != NULL) {
419 //Create transaction id
421 if ((tosend = calloc(1, sizeof(trans_req_data_t))) == NULL) {
422 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
423 pthread_cond_destroy(&tcond);
424 pthread_mutex_destroy(&tlock);
427 free(thread_data_array);
431 tosend->f.control = TRANS_REQUEST;
432 sprintf(tosend->f.trans_id, "%x_%d", pile->mid, newtid);
433 tosend->f.mcount = pilecount;
434 tosend->f.numread = pile->numread;
435 tosend->f.nummod = pile->nummod;
436 tosend->f.numcreated = pile->numcreated;
437 tosend->f.sum_bytes = pile->sum_bytes;
438 tosend->listmid = listmid;
439 tosend->objread = pile->objread;
440 tosend->oidmod = pile->oidmod;
441 tosend->oidcreated = pile->oidcreated;
442 thread_data_array[threadnum].thread_id = threadnum;
443 thread_data_array[threadnum].mid = pile->mid;
444 thread_data_array[threadnum].pilecount = pilecount;
445 thread_data_array[threadnum].buffer = tosend;
446 thread_data_array[threadnum].recvmsg = rcvd_control_msg;
447 thread_data_array[threadnum].threshold = &tcond;
448 thread_data_array[threadnum].lock = &tlock;
449 thread_data_array[threadnum].count = &trecvcount;
450 thread_data_array[threadnum].replyctrl = &treplyctrl;
451 thread_data_array[threadnum].replyretry = &treplyretry;
452 thread_data_array[threadnum].rec = record;
453 /* If local do not create any extra connection */
454 if(pile->mid != myIpAddr) { /* Not local */
455 rc = pthread_create(&thread[threadnum], NULL, transRequest, (void *) &thread_data_array[threadnum]);
457 perror("Error in pthread create\n");
458 pthread_cond_destroy(&tcond);
459 pthread_mutex_destroy(&tlock);
462 free(thread_data_array);
468 ltdata->tdata = &thread_data_array[threadnum];
469 ltdata->transinfo = &transinfo;
470 val = pthread_create(&thread[threadnum], NULL, handleLocalReq, (void *) ltdata);
472 perror("Error in pthread create\n");
473 pthread_cond_destroy(&tcond);
474 pthread_mutex_destroy(&tlock);
477 free(thread_data_array);
487 /* Free attribute and wait for the other threads */
488 pthread_attr_destroy(&attr);
489 for (i = 0 ;i < pilecount ; i++) {
490 rc = pthread_join(thread[i], NULL);
493 printf("ERROR return code from pthread_join() is %d\n", rc);
494 pthread_cond_destroy(&tcond);
495 pthread_mutex_destroy(&tlock);
498 free(thread_data_array);
503 free(thread_data_array[i].buffer);
507 pthread_cond_destroy(&tcond);
508 pthread_mutex_destroy(&tlock);
511 free(thread_data_array);
514 /* wait a random amount of time */
515 if (treplyretry == 1)
518 /* Retry trans commit procedure if not sucessful in the first try */
519 } while (treplyretry == 1);
524 /* This function sends information involved in the transaction request
525 * to participants and accepts a response from particpants.
526 * It calls decideresponse() to decide on what control message
527 * to send next to participants and sends the message using sendResponse()*/
528 void *transRequest(void *threadarg) {
530 struct sockaddr_in serv_addr;
531 struct hostent *server;
532 thread_data_array_t *tdata;
533 objheader_t *headeraddr;
534 char buffer[RECEIVE_BUFFER_SIZE], control, recvcontrol;
535 char machineip[16], retval;
537 tdata = (thread_data_array_t *) threadarg;
539 /* Send Trans Request */
540 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
541 perror("Error in socket for TRANS_REQUEST\n");
545 bzero((char*) &serv_addr, sizeof(serv_addr));
546 serv_addr.sin_family = AF_INET;
547 serv_addr.sin_port = htons(LISTEN_PORT);
548 midtoIP(tdata->mid,machineip);
549 machineip[15] = '\0';
550 serv_addr.sin_addr.s_addr = inet_addr(machineip);
551 /* Open Connection */
552 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
553 perror("Error in connect for TRANS_REQUEST\n");
558 printf("DEBUG-> trans.c Sending TRANS_REQUEST to mid %s\n", machineip);
559 /* Send bytes of data with TRANS_REQUEST control message */
560 if (send(sd, &(tdata->buffer->f), sizeof(fixed_data_t),MSG_NOSIGNAL) < sizeof(fixed_data_t)) {
561 perror("Error sending fixed bytes for thread\n");
565 /* Send list of machines involved in the transaction */
567 int size=sizeof(unsigned int)*tdata->pilecount;
568 if (send(sd, tdata->buffer->listmid, size, MSG_NOSIGNAL) < size) {
569 perror("Error sending list of machines for thread\n");
574 /* Send oids and version number tuples for objects that are read */
576 int size=(sizeof(unsigned int)+sizeof(short))*tdata->buffer->f.numread;
577 if (send(sd, tdata->buffer->objread, size, MSG_NOSIGNAL) < size) {
578 perror("Error sending tuples for thread\n");
583 /* Send objects that are modified */
584 for(i = 0; i < tdata->buffer->f.nummod ; i++) {
586 headeraddr = chashSearch(tdata->rec->lookupTable, tdata->buffer->oidmod[i]);
587 size=sizeof(objheader_t)+classsize[TYPE(headeraddr)];
588 if (send(sd, headeraddr, size, MSG_NOSIGNAL) < size) {
589 perror("Error sending obj modified for thread\n");
595 /* Read control message from Participant */
596 if((n = read(sd, &control, sizeof(char))) <= 0) {
597 perror("Error in reading control message from Participant\n");
601 recvcontrol = control;
603 /* Update common data structure and increment count */
604 tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol;
606 /* Lock and update count */
607 /* Thread sleeps until all messages from pariticipants are received by coordinator */
608 pthread_mutex_lock(tdata->lock);
610 (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */
612 /* Wake up the threads and invoke decideResponse (once) */
613 if(*(tdata->count) == tdata->pilecount) {
614 if (decideResponse(tdata) != 0) {
615 printf("decideResponse returned error %s,%d\n", __FILE__, __LINE__);
616 pthread_mutex_unlock(tdata->lock);
620 pthread_cond_broadcast(tdata->threshold);
622 pthread_cond_wait(tdata->threshold, tdata->lock);
624 pthread_mutex_unlock(tdata->lock);
626 /* Send the final response such as TRANS_COMMIT or TRANS_ABORT t
627 * to all participants in their respective socket */
628 if (sendResponse(tdata, sd) == 0) {
629 printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__);
630 pthread_mutex_unlock(tdata->lock);
635 /* Close connection */
640 /* This function decides the reponse that needs to be sent to
641 * all Participant machines after the TRANS_REQUEST protocol */
642 int decideResponse(thread_data_array_t *tdata) {
644 int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
647 for (i = 0 ; i < tdata->pilecount ; i++) {
648 control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses
649 written onto the shared array */
659 case TRANS_SOFT_ABORT:
663 printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
669 if(transdisagree > 0) {
670 *(tdata->replyctrl) = TRANS_ABORT;
672 objstrDelete(tdata->rec->cache);
673 chashDelete(tdata->rec->lookupTable);
675 } else if(transagree == tdata->pilecount){
677 *(tdata->replyctrl) = TRANS_COMMIT;
679 objstrDelete(tdata->rec->cache);
680 chashDelete(tdata->rec->lookupTable);
682 } else if(transsoftabort > 0 && transdisagree == 0) {
683 /* Send Abort in soft abort case followed by retry commiting transaction again*/
684 *(tdata->replyctrl) = TRANS_ABORT;
685 *(tdata->replyretry) = 1;
692 /* This function sends the final response to remote machines per thread in their respective socket id */
693 char sendResponse(thread_data_array_t *tdata, int sd) {
694 int n, N, sum, oidcount = 0;
695 char *ptr, retval = 0;
696 unsigned int *oidnotfound;
698 /* If the decided response is due to a soft abort and missing objects at the Participant's side */
699 if(tdata->recvmsg[tdata->thread_id].rcv_status == TRANS_SOFT_ABORT) {
700 /* Read list of objects missing */
701 if((read(sd, &oidcount, sizeof(int)) != 0) && (oidcount != 0)) {
702 N = oidcount * sizeof(unsigned int);
703 if((oidnotfound = calloc(oidcount, sizeof(unsigned int))) == NULL) {
704 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
707 ptr = (char *) oidnotfound;
709 n = read(sd, ptr+sum, N-sum);
711 } while(sum < N && n !=0);
713 retval = TRANS_SOFT_ABORT;
715 /* If the decided response is TRANS_ABORT */
716 if(*(tdata->replyctrl) == TRANS_ABORT) {
717 retval = TRANS_ABORT;
718 } else if(*(tdata->replyctrl) == TRANS_COMMIT) { /* If the decided response is TRANS_COMMIT */
719 retval = TRANS_COMMIT;
722 if (send(sd, tdata->replyctrl, sizeof(char),MSG_NOSIGNAL) < sizeof(char)) {
723 perror("Error sending ctrl message for participant\n");
729 /* This function opens a connection, places an object read request to the
730 * remote machine, reads the control message and object if available and
731 * copies the object and its header to the local cache.
732 * TODO replace mnum and midtoIP() with MACHINE_IP address later */
734 void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
736 struct sockaddr_in serv_addr;
737 struct hostent *server;
743 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
744 perror("Error in socket\n");
747 bzero((char*) &serv_addr, sizeof(serv_addr));
748 serv_addr.sin_family = AF_INET;
749 serv_addr.sin_port = htons(LISTEN_PORT);
750 //serv_addr.sin_addr.s_addr = inet_addr(MACHINE_IP);
751 midtoIP(mnum,machineip);
752 machineip[15] = '\0';
753 serv_addr.sin_addr.s_addr = inet_addr(machineip);
754 /* Open connection */
755 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
756 perror("Error in connect\n");
759 char readrequest[sizeof(char)+sizeof(unsigned int)];
760 readrequest[0] = READ_REQUEST;
761 *((unsigned int *)(&readrequest[1])) = oid;
762 if (send(sd, &readrequest, sizeof(readrequest), MSG_NOSIGNAL) < sizeof(readrequest)) {
763 perror("Error sending message\n");
768 printf("DEBUG -> ready to rcv ...\n");
770 /* Read response from the Participant */
771 if((val = read(sd, &control, sizeof(char))) <= 0) {
772 perror("No control response for getRemoteObj sent\n");
776 case OBJECT_NOT_FOUND:
779 /* Read object if found into local cache */
780 if((val = read(sd, &size, sizeof(int))) <= 0) {
781 perror("No size is read from the participant\n");
784 objcopy = objstrAlloc(record->cache, size);
785 if((val = read(sd, objcopy, size)) <= 0) {
786 perror("No objects are read from the remote participant\n");
789 /* Insert into cache's lookup table */
790 chashInsert(record->lookupTable, oid, objcopy);
793 printf("Error in recv request from participant on a READ_REQUEST %s, %d\n",__FILE__, __LINE__);
796 /* Close connection */
801 /* This function handles the local objects involved in a transaction commiting process.
802 * It also makes a decision if this local machine sends AGREE or DISAGREE or SOFT_ABORT to coordinator.
803 * Note Coordinator = local machine
804 * It wakes up the other threads from remote participants that are waiting for the coordinator's decision and
805 * based on common agreement it either commits or aborts the transaction.
806 * It also frees the memory resources */
807 void *handleLocalReq(void *threadarg) {
808 int val, i = 0, size, offset = 0;
810 char control = 0, *ptr;
812 unsigned int *oidnotfound = NULL, *oidlocked = NULL;
814 objheader_t *headptr, *headeraddr;
815 local_thread_data_array_t *localtdata;
817 localtdata = (local_thread_data_array_t *) threadarg;
819 /* Counters and arrays to formulate decision on control message to be sent */
820 oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
821 oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
822 int objnotfound = 0, objlocked = 0;
823 int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
825 /* modptr points to the beginning of the object store
826 * created at the Pariticipant */
827 pthread_mutex_lock(&mainobjstore_mutex);
828 if ((modptr = objstrAlloc(mainobjstore, localtdata->tdata->buffer->f.sum_bytes)) == NULL) {
829 printf("objstrAlloc error for modified objects %s, %d\n", __FILE__, __LINE__);
830 pthread_mutex_unlock(&mainobjstore_mutex);
833 pthread_mutex_unlock(&mainobjstore_mutex);
834 /* Write modified objects into the mainobject store */
835 for(i = 0; i< localtdata->tdata->buffer->f.nummod; i++) {
836 headeraddr = chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidmod[i]);
837 size = sizeof(objheader_t) + classsize[TYPE(headeraddr)];
838 memcpy(modptr+offset, headeraddr, size);
841 /* Write new objects into the mainobject store */
842 for(i = 0; i< localtdata->tdata->buffer->f.numcreated; i++) {
843 headeraddr = chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidcreated[i]);
844 size = sizeof(objheader_t) + classsize[TYPE(headeraddr)];
845 memcpy(modptr+offset, headeraddr, size);
852 /* Process each oid in the machine pile/ group per thread */
853 for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) {
854 if (i < localtdata->tdata->buffer->f.numread) {//Objs only read and not modified
855 int incr = sizeof(unsigned int) + sizeof(short);// Offset that points to next position in the objread array
857 oid = *((unsigned int *)(localtdata->tdata->buffer->objread + incr));
858 incr += sizeof(unsigned int);
859 version = *((short *)(localtdata->tdata->buffer->objread + incr));
860 } else {//Objs modified
861 headptr = (objheader_t *)ptr;
863 version = headptr->version;
864 ptr += sizeof(objheader_t) + classsize[TYPE(headptr)];
867 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
869 /* Save the oids not found and number of oids not found for later use */
870 if ((mobj = mhashSearch(oid)) == NULL) {/* Obj not found */
871 /* Save the oids not found and number of oids not found for later use */
872 oidnotfound[objnotfound] = oid;
874 } else { /* If Obj found in machine (i.e. has not moved) */
875 /* Check if Obj is locked by any previous transaction */
876 if (STATUS(((objheader_t *)mobj)) & LOCK) {
877 if (version == ((objheader_t *)mobj)->version) { /* If not locked then match versions */
879 } else {/* If versions don't match ...HARD ABORT */
881 /* Send TRANS_DISAGREE to Coordinator */
882 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
884 } else {/* If Obj is not locked then lock object */
885 STATUS(((objheader_t *)mobj)) |= LOCK;
886 //TODO Remove this for Testing
887 //randomdelay(); -- Why is this here. BCD
889 /* Save all object oids that are locked on this machine during this transaction request call */
890 oidlocked[objlocked] = OID(((objheader_t *)mobj));
892 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
894 } else { /* If versions don't match ...HARD ABORT */
896 /* Send TRANS_DISAGREE to Coordinator */
897 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
903 /* Condition to send TRANS_AGREE */
904 if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
905 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
907 /* Condition to send TRANS_SOFT_ABORT */
908 if((v_matchlock > 0 && v_nomatch == 0) || (objnotfound > 0 && v_nomatch == 0)) {
909 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
910 //TODO currently the only soft abort case that is supported is when object locked by previous
911 //transaction => v_matchlock > 0
912 //The other case for SOFT ABORT i.e. when object is not found but versions match is not supported
913 /* Send number of oids not found and the missing oids if objects are missing in the machine */
914 /* TODO Remember to store the oidnotfound for later use
915 if(objnotfound != 0) {
916 int size = sizeof(unsigned int)* objnotfound;
921 /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
922 * if Participant receives a TRANS_COMMIT */
923 localtdata->transinfo->objlocked = oidlocked;
924 localtdata->transinfo->objnotfound = oidnotfound;
925 localtdata->transinfo->modptr = modptr;
926 localtdata->transinfo->numlocked = objlocked;
927 localtdata->transinfo->numnotfound = objnotfound;
929 /* Lock and update count */
930 //Thread sleeps until all messages from pariticipants are received by coordinator
931 pthread_mutex_lock(localtdata->tdata->lock);
932 (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */
934 /* Wake up the threads and invoke decideResponse (once) */
935 if(*(localtdata->tdata->count) == localtdata->tdata->pilecount) {
936 if (decideResponse(localtdata->tdata) != 0) {
937 printf("decideResponse returned error %s,%d\n", __FILE__, __LINE__);
938 pthread_mutex_unlock(localtdata->tdata->lock);
941 pthread_cond_broadcast(localtdata->tdata->threshold);
943 pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock);
945 pthread_mutex_unlock(localtdata->tdata->lock);
947 /*Based on DecideResponse(), Either COMMIT or ABORT the operation*/
948 if(*(localtdata->tdata->replyctrl) == TRANS_ABORT){
949 if(transAbortProcess(modptr,oidlocked, localtdata->transinfo->numlocked, localtdata->tdata->buffer->f.nummod) != 0) {
950 printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
953 }else if(*(localtdata->tdata->replyctrl) == TRANS_COMMIT){
954 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) {
955 printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
962 if (localtdata->transinfo->objlocked != NULL) {
963 free(localtdata->transinfo->objlocked);
964 localtdata->transinfo->objlocked = NULL;
966 if (localtdata->transinfo->objnotfound != NULL) {
967 free(localtdata->transinfo->objnotfound);
968 localtdata->transinfo->objnotfound = NULL;
973 /* This function completes the ABORT process if the transaction is aborting
975 int transAbortProcess(void *modptr, unsigned int *objlocked, int numlocked, int nummod) {
978 objheader_t *tmp_header;
981 /* Set all ref counts as 1 and do garbage collection */
982 ptr = (char *)modptr;
983 for(i = 0; i< nummod; i++) {
984 tmp_header = (objheader_t *)ptr;
985 tmp_header->rcount = 0;
986 ptr += sizeof(objheader_t) + classsize[TYPE(tmp_header)];
988 /* Unlock objects that was locked due to this transaction */
989 for(i = 0; i< numlocked; i++) {
990 if((header = mhashSearch(objlocked[i])) == NULL) {
991 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
994 STATUS(((objheader_t *)header)) &= ~(LOCK);
997 /* Send ack to Coordinator */
999 /*Free the pointer */
1004 /*This function completes the COMMIT process is the transaction is commiting
1006 int transComProcess(void *modptr, unsigned int *oidmod, unsigned int *oidcreated, unsigned int *objlocked, int nummod, int numcreated, int numlocked) {
1007 objheader_t *header;
1008 int i = 0, offset = 0;
1011 /* Process each modified object saved in the mainobject store */
1012 for(i = 0; i < nummod; i++) {
1013 if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
1014 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1017 /* Change reference count of older address and free space in objstr ?? */
1020 /* Change ptr address in mhash table */
1021 mhashRemove(oidmod[i]); //TODO: this shouldn't be necessary
1022 mhashInsert(oidmod[i], (((char *)modptr) + offset));
1023 offset += sizeof(objheader_t) + classsize[TYPE(header)];
1025 /* Update object version number */
1026 header = (objheader_t *) mhashSearch(oidmod[i]);
1027 header->version += 1;
1030 for (i = 0; i < numcreated; i++)
1032 header = (objheader_t *)(((char *)modptr) + offset);
1033 mhashInsert(oidcreated[i], (((char *)modptr) + offset));
1034 offset += sizeof(objheader_t) + classsize[TYPE(header)];
1036 lhashInsert(oidcreated[i], myIpAddr);
1039 /* Unlock locked objects */
1040 for(i = 0; i < numlocked; i++) {
1041 if((header = (objheader_t *) mhashSearch(objlocked[i])) == NULL) {
1042 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1045 STATUS(header) &= ~(LOCK);
1048 //TODO Update location lookup table
1050 /* Send ack to Coordinator */
1054 /* This function checks if the prefetch oids are same and have same offsets
1055 * for case x.a.b and y.a.b where x and y have same oid's
1056 * or if a.b.c is a subset of x.b.c.d*/
1057 /* check for case where the generated request a.y.z or x.y.z.g then
1058 * prefetch needs to be generated for x.y.z.g if oid of a and x are same*/
1059 void checkPrefetchTuples(prefetchqelem_t *node) {
1060 int i,j, count,k, sindex, index;
1062 int ntuples, slength;
1064 short *endoffsets, *arryfields;
1066 /* Check for the case x.y.z and a.b.c are same oids */
1067 ptr = (char *) node;
1068 ntuples = *(GET_NTUPLES(ptr));
1069 oid = GET_PTR_OID(ptr);
1070 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1071 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1072 /* Find offset length for each tuple */
1073 int numoffset[ntuples];
1074 numoffset[0] = endoffsets[0];
1075 for(i = 1; i<ntuples; i++) {
1076 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1078 /* Check for redundant tuples by comparing oids of each tuple */
1079 for(i = 0; i < ntuples; i++) {
1082 for(j = i+1 ; j < ntuples; j++) {
1085 /*If oids of tuples match */
1086 if (oid[i] == oid[j]) {
1087 /* Find the smallest offset length of two tuples*/
1088 if(numoffset[i] > numoffset[j]){
1089 slength = numoffset[j];
1093 slength = numoffset[i];
1097 /* Compare the offset values based on the current indices
1098 * break if they do not match
1099 * if all offset values match then pick the largest tuple*/
1103 index = endoffsets[j -1];
1104 for(count = 0; count < slength; count ++) {
1105 if (arryfields[k] != arryfields[index]) {
1112 k = endoffsets[i-1];
1113 index = endoffsets[j-1];
1114 printf("Value of slength = %d\n", slength);
1115 for(count = 0; count < slength; count++) {
1116 if(arryfields[k] != arryfields[index]) {
1124 if(slength == count) {
1132 void checkPreCache(prefetchqelem_t *node, int *numoffset, int counter, int loopcount, unsigned int objoid, int index, int iter, int oidnfound) {
1134 int ntuples, i, k, flag;
1136 short *endoffsets, *arryfields;
1137 objheader_t *header;
1139 ptr = (char *) node;
1140 ntuples = *(GET_NTUPLES(ptr));
1141 oid = GET_PTR_OID(ptr);
1142 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1143 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1145 if(oidnfound == 1) {
1146 if((header = (objheader_t *) prehashSearch(objoid)) == NULL) {
1148 } else { //Found in Prefetch Cache
1149 //TODO Decide if object is too old, if old remove from cache
1150 tmp = (char *) header;
1151 /* Check if any of the offset oid is available in the Prefetch cache */
1152 for(i = counter; i < loopcount; i++) {
1153 objoid = *(tmp + sizeof(objheader_t) + arryfields[counter]);
1154 if((header = (objheader_t *)prehashSearch(objoid)) != NULL) {
1163 for(i = counter; i<loopcount; i++) {
1164 if((header = (objheader_t *)prehashSearch(objoid)) != NULL) {
1165 tmp = (char *) header;
1166 objoid = *(tmp + sizeof(objheader_t) + arryfields[index]);
1176 /* If oid not found locally or in prefetch cache then
1177 * assign the latest oid found as the new oid
1178 * and copy left over offsets into the arrayoffsetfieldarray*/
1180 numoffset[iter] = numoffset[iter] - (i+1);
1181 for(k = 0; k < numoffset[iter] ; k++) {
1182 arryfields[endoffsets[counter]+k] = arryfields[endoffsets[counter]+k+1];
1187 numoffset[iter] = 0;
1191 /* This function makes machine piles to be added into the machine pile queue for each prefetch call */
1192 prefetchpile_t *makePreGroups(prefetchqelem_t *node, int *numoffset) {
1194 int ntuples, slength, i, machinenum;
1197 short *endoffsets, *arryfields, *offset;
1198 prefetchpile_t *head = NULL;
1200 /* Check for the case x.y.z and a.b.c are same oids */
1201 ptr = (char *) node;
1202 ntuples = *(GET_NTUPLES(ptr));
1203 oid = GET_PTR_OID(ptr);
1204 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1205 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1207 /* Check for redundant tuples by comparing oids of each tuple */
1208 for(i = 0; i < ntuples; i++) {
1211 /* For each tuple make piles */
1212 if ((machinenum = lhashSearch(oid[i])) == 0) {
1213 printf("Error: No such Machine %s, %d\n", __FILE__, __LINE__);
1216 /* Insert into machine pile */
1217 offset = &arryfields[endoffsets[i-1]];
1218 insertPile(machinenum, oid[i], numoffset[i], offset, &head);
1224 /* This function checks if the oids within the prefetch tuples are available locally.
1225 * If yes then makes the tuple invalid. If no then rearranges oid and offset values in
1226 * the prefetchqelem_t node to represent a new prefetch tuple */
1227 prefetchpile_t *foundLocal(prefetchqelem_t *node) {
1228 int ntuples,i, j, k, oidnfound = 0, index, flag;
1230 unsigned int objoid;
1232 objheader_t *objheader;
1233 short *endoffsets, *arryfields;
1234 prefetchpile_t *head = NULL;
1236 ptr = (char *) node;
1237 ntuples = *(GET_NTUPLES(ptr));
1238 oid = GET_PTR_OID(ptr);
1239 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1240 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1241 /* Find offset length for each tuple */
1242 int numoffset[ntuples];//Number of offsets for each tuple
1243 numoffset[0] = endoffsets[0];
1244 for(i = 1; i<ntuples; i++) {
1245 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1247 for(i = 0; i < ntuples; i++) {
1250 /* If object found locally */
1251 if((objheader = (objheader_t*) mhashSearch(oid[i])) != NULL) {
1253 tmp = (char *) objheader;
1254 /* Find the oid of its offset value */
1258 index = endoffsets[i - 1];
1259 for(j = 0 ; j < numoffset[i] ; j++) {
1260 objoid = *(tmp + sizeof(objheader_t) + arryfields[index]);
1261 /*If oid found locally then
1262 *assign the latest oid found as the new oid
1263 *and copy left over offsets into the arrayoffsetfieldarray*/
1265 numoffset[i] = numoffset[i] - (j+1);
1266 for(k = 0; k < numoffset[i]; k++)
1267 arryfields[endoffsets[j]+ k] = arryfields[endoffsets[j]+k+1];
1269 /*New offset oid not found */
1270 if((objheader = (objheader_t*) mhashSearch(objoid)) == NULL) {
1272 checkPreCache(node, numoffset, j, numoffset[i], objoid, index, i, oidnfound);
1278 /*If all offset oids are found locally,make the prefetch tuple invalid */
1285 /* Look in Prefetch cache */
1286 checkPreCache(node, numoffset, 0, numoffset[i], oid[i], 0, i, oidnfound);
1290 /* Make machine groups */
1291 head = makePreGroups(node, numoffset);
1295 /* This function is called by the thread calling transPrefetch */
1296 void *transPrefetch(void *t) {
1297 prefetchqelem_t *qnode;
1298 prefetchpile_t *pilehead = NULL;
1301 /* lock mutex of primary prefetch queue */
1302 pthread_mutex_lock(&pqueue.qlock);
1303 /* while primary queue is empty, then wait */
1304 while((pqueue.front == NULL) && (pqueue.rear == NULL)) {
1305 pthread_cond_wait(&pqueue.qcond, &pqueue.qlock);
1308 /* dequeue node to create a machine piles and finally unlock mutex */
1309 if((qnode = pre_dequeue()) == NULL) {
1310 printf("Error: No node returned %s, %d\n", __FILE__, __LINE__);
1313 pthread_mutex_unlock(&pqueue.qlock);
1314 /* Reduce redundant prefetch requests */
1315 checkPrefetchTuples(qnode);
1316 /* Check if the tuples are found locally, if yes then reduce them further*/
1317 /* and group requests by remote machine ids by calling the makePreGroups() */
1318 pilehead = foundLocal(qnode);
1320 /* Lock mutex of pool queue */
1321 pthread_mutex_lock(&mcqueue.qlock);
1322 /* Update the pool queue with the new remote machine piles generated per prefetch call */
1323 mcpileenqueue(pilehead);
1324 /* Broadcast signal on machine pile queue */
1325 pthread_cond_broadcast(&mcqueue.qcond);
1326 /* Unlock mutex of machine pile queue */
1327 pthread_mutex_unlock(&mcqueue.qlock);
1328 /* Deallocate the prefetch queue pile node */
1334 /* Each thread in the pool of threads calls this function to establish connection with
1335 * remote machines, send the prefetch requests and process the reponses from
1336 * the remote machines .
1337 * The thread is active throughout the period of runtime */
1339 void *mcqProcess(void *threadid) {
1341 prefetchpile_t *mcpilenode;
1343 tid = (int) threadid;
1345 /* Lock mutex of mc pile queue */
1346 pthread_mutex_lock(&mcqueue.qlock);
1347 /* When mc pile queue is empty, wait */
1348 while((mcqueue.front == NULL) && (mcqueue.rear == NULL)) {
1349 pthread_cond_wait(&mcqueue.qcond, &mcqueue.qlock);
1351 /* Dequeue node to send remote machine connections*/
1352 if((mcpilenode = mcpiledequeue()) == NULL) {
1353 printf("Dequeue Error: No node returned %s %d\n", __FILE__, __LINE__);
1357 pthread_mutex_unlock(&mcqueue.qlock);
1359 /*Initiate connection to remote host and send request */
1360 /* Process Request */
1361 sendPrefetchReq(mcpilenode, tid);
1363 /* Deallocate the machine queue pile node */
1364 mcdealloc(mcpilenode);
1368 void sendPrefetchReq(prefetchpile_t *mcpilenode, int threadid) {
1369 int sd, i, offset, off, len, endpair, count = 0;
1370 struct sockaddr_in serv_addr;
1371 struct hostent *server;
1372 char machineip[16], control;
1376 /* Send Trans Prefetch Request */
1377 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
1378 perror("Error in socket for TRANS_REQUEST\n");
1381 bzero((char*) &serv_addr, sizeof(serv_addr));
1382 serv_addr.sin_family = AF_INET;
1383 serv_addr.sin_port = htons(LISTEN_PORT);
1384 //serv_addr.sin_addr.s_addr = inet_addr(MACHINE_IP);
1385 midtoIP(mcpilenode->mid ,machineip);
1386 machineip[15] = '\0';
1387 serv_addr.sin_addr.s_addr = inet_addr(machineip);
1389 /* Open Connection */
1390 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
1391 perror("Error in connect for TRANS_REQUEST\n");
1395 /* Send TRANS_PREFETCH control message */
1396 control = TRANS_PREFETCH;
1397 if(send(sd, &control, sizeof(char), MSG_NOSIGNAL) < sizeof(char)) {
1398 perror("Error in sending prefetch control\n");
1402 /* Send Oids and offsets in pairs */
1403 tmp = mcpilenode->objpiles;
1404 while(tmp != NULL) {
1406 count++; /* Keeps track of the number of oid and offset tuples sent per remote machine */
1407 len = sizeof(int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1408 char oidnoffset[len];
1409 memcpy(oidnoffset, &len, sizeof(int));
1411 memcpy(oidnoffset + off, &tmp->oid, sizeof(unsigned int));
1412 off += sizeof(unsigned int);
1413 for(i = 0; i < tmp->numoffset; i++) {
1414 memcpy(oidnoffset + off, &tmp->offset[i], sizeof(short));
1417 if (send(sd, &oidnoffset, sizeof(oidnoffset),MSG_NOSIGNAL) < sizeof(oidnoffset)) {
1418 perror("Error sending fixed bytes for thread\n");
1424 /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
1426 if (send(sd, &endpair, sizeof(int), MSG_NOSIGNAL) < sizeof(int)) {
1427 perror("Error sending fixed bytes for thread\n");
1431 /* Get Response from the remote machine */
1432 getPrefetchResponse(count,sd);
1437 void getPrefetchResponse(int count, int sd) {
1438 int i = 0, val, n, N, sum, index, objsize;
1439 unsigned int bufsize,oid;
1440 char buffer[RECEIVE_BUFFER_SIZE], control;
1442 void *modptr, *oldptr;
1444 /* Read prefetch response from the Remote machine */
1445 if((val = read(sd, &control, sizeof(char))) <= 0) {
1446 perror("No control response for Prefetch request sent\n");
1450 if(control == TRANS_PREFETCH_RESPONSE) {
1451 /*For each oid and offset tuple sent as prefetch request to remote machine*/
1453 /* Clear contents of buffer */
1454 memset(buffer, 0, RECEIVE_BUFFER_SIZE);
1457 /* Read the size of buffer to be received */
1458 if((N = read(sd, buffer, sizeof(unsigned int))) <= 0) {
1459 perror("Size of buffer not recv\n");
1462 memcpy(&bufsize, buffer, sizeof(unsigned int));
1463 ptr = buffer + sizeof(unsigned int);
1464 /* Keep receiving the buffer containing oid info */
1466 n = recv((int)sd, (void *)ptr+sum, bufsize-sum, 0);
1468 } while(sum < bufsize && n != 0);
1469 /* Decode the contents of the buffer */
1470 index = sizeof(unsigned int);
1471 while(index < (bufsize - sizeof(unsigned int))) {
1472 if(buffer[index] == OBJECT_FOUND) {
1473 /* Increment it to get the object */
1474 index += sizeof(char);
1475 memcpy(&oid, buffer + index, sizeof(unsigned int));
1476 index += sizeof(unsigned int);
1477 /* For each object found add to Prefetch Cache */
1478 memcpy(&objsize, buffer + index, sizeof(int));
1479 pthread_mutex_lock(&prefetchcache_mutex);
1480 if ((modptr = objstrAlloc(prefetchcache, objsize)) == NULL) {
1481 printf("objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
1482 pthread_mutex_unlock(&prefetchcache_mutex);
1485 pthread_mutex_unlock(&prefetchcache_mutex);
1486 memcpy(modptr, buffer+index, objsize);
1488 /* Insert the oid and its address into the prefetch hash lookup table */
1489 /* Do a version comparison if the oid exists */
1490 if((oldptr = prehashSearch(oid)) != NULL) {
1491 /* If older version then update with new object ptr */
1492 if(((objheader_t *)oldptr)->version < ((objheader_t *)modptr)->version) {
1494 prehashInsert(oid, modptr);
1495 } else if(((objheader_t *)oldptr)->version == ((objheader_t *)modptr)->version) {
1496 /* Add the new object ptr to hash table */
1497 prehashInsert(oid, modptr);
1498 } else { /* Do nothing */
1501 } else {/*If doesn't no match found in hashtable, add the object ptr to hash table*/
1502 prehashInsert(oid, modptr);
1504 /* Lock the Prefetch Cache look up table*/
1505 pthread_mutex_lock(&pflookup.lock);
1506 /* Broadcast signal on prefetch cache condition variable */
1507 pthread_cond_broadcast(&pflookup.cond);
1508 /* Unlock the Prefetch Cache look up table*/
1509 pthread_mutex_unlock(&pflookup.lock);
1510 } else if(buffer[index] == OBJECT_NOT_FOUND) {
1511 /* Increment it to get the object */
1512 /* TODO: For each object not found query DHT for new location and retrieve the object */
1513 index += sizeof(char);
1514 memcpy(&oid, buffer + index, sizeof(unsigned int));
1515 index += sizeof(unsigned int);
1516 /* Throw an error */
1517 printf("OBJECT NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n");
1520 printf("Error in decoding the index value %s, %d\n",__FILE__, __LINE__);
1528 printf("Error in receving response for prefetch request %s, %d\n",__FILE__, __LINE__);
1532 unsigned short getObjType(unsigned int oid)
1534 objheader_t *objheader;
1535 unsigned short numoffsets = 0;
1537 if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL)
1539 if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1541 prefetch(1, &oid, &numoffsets, NULL);
1542 while ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1544 pthread_mutex_lock(&pflookup.lock);
1545 pthread_cond_wait(&pflookup.cond, &pflookup.lock);
1546 pthread_mutex_unlock(&pflookup.lock);
1551 return TYPE(objheader);
1554 int startRemoteThread(unsigned int oid, unsigned int mid)
1557 struct sockaddr_in remoteAddr;
1558 char msg[1 + sizeof(unsigned int)];
1562 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
1564 perror("startRemoteThread():socket()");
1568 bzero(&remoteAddr, sizeof(remoteAddr));
1569 remoteAddr.sin_family = AF_INET;
1570 remoteAddr.sin_port = htons(LISTEN_PORT);
1571 remoteAddr.sin_addr.s_addr = htonl(mid);
1573 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0)
1575 printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
1576 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1581 msg[0] = START_REMOTE_THREAD;
1582 memcpy(&msg[1], &oid, sizeof(unsigned int));
1584 bytesSent = send(sock, msg, 1 + sizeof(unsigned int), 0);
1587 perror("startRemoteThread():send()");
1590 else if (bytesSent != 1 + sizeof(unsigned int))
1592 printf("startRemoteThread(): error, sent %d bytes\n", bytesSent);
1605 //TODO: when reusing oids, make sure they are not already in use!
1606 unsigned int getNewOID(void) {
1607 static unsigned int id = 0xFFFFFFFF;
1610 if (id > oidMax || id < oidMin)
1617 int processConfigFile()
1620 const int maxLineLength = 200;
1621 char lineBuffer[maxLineLength];
1623 const char *delimiters = " \t\n";
1627 configFile = fopen(CONFIG_FILENAME, "r");
1628 if (configFile == NULL)
1630 printf("error opening %s:\n", CONFIG_FILENAME);
1635 numHostsInSystem = 0;
1636 sizeOfHostArray = 8;
1637 hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
1639 while(fgets(lineBuffer, maxLineLength, configFile) != NULL)
1641 commentBegin = strchr(lineBuffer, '#');
1642 if (commentBegin != NULL)
1643 *commentBegin = '\0';
1644 token = strtok(lineBuffer, delimiters);
1645 while (token != NULL)
1647 tmpAddr = inet_addr(token);
1648 if ((int)tmpAddr == -1)
1650 printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
1655 addHost(htonl(tmpAddr));
1656 token = strtok(NULL, delimiters);
1662 if (numHostsInSystem < 1)
1664 printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
1668 myIpAddr = getMyIpAddr("en1");
1670 myIpAddr = getMyIpAddr("eth0");
1672 myIndexInHostArray = findHost(myIpAddr);
1673 if (myIndexInHostArray == -1)
1675 printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
1678 oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
1679 oidMin = oidsPerBlock * myIndexInHostArray;
1680 if (myIndexInHostArray == numHostsInSystem - 1)
1681 oidMax = 0xFFFFFFFF;
1683 oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
1688 void addHost(unsigned int hostIp)
1690 unsigned int *tmpArray;
1692 if (findHost(hostIp) != -1)
1695 if (numHostsInSystem == sizeOfHostArray)
1697 tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
1698 memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
1700 hostIpAddrs = tmpArray;
1703 hostIpAddrs[numHostsInSystem++] = hostIp;
1708 int findHost(unsigned int hostIp)
1711 for (i = 0; i < numHostsInSystem; i++)
1712 if (hostIpAddrs[i] == hostIp)