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 extern prehashtable_t pflookup; //Global Prefetch cache's lookup table
34 pthread_t wthreads[NUM_THREADS]; //Worker threads for working on the prefetch queue
36 extern objstr_t *mainobjstore;
37 unsigned int myIpAddr;
38 unsigned int *hostIpAddrs;
41 int myIndexInHostArray;
42 unsigned int oidsPerBlock;
46 plistnode_t *createPiles(transrecord_t *);
47 inline int arrayLength(int *array) {
49 for(i=0 ;array[i] != -1; i++)
53 inline int findmax(int *array, int arraylength) {
56 for(i = 0; i < arraylength; i++){
63 /* This function is a prefetch call generated by the compiler that
64 * populates the shared primary prefetch queue*/
65 void prefetch(int ntuples, unsigned int *oids, unsigned short *endoffsets, short *arrayfields) {
69 /* Allocate for the queue node*/
71 qnodesize = sizeof(prefetchqelem_t) + sizeof(int) + ntuples * (sizeof(short) + sizeof(unsigned int)) + endoffsets[ntuples - 1] * sizeof(short);
72 if((node = calloc(1, qnodesize)) == NULL) {
73 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
76 /* Set queue node values */
77 len = sizeof(prefetchqelem_t);
78 memcpy(node + len, &ntuples, sizeof(int));
80 memcpy(node + len, oids, ntuples*sizeof(unsigned int));
81 len += ntuples * sizeof(unsigned int);
82 memcpy(node + len, endoffsets, ntuples*sizeof(short));
83 len += ntuples * sizeof(short);
84 memcpy(node + len, arrayfields, endoffsets[ntuples-1]*sizeof(short));
85 /* Lock and insert into primary prefetch queue */
86 pthread_mutex_lock(&pqueue.qlock);
87 pre_enqueue((prefetchqelem_t *)node);
88 pthread_cond_signal(&pqueue.qcond);
89 pthread_mutex_unlock(&pqueue.qlock);
92 /* This function starts up the transaction runtime. */
93 int dstmStartup(const char * option) {
94 pthread_t thread_Listen;
96 int master=strcmp(option, "master")==0;
98 if (processConfigFile() != 0)
99 return 0; //TODO: return error value, cause main program to exit
105 pthread_attr_init(&attr);
106 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
107 pthread_create(&thread_Listen, &attr, dstmListen, NULL);
117 /* This function initiates the prefetch thread
118 * A queue is shared between the main thread of execution
119 * and the prefetch thread to process the prefetch call
120 * Call from compiler populates the shared queue with prefetch requests while prefetch thread
121 * processes the prefetch requests */
124 //Create and initialize prefetch cache structure
125 prefetchcache = objstrCreate(PREFETCH_CACHE_SIZE);
126 //Create prefetch cache lookup table
127 if(prehashCreate(HASH_SIZE, LOADFACTOR))
129 //Initialize primary shared queue
131 //Initialize machine pile w/prefetch oids and offsets shared queue
133 //Create the primary prefetch thread
134 pthread_create(&tPrefetch, NULL, transPrefetch, NULL);
135 //Create and Initialize a pool of threads
136 /* Threads are active for the entire period runtime is running */
137 for(t = 0; t< NUM_THREADS; t++) {
138 rc = pthread_create(&wthreads[t], NULL, mcqProcess, (void *)t);
140 printf("Thread create error %s, %d\n", __FILE__, __LINE__);
146 /* This function stops the threads spawned */
149 pthread_cancel(tPrefetch);
150 for(t = 0; t < NUM_THREADS; t++)
151 pthread_cancel(wthreads[t]);
156 /* This functions inserts randowm wait delays in the order of msec
157 * Mostly used when transaction commits retry*/
158 void randomdelay(void)
160 struct timespec req, rem;
165 req.tv_nsec = (long)(1000000 + (t%10000000)); //1-11 msec
166 nanosleep(&req, &rem);
170 /* This function initializes things required in the transaction start*/
171 transrecord_t *transStart()
173 transrecord_t *tmp = malloc(sizeof(transrecord_t));
174 tmp->cache = objstrCreate(1048576);
175 tmp->lookupTable = chashCreate(HASH_SIZE, LOADFACTOR);
177 tmp->revertlist=NULL;
182 /* This function finds the location of the objects involved in a transaction
183 * and returns the pointer to the object if found in a remote location */
184 objheader_t *transRead(transrecord_t *record, unsigned int oid) {
185 unsigned int machinenumber;
186 objheader_t *tmp, *objheader;
188 int size, rc, found = 0;
193 rc = gettimeofday(&tp, NULL);
195 /* Convert from timeval to timespec */
196 ts.tv_nsec = tp.tv_usec * 1000;
198 /* Search local transaction cache */
199 if((objheader = (objheader_t *)chashSearch(record->lookupTable, oid)) != NULL){
201 } else if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
202 /* Look up in machine lookup table and copy into cache*/
203 tmp = mhashSearch(oid);
204 size = sizeof(objheader_t)+classsize[TYPE(tmp)];
205 objcopy = objstrAlloc(record->cache, size);
206 memcpy(objcopy, (void *)objheader, size);
207 /* Insert into cache's lookup table */
208 chashInsert(record->lookupTable, OID(objheader), objcopy);
210 } else if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) { /* Look up in prefetch cache */
212 size = sizeof(objheader_t)+classsize[TYPE(tmp)];
213 objcopy = objstrAlloc(record->cache, size);
214 memcpy(objcopy, (void *)tmp, size);
215 /* Insert into cache's lookup table */
216 chashInsert(record->lookupTable, OID(tmp), objcopy);
218 } else { /* If not found anywhere, then block until object appears in prefetch cache */
220 printf("Inside remote machine\n");
221 pthread_mutex_lock(&pflookup.lock);
223 rc = pthread_cond_timedwait(&pflookup.cond, &pflookup.lock, &ts);
224 if(rc == ETIMEDOUT) {
225 printf("Wait timed out\n");
226 /* Check Prefetch cache again */
227 if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) { /* Look up in prefetch cache */
229 size = sizeof(objheader_t)+classsize[TYPE(tmp)];
230 objcopy = objstrAlloc(record->cache, size);
231 memcpy(objcopy, (void *)tmp, size);
232 /* Insert into cache's lookup table */
233 chashInsert(record->lookupTable, OID(tmp), objcopy);
236 pthread_mutex_unlock(&pflookup.lock);
239 pthread_mutex_unlock(&pflookup.lock);
243 /* Get the object from the remote location */
244 machinenumber = lhashSearch(oid);
245 objcopy = getRemoteObj(record, machinenumber, oid);
246 if(objcopy == NULL) {
247 //If object is not found in Remote location
256 /* This function creates objects in the transaction record */
257 objheader_t *transCreateObj(transrecord_t *record, unsigned int size)
259 objheader_t *tmp = (objheader_t *) objstrAlloc(record->cache, (sizeof(objheader_t) + size));
260 OID(tmp) = getNewOID();
264 chashInsert(record->lookupTable, OID(tmp), tmp);
268 /* This function creates machine piles based on all machines involved in a
269 * transaction commit request */
270 plistnode_t *createPiles(transrecord_t *record) {
272 unsigned int size;/* Represents number of bins in the chash table */
273 chashlistnode_t *curr, *ptr, *next;
274 plistnode_t *pile = NULL;
275 unsigned int machinenum;
276 void *localmachinenum;
277 objheader_t *headeraddr;
279 ptr = record->lookupTable->table;
280 size = record->lookupTable->size;
282 for(i = 0; i < size ; i++) {
284 /* Inner loop to traverse the linked list of the cache lookupTable */
285 while(curr != NULL) {
286 //if the first bin in hash table is empty
292 if ((headeraddr = chashSearch(record->lookupTable, curr->key)) == NULL) {
293 printf("Error: No such oid %s, %d\n", __FILE__, __LINE__);
297 //Get machine location for object id (and whether local or not)
298 if (STATUS(headeraddr) & NEW || mhashSearch(curr->key) != NULL) {
299 machinenum = myIpAddr;
300 } else if ((machinenum = lhashSearch(curr->key)) == 0) {
301 printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
305 //Make machine groups
306 if ((pile = pInsert(pile, headeraddr, machinenum, record->lookupTable->numelements)) == NULL) {
307 printf("pInsert error %s, %d\n", __FILE__, __LINE__);
317 /* This function initiates the transaction commit process
318 * Spawns threads for each of the new connections with Participants
319 * and creates new piles by calling the createPiles(),
320 * Sends a transrequest() to each remote machines for objects found remotely
321 * and calls handleLocalReq() to process objects found locally */
322 int transCommit(transrecord_t *record) {
323 unsigned int tot_bytes_mod, *listmid;
324 plistnode_t *pile, *pile_ptr;
326 int pilecount = 0, offset, threadnum = 0, trecvcount = 0, tmachcount = 0;
327 char buffer[RECEIVE_BUFFER_SIZE],control;
328 char transid[TID_LEN];
329 trans_req_data_t *tosend;
330 trans_commit_data_t transinfo;
331 static int newtid = 0;
332 char treplyctrl = 0, treplyretry = 0; /* keeps track of the common response that needs to be sent */
337 /* Look through all the objects in the transaction record and make piles
338 * for each machine involved in the transaction*/
339 pile_ptr = pile = createPiles(record);
341 /* Create the packet to be sent in TRANS_REQUEST */
343 /* Count the number of participants */
344 pilecount = pCount(pile);
346 /* Create a list of machine ids(Participants) involved in transaction */
347 if((listmid = calloc(pilecount, sizeof(unsigned int))) == NULL) {
348 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
351 pListMid(pile, listmid);
354 /* Initialize thread variables,
355 * Spawn a thread for each Participant involved in a transaction */
356 pthread_t thread[pilecount];
358 pthread_cond_t tcond;
359 pthread_mutex_t tlock;
360 pthread_mutex_t tlshrd;
362 thread_data_array_t *thread_data_array;
363 if((thread_data_array = (thread_data_array_t *) malloc(sizeof(thread_data_array_t)*pilecount)) == NULL) {
364 printf("Malloc error %s, %d\n", __FILE__, __LINE__);
365 pthread_cond_destroy(&tcond);
366 pthread_mutex_destroy(&tlock);
372 local_thread_data_array_t *ltdata;
373 if((ltdata = calloc(1, sizeof(local_thread_data_array_t))) == NULL) {
374 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
375 pthread_cond_destroy(&tcond);
376 pthread_mutex_destroy(&tlock);
379 free(thread_data_array);
383 thread_response_t rcvd_control_msg[pilecount]; /* Shared thread array that keeps track of responses of participants */
385 /* Initialize and set thread detach attribute */
386 pthread_attr_init(&attr);
387 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
388 pthread_mutex_init(&tlock, NULL);
389 pthread_cond_init(&tcond, NULL);
391 /* Process each machine pile */
392 while(pile != NULL) {
393 //Create transaction id
395 if ((tosend = calloc(1, sizeof(trans_req_data_t))) == NULL) {
396 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
397 pthread_cond_destroy(&tcond);
398 pthread_mutex_destroy(&tlock);
401 free(thread_data_array);
405 tosend->f.control = TRANS_REQUEST;
406 sprintf(tosend->f.trans_id, "%x_%d", pile->mid, newtid);
407 tosend->f.mcount = pilecount;
408 tosend->f.numread = pile->numread;
409 tosend->f.nummod = pile->nummod;
410 tosend->f.numcreated = pile->numcreated;
411 tosend->f.sum_bytes = pile->sum_bytes;
412 tosend->listmid = listmid;
413 tosend->objread = pile->objread;
414 tosend->oidmod = pile->oidmod;
415 tosend->oidcreated = pile->oidcreated;
416 thread_data_array[threadnum].thread_id = threadnum;
417 thread_data_array[threadnum].mid = pile->mid;
418 thread_data_array[threadnum].pilecount = pilecount;
419 thread_data_array[threadnum].buffer = tosend;
420 thread_data_array[threadnum].recvmsg = rcvd_control_msg;
421 thread_data_array[threadnum].threshold = &tcond;
422 thread_data_array[threadnum].lock = &tlock;
423 thread_data_array[threadnum].count = &trecvcount;
424 thread_data_array[threadnum].replyctrl = &treplyctrl;
425 thread_data_array[threadnum].replyretry = &treplyretry;
426 thread_data_array[threadnum].rec = record;
427 /* If local do not create any extra connection */
428 if(pile->mid != myIpAddr) { /* Not local */
429 rc = pthread_create(&thread[threadnum], NULL, transRequest, (void *) &thread_data_array[threadnum]);
431 perror("Error in pthread create\n");
432 pthread_cond_destroy(&tcond);
433 pthread_mutex_destroy(&tlock);
436 free(thread_data_array);
442 ltdata->tdata = &thread_data_array[threadnum];
443 ltdata->transinfo = &transinfo;
444 val = pthread_create(&thread[threadnum], NULL, handleLocalReq, (void *) ltdata);
446 perror("Error in pthread create\n");
447 pthread_cond_destroy(&tcond);
448 pthread_mutex_destroy(&tlock);
451 free(thread_data_array);
461 /* Free attribute and wait for the other threads */
462 pthread_attr_destroy(&attr);
463 for (i = 0 ;i < pilecount ; i++) {
464 rc = pthread_join(thread[i], NULL);
467 printf("ERROR return code from pthread_join() is %d\n", rc);
468 pthread_cond_destroy(&tcond);
469 pthread_mutex_destroy(&tlock);
472 free(thread_data_array);
477 free(thread_data_array[i].buffer);
481 pthread_cond_destroy(&tcond);
482 pthread_mutex_destroy(&tlock);
485 free(thread_data_array);
488 /* wait a random amount of time */
489 if (treplyretry == 1)
492 /* Retry trans commit procedure if not sucessful in the first try */
493 } while (treplyretry == 1);
498 /* This function sends information involved in the transaction request
499 * to participants and accepts a response from particpants.
500 * It calls decideresponse() to decide on what control message
501 * to send next to participants and sends the message using sendResponse()*/
502 void *transRequest(void *threadarg) {
504 struct sockaddr_in serv_addr;
505 struct hostent *server;
506 thread_data_array_t *tdata;
507 objheader_t *headeraddr;
508 char buffer[RECEIVE_BUFFER_SIZE], control, recvcontrol;
509 char machineip[16], retval;
511 tdata = (thread_data_array_t *) threadarg;
513 /* Send Trans Request */
514 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
515 perror("Error in socket for TRANS_REQUEST\n");
519 bzero((char*) &serv_addr, sizeof(serv_addr));
520 serv_addr.sin_family = AF_INET;
521 serv_addr.sin_port = htons(LISTEN_PORT);
522 midtoIP(tdata->mid,machineip);
523 machineip[15] = '\0';
524 serv_addr.sin_addr.s_addr = inet_addr(machineip);
525 /* Open Connection */
526 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
527 perror("Error in connect for TRANS_REQUEST\n");
532 printf("DEBUG-> trans.c Sending TRANS_REQUEST to mid %s\n", machineip);
533 /* Send bytes of data with TRANS_REQUEST control message */
534 if (send(sd, &(tdata->buffer->f), sizeof(fixed_data_t),MSG_NOSIGNAL) < sizeof(fixed_data_t)) {
535 perror("Error sending fixed bytes for thread\n");
539 /* Send list of machines involved in the transaction */
541 int size=sizeof(unsigned int)*tdata->pilecount;
542 if (send(sd, tdata->buffer->listmid, size, MSG_NOSIGNAL) < size) {
543 perror("Error sending list of machines for thread\n");
548 /* Send oids and version number tuples for objects that are read */
550 int size=(sizeof(unsigned int)+sizeof(short))*tdata->buffer->f.numread;
551 if (send(sd, tdata->buffer->objread, size, MSG_NOSIGNAL) < size) {
552 perror("Error sending tuples for thread\n");
557 /* Send objects that are modified */
558 for(i = 0; i < tdata->buffer->f.nummod ; i++) {
560 headeraddr = chashSearch(tdata->rec->lookupTable, tdata->buffer->oidmod[i]);
561 size=sizeof(objheader_t)+classsize[TYPE(headeraddr)];
562 if (send(sd, headeraddr, size, MSG_NOSIGNAL) < size) {
563 perror("Error sending obj modified for thread\n");
569 /* Read control message from Participant */
570 if((n = read(sd, &control, sizeof(char))) <= 0) {
571 perror("Error in reading control message from Participant\n");
575 recvcontrol = control;
577 /* Update common data structure and increment count */
578 tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol;
580 /* Lock and update count */
581 /* Thread sleeps until all messages from pariticipants are received by coordinator */
582 pthread_mutex_lock(tdata->lock);
584 (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */
586 /* Wake up the threads and invoke decideResponse (once) */
587 if(*(tdata->count) == tdata->pilecount) {
588 if (decideResponse(tdata) != 0) {
589 printf("decideResponse returned error %s,%d\n", __FILE__, __LINE__);
590 pthread_mutex_unlock(tdata->lock);
594 pthread_cond_broadcast(tdata->threshold);
596 pthread_cond_wait(tdata->threshold, tdata->lock);
598 pthread_mutex_unlock(tdata->lock);
600 /* Send the final response such as TRANS_COMMIT or TRANS_ABORT t
601 * to all participants in their respective socket */
602 if (sendResponse(tdata, sd) == 0) {
603 printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__);
604 pthread_mutex_unlock(tdata->lock);
609 /* Close connection */
614 /* This function decides the reponse that needs to be sent to
615 * all Participant machines after the TRANS_REQUEST protocol */
616 int decideResponse(thread_data_array_t *tdata) {
618 int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
621 for (i = 0 ; i < tdata->pilecount ; i++) {
622 control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses
623 written onto the shared array */
633 case TRANS_SOFT_ABORT:
637 printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
643 if(transdisagree > 0) {
644 *(tdata->replyctrl) = TRANS_ABORT;
646 objstrDelete(tdata->rec->cache);
647 chashDelete(tdata->rec->lookupTable);
649 } else if(transagree == tdata->pilecount){
651 *(tdata->replyctrl) = TRANS_COMMIT;
653 objstrDelete(tdata->rec->cache);
654 chashDelete(tdata->rec->lookupTable);
656 } else if(transsoftabort > 0 && transdisagree == 0) {
657 /* Send Abort in soft abort case followed by retry commiting transaction again*/
658 *(tdata->replyctrl) = TRANS_ABORT;
659 *(tdata->replyretry) = 1;
666 /* This function sends the final response to remote machines per thread in their respective socket id */
667 char sendResponse(thread_data_array_t *tdata, int sd) {
668 int n, N, sum, oidcount = 0;
669 char *ptr, retval = 0;
670 unsigned int *oidnotfound;
672 /* If the decided response is due to a soft abort and missing objects at the Participant's side */
673 if(tdata->recvmsg[tdata->thread_id].rcv_status == TRANS_SOFT_ABORT) {
674 /* Read list of objects missing */
675 if((read(sd, &oidcount, sizeof(int)) != 0) && (oidcount != 0)) {
676 N = oidcount * sizeof(unsigned int);
677 if((oidnotfound = calloc(oidcount, sizeof(unsigned int))) == NULL) {
678 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
681 ptr = (char *) oidnotfound;
683 n = read(sd, ptr+sum, N-sum);
685 } while(sum < N && n !=0);
687 retval = TRANS_SOFT_ABORT;
689 /* If the decided response is TRANS_ABORT */
690 if(*(tdata->replyctrl) == TRANS_ABORT) {
691 retval = TRANS_ABORT;
692 } else if(*(tdata->replyctrl) == TRANS_COMMIT) { /* If the decided response is TRANS_COMMIT */
693 retval = TRANS_COMMIT;
696 if (send(sd, tdata->replyctrl, sizeof(char),MSG_NOSIGNAL) < sizeof(char)) {
697 perror("Error sending ctrl message for participant\n");
703 /* This function opens a connection, places an object read request to the
704 * remote machine, reads the control message and object if available and
705 * copies the object and its header to the local cache.
706 * TODO replace mnum and midtoIP() with MACHINE_IP address later */
708 void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
710 struct sockaddr_in serv_addr;
711 struct hostent *server;
717 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
718 perror("Error in socket\n");
721 bzero((char*) &serv_addr, sizeof(serv_addr));
722 serv_addr.sin_family = AF_INET;
723 serv_addr.sin_port = htons(LISTEN_PORT);
724 //serv_addr.sin_addr.s_addr = inet_addr(MACHINE_IP);
725 midtoIP(mnum,machineip);
726 machineip[15] = '\0';
727 serv_addr.sin_addr.s_addr = inet_addr(machineip);
728 /* Open connection */
729 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
730 perror("Error in connect\n");
733 char readrequest[sizeof(char)+sizeof(unsigned int)];
734 readrequest[0] = READ_REQUEST;
735 *((unsigned int *)(&readrequest[1])) = oid;
736 if (send(sd, &readrequest, sizeof(readrequest), MSG_NOSIGNAL) < sizeof(readrequest)) {
737 perror("Error sending message\n");
742 printf("DEBUG -> ready to rcv ...\n");
744 /* Read response from the Participant */
745 if((val = read(sd, &control, sizeof(char))) <= 0) {
746 perror("No control response for getRemoteObj sent\n");
750 case OBJECT_NOT_FOUND:
753 /* Read object if found into local cache */
754 if((val = read(sd, &size, sizeof(int))) <= 0) {
755 perror("No size is read from the participant\n");
758 objcopy = objstrAlloc(record->cache, size);
759 if((val = read(sd, objcopy, size)) <= 0) {
760 perror("No objects are read from the remote participant\n");
763 /* Insert into cache's lookup table */
764 chashInsert(record->lookupTable, oid, objcopy);
767 printf("Error in recv request from participant on a READ_REQUEST %s, %d\n",__FILE__, __LINE__);
770 /* Close connection */
775 /* This function handles the local objects involved in a transaction commiting process.
776 * It also makes a decision if this local machine sends AGREE or DISAGREE or SOFT_ABORT to coordinator.
777 * Note Coordinator = local machine
778 * It wakes up the other threads from remote participants that are waiting for the coordinator's decision and
779 * based on common agreement it either commits or aborts the transaction.
780 * It also frees the memory resources */
781 void *handleLocalReq(void *threadarg) {
782 int val, i = 0, size, offset = 0;
784 char control = 0, *ptr;
786 unsigned int *oidnotfound = NULL, *oidlocked = NULL;
788 objheader_t *headptr, *headeraddr;
789 local_thread_data_array_t *localtdata;
791 localtdata = (local_thread_data_array_t *) threadarg;
793 /* Counters and arrays to formulate decision on control message to be sent */
794 oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
795 oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
796 int objnotfound = 0, objlocked = 0;
797 int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
799 /* modptr points to the beginning of the object store
800 * created at the Pariticipant */
801 if ((modptr = objstrAlloc(mainobjstore, localtdata->tdata->buffer->f.sum_bytes)) == NULL) {
802 printf("objstrAlloc error for modified objects %s, %d\n", __FILE__, __LINE__);
805 /* Write modified objects into the mainobject store */
806 for(i = 0; i< localtdata->tdata->buffer->f.nummod; i++) {
807 headeraddr = chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidmod[i]);
808 size = sizeof(objheader_t) + classsize[TYPE(headeraddr)];
809 memcpy(modptr+offset, headeraddr, size);
812 /* Write new objects into the mainobject store */
813 for(i = 0; i< localtdata->tdata->buffer->f.numcreated; i++) {
814 headeraddr = chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidcreated[i]);
815 size = sizeof(objheader_t) + classsize[TYPE(headeraddr)];
816 memcpy(modptr+offset, headeraddr, size);
823 /* Process each oid in the machine pile/ group per thread */
824 for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) {
825 if (i < localtdata->tdata->buffer->f.numread) {//Objs only read and not modified
826 int incr = sizeof(unsigned int) + sizeof(short);// Offset that points to next position in the objread array
828 oid = *((unsigned int *)(localtdata->tdata->buffer->objread + incr));
829 incr += sizeof(unsigned int);
830 version = *((short *)(localtdata->tdata->buffer->objread + incr));
831 } else {//Objs modified
832 headptr = (objheader_t *)ptr;
834 version = headptr->version;
835 ptr += sizeof(objheader_t) + classsize[TYPE(headptr)];
838 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
840 /* Save the oids not found and number of oids not found for later use */
841 if ((mobj = mhashSearch(oid)) == NULL) {/* Obj not found */
842 /* Save the oids not found and number of oids not found for later use */
843 oidnotfound[objnotfound] = oid;
845 } else { /* If Obj found in machine (i.e. has not moved) */
846 /* Check if Obj is locked by any previous transaction */
847 if (STATUS(((objheader_t *)mobj)) & LOCK) {
848 if (version == ((objheader_t *)mobj)->version) { /* If not locked then match versions */
850 } else {/* If versions don't match ...HARD ABORT */
852 /* Send TRANS_DISAGREE to Coordinator */
853 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
855 } else {/* If Obj is not locked then lock object */
856 STATUS(((objheader_t *)mobj)) |= LOCK;
857 //TODO Remove this for Testing
858 //randomdelay(); -- Why is this here. BCD
860 /* Save all object oids that are locked on this machine during this transaction request call */
861 oidlocked[objlocked] = OID(((objheader_t *)mobj));
863 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
865 } else { /* If versions don't match ...HARD ABORT */
867 /* Send TRANS_DISAGREE to Coordinator */
868 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
874 /* Condition to send TRANS_AGREE */
875 if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
876 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
878 /* Condition to send TRANS_SOFT_ABORT */
879 if((v_matchlock > 0 && v_nomatch == 0) || (objnotfound > 0 && v_nomatch == 0)) {
880 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
881 //TODO currently the only soft abort case that is supported is when object locked by previous
882 //transaction => v_matchlock > 0
883 //The other case for SOFT ABORT i.e. when object is not found but versions match is not supported
884 /* Send number of oids not found and the missing oids if objects are missing in the machine */
885 /* TODO Remember to store the oidnotfound for later use
886 if(objnotfound != 0) {
887 int size = sizeof(unsigned int)* objnotfound;
892 /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
893 * if Participant receives a TRANS_COMMIT */
894 localtdata->transinfo->objlocked = oidlocked;
895 localtdata->transinfo->objnotfound = oidnotfound;
896 localtdata->transinfo->modptr = modptr;
897 localtdata->transinfo->numlocked = objlocked;
898 localtdata->transinfo->numnotfound = objnotfound;
900 /* Lock and update count */
901 //Thread sleeps until all messages from pariticipants are received by coordinator
902 pthread_mutex_lock(localtdata->tdata->lock);
903 (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */
905 /* Wake up the threads and invoke decideResponse (once) */
906 if(*(localtdata->tdata->count) == localtdata->tdata->pilecount) {
907 if (decideResponse(localtdata->tdata) != 0) {
908 printf("decideResponse returned error %s,%d\n", __FILE__, __LINE__);
909 pthread_mutex_unlock(localtdata->tdata->lock);
912 pthread_cond_broadcast(localtdata->tdata->threshold);
914 pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock);
916 pthread_mutex_unlock(localtdata->tdata->lock);
918 /*Based on DecideResponse(), Either COMMIT or ABORT the operation*/
919 if(*(localtdata->tdata->replyctrl) == TRANS_ABORT){
920 if(transAbortProcess(modptr,oidlocked, localtdata->transinfo->numlocked, localtdata->tdata->buffer->f.nummod) != 0) {
921 printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
924 }else if(*(localtdata->tdata->replyctrl) == TRANS_COMMIT){
925 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) {
926 printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
933 if (localtdata->transinfo->objlocked != NULL) {
934 free(localtdata->transinfo->objlocked);
935 localtdata->transinfo->objlocked = NULL;
937 if (localtdata->transinfo->objnotfound != NULL) {
938 free(localtdata->transinfo->objnotfound);
939 localtdata->transinfo->objnotfound = NULL;
944 /* This function completes the ABORT process if the transaction is aborting
946 int transAbortProcess(void *modptr, unsigned int *objlocked, int numlocked, int nummod) {
949 objheader_t *tmp_header;
952 /* Set all ref counts as 1 and do garbage collection */
953 ptr = (char *)modptr;
954 for(i = 0; i< nummod; i++) {
955 tmp_header = (objheader_t *)ptr;
956 tmp_header->rcount = 0;
957 ptr += sizeof(objheader_t) + classsize[TYPE(tmp_header)];
959 /* Unlock objects that was locked due to this transaction */
960 for(i = 0; i< numlocked; i++) {
961 if((header = mhashSearch(objlocked[i])) == NULL) {
962 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
965 STATUS(((objheader_t *)header)) &= ~(LOCK);
968 /* Send ack to Coordinator */
970 /*Free the pointer */
975 /*This function completes the COMMIT process is the transaction is commiting
977 int transComProcess(void *modptr, unsigned int *oidmod, unsigned int *oidcreated, unsigned int *objlocked, int nummod, int numcreated, int numlocked) {
979 int i = 0, offset = 0;
982 /* Process each modified object saved in the mainobject store */
983 for(i = 0; i < nummod; i++) {
984 if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
985 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
988 /* Change reference count of older address and free space in objstr ?? */
991 /* Change ptr address in mhash table */
992 mhashRemove(oidmod[i]); //TODO: this shouldn't be necessary
993 mhashInsert(oidmod[i], (((char *)modptr) + offset));
994 offset += sizeof(objheader_t) + classsize[TYPE(header)];
996 /* Update object version number */
997 header = (objheader_t *) mhashSearch(oidmod[i]);
998 header->version += 1;
1001 for (i = 0; i < numcreated; i++)
1003 header = (objheader_t *)(((char *)modptr) + offset);
1004 mhashInsert(oidcreated[i], (((char *)modptr) + offset));
1005 offset += sizeof(objheader_t) + classsize[TYPE(header)];
1007 lhashInsert(oidcreated[i], myIpAddr);
1010 /* Unlock locked objects */
1011 for(i = 0; i < numlocked; i++) {
1012 if((header = (objheader_t *) mhashSearch(objlocked[i])) == NULL) {
1013 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1016 STATUS(header) &= ~(LOCK);
1019 //TODO Update location lookup table
1021 /* Send ack to Coordinator */
1025 /* This function checks if the prefetch oids are same and have same offsets
1026 * for case x.a.b and y.a.b where x and y have same oid's
1027 * or if a.b.c is a subset of x.b.c.d*/
1028 /* check for case where the generated request a.y.z or x.y.z.g then
1029 * prefetch needs to be generated for x.y.z.g if oid of a and x are same*/
1030 void checkPrefetchTuples(prefetchqelem_t *node) {
1031 int i,j, count,k, sindex, index;
1033 int ntuples, slength;
1035 short *endoffsets, *arryfields;
1037 /* Check for the case x.y.z and a.b.c are same oids */
1038 ptr = (char *) node;
1039 ntuples = *(GET_NTUPLES(ptr));
1040 oid = GET_PTR_OID(ptr);
1041 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1042 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1043 /* Find offset length for each tuple */
1044 int numoffset[ntuples];
1045 numoffset[0] = endoffsets[0];
1046 for(i = 1; i<ntuples; i++) {
1047 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1049 /* Check for redundant tuples by comparing oids of each tuple */
1050 for(i = 0; i < ntuples; i++) {
1053 for(j = i+1 ; j < ntuples; j++) {
1056 /*If oids of tuples match */
1057 if (oid[i] == oid[j]) {
1058 /* Find the smallest offset length of two tuples*/
1059 if(numoffset[i] > numoffset[j]){
1060 slength = numoffset[j];
1064 slength = numoffset[i];
1068 /* Compare the offset values based on the current indices
1069 * break if they do not match
1070 * if all offset values match then pick the largest tuple*/
1074 index = endoffsets[j -1];
1075 for(count = 0; count < slength; count ++) {
1076 if (arryfields[k] != arryfields[index]) {
1083 k = endoffsets[i-1];
1084 index = endoffsets[j-1];
1085 printf("Value of slength = %d\n", slength);
1086 for(count = 0; count < slength; count++) {
1087 if(arryfields[k] != arryfields[index]) {
1095 if(slength == count) {
1103 void checkPreCache(prefetchqelem_t *node, int *numoffset, int counter, int loopcount, unsigned int objoid, int index, int iter, int oidnfound) {
1105 int ntuples, i, k, flag;
1107 short *endoffsets, *arryfields;
1108 objheader_t *header;
1110 ptr = (char *) node;
1111 ntuples = *(GET_NTUPLES(ptr));
1112 oid = GET_PTR_OID(ptr);
1113 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1114 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1116 if(oidnfound == 1) {
1117 if((header = (objheader_t *) prehashSearch(objoid)) == NULL) {
1119 } else { //Found in Prefetch Cache
1120 //TODO Decide if object is too old, if old remove from cache
1121 tmp = (char *) header;
1122 /* Check if any of the offset oid is available in the Prefetch cache */
1123 for(i = counter; i < loopcount; i++) {
1124 objoid = *(tmp + sizeof(objheader_t) + arryfields[counter]);
1125 if((header = (objheader_t *)prehashSearch(objoid)) != NULL) {
1134 for(i = counter; i<loopcount; i++) {
1135 if((header = (objheader_t *)prehashSearch(objoid)) != NULL) {
1136 tmp = (char *) header;
1137 objoid = *(tmp + sizeof(objheader_t) + arryfields[index]);
1147 /* If oid not found locally or in prefetch cache then
1148 * assign the latest oid found as the new oid
1149 * and copy left over offsets into the arrayoffsetfieldarray*/
1151 numoffset[iter] = numoffset[iter] - (i+1);
1152 for(k = 0; k < numoffset[iter] ; k++) {
1153 arryfields[endoffsets[counter]+k] = arryfields[endoffsets[counter]+k+1];
1158 numoffset[iter] = 0;
1162 /* This function makes machine piles to be added into the machine pile queue for each prefetch call */
1163 prefetchpile_t *makePreGroups(prefetchqelem_t *node, int *numoffset) {
1165 int ntuples, slength, i, machinenum;
1168 short *endoffsets, *arryfields, *offset;
1169 prefetchpile_t *head = NULL;
1171 /* Check for the case x.y.z and a.b.c are same oids */
1172 ptr = (char *) node;
1173 ntuples = *(GET_NTUPLES(ptr));
1174 oid = GET_PTR_OID(ptr);
1175 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1176 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1178 /* Check for redundant tuples by comparing oids of each tuple */
1179 for(i = 0; i < ntuples; i++) {
1182 /* For each tuple make piles */
1183 if ((machinenum = lhashSearch(oid[i])) == 0) {
1184 printf("Error: No such Machine %s, %d\n", __FILE__, __LINE__);
1187 /* Insert into machine pile */
1188 offset = &arryfields[endoffsets[i-1]];
1189 insertPile(machinenum, oid[i], numoffset[i], offset, head);
1196 /* This function checks if the oids within the prefetch tuples are available locally.
1197 * If yes then makes the tuple invalid. If no then rearranges oid and offset values in
1198 * the prefetchqelem_t node to represent a new prefetch tuple */
1199 prefetchpile_t *foundLocal(prefetchqelem_t *node) {
1200 int ntuples,i, j, k, oidnfound = 0, index, flag;
1202 unsigned int objoid;
1204 objheader_t *objheader;
1205 short *endoffsets, *arryfields;
1206 prefetchpile_t *head = NULL;
1208 ptr = (char *) node;
1209 ntuples = *(GET_NTUPLES(ptr));
1210 oid = GET_PTR_OID(ptr);
1211 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1212 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1213 /* Find offset length for each tuple */
1214 int numoffset[ntuples];//Number of offsets for each tuple
1215 numoffset[0] = endoffsets[0];
1216 for(i = 1; i<ntuples; i++) {
1217 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1219 for(i = 0; i < ntuples; i++) {
1222 /* If object found locally */
1223 if((objheader = (objheader_t*) mhashSearch(oid[i])) != NULL) {
1225 tmp = (char *) objheader;
1226 /* Find the oid of its offset value */
1230 index = endoffsets[i - 1];
1231 for(j = 0 ; j < numoffset[i] ; j++) {
1232 objoid = *(tmp + sizeof(objheader_t) + arryfields[index]);
1233 /*If oid found locally then
1234 *assign the latest oid found as the new oid
1235 *and copy left over offsets into the arrayoffsetfieldarray*/
1237 numoffset[i] = numoffset[i] - (j+1);
1238 for(k = 0; k < numoffset[i]; k++)
1239 arryfields[endoffsets[j]+ k] = arryfields[endoffsets[j]+k+1];
1241 /*New offset oid not found */
1242 if((objheader = (objheader_t*) mhashSearch(objoid)) == NULL) {
1244 checkPreCache(node, numoffset, j, numoffset[i], objoid, index, i, oidnfound);
1250 /*If all offset oids are found locally,make the prefetch tuple invalid */
1257 /* Look in Prefetch cache */
1258 checkPreCache(node, numoffset, 0, numoffset[i], oid[i], 0, i, oidnfound);
1262 /* Make machine groups */
1263 head = makePreGroups(node, numoffset);
1267 /* This function is called by the thread calling transPrefetch */
1268 void *transPrefetch(void *t) {
1269 prefetchqelem_t *qnode;
1270 prefetchpile_t *pilehead = NULL;
1273 /* lock mutex of primary prefetch queue */
1274 pthread_mutex_lock(&pqueue.qlock);
1275 /* while primary queue is empty, then wait */
1276 while((pqueue.front == NULL) && (pqueue.rear == NULL)) {
1277 pthread_cond_wait(&pqueue.qcond, &pqueue.qlock);
1280 /* dequeue node to create a machine piles and finally unlock mutex */
1281 if((qnode = pre_dequeue()) == NULL) {
1282 printf("Error: No node returned %s, %d\n", __FILE__, __LINE__);
1285 pthread_mutex_unlock(&pqueue.qlock);
1286 /* Reduce redundant prefetch requests */
1287 checkPrefetchTuples(qnode);
1288 /* Check if the tuples are found locally, if yes then reduce them further*/
1289 /* and group requests by remote machine ids by calling the makePreGroups() */
1290 pilehead = foundLocal(qnode);
1292 /* Lock mutex of pool queue */
1293 pthread_mutex_lock(&mcqueue.qlock);
1294 /* Update the pool queue with the new remote machine piles generated per prefetch call */
1295 mcpileenqueue(pilehead);
1296 /* Broadcast signal on machine pile queue */
1297 pthread_cond_broadcast(&mcqueue.qcond);
1298 /* Unlock mutex of machine pile queue */
1299 pthread_mutex_unlock(&mcqueue.qlock);
1300 /* Deallocate the prefetch queue pile node */
1306 /* Each thread in the pool of threads calls this function to establish connection with
1307 * remote machines, send the prefetch requests and process the reponses from
1308 * the remote machines .
1309 * The thread is active throughout the period of runtime */
1311 void *mcqProcess(void *threadid) {
1313 prefetchpile_t *mcpilenode;
1315 tid = (int) threadid;
1317 /* Lock mutex of mc pile queue */
1318 pthread_mutex_lock(&mcqueue.qlock);
1319 /* When mc pile queue is empty, wait */
1320 while((mcqueue.front == NULL) && (mcqueue.rear == NULL)) {
1321 pthread_cond_wait(&mcqueue.qcond, &mcqueue.qlock);
1323 /* Dequeue node to send remote machine connections*/
1324 if((mcpilenode = mcpiledequeue()) == NULL) {
1325 printf("Dequeue Error: No node returned %s %d\n", __FILE__, __LINE__);
1329 pthread_mutex_unlock(&mcqueue.qlock);
1331 /*Initiate connection to remote host and send request */
1332 /* Process Request */
1333 sendPrefetchReq(mcpilenode, tid);
1335 /* Deallocate the machine queue pile node */
1336 mcdealloc(mcpilenode);
1340 void sendPrefetchReq(prefetchpile_t *mcpilenode, int threadid) {
1341 int sd, i, offset, off, len, endpair, numoffsets, count = 0;
1342 struct sockaddr_in serv_addr;
1343 struct hostent *server;
1344 char machineip[16], control;
1348 /* Send Trans Prefetch Request */
1349 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
1350 perror("Error in socket for TRANS_REQUEST\n");
1353 bzero((char*) &serv_addr, sizeof(serv_addr));
1354 serv_addr.sin_family = AF_INET;
1355 serv_addr.sin_port = htons(LISTEN_PORT);
1356 //serv_addr.sin_addr.s_addr = inet_addr(MACHINE_IP);
1357 midtoIP(mcpilenode->mid ,machineip);
1358 machineip[15] = '\0';
1359 serv_addr.sin_addr.s_addr = inet_addr(machineip);
1361 /* Open Connection */
1362 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
1363 perror("Error in connect for TRANS_REQUEST\n");
1367 /* Send TRANS_PREFETCH control message */
1368 control = TRANS_PREFETCH;
1369 if(send(sd, &control, sizeof(char), MSG_NOSIGNAL) < sizeof(char)) {
1370 perror("Error in sending prefetch control\n");
1374 /* Send Oids and offsets in pairs */
1375 tmp = mcpilenode->objpiles;
1376 while(tmp != NULL) {
1378 count++; /* Keeps track of the number of oid and offset tuples sent per remote machine */
1379 len = sizeof(int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1380 char oidnoffset[len];
1381 memcpy(oidnoffset, &len, sizeof(int));
1383 memcpy(oidnoffset + off, &tmp->oid, sizeof(unsigned int));
1384 off += sizeof(unsigned int);
1385 for(i = 0; i < numoffsets; i++) {
1386 offset = off + (i * sizeof(short));
1387 memcpy(oidnoffset + offset, tmp->offset, sizeof(short));
1389 if (send(sd, &oidnoffset, sizeof(oidnoffset),MSG_NOSIGNAL) < sizeof(oidnoffset)) {
1390 perror("Error sending fixed bytes for thread\n");
1396 /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
1398 if (send(sd, &endpair, sizeof(int), MSG_NOSIGNAL) < sizeof(int)) {
1399 perror("Error sending fixed bytes for thread\n");
1403 /* Get Response from the remote machine */
1404 getPrefetchResponse(count,sd);
1409 void getPrefetchResponse(int count, int sd) {
1410 int i = 0, val, n, N, sum, index, objsize;
1411 unsigned int bufsize,oid;
1412 char buffer[RECEIVE_BUFFER_SIZE], control;
1414 void *modptr, *oldptr;
1416 /* Read prefetch response from the Remote machine */
1417 if((val = read(sd, &control, sizeof(char))) <= 0) {
1418 perror("No control response for Prefetch request sent\n");
1422 if(control == TRANS_PREFETCH_RESPONSE) {
1423 /*For each oid and offset tuple sent as prefetch request to remote machine*/
1425 /* Clear contents of buffer */
1426 memset(buffer, 0, RECEIVE_BUFFER_SIZE);
1429 /* Read the size of buffer to be received */
1430 if((N = read(sd, buffer, sizeof(unsigned int))) <= 0) {
1431 perror("Size of buffer not recv\n");
1434 memcpy(&bufsize, buffer, sizeof(unsigned int));
1435 ptr = buffer + sizeof(unsigned int);
1436 /* Keep receiving the buffer containing oid info */
1438 n = recv((int)sd, (void *)ptr+sum, bufsize-sum, 0);
1440 } while(sum < bufsize && n != 0);
1441 /* Decode the contents of the buffer */
1442 index = sizeof(unsigned int);
1443 while(index < (bufsize - sizeof(unsigned int))) {
1444 if(buffer[index] == OBJECT_FOUND) {
1445 /* Increment it to get the object */
1446 index += sizeof(char);
1447 memcpy(&oid, buffer + index, sizeof(unsigned int));
1448 index += sizeof(unsigned int);
1449 /* Lock the Prefetch Cache look up table*/
1450 pthread_mutex_lock(&pflookup.lock);
1451 /* For each object found add to Prefetch Cache */
1452 memcpy(&objsize, buffer + index, sizeof(int));
1453 if ((modptr = objstrAlloc(prefetchcache, objsize)) == NULL) {
1454 printf("objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
1457 memcpy(modptr, buffer+index, objsize);
1458 index += sizeof(int);
1459 /* Insert the oid and its address into the prefetch hash lookup table */
1460 /* Do a version comparison if the oid exists */
1461 if((oldptr = prehashSearch(oid)) != NULL) {
1462 /* If older version then update with new object ptr */
1463 if(((objheader_t *)oldptr)->version < ((objheader_t *)modptr)->version) {
1465 prehashInsert(oid, modptr);
1466 } else if(((objheader_t *)oldptr)->version == ((objheader_t *)modptr)->version) {
1467 /* Add the new object ptr to hash table */
1468 prehashInsert(oid, modptr);
1469 } else { /* Do nothing */
1472 } else {/*If doesn't no match found in hashtable, add the object ptr to hash table*/
1473 prehashInsert(oid, modptr);
1475 /* Broadcast signal on prefetch cache condition variable */
1476 pthread_cond_broadcast(&pflookup.cond);
1477 /* Unlock the Prefetch Cache look up table*/
1478 pthread_mutex_unlock(&pflookup.lock);
1479 } else if(buffer[index] == OBJECT_NOT_FOUND) {
1480 /* Increment it to get the object */
1481 /* TODO: For each object not found query DHT for new location and retrieve the object */
1482 index += sizeof(char);
1483 memcpy(&oid, buffer + index, sizeof(unsigned int));
1484 index += sizeof(unsigned int);
1485 /* Throw an error */
1486 printf("OBJECT NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n");
1489 printf("Error in decoding the index value %s, %d\n",__FILE__, __LINE__);
1495 printf("Error in receving response for prefetch request %s, %d\n",__FILE__, __LINE__);
1499 unsigned short getObjType(unsigned int oid)
1501 objheader_t *objheader;
1502 unsigned short numoffsets = 0;
1504 if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL)
1506 if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1508 prefetch(1, &oid, &numoffsets, NULL);
1509 pthread_mutex_lock(&pflookup.lock);
1510 while ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1511 pthread_cond_wait(&pflookup.cond, &pflookup.lock);
1512 pthread_mutex_unlock(&pflookup.lock);
1516 return TYPE(objheader);
1519 int startRemoteThread(unsigned int oid, unsigned int mid)
1522 struct sockaddr_in remoteAddr;
1523 char msg[1 + sizeof(unsigned int)];
1527 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
1529 perror("startRemoteThread():socket()");
1533 bzero(&remoteAddr, sizeof(remoteAddr));
1534 remoteAddr.sin_family = AF_INET;
1535 remoteAddr.sin_port = htons(LISTEN_PORT);
1536 remoteAddr.sin_addr.s_addr = htonl(mid);
1538 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0)
1540 printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
1541 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1546 msg[0] = START_REMOTE_THREAD;
1547 memcpy(&msg[1], &oid, sizeof(unsigned int));
1549 bytesSent = send(sock, msg, 1 + sizeof(unsigned int), 0);
1552 perror("startRemoteThread():send()");
1555 else if (bytesSent != 1 + sizeof(unsigned int))
1557 printf("startRemoteThread(): error, sent %d bytes\n", bytesSent);
1570 //TODO: when reusing oids, make sure they are not already in use!
1571 unsigned int getNewOID(void) {
1572 static unsigned int id = 0xFFFFFFFF;
1575 if (id > oidMax || id < oidMin)
1582 int processConfigFile()
1585 const int maxLineLength = 200;
1586 char lineBuffer[maxLineLength];
1588 const char *delimiters = " \t\n";
1592 configFile = fopen(CONFIG_FILENAME, "r");
1593 if (configFile == NULL)
1595 printf("error opening %s:\n", CONFIG_FILENAME);
1600 numHostsInSystem = 0;
1601 sizeOfHostArray = 8;
1602 hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
1604 while(fgets(lineBuffer, maxLineLength, configFile) != NULL)
1606 commentBegin = strchr(lineBuffer, '#');
1607 if (commentBegin != NULL)
1608 *commentBegin = '\0';
1609 token = strtok(lineBuffer, delimiters);
1610 while (token != NULL)
1612 tmpAddr = inet_addr(token);
1613 if ((int)tmpAddr == -1)
1615 printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
1620 addHost(htonl(tmpAddr));
1621 token = strtok(NULL, delimiters);
1627 if (numHostsInSystem < 1)
1629 printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
1633 myIpAddr = getMyIpAddr("en1");
1635 myIpAddr = getMyIpAddr("eth0");
1637 myIndexInHostArray = findHost(myIpAddr);
1638 if (myIndexInHostArray == -1)
1640 printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
1643 oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
1644 oidMin = oidsPerBlock * myIndexInHostArray;
1645 if (myIndexInHostArray == numHostsInSystem - 1)
1646 oidMax = 0xFFFFFFFF;
1648 oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
1653 void addHost(unsigned int hostIp)
1655 unsigned int *tmpArray;
1657 if (findHost(hostIp) != -1)
1660 if (numHostsInSystem == sizeOfHostArray)
1662 tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
1663 memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
1665 hostIpAddrs = tmpArray;
1668 hostIpAddrs[numHostsInSystem++] = hostIp;
1673 int findHost(unsigned int hostIp)
1676 for (i = 0; i < numHostsInSystem; i++)
1677 if (hostIpAddrs[i] == hostIp)