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);
212 size += sizeof(objheader_t);
213 objcopy = objstrAlloc(record->cache, size);
214 memcpy(objcopy, (void *)objheader, size);
215 /* Insert into cache's lookup table */
216 chashInsert(record->lookupTable, OID(objheader), objcopy);
222 } else if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) { /* Look up in prefetch cache */
225 size+=sizeof(objheader_t);
226 objcopy = objstrAlloc(record->cache, size);
227 memcpy(objcopy, (void *)tmp, size);
228 /* Insert into cache's lookup table */
229 chashInsert(record->lookupTable, OID(tmp), objcopy);
235 } else { /* If not found anywhere, then block until object appears in prefetch cache */
237 printf("Inside remote machine\n");
238 pthread_mutex_lock(&pflookup.lock);
240 rc = pthread_cond_timedwait(&pflookup.cond, &pflookup.lock, &ts);
241 if(rc == ETIMEDOUT) {
242 printf("Wait timed out\n");
243 /* Check Prefetch cache again */
244 if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) { /* Look up in prefetch cache */
247 size+=sizeof(objheader_t);
248 objcopy = objstrAlloc(record->cache, size);
249 memcpy(objcopy, (void *)tmp, size);
250 /* Insert into cache's lookup table */
251 chashInsert(record->lookupTable, OID(tmp), objcopy);
258 pthread_mutex_unlock(&pflookup.lock);
261 pthread_mutex_unlock(&pflookup.lock);
265 /* Get the object from the remote location */
266 machinenumber = lhashSearch(oid);
267 objcopy = getRemoteObj(record, machinenumber, oid);
268 if(objcopy == NULL) {
269 //If object is not found in Remote location
281 /* This function creates objects in the transaction record */
282 objheader_t *transCreateObj(transrecord_t *record, unsigned int size)
284 objheader_t *tmp = (objheader_t *) objstrAlloc(record->cache, (sizeof(objheader_t) + size));
285 OID(tmp) = getNewOID();
289 chashInsert(record->lookupTable, OID(tmp), tmp);
291 return &tmp[1]; //want space after object header
297 /* This function creates machine piles based on all machines involved in a
298 * transaction commit request */
299 plistnode_t *createPiles(transrecord_t *record) {
301 unsigned int size;/* Represents number of bins in the chash table */
302 chashlistnode_t *curr, *ptr, *next;
303 plistnode_t *pile = NULL;
304 unsigned int machinenum;
305 void *localmachinenum;
306 objheader_t *headeraddr;
308 ptr = record->lookupTable->table;
309 size = record->lookupTable->size;
311 for(i = 0; i < size ; i++) {
313 /* Inner loop to traverse the linked list of the cache lookupTable */
314 while(curr != NULL) {
315 //if the first bin in hash table is empty
321 if ((headeraddr = chashSearch(record->lookupTable, curr->key)) == NULL) {
322 printf("Error: No such oid %s, %d\n", __FILE__, __LINE__);
326 //Get machine location for object id (and whether local or not)
327 if (STATUS(headeraddr) & NEW || mhashSearch(curr->key) != NULL) {
328 machinenum = myIpAddr;
329 } else if ((machinenum = lhashSearch(curr->key)) == 0) {
330 printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
334 //Make machine groups
335 if ((pile = pInsert(pile, headeraddr, machinenum, record->lookupTable->numelements)) == NULL) {
336 printf("pInsert error %s, %d\n", __FILE__, __LINE__);
346 /* This function initiates the transaction commit process
347 * Spawns threads for each of the new connections with Participants
348 * and creates new piles by calling the createPiles(),
349 * Sends a transrequest() to each remote machines for objects found remotely
350 * and calls handleLocalReq() to process objects found locally */
351 int transCommit(transrecord_t *record) {
352 unsigned int tot_bytes_mod, *listmid;
353 plistnode_t *pile, *pile_ptr;
355 int pilecount = 0, offset, threadnum = 0, trecvcount = 0, tmachcount = 0;
356 char buffer[RECEIVE_BUFFER_SIZE],control;
357 char transid[TID_LEN];
358 trans_req_data_t *tosend;
359 trans_commit_data_t transinfo;
360 static int newtid = 0;
361 char treplyctrl = 0, treplyretry = 0; /* keeps track of the common response that needs to be sent */
366 /* Look through all the objects in the transaction record and make piles
367 * for each machine involved in the transaction*/
368 pile_ptr = pile = createPiles(record);
370 /* Create the packet to be sent in TRANS_REQUEST */
372 /* Count the number of participants */
373 pilecount = pCount(pile);
375 /* Create a list of machine ids(Participants) involved in transaction */
376 if((listmid = calloc(pilecount, sizeof(unsigned int))) == NULL) {
377 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
380 pListMid(pile, listmid);
383 /* Initialize thread variables,
384 * Spawn a thread for each Participant involved in a transaction */
385 pthread_t thread[pilecount];
387 pthread_cond_t tcond;
388 pthread_mutex_t tlock;
389 pthread_mutex_t tlshrd;
391 thread_data_array_t *thread_data_array;
392 if((thread_data_array = (thread_data_array_t *) malloc(sizeof(thread_data_array_t)*pilecount)) == NULL) {
393 printf("Malloc error %s, %d\n", __FILE__, __LINE__);
394 pthread_cond_destroy(&tcond);
395 pthread_mutex_destroy(&tlock);
401 local_thread_data_array_t *ltdata;
402 if((ltdata = calloc(1, sizeof(local_thread_data_array_t))) == NULL) {
403 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
404 pthread_cond_destroy(&tcond);
405 pthread_mutex_destroy(&tlock);
408 free(thread_data_array);
412 thread_response_t rcvd_control_msg[pilecount]; /* Shared thread array that keeps track of responses of participants */
414 /* Initialize and set thread detach attribute */
415 pthread_attr_init(&attr);
416 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
417 pthread_mutex_init(&tlock, NULL);
418 pthread_cond_init(&tcond, NULL);
420 /* Process each machine pile */
421 while(pile != NULL) {
422 //Create transaction id
424 if ((tosend = calloc(1, sizeof(trans_req_data_t))) == NULL) {
425 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
426 pthread_cond_destroy(&tcond);
427 pthread_mutex_destroy(&tlock);
430 free(thread_data_array);
434 tosend->f.control = TRANS_REQUEST;
435 sprintf(tosend->f.trans_id, "%x_%d", pile->mid, newtid);
436 tosend->f.mcount = pilecount;
437 tosend->f.numread = pile->numread;
438 tosend->f.nummod = pile->nummod;
439 tosend->f.numcreated = pile->numcreated;
440 tosend->f.sum_bytes = pile->sum_bytes;
441 tosend->listmid = listmid;
442 tosend->objread = pile->objread;
443 tosend->oidmod = pile->oidmod;
444 tosend->oidcreated = pile->oidcreated;
445 thread_data_array[threadnum].thread_id = threadnum;
446 thread_data_array[threadnum].mid = pile->mid;
447 thread_data_array[threadnum].pilecount = pilecount;
448 thread_data_array[threadnum].buffer = tosend;
449 thread_data_array[threadnum].recvmsg = rcvd_control_msg;
450 thread_data_array[threadnum].threshold = &tcond;
451 thread_data_array[threadnum].lock = &tlock;
452 thread_data_array[threadnum].count = &trecvcount;
453 thread_data_array[threadnum].replyctrl = &treplyctrl;
454 thread_data_array[threadnum].replyretry = &treplyretry;
455 thread_data_array[threadnum].rec = record;
456 /* If local do not create any extra connection */
457 if(pile->mid != myIpAddr) { /* Not local */
458 rc = pthread_create(&thread[threadnum], NULL, transRequest, (void *) &thread_data_array[threadnum]);
460 perror("Error in pthread create\n");
461 pthread_cond_destroy(&tcond);
462 pthread_mutex_destroy(&tlock);
465 free(thread_data_array);
471 ltdata->tdata = &thread_data_array[threadnum];
472 ltdata->transinfo = &transinfo;
473 val = pthread_create(&thread[threadnum], NULL, handleLocalReq, (void *) ltdata);
475 perror("Error in pthread create\n");
476 pthread_cond_destroy(&tcond);
477 pthread_mutex_destroy(&tlock);
480 free(thread_data_array);
490 /* Free attribute and wait for the other threads */
491 pthread_attr_destroy(&attr);
492 for (i = 0 ;i < pilecount ; i++) {
493 rc = pthread_join(thread[i], NULL);
496 printf("ERROR return code from pthread_join() is %d\n", rc);
497 pthread_cond_destroy(&tcond);
498 pthread_mutex_destroy(&tlock);
501 free(thread_data_array);
506 free(thread_data_array[i].buffer);
510 pthread_cond_destroy(&tcond);
511 pthread_mutex_destroy(&tlock);
514 free(thread_data_array);
517 /* wait a random amount of time */
518 if (treplyretry == 1)
521 /* Retry trans commit procedure if not sucessful in the first try */
522 } while (treplyretry == 1);
527 /* This function sends information involved in the transaction request
528 * to participants and accepts a response from particpants.
529 * It calls decideresponse() to decide on what control message
530 * to send next to participants and sends the message using sendResponse()*/
531 void *transRequest(void *threadarg) {
533 struct sockaddr_in serv_addr;
534 struct hostent *server;
535 thread_data_array_t *tdata;
536 objheader_t *headeraddr;
537 char buffer[RECEIVE_BUFFER_SIZE], control, recvcontrol;
538 char machineip[16], retval;
540 tdata = (thread_data_array_t *) threadarg;
542 /* Send Trans Request */
543 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
544 perror("Error in socket for TRANS_REQUEST\n");
548 bzero((char*) &serv_addr, sizeof(serv_addr));
549 serv_addr.sin_family = AF_INET;
550 serv_addr.sin_port = htons(LISTEN_PORT);
551 midtoIP(tdata->mid,machineip);
552 machineip[15] = '\0';
553 serv_addr.sin_addr.s_addr = inet_addr(machineip);
554 /* Open Connection */
555 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
556 perror("Error in connect for TRANS_REQUEST\n");
561 printf("DEBUG-> trans.c Sending TRANS_REQUEST to mid %s\n", machineip);
562 /* Send bytes of data with TRANS_REQUEST control message */
563 if (send(sd, &(tdata->buffer->f), sizeof(fixed_data_t),MSG_NOSIGNAL) < sizeof(fixed_data_t)) {
564 perror("Error sending fixed bytes for thread\n");
568 /* Send list of machines involved in the transaction */
570 int size=sizeof(unsigned int)*tdata->pilecount;
571 if (send(sd, tdata->buffer->listmid, size, MSG_NOSIGNAL) < size) {
572 perror("Error sending list of machines for thread\n");
577 /* Send oids and version number tuples for objects that are read */
579 int size=(sizeof(unsigned int)+sizeof(short))*tdata->buffer->f.numread;
580 if (send(sd, tdata->buffer->objread, size, MSG_NOSIGNAL) < size) {
581 perror("Error sending tuples for thread\n");
586 /* Send objects that are modified */
587 for(i = 0; i < tdata->buffer->f.nummod ; i++) {
589 headeraddr = chashSearch(tdata->rec->lookupTable, tdata->buffer->oidmod[i]);
590 GETSIZE(size,headeraddr);
591 size+=sizeof(objheader_t);
592 if (send(sd, headeraddr, size, MSG_NOSIGNAL) < size) {
593 perror("Error sending obj modified for thread\n");
599 /* Read control message from Participant */
600 if((n = read(sd, &control, sizeof(char))) <= 0) {
601 perror("Error in reading control message from Participant\n");
605 recvcontrol = control;
607 /* Update common data structure and increment count */
608 tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol;
610 /* Lock and update count */
611 /* Thread sleeps until all messages from pariticipants are received by coordinator */
612 pthread_mutex_lock(tdata->lock);
614 (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */
616 /* Wake up the threads and invoke decideResponse (once) */
617 if(*(tdata->count) == tdata->pilecount) {
618 if (decideResponse(tdata) != 0) {
619 printf("decideResponse returned error %s,%d\n", __FILE__, __LINE__);
620 pthread_mutex_unlock(tdata->lock);
624 pthread_cond_broadcast(tdata->threshold);
626 pthread_cond_wait(tdata->threshold, tdata->lock);
628 pthread_mutex_unlock(tdata->lock);
630 /* Send the final response such as TRANS_COMMIT or TRANS_ABORT t
631 * to all participants in their respective socket */
632 if (sendResponse(tdata, sd) == 0) {
633 printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__);
634 pthread_mutex_unlock(tdata->lock);
639 /* Close connection */
644 /* This function decides the reponse that needs to be sent to
645 * all Participant machines after the TRANS_REQUEST protocol */
646 int decideResponse(thread_data_array_t *tdata) {
648 int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
651 for (i = 0 ; i < tdata->pilecount ; i++) {
652 control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses
653 written onto the shared array */
663 case TRANS_SOFT_ABORT:
667 printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
673 if(transdisagree > 0) {
674 *(tdata->replyctrl) = TRANS_ABORT;
676 objstrDelete(tdata->rec->cache);
677 chashDelete(tdata->rec->lookupTable);
679 } else if(transagree == tdata->pilecount){
681 *(tdata->replyctrl) = TRANS_COMMIT;
683 objstrDelete(tdata->rec->cache);
684 chashDelete(tdata->rec->lookupTable);
686 } else if(transsoftabort > 0 && transdisagree == 0) {
687 /* Send Abort in soft abort case followed by retry commiting transaction again*/
688 *(tdata->replyctrl) = TRANS_ABORT;
689 *(tdata->replyretry) = 1;
696 /* This function sends the final response to remote machines per thread in their respective socket id */
697 char sendResponse(thread_data_array_t *tdata, int sd) {
698 int n, N, sum, oidcount = 0;
699 char *ptr, retval = 0;
700 unsigned int *oidnotfound;
702 /* If the decided response is due to a soft abort and missing objects at the Participant's side */
703 if(tdata->recvmsg[tdata->thread_id].rcv_status == TRANS_SOFT_ABORT) {
704 /* Read list of objects missing */
705 if((read(sd, &oidcount, sizeof(int)) != 0) && (oidcount != 0)) {
706 N = oidcount * sizeof(unsigned int);
707 if((oidnotfound = calloc(oidcount, sizeof(unsigned int))) == NULL) {
708 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
711 ptr = (char *) oidnotfound;
713 n = read(sd, ptr+sum, N-sum);
715 } while(sum < N && n !=0);
717 retval = TRANS_SOFT_ABORT;
719 /* If the decided response is TRANS_ABORT */
720 if(*(tdata->replyctrl) == TRANS_ABORT) {
721 retval = TRANS_ABORT;
722 } else if(*(tdata->replyctrl) == TRANS_COMMIT) { /* If the decided response is TRANS_COMMIT */
723 retval = TRANS_COMMIT;
726 if (send(sd, tdata->replyctrl, sizeof(char),MSG_NOSIGNAL) < sizeof(char)) {
727 perror("Error sending ctrl message for participant\n");
733 /* This function opens a connection, places an object read request to the
734 * remote machine, reads the control message and object if available and
735 * copies the object and its header to the local cache.
736 * TODO replace mnum and midtoIP() with MACHINE_IP address later */
738 void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
740 struct sockaddr_in serv_addr;
741 struct hostent *server;
747 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
748 perror("Error in socket\n");
751 bzero((char*) &serv_addr, sizeof(serv_addr));
752 serv_addr.sin_family = AF_INET;
753 serv_addr.sin_port = htons(LISTEN_PORT);
754 //serv_addr.sin_addr.s_addr = inet_addr(MACHINE_IP);
755 midtoIP(mnum,machineip);
756 machineip[15] = '\0';
757 serv_addr.sin_addr.s_addr = inet_addr(machineip);
758 /* Open connection */
759 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
760 perror("Error in connect\n");
763 char readrequest[sizeof(char)+sizeof(unsigned int)];
764 readrequest[0] = READ_REQUEST;
765 *((unsigned int *)(&readrequest[1])) = oid;
766 if (send(sd, &readrequest, sizeof(readrequest), MSG_NOSIGNAL) < sizeof(readrequest)) {
767 perror("Error sending message\n");
772 printf("DEBUG -> ready to rcv ...\n");
774 /* Read response from the Participant */
775 if((val = read(sd, &control, sizeof(char))) <= 0) {
776 perror("No control response for getRemoteObj sent\n");
780 case OBJECT_NOT_FOUND:
783 /* Read object if found into local cache */
784 if((val = read(sd, &size, sizeof(int))) <= 0) {
785 perror("No size is read from the participant\n");
788 objcopy = objstrAlloc(record->cache, size);
789 if((val = read(sd, objcopy, size)) <= 0) {
790 perror("No objects are read from the remote participant\n");
793 /* Insert into cache's lookup table */
794 chashInsert(record->lookupTable, oid, objcopy);
797 printf("Error in recv request from participant on a READ_REQUEST %s, %d\n",__FILE__, __LINE__);
800 /* Close connection */
805 /* This function handles the local objects involved in a transaction commiting process.
806 * It also makes a decision if this local machine sends AGREE or DISAGREE or SOFT_ABORT to coordinator.
807 * Note Coordinator = local machine
808 * It wakes up the other threads from remote participants that are waiting for the coordinator's decision and
809 * based on common agreement it either commits or aborts the transaction.
810 * It also frees the memory resources */
811 void *handleLocalReq(void *threadarg) {
812 int val, i = 0, size, offset = 0;
814 char control = 0, *ptr;
816 unsigned int *oidnotfound = NULL, *oidlocked = NULL;
818 objheader_t *headptr, *headeraddr;
819 local_thread_data_array_t *localtdata;
821 localtdata = (local_thread_data_array_t *) threadarg;
823 /* Counters and arrays to formulate decision on control message to be sent */
824 oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
825 oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
826 int objnotfound = 0, objlocked = 0;
827 int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
829 /* modptr points to the beginning of the object store
830 * created at the Pariticipant */
831 pthread_mutex_lock(&mainobjstore_mutex);
832 if ((modptr = objstrAlloc(mainobjstore, localtdata->tdata->buffer->f.sum_bytes)) == NULL) {
833 printf("objstrAlloc error for modified objects %s, %d\n", __FILE__, __LINE__);
834 pthread_mutex_unlock(&mainobjstore_mutex);
837 pthread_mutex_unlock(&mainobjstore_mutex);
838 /* Write modified objects into the mainobject store */
839 for(i = 0; i< localtdata->tdata->buffer->f.nummod; i++) {
840 headeraddr = chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidmod[i]);
841 GETSIZE(size,headeraddr);
842 size+=sizeof(objheader_t);
843 memcpy(modptr+offset, headeraddr, size);
846 /* Write new objects into the mainobject store */
847 for(i = 0; i< localtdata->tdata->buffer->f.numcreated; i++) {
848 headeraddr = chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidcreated[i]);
849 GETSIZE(size, headeraddr);
850 size+=sizeof(objheader_t);
851 memcpy(modptr+offset, headeraddr, size);
858 /* Process each oid in the machine pile/ group per thread */
859 for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) {
860 if (i < localtdata->tdata->buffer->f.numread) {//Objs only read and not modified
861 int incr = sizeof(unsigned int) + sizeof(short);// Offset that points to next position in the objread array
863 oid = *((unsigned int *)(localtdata->tdata->buffer->objread + incr));
864 incr += sizeof(unsigned int);
865 version = *((short *)(localtdata->tdata->buffer->objread + incr));
866 } else {//Objs modified
868 headptr = (objheader_t *)ptr;
870 version = headptr->version;
871 GETSIZE(tmpsize, headptr);
872 ptr += sizeof(objheader_t) + tmpsize;
875 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
877 /* Save the oids not found and number of oids not found for later use */
878 if ((mobj = mhashSearch(oid)) == NULL) {/* Obj not found */
879 /* Save the oids not found and number of oids not found for later use */
880 oidnotfound[objnotfound] = oid;
882 } else { /* If Obj found in machine (i.e. has not moved) */
883 /* Check if Obj is locked by any previous transaction */
884 if (STATUS(((objheader_t *)mobj)) & LOCK) {
885 if (version == ((objheader_t *)mobj)->version) { /* If not locked then match versions */
887 } else {/* If versions don't match ...HARD ABORT */
889 /* Send TRANS_DISAGREE to Coordinator */
890 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
892 } else {/* If Obj is not locked then lock object */
893 STATUS(((objheader_t *)mobj)) |= LOCK;
894 //TODO Remove this for Testing
895 //randomdelay(); -- Why is this here. BCD
897 /* Save all object oids that are locked on this machine during this transaction request call */
898 oidlocked[objlocked] = OID(((objheader_t *)mobj));
900 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
902 } else { /* If versions don't match ...HARD ABORT */
904 /* Send TRANS_DISAGREE to Coordinator */
905 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
911 /* Condition to send TRANS_AGREE */
912 if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
913 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
915 /* Condition to send TRANS_SOFT_ABORT */
916 if((v_matchlock > 0 && v_nomatch == 0) || (objnotfound > 0 && v_nomatch == 0)) {
917 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
918 //TODO currently the only soft abort case that is supported is when object locked by previous
919 //transaction => v_matchlock > 0
920 //The other case for SOFT ABORT i.e. when object is not found but versions match is not supported
921 /* Send number of oids not found and the missing oids if objects are missing in the machine */
922 /* TODO Remember to store the oidnotfound for later use
923 if(objnotfound != 0) {
924 int size = sizeof(unsigned int)* objnotfound;
929 /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
930 * if Participant receives a TRANS_COMMIT */
931 localtdata->transinfo->objlocked = oidlocked;
932 localtdata->transinfo->objnotfound = oidnotfound;
933 localtdata->transinfo->modptr = modptr;
934 localtdata->transinfo->numlocked = objlocked;
935 localtdata->transinfo->numnotfound = objnotfound;
937 /* Lock and update count */
938 //Thread sleeps until all messages from pariticipants are received by coordinator
939 pthread_mutex_lock(localtdata->tdata->lock);
940 (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */
942 /* Wake up the threads and invoke decideResponse (once) */
943 if(*(localtdata->tdata->count) == localtdata->tdata->pilecount) {
944 if (decideResponse(localtdata->tdata) != 0) {
945 printf("decideResponse returned error %s,%d\n", __FILE__, __LINE__);
946 pthread_mutex_unlock(localtdata->tdata->lock);
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__);
970 if (localtdata->transinfo->objlocked != NULL) {
971 free(localtdata->transinfo->objlocked);
972 localtdata->transinfo->objlocked = NULL;
974 if (localtdata->transinfo->objnotfound != NULL) {
975 free(localtdata->transinfo->objnotfound);
976 localtdata->transinfo->objnotfound = NULL;
981 /* This function completes the ABORT process if the transaction is aborting
983 int transAbortProcess(void *modptr, unsigned int *objlocked, int numlocked, int nummod) {
986 objheader_t *tmp_header;
989 /* Set all ref counts as 1 and do garbage collection */
990 ptr = (char *)modptr;
991 for(i = 0; i< nummod; i++) {
993 tmp_header = (objheader_t *)ptr;
994 tmp_header->rcount = 0;
995 GETSIZE(tmpsize, tmp_header);
996 ptr += sizeof(objheader_t) + tmpsize;
998 /* Unlock objects that was locked due to this transaction */
999 for(i = 0; i< numlocked; i++) {
1000 if((header = mhashSearch(objlocked[i])) == NULL) {
1001 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1004 STATUS(((objheader_t *)header)) &= ~(LOCK);
1007 /* Send ack to Coordinator */
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 */
1068 /* This function checks if the prefetch oids are same and have same offsets
1069 * for case x.a.b and y.a.b where x and y have same oid's
1070 * or if a.b.c is a subset of x.b.c.d*/
1071 /* check for case where the generated request a.y.z or x.y.z.g then
1072 * prefetch needs to be generated for x.y.z.g if oid of a and x are same*/
1073 void checkPrefetchTuples(prefetchqelem_t *node) {
1074 int i,j, count,k, sindex, index;
1076 int ntuples, slength;
1078 short *endoffsets, *arryfields;
1080 /* Check for the case x.y.z and a.b.c are same oids */
1081 ptr = (char *) node;
1082 ntuples = *(GET_NTUPLES(ptr));
1083 oid = GET_PTR_OID(ptr);
1084 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1085 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1086 /* Find offset length for each tuple */
1087 int numoffset[ntuples];
1088 numoffset[0] = endoffsets[0];
1089 for(i = 1; i<ntuples; i++) {
1090 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1092 /* Check for redundant tuples by comparing oids of each tuple */
1093 for(i = 0; i < ntuples; i++) {
1096 for(j = i+1 ; j < ntuples; j++) {
1099 /*If oids of tuples match */
1100 if (oid[i] == oid[j]) {
1101 /* Find the smallest offset length of two tuples*/
1102 if(numoffset[i] > numoffset[j]){
1103 slength = numoffset[j];
1107 slength = numoffset[i];
1111 /* Compare the offset values based on the current indices
1112 * break if they do not match
1113 * if all offset values match then pick the largest tuple*/
1117 index = endoffsets[j -1];
1118 for(count = 0; count < slength; count ++) {
1119 if (arryfields[k] != arryfields[index]) {
1126 k = endoffsets[i-1];
1127 index = endoffsets[j-1];
1128 printf("Value of slength = %d\n", slength);
1129 for(count = 0; count < slength; count++) {
1130 if(arryfields[k] != arryfields[index]) {
1138 if(slength == count) {
1146 void checkPreCache(prefetchqelem_t *node, int *numoffset, int counter, int loopcount, unsigned int objoid, int index, int iter, int oidnfound) {
1148 int ntuples, i, k, flag;
1150 short *endoffsets, *arryfields;
1151 objheader_t *header;
1153 ptr = (char *) node;
1154 ntuples = *(GET_NTUPLES(ptr));
1155 oid = GET_PTR_OID(ptr);
1156 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1157 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1159 if(oidnfound == 1) {
1160 if((header = (objheader_t *) prehashSearch(objoid)) == NULL) {
1162 } else { //Found in Prefetch Cache
1163 //TODO Decide if object is too old, if old remove from cache
1164 tmp = (char *) header;
1165 /* Check if any of the offset oid is available in the Prefetch cache */
1166 for(i = counter; i < loopcount; i++) {
1167 objoid = *(tmp + sizeof(objheader_t) + arryfields[counter]);
1168 if((header = (objheader_t *)prehashSearch(objoid)) != NULL) {
1177 for(i = counter; i<loopcount; i++) {
1178 if((header = (objheader_t *)prehashSearch(objoid)) != NULL) {
1179 tmp = (char *) header;
1180 objoid = *(tmp + sizeof(objheader_t) + arryfields[index]);
1190 /* If oid not found locally or in prefetch cache then
1191 * assign the latest oid found as the new oid
1192 * and copy left over offsets into the arrayoffsetfieldarray*/
1194 numoffset[iter] = numoffset[iter] - (i+1);
1195 for(k = 0; k < numoffset[iter] ; k++) {
1196 arryfields[endoffsets[counter]+k] = arryfields[endoffsets[counter]+k+1];
1201 numoffset[iter] = 0;
1205 /* This function makes machine piles to be added into the machine pile queue for each prefetch call */
1206 prefetchpile_t *makePreGroups(prefetchqelem_t *node, int *numoffset) {
1208 int ntuples, slength, i, machinenum;
1211 short *endoffsets, *arryfields, *offset;
1212 prefetchpile_t *head = NULL;
1214 /* Check for the case x.y.z and a.b.c are same oids */
1215 ptr = (char *) node;
1216 ntuples = *(GET_NTUPLES(ptr));
1217 oid = GET_PTR_OID(ptr);
1218 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1219 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1221 /* Check for redundant tuples by comparing oids of each tuple */
1222 for(i = 0; i < ntuples; i++) {
1225 /* For each tuple make piles */
1226 if ((machinenum = lhashSearch(oid[i])) == 0) {
1227 printf("Error: No such Machine %s, %d\n", __FILE__, __LINE__);
1230 /* Insert into machine pile */
1231 offset = &arryfields[endoffsets[i-1]];
1232 insertPile(machinenum, oid[i], numoffset[i], offset, &head);
1238 /* This function checks if the oids within the prefetch tuples are available locally.
1239 * If yes then makes the tuple invalid. If no then rearranges oid and offset values in
1240 * the prefetchqelem_t node to represent a new prefetch tuple */
1241 prefetchpile_t *foundLocal(prefetchqelem_t *node) {
1242 int ntuples,i, j, k, oidnfound = 0, index, flag;
1244 unsigned int objoid;
1246 objheader_t *objheader;
1247 short *endoffsets, *arryfields;
1248 prefetchpile_t *head = NULL;
1250 ptr = (char *) node;
1251 ntuples = *(GET_NTUPLES(ptr));
1252 oid = GET_PTR_OID(ptr);
1253 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1254 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1255 /* Find offset length for each tuple */
1256 int numoffset[ntuples];//Number of offsets for each tuple
1257 numoffset[0] = endoffsets[0];
1258 for(i = 1; i<ntuples; i++) {
1259 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1261 for(i = 0; i < ntuples; i++) {
1264 /* If object found locally */
1265 if((objheader = (objheader_t*) mhashSearch(oid[i])) != NULL) {
1267 tmp = (char *) objheader;
1268 /* Find the oid of its offset value */
1272 index = endoffsets[i - 1];
1273 for(j = 0 ; j < numoffset[i] ; j++) {
1274 objoid = *(tmp + sizeof(objheader_t) + arryfields[index]);
1275 /*If oid found locally then
1276 *assign the latest oid found as the new oid
1277 *and copy left over offsets into the arrayoffsetfieldarray*/
1279 numoffset[i] = numoffset[i] - (j+1);
1280 for(k = 0; k < numoffset[i]; k++)
1281 arryfields[endoffsets[j]+ k] = arryfields[endoffsets[j]+k+1];
1283 /*New offset oid not found */
1284 if((objheader = (objheader_t*) mhashSearch(objoid)) == NULL) {
1286 checkPreCache(node, numoffset, j, numoffset[i], objoid, index, i, oidnfound);
1292 /*If all offset oids are found locally,make the prefetch tuple invalid */
1299 /* Look in Prefetch cache */
1300 checkPreCache(node, numoffset, 0, numoffset[i], oid[i], 0, i, oidnfound);
1304 /* Make machine groups */
1305 head = makePreGroups(node, numoffset);
1309 /* This function is called by the thread calling transPrefetch */
1310 void *transPrefetch(void *t) {
1311 prefetchqelem_t *qnode;
1312 prefetchpile_t *pilehead = NULL;
1315 /* lock mutex of primary prefetch queue */
1316 pthread_mutex_lock(&pqueue.qlock);
1317 /* while primary queue is empty, then wait */
1318 while((pqueue.front == NULL) && (pqueue.rear == NULL)) {
1319 pthread_cond_wait(&pqueue.qcond, &pqueue.qlock);
1322 /* dequeue node to create a machine piles and finally unlock mutex */
1323 if((qnode = pre_dequeue()) == NULL) {
1324 printf("Error: No node returned %s, %d\n", __FILE__, __LINE__);
1327 pthread_mutex_unlock(&pqueue.qlock);
1328 /* Reduce redundant prefetch requests */
1329 checkPrefetchTuples(qnode);
1330 /* Check if the tuples are found locally, if yes then reduce them further*/
1331 /* and group requests by remote machine ids by calling the makePreGroups() */
1332 pilehead = foundLocal(qnode);
1334 /* Lock mutex of pool queue */
1335 pthread_mutex_lock(&mcqueue.qlock);
1336 /* Update the pool queue with the new remote machine piles generated per prefetch call */
1337 mcpileenqueue(pilehead);
1338 /* Broadcast signal on machine pile queue */
1339 pthread_cond_broadcast(&mcqueue.qcond);
1340 /* Unlock mutex of machine pile queue */
1341 pthread_mutex_unlock(&mcqueue.qlock);
1342 /* Deallocate the prefetch queue pile node */
1348 /* Each thread in the pool of threads calls this function to establish connection with
1349 * remote machines, send the prefetch requests and process the reponses from
1350 * the remote machines .
1351 * The thread is active throughout the period of runtime */
1353 void *mcqProcess(void *threadid) {
1355 prefetchpile_t *mcpilenode;
1357 tid = (int) threadid;
1359 /* Lock mutex of mc pile queue */
1360 pthread_mutex_lock(&mcqueue.qlock);
1361 /* When mc pile queue is empty, wait */
1362 while((mcqueue.front == NULL) && (mcqueue.rear == NULL)) {
1363 pthread_cond_wait(&mcqueue.qcond, &mcqueue.qlock);
1365 /* Dequeue node to send remote machine connections*/
1366 if((mcpilenode = mcpiledequeue()) == NULL) {
1367 printf("Dequeue Error: No node returned %s %d\n", __FILE__, __LINE__);
1371 pthread_mutex_unlock(&mcqueue.qlock);
1373 /*Initiate connection to remote host and send request */
1374 /* Process Request */
1375 sendPrefetchReq(mcpilenode, tid);
1377 /* Deallocate the machine queue pile node */
1378 mcdealloc(mcpilenode);
1382 void sendPrefetchReq(prefetchpile_t *mcpilenode, int threadid) {
1383 int sd, i, offset, off, len, endpair, count = 0;
1384 struct sockaddr_in serv_addr;
1385 struct hostent *server;
1386 char machineip[16], control;
1390 /* Send Trans Prefetch Request */
1391 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
1392 perror("Error in socket for TRANS_REQUEST\n");
1395 bzero((char*) &serv_addr, sizeof(serv_addr));
1396 serv_addr.sin_family = AF_INET;
1397 serv_addr.sin_port = htons(LISTEN_PORT);
1398 //serv_addr.sin_addr.s_addr = inet_addr(MACHINE_IP);
1399 midtoIP(mcpilenode->mid ,machineip);
1400 machineip[15] = '\0';
1401 serv_addr.sin_addr.s_addr = inet_addr(machineip);
1403 /* Open Connection */
1404 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
1405 perror("Error in connect for TRANS_REQUEST\n");
1409 /* Send TRANS_PREFETCH control message */
1410 control = TRANS_PREFETCH;
1411 if(send(sd, &control, sizeof(char), MSG_NOSIGNAL) < sizeof(char)) {
1412 perror("Error in sending prefetch control\n");
1416 /* Send Oids and offsets in pairs */
1417 tmp = mcpilenode->objpiles;
1418 while(tmp != NULL) {
1420 count++; /* Keeps track of the number of oid and offset tuples sent per remote machine */
1421 len = sizeof(int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1422 char oidnoffset[len];
1423 memcpy(oidnoffset, &len, sizeof(int));
1425 memcpy(oidnoffset + off, &tmp->oid, sizeof(unsigned int));
1426 off += sizeof(unsigned int);
1427 for(i = 0; i < tmp->numoffset; i++) {
1428 memcpy(oidnoffset + off, &tmp->offset[i], sizeof(short));
1431 if (send(sd, &oidnoffset, sizeof(oidnoffset),MSG_NOSIGNAL) < sizeof(oidnoffset)) {
1432 perror("Error sending fixed bytes for thread\n");
1438 /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
1440 if (send(sd, &endpair, sizeof(int), MSG_NOSIGNAL) < sizeof(int)) {
1441 perror("Error sending fixed bytes for thread\n");
1445 /* Get Response from the remote machine */
1446 getPrefetchResponse(count,sd);
1451 void getPrefetchResponse(int count, int sd) {
1452 int i = 0, val, n, N, sum, index, objsize;
1453 unsigned int bufsize,oid;
1454 char buffer[RECEIVE_BUFFER_SIZE], control;
1456 void *modptr, *oldptr;
1458 /* Read prefetch response from the Remote machine */
1459 if((val = read(sd, &control, sizeof(char))) <= 0) {
1460 perror("No control response for Prefetch request sent\n");
1464 if(control == TRANS_PREFETCH_RESPONSE) {
1465 /*For each oid and offset tuple sent as prefetch request to remote machine*/
1469 /* Read the size of buffer to be received */
1470 if((N = read(sd, buffer, sizeof(unsigned int))) <= 0) {
1471 perror("Size of buffer not recv\n");
1474 memcpy(&bufsize, buffer, sizeof(unsigned int));
1475 ptr = buffer + sizeof(unsigned int);
1476 /* Keep receiving the buffer containing oid info */
1478 n = recv((int)sd, (void *)ptr+sum, bufsize-sum, 0);
1480 } while(sum < bufsize && n != 0);
1481 /* Decode the contents of the buffer */
1482 index = sizeof(unsigned int);
1483 while(index < (bufsize - sizeof(unsigned int))) {
1484 if(buffer[index] == OBJECT_FOUND) {
1485 /* Increment it to get the object */
1486 index += sizeof(char);
1487 memcpy(&oid, buffer + index, sizeof(unsigned int));
1488 index += sizeof(unsigned int);
1489 /* For each object found add to Prefetch Cache */
1490 memcpy(&objsize, buffer + index, sizeof(int));
1492 pthread_mutex_lock(&prefetchcache_mutex);
1493 if ((modptr = objstrAlloc(prefetchcache, objsize)) == NULL) {
1494 printf("objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
1495 pthread_mutex_unlock(&prefetchcache_mutex);
1498 pthread_mutex_unlock(&prefetchcache_mutex);
1499 memcpy(modptr, buffer+index, objsize);
1501 /* Insert the oid and its address into the prefetch hash lookup table */
1502 /* Do a version comparison if the oid exists */
1503 if((oldptr = prehashSearch(oid)) != NULL) {
1504 /* If older version then update with new object ptr */
1505 if(((objheader_t *)oldptr)->version < ((objheader_t *)modptr)->version) {
1507 prehashInsert(oid, modptr);
1508 } else if(((objheader_t *)oldptr)->version == ((objheader_t *)modptr)->version) {
1509 /* Add the new object ptr to hash table */
1510 prehashInsert(oid, modptr);
1511 } else { /* Do nothing */
1514 } else {/*If doesn't no match found in hashtable, add the object ptr to hash table*/
1515 prehashInsert(oid, modptr);
1517 /* Lock the Prefetch Cache look up table*/
1518 pthread_mutex_lock(&pflookup.lock);
1519 /* Broadcast signal on prefetch cache condition variable */
1520 pthread_cond_broadcast(&pflookup.cond);
1521 /* Unlock the Prefetch Cache look up table*/
1522 pthread_mutex_unlock(&pflookup.lock);
1523 } else if(buffer[index] == OBJECT_NOT_FOUND) {
1524 /* Increment it to get the object */
1525 /* TODO: For each object not found query DHT for new location and retrieve the object */
1526 index += sizeof(char);
1527 memcpy(&oid, buffer + index, sizeof(unsigned int));
1528 index += sizeof(unsigned int);
1529 /* Throw an error */
1530 printf("OBJECT NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n");
1533 printf("Error in decoding the index value %s, %d\n",__FILE__, __LINE__);
1541 printf("Error in receving response for prefetch request %s, %d\n",__FILE__, __LINE__);
1545 unsigned short getObjType(unsigned int oid)
1547 objheader_t *objheader;
1548 unsigned short numoffsets = 0;
1550 if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL)
1552 if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1554 prefetch(1, &oid, &numoffsets, NULL);
1555 while ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1557 pthread_mutex_lock(&pflookup.lock);
1558 pthread_cond_wait(&pflookup.cond, &pflookup.lock);
1559 pthread_mutex_unlock(&pflookup.lock);
1564 return TYPE(objheader);
1567 int startRemoteThread(unsigned int oid, unsigned int mid)
1570 struct sockaddr_in remoteAddr;
1571 char msg[1 + sizeof(unsigned int)];
1575 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
1577 perror("startRemoteThread():socket()");
1581 bzero(&remoteAddr, sizeof(remoteAddr));
1582 remoteAddr.sin_family = AF_INET;
1583 remoteAddr.sin_port = htons(LISTEN_PORT);
1584 remoteAddr.sin_addr.s_addr = htonl(mid);
1586 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0)
1588 printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
1589 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1594 msg[0] = START_REMOTE_THREAD;
1595 memcpy(&msg[1], &oid, sizeof(unsigned int));
1597 bytesSent = send(sock, msg, 1 + sizeof(unsigned int), 0);
1600 perror("startRemoteThread():send()");
1603 else if (bytesSent != 1 + sizeof(unsigned int))
1605 printf("startRemoteThread(): error, sent %d bytes\n", bytesSent);
1618 //TODO: when reusing oids, make sure they are not already in use!
1619 unsigned int getNewOID(void) {
1620 static unsigned int id = 0xFFFFFFFF;
1623 if (id > oidMax || id < oidMin)
1630 int processConfigFile()
1633 const int maxLineLength = 200;
1634 char lineBuffer[maxLineLength];
1636 const char *delimiters = " \t\n";
1640 configFile = fopen(CONFIG_FILENAME, "r");
1641 if (configFile == NULL)
1643 printf("error opening %s:\n", CONFIG_FILENAME);
1648 numHostsInSystem = 0;
1649 sizeOfHostArray = 8;
1650 hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
1652 while(fgets(lineBuffer, maxLineLength, configFile) != NULL)
1654 commentBegin = strchr(lineBuffer, '#');
1655 if (commentBegin != NULL)
1656 *commentBegin = '\0';
1657 token = strtok(lineBuffer, delimiters);
1658 while (token != NULL)
1660 tmpAddr = inet_addr(token);
1661 if ((int)tmpAddr == -1)
1663 printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
1668 addHost(htonl(tmpAddr));
1669 token = strtok(NULL, delimiters);
1675 if (numHostsInSystem < 1)
1677 printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
1681 myIpAddr = getMyIpAddr("en1");
1683 myIpAddr = getMyIpAddr("eth0");
1685 myIndexInHostArray = findHost(myIpAddr);
1686 if (myIndexInHostArray == -1)
1688 printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
1691 oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
1692 oidMin = oidsPerBlock * myIndexInHostArray;
1693 if (myIndexInHostArray == numHostsInSystem - 1)
1694 oidMax = 0xFFFFFFFF;
1696 oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
1701 void addHost(unsigned int hostIp)
1703 unsigned int *tmpArray;
1705 if (findHost(hostIp) != -1)
1708 if (numHostsInSystem == sizeOfHostArray)
1710 tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
1711 memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
1713 hostIpAddrs = tmpArray;
1716 hostIpAddrs[numHostsInSystem++] = hostIp;
1721 int findHost(unsigned int hostIp)
1724 for (i = 0; i < numHostsInSystem; i++)
1725 if (hostIpAddrs[i] == hostIp)