4 #include "machinepile.h"
9 #include "threadnotify.h"
12 #include <sys/types.h>
13 #include <sys/socket.h>
15 #include <netinet/in.h>
16 #include <sys/types.h>
22 #define LISTEN_PORT 2156
23 #define RECEIVE_BUFFER_SIZE 2048
24 #define NUM_THREADS 10
25 #define PREFETCH_CACHE_SIZE 1048576 //1MB
26 #define CONFIG_FILENAME "dstm.conf"
28 /* Global Variables */
29 extern int classsize[];
30 extern primarypfq_t pqueue; //Shared prefetch queue
31 extern mcpileq_t mcqueue; //Shared queue containing prefetch requests sorted by remote machineids
32 objstr_t *prefetchcache; //Global Prefetch cache
33 pthread_mutex_t prefetchcache_mutex;// Mutex to lock Prefetch Cache
34 pthread_mutexattr_t prefetchcache_mutex_attr; /* Attribute for lock to make it a recursive lock */
35 extern pthread_mutex_t mainobjstore_mutex;// Mutex to lock main Object store
36 extern prehashtable_t pflookup; //Global Prefetch cache's lookup table
37 pthread_t wthreads[NUM_THREADS]; //Worker threads for working on the prefetch queue
38 pthread_t tPrefetch; /* Primary Prefetch thread that processes the prefetch queue */
39 extern objstr_t *mainobjstore;
40 unsigned int myIpAddr;
41 unsigned int *hostIpAddrs;
44 int myIndexInHostArray;
45 unsigned int oidsPerBlock;
49 pthread_mutex_t mlock = PTHREAD_MUTEX_INITIALIZER;
51 void printhex(unsigned char *, int);
52 plistnode_t *createPiles(transrecord_t *);
54 void printhex(unsigned char *ptr, int numBytes)
57 for (i = 0; i < numBytes; i++)
60 printf("0%x ", ptr[i]);
62 printf("%x ", ptr[i]);
68 inline int arrayLength(int *array) {
70 for(i=0 ;array[i] != -1; i++)
74 inline int findmax(int *array, int arraylength) {
77 for(i = 0; i < arraylength; i++){
84 /* This function is a prefetch call generated by the compiler that
85 * populates the shared primary prefetch queue*/
86 void prefetch(int ntuples, unsigned int *oids, unsigned short *endoffsets, short *arrayfields) {
92 // rc=pthread_create(&tPrefetch, NULL, transPrefetch, NULL);
95 /* Allocate for the queue node*/
98 qnodesize = sizeof(prefetchqelem_t) + sizeof(int) + ntuples * (sizeof(unsigned short) + sizeof(unsigned int)) + endoffsets[ntuples - 1] * sizeof(unsigned short);
99 if((node = calloc(1, qnodesize)) == NULL) {
100 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
103 /* Set queue node values */
104 len = sizeof(prefetchqelem_t);
105 memcpy(node + len, &ntuples, sizeof(int));
107 memcpy(node + len, oids, ntuples*sizeof(unsigned int));
108 len += ntuples * sizeof(unsigned int);
109 memcpy(node + len, endoffsets, ntuples*sizeof(unsigned short));
110 len += ntuples * sizeof(unsigned short);
111 memcpy(node + len, arrayfields, endoffsets[ntuples-1]*sizeof(unsigned short));
112 /* Lock and insert into primary prefetch queue */
113 pthread_mutex_lock(&pqueue.qlock);
114 pre_enqueue((prefetchqelem_t *)node);
115 pthread_cond_signal(&pqueue.qcond);
116 pthread_mutex_unlock(&pqueue.qlock);
120 /* This function starts up the transaction runtime. */
121 int dstmStartup(const char * option) {
122 pthread_t thread_Listen;
124 int master=option!=NULL && strcmp(option, "master")==0;
126 if (processConfigFile() != 0)
127 return 0; //TODO: return error value, cause main program to exit
133 pthread_attr_init(&attr);
134 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
135 pthread_create(&thread_Listen, &attr, dstmListen, NULL);
144 //TODO Use this later
145 void *pCacheAlloc(objstr_t *store, unsigned int size) {
151 while(ptr->next != NULL) {
152 /* check if store is empty */
153 if(((unsigned int)ptr->top - (unsigned int)ptr - sizeof(objstr_t) + size) <= ptr->size) {
168 /* This function initiates the prefetch thread
169 * A queue is shared between the main thread of execution
170 * and the prefetch thread to process the prefetch call
171 * Call from compiler populates the shared queue with prefetch requests while prefetch thread
172 * processes the prefetch requests */
176 //Create and initialize prefetch cache structure
177 prefetchcache = objstrCreate(PREFETCH_CACHE_SIZE);
178 //prefetchcache->next = objstrCreate(PREFETCH_CACHE_SIZE);
179 //prefetchcache->next->next = objstrCreate(PREFETCH_CACHE_SIZE);
181 /* Initialize attributes for mutex */
182 pthread_mutexattr_init(&prefetchcache_mutex_attr);
183 pthread_mutexattr_settype(&prefetchcache_mutex_attr, PTHREAD_MUTEX_RECURSIVE_NP);
185 pthread_mutex_init(&prefetchcache_mutex, &prefetchcache_mutex_attr);
187 //Create prefetch cache lookup table
188 if(prehashCreate(HASH_SIZE, LOADFACTOR))
190 //Initialize primary shared queue
192 //Initialize machine pile w/prefetch oids and offsets shared queue
195 //Create the primary prefetch thread
197 retval=pthread_create(&tPrefetch, NULL, transPrefetch, NULL);
199 pthread_detach(tPrefetch);
201 //Create and Initialize a pool of threads
202 /* Threads are active for the entire period runtime is running */
203 for(t = 0; t< NUM_THREADS; t++) {
205 rc = pthread_create(&wthreads[t], NULL, mcqProcess, (void *)t);
207 pthread_detach(wthreads[t]);
211 /* This function stops the threads spawned */
214 pthread_cancel(tPrefetch);
215 for(t = 0; t < NUM_THREADS; t++)
216 pthread_cancel(wthreads[t]);
221 /* This functions inserts randowm wait delays in the order of msec
222 * Mostly used when transaction commits retry*/
230 req.tv_nsec = (long)(1000000 + (t%10000000)); //1-11 msec
231 nanosleep(&req, NULL);
235 /* This function initializes things required in the transaction start*/
236 transrecord_t *transStart()
238 transrecord_t *tmp = calloc(1, sizeof(transrecord_t));
239 tmp->cache = objstrCreate(1048576);
240 tmp->lookupTable = chashCreate(HASH_SIZE, LOADFACTOR);
242 tmp->revertlist=NULL;
247 /* This function finds the location of the objects involved in a transaction
248 * and returns the pointer to the object if found in a remote location */
249 objheader_t *transRead(transrecord_t *record, unsigned int oid) {
250 unsigned int machinenumber;
251 objheader_t *tmp, *objheader;
252 objheader_t *objcopy;
253 int size, rc, found = 0;
262 rc = gettimeofday(&tp, NULL);
266 if (tp.tv_usec >= 1000000)
268 tp.tv_usec -= 1000000;
271 /* Convert from timeval to timespec */
272 ts.tv_sec = tp.tv_sec;
273 ts.tv_nsec = tp.tv_usec * 1000;
275 /* Search local transaction cache */
276 if((objheader = (objheader_t *)chashSearch(record->lookupTable, oid)) != NULL){
278 return &objheader[1];
282 } else if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
283 /* Look up in machine lookup table and copy into cache*/
284 GETSIZE(size, objheader);
285 size += sizeof(objheader_t);
286 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
287 memcpy(objcopy, objheader, size);
288 /* Insert into cache's lookup table */
289 chashInsert(record->lookupTable, OID(objheader), objcopy);
295 } else if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) { /* Look up in prefetch cache */
297 size+=sizeof(objheader_t);
298 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
299 memcpy(objcopy, tmp, size);
300 /* Insert into cache's lookup table */
301 chashInsert(record->lookupTable, OID(tmp), objcopy);
308 /*If object not found in prefetch cache then block until object appears in the prefetch cache */
309 pthread_mutex_lock(&pflookup.lock);
311 rc = pthread_cond_timedwait(&pflookup.cond, &pflookup.lock, &ts);
312 /* Check Prefetch cache again */
313 if((tmp =(objheader_t *) prehashSearch(oid)) != NULL) {
316 size+=sizeof(objheader_t);
317 objcopy = (objheader_t *) objstrAlloc(record->cache, size);
318 memcpy(objcopy, tmp, size);
319 chashInsert(record->lookupTable, OID(tmp), objcopy);
320 pthread_mutex_unlock(&pflookup.lock);
326 } else if (rc == ETIMEDOUT) {
327 pthread_mutex_unlock(&pflookup.lock);
332 /* Get the object from the remote location */
333 machinenumber = lhashSearch(oid);
334 objcopy = getRemoteObj(record, machinenumber, oid);
335 if(objcopy == NULL) {
336 printf("Error: Object not found in Remote location %s, %d\n", __FILE__, __LINE__);
348 /* This function creates objects in the transaction record */
349 objheader_t *transCreateObj(transrecord_t *record, unsigned int size)
351 objheader_t *tmp = (objheader_t *) objstrAlloc(record->cache, (sizeof(objheader_t) + size));
352 tmp->notifylist = NULL;
353 OID(tmp) = getNewOID();
357 chashInsert(record->lookupTable, OID(tmp), tmp);
360 return &tmp[1]; //want space after object header
366 /* This function creates machine piles based on all machines involved in a
367 * transaction commit request */
368 plistnode_t *createPiles(transrecord_t *record) {
370 unsigned int size;/* Represents number of bins in the chash table */
371 chashlistnode_t *curr, *ptr, *next;
372 plistnode_t *pile = NULL;
373 unsigned int machinenum;
374 void *localmachinenum;
375 objheader_t *headeraddr;
377 ptr = record->lookupTable->table;
378 size = record->lookupTable->size;
380 for(i = 0; i < size ; i++) {
382 /* Inner loop to traverse the linked list of the cache lookupTable */
383 while(curr != NULL) {
384 //if the first bin in hash table is empty
390 if ((headeraddr = chashSearch(record->lookupTable, curr->key)) == NULL) {
391 printf("Error: No such oid %s, %d\n", __FILE__, __LINE__);
395 //Get machine location for object id (and whether local or not)
396 if (STATUS(headeraddr) & NEW || (mhashSearch(curr->key) != NULL)) {
397 machinenum = myIpAddr;
398 } else if ((machinenum = lhashSearch(curr->key)) == 0) {
399 printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
403 //Make machine groups
404 if ((pile = pInsert(pile, headeraddr, machinenum, record->lookupTable->numelements)) == NULL) {
405 printf("pInsert error %s, %d\n", __FILE__, __LINE__);
415 /* This function initiates the transaction commit process
416 * Spawns threads for each of the new connections with Participants
417 * and creates new piles by calling the createPiles(),
418 * Sends a transrequest() to each remote machines for objects found remotely
419 * and calls handleLocalReq() to process objects found locally */
420 int transCommit(transrecord_t *record) {
421 unsigned int tot_bytes_mod, *listmid;
422 plistnode_t *pile, *pile_ptr;
424 int pilecount, offset, threadnum = 0, trecvcount = 0;
425 char buffer[RECEIVE_BUFFER_SIZE],control;
426 char transid[TID_LEN];
427 trans_req_data_t *tosend;
428 trans_commit_data_t transinfo;
429 static int newtid = 0;
430 char treplyctrl = 0, treplyretry = 0; /* keeps track of the common response that needs to be sent */
433 /* Look through all the objects in the transaction record and make piles
434 * for each machine involved in the transaction*/
435 pile_ptr = pile = createPiles(record);
437 /* Create the packet to be sent in TRANS_REQUEST */
439 /* Count the number of participants */
440 pilecount = pCount(pile);
442 /* Create a list of machine ids(Participants) involved in transaction */
443 if((listmid = calloc(pilecount, sizeof(unsigned int))) == NULL) {
444 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
447 pListMid(pile, listmid);
450 /* Initialize thread variables,
451 * Spawn a thread for each Participant involved in a transaction */
452 pthread_t thread[pilecount];
454 pthread_cond_t tcond;
455 pthread_mutex_t tlock;
456 pthread_mutex_t tlshrd;
458 thread_data_array_t *thread_data_array;
459 if((thread_data_array = (thread_data_array_t *) calloc(pilecount, sizeof(thread_data_array_t))) == NULL) {
460 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
461 pthread_cond_destroy(&tcond);
462 pthread_mutex_destroy(&tlock);
468 local_thread_data_array_t *ltdata;
469 if((ltdata = calloc(1, sizeof(local_thread_data_array_t))) == NULL) {
470 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
471 pthread_cond_destroy(&tcond);
472 pthread_mutex_destroy(&tlock);
475 free(thread_data_array);
479 thread_response_t rcvd_control_msg[pilecount]; /* Shared thread array that keeps track of responses of participants */
481 /* Initialize and set thread detach attribute */
482 pthread_attr_init(&attr);
483 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
484 pthread_mutex_init(&tlock, NULL);
485 pthread_cond_init(&tcond, NULL);
487 /* Process each machine pile */
488 while(pile != NULL) {
489 //Create transaction id
491 if ((tosend = calloc(1, sizeof(trans_req_data_t))) == NULL) {
492 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
493 pthread_cond_destroy(&tcond);
494 pthread_mutex_destroy(&tlock);
497 free(thread_data_array);
501 tosend->f.control = TRANS_REQUEST;
502 sprintf(tosend->f.trans_id, "%x_%d", pile->mid, newtid);
503 tosend->f.mcount = pilecount;
504 tosend->f.numread = pile->numread;
505 tosend->f.nummod = pile->nummod;
506 tosend->f.numcreated = pile->numcreated;
507 tosend->f.sum_bytes = pile->sum_bytes;
508 tosend->listmid = listmid;
509 tosend->objread = pile->objread;
510 tosend->oidmod = pile->oidmod;
511 tosend->oidcreated = pile->oidcreated;
512 thread_data_array[threadnum].thread_id = threadnum;
513 thread_data_array[threadnum].mid = pile->mid;
514 thread_data_array[threadnum].buffer = tosend;
515 thread_data_array[threadnum].recvmsg = rcvd_control_msg;
516 thread_data_array[threadnum].threshold = &tcond;
517 thread_data_array[threadnum].lock = &tlock;
518 thread_data_array[threadnum].count = &trecvcount;
519 thread_data_array[threadnum].replyctrl = &treplyctrl;
520 thread_data_array[threadnum].replyretry = &treplyretry;
521 thread_data_array[threadnum].rec = record;
522 /* If local do not create any extra connection */
523 if(pile->mid != myIpAddr) { /* Not local */
525 rc = pthread_create(&thread[threadnum], &attr, transRequest, (void *) &thread_data_array[threadnum]);
528 perror("Error in pthread create\n");
529 pthread_cond_destroy(&tcond);
530 pthread_mutex_destroy(&tlock);
533 for (i = 0; i < threadnum; i++)
534 free(thread_data_array[i].buffer);
535 free(thread_data_array);
540 ltdata->tdata = &thread_data_array[threadnum];
541 ltdata->transinfo = &transinfo;
543 val = pthread_create(&thread[threadnum], &attr, handleLocalReq, (void *) ltdata);
546 perror("Error in pthread create\n");
547 pthread_cond_destroy(&tcond);
548 pthread_mutex_destroy(&tlock);
551 for (i = 0; i < threadnum; i++)
552 free(thread_data_array[i].buffer);
553 free(thread_data_array);
563 /* Free attribute and wait for the other threads */
564 pthread_attr_destroy(&attr);
566 for (i = 0; i < threadnum; i++) {
567 rc = pthread_join(thread[i], NULL);
570 printf("Error: return code from pthread_join() is %d\n", rc);
571 pthread_cond_destroy(&tcond);
572 pthread_mutex_destroy(&tlock);
575 for (j = i; j < threadnum; j++) {
576 free(thread_data_array[j].buffer);
580 free(thread_data_array[i].buffer);
584 pthread_cond_destroy(&tcond);
585 pthread_mutex_destroy(&tlock);
590 if(treplyctrl == TRANS_ABORT) {
592 objstrDelete(record->cache);
593 chashDelete(record->lookupTable);
595 free(thread_data_array);
598 } else if(treplyctrl == TRANS_COMMIT) {
600 objstrDelete(record->cache);
601 chashDelete(record->lookupTable);
603 free(thread_data_array);
607 //TODO Add other cases
608 printf("DEBUG-> THIS SHOULD NOT HAPPEN.....EXIT PROGRAM\n");
615 /* This function sends information involved in the transaction request
616 * to participants and accepts a response from particpants.
617 * It calls decideresponse() to decide on what control message
618 * to send next to participants and sends the message using sendResponse()*/
619 void *transRequest(void *threadarg) {
621 struct sockaddr_in serv_addr;
622 struct hostent *server;
623 thread_data_array_t *tdata;
624 objheader_t *headeraddr;
625 char buffer[RECEIVE_BUFFER_SIZE], control, recvcontrol;
626 char machineip[16], retval;
629 tdata = (thread_data_array_t *) threadarg;
631 /* Send Trans Request */
632 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
633 perror("Error in socket for TRANS_REQUEST\n");
636 bzero((char*) &serv_addr, sizeof(serv_addr));
637 serv_addr.sin_family = AF_INET;
638 serv_addr.sin_port = htons(LISTEN_PORT);
639 midtoIP(tdata->mid,machineip);
640 machineip[15] = '\0';
641 serv_addr.sin_addr.s_addr = inet_addr(machineip);
642 /* Open Connection */
643 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
644 perror("Error in connect for TRANS_REQUEST\n");
649 /* Send bytes of data with TRANS_REQUEST control message */
650 if (send(sd, &(tdata->buffer->f), sizeof(fixed_data_t),MSG_NOSIGNAL) < sizeof(fixed_data_t)) {
651 perror("Error sending fixed bytes for thread\n");
655 /* Send list of machines involved in the transaction */
657 int size=sizeof(unsigned int)*tdata->buffer->f.mcount;
658 if (send(sd, tdata->buffer->listmid, size, MSG_NOSIGNAL) < size) {
659 perror("Error sending list of machines for thread\n");
664 /* Send oids and version number tuples for objects that are read */
666 int size=(sizeof(unsigned int)+sizeof(short))*tdata->buffer->f.numread;
667 if (send(sd, tdata->buffer->objread, size, MSG_NOSIGNAL) < size) {
668 perror("Error sending tuples for thread\n");
673 /* Send objects that are modified */
674 for(i = 0; i < tdata->buffer->f.nummod ; i++) {
676 headeraddr = chashSearch(tdata->rec->lookupTable, tdata->buffer->oidmod[i]);
677 GETSIZE(size,headeraddr);
678 size+=sizeof(objheader_t);
679 if (send(sd, headeraddr, size, MSG_NOSIGNAL) < size) {
680 perror("Error sending obj modified for thread\n");
686 /* Read control message from Participant */
687 if((n = read(sd, &control, sizeof(char))) <= 0) {
688 perror("Error in reading control message from Participant\n");
693 recvcontrol = control;
695 /* Update common data structure and increment count */
696 tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol;
698 /* Lock and update count */
699 /* Thread sleeps until all messages from pariticipants are received by coordinator */
700 pthread_mutex_lock(tdata->lock);
702 (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */
704 /* Wake up the threads and invoke decideResponse (once) */
705 if(*(tdata->count) == tdata->buffer->f.mcount) {
706 decideResponse(tdata);
707 pthread_cond_broadcast(tdata->threshold);
709 pthread_cond_wait(tdata->threshold, tdata->lock);
711 pthread_mutex_unlock(tdata->lock);
713 /* Send the final response such as TRANS_COMMIT or TRANS_ABORT t
714 * to all participants in their respective socket */
715 if (sendResponse(tdata, sd) == 0) {
716 printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__);
721 if ((retval = recv((int)sd, &control, sizeof(char), 0))<= 0) {
722 printf("Error: In receiving control %s,%d\n", __FILE__, __LINE__);
727 if(control == TRANS_UNSUCESSFUL) {
728 //printf("DEBUG-> TRANS_ABORTED\n");
729 } else if(control == TRANS_SUCESSFUL) {
730 //printf("DEBUG-> TRANS_SUCCESSFUL\n");
732 //printf("DEBUG-> Error: Incorrect Transaction End Message %d\n", control);
735 /* Close connection */
740 /* This function decides the reponse that needs to be sent to
741 * all Participant machines after the TRANS_REQUEST protocol */
742 void decideResponse(thread_data_array_t *tdata) {
744 int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
747 for (i = 0 ; i < tdata->buffer->f.mcount; i++) {
748 control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses
749 written onto the shared array */
752 printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
753 /* treat as disagree, pass thru */
762 case TRANS_SOFT_ABORT:
768 if(transdisagree > 0) {
770 *(tdata->replyctrl) = TRANS_ABORT;
771 *(tdata->replyretry) = 0;
772 /* clear objects from prefetch cache */
773 for (i = 0; i < tdata->buffer->f.numread; i++)
774 prehashRemove(*((unsigned int *)(((char *)tdata->buffer->objread) + (sizeof(unsigned int) + sizeof(unsigned short))*i)));
775 for (i = 0; i < tdata->buffer->f.nummod; i++)
776 prehashRemove(tdata->buffer->oidmod[i]);
777 } else if(transagree == tdata->buffer->f.mcount){
779 *(tdata->replyctrl) = TRANS_COMMIT;
780 *(tdata->replyretry) = 0;
782 /* Send Abort in soft abort case followed by retry commiting transaction again*/
783 *(tdata->replyctrl) = TRANS_ABORT;
784 *(tdata->replyretry) = 1;
789 /* This function sends the final response to remote machines per thread in their respective socket id
790 * It returns a char that is only needed to check the correctness of execution of this function inside
792 char sendResponse(thread_data_array_t *tdata, int sd) {
793 int n, N, sum, oidcount = 0, control;
794 char *ptr, retval = 0;
795 unsigned int *oidnotfound;
797 /* If the decided response is due to a soft abort and missing objects at the Participant's side */
798 if(tdata->recvmsg[tdata->thread_id].rcv_status == TRANS_SOFT_ABORT) {
799 /* Read list of objects missing */
800 if((read(sd, &oidcount, sizeof(int)) != 0) && (oidcount != 0)) {
801 N = oidcount * sizeof(unsigned int);
802 if((oidnotfound = calloc(oidcount, sizeof(unsigned int))) == NULL) {
803 printf("Calloc error %s, %d\n", __FILE__, __LINE__);
806 ptr = (char *) oidnotfound;
808 n = read(sd, ptr+sum, N-sum);
810 } while(sum < N && n !=0);
812 retval = TRANS_SOFT_ABORT;
814 /* If the decided response is TRANS_ABORT */
815 if(*(tdata->replyctrl) == TRANS_ABORT) {
816 retval = TRANS_ABORT;
817 } else if(*(tdata->replyctrl) == TRANS_COMMIT) { /* If the decided response is TRANS_COMMIT */
818 retval = TRANS_COMMIT;
821 if (send(sd, tdata->replyctrl, sizeof(char),MSG_NOSIGNAL) < sizeof(char)) {
822 perror("Error sending ctrl message for participant\n");
829 /* This function opens a connection, places an object read request to the
830 * remote machine, reads the control message and object if available and
831 * copies the object and its header to the local cache.
834 void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
836 struct sockaddr_in serv_addr;
837 struct hostent *server;
844 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
845 perror("Error in socket\n");
849 bzero((char*) &serv_addr, sizeof(serv_addr));
850 serv_addr.sin_family = AF_INET;
851 serv_addr.sin_port = htons(LISTEN_PORT);
852 midtoIP(mnum,machineip);
853 machineip[15] = '\0';
854 serv_addr.sin_addr.s_addr = inet_addr(machineip);
856 /* Open connection */
857 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
858 perror("Error in connect\n");
861 char readrequest[sizeof(char)+sizeof(unsigned int)];
862 readrequest[0] = READ_REQUEST;
863 *((unsigned int *)(&readrequest[1])) = oid;
864 if (send(sd, readrequest, sizeof(readrequest), MSG_NOSIGNAL) < sizeof(readrequest)) {
865 perror("Error sending message\n");
869 /* Read response from the Participant */
870 if((val = read(sd, &control, sizeof(char))) <= 0) {
871 perror("No control response for getRemoteObj sent\n");
875 case OBJECT_NOT_FOUND:
878 /* Read object if found into local cache */
879 if((val = read(sd, &size, sizeof(int))) <= 0) {
880 perror("No size is read from the participant\n");
883 objcopy = objstrAlloc(record->cache, size);
884 if((val = read(sd, (char *)objcopy, size)) <= 0) {
885 perror("No objects are read from the remote participant\n");
888 /* Insert into cache's lookup table */
889 chashInsert(record->lookupTable, oid, objcopy);
892 printf("Error in recv request from participant on a READ_REQUEST %s, %d\n",__FILE__, __LINE__);
895 /* Close connection */
900 /* This function handles the local objects involved in a transaction commiting process.
901 * It also makes a decision if this local machine sends AGREE or DISAGREE or SOFT_ABORT to coordinator.
902 * Note Coordinator = local machine
903 * It wakes up the other threads from remote participants that are waiting for the coordinator's decision and
904 * based on common agreement it either commits or aborts the transaction.
905 * It also frees the memory resources */
906 void *handleLocalReq(void *threadarg) {
907 unsigned int *oidnotfound = NULL, *oidlocked = NULL;
908 local_thread_data_array_t *localtdata;
909 int objnotfound = 0, objlocked = 0;
910 int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
913 unsigned short version;
915 objheader_t *headptr;
917 localtdata = (local_thread_data_array_t *) threadarg;
919 /* Counters and arrays to formulate decision on control message to be sent */
920 oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
921 oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
923 numread = localtdata->tdata->buffer->f.numread;
924 /* Process each oid in the machine pile/ group per thread */
925 for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) {
926 if (i < localtdata->tdata->buffer->f.numread) {
927 int incr = sizeof(unsigned int) + sizeof(short);// Offset that points to next position in the objread array
929 oid = *((unsigned int *)(((char *)localtdata->tdata->buffer->objread) + incr));
930 version = *((short *)(((char *)localtdata->tdata->buffer->objread) + incr + sizeof(unsigned int)));
931 } else { // Objects Modified
933 headptr = (objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidmod[i-numread]);
934 if (headptr == NULL) {
935 printf("Error: handleLocalReq() returning NULL %s, %d\n", __FILE__, __LINE__);
939 version = headptr->version;
941 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
943 /* Save the oids not found and number of oids not found for later use */
944 if ((mobj = mhashSearch(oid)) == NULL) { /* Obj not found */
945 /* Save the oids not found and number of oids not found for later use */
946 oidnotfound[objnotfound] = oid;
948 } else { /* If Obj found in machine (i.e. has not moved) */
949 /* Check if Obj is locked by any previous transaction */
950 if ((STATUS((objheader_t *)mobj) & LOCK) == LOCK) {
951 if (version == ((objheader_t *)mobj)->version) { /* If locked then match versions */
953 } else {/* If versions don't match ...HARD ABORT */
955 /* Send TRANS_DISAGREE to Coordinator */
956 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
958 } else {/* If Obj is not locked then lock object */
959 STATUS(((objheader_t *)mobj)) |= LOCK;
960 /* Save all object oids that are locked on this machine during this transaction request call */
961 oidlocked[objlocked] = OID(((objheader_t *)mobj));
963 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
965 } else { /* If versions don't match ...HARD ABORT */
967 /* Send TRANS_DISAGREE to Coordinator */
968 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
973 /* Condition to send TRANS_AGREE */
974 if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
975 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
977 /* Condition to send TRANS_SOFT_ABORT */
978 if((v_matchlock > 0 && v_nomatch == 0) || (objnotfound > 0 && v_nomatch == 0)) {
979 localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
982 /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
983 * if Participant receives a TRANS_COMMIT */
984 localtdata->transinfo->objlocked = oidlocked;
985 localtdata->transinfo->objnotfound = oidnotfound;
986 localtdata->transinfo->modptr = NULL;
987 localtdata->transinfo->numlocked = objlocked;
988 localtdata->transinfo->numnotfound = objnotfound;
989 /* Lock and update count */
990 //Thread sleeps until all messages from pariticipants are received by coordinator
991 pthread_mutex_lock(localtdata->tdata->lock);
992 (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */
994 /* Wake up the threads and invoke decideResponse (once) */
995 if(*(localtdata->tdata->count) == localtdata->tdata->buffer->f.mcount) {
996 decideResponse(localtdata->tdata);
997 pthread_cond_broadcast(localtdata->tdata->threshold);
999 pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock);
1001 pthread_mutex_unlock(localtdata->tdata->lock);
1002 if(*(localtdata->tdata->replyctrl) == TRANS_ABORT){
1003 if(transAbortProcess(localtdata) != 0) {
1004 printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
1007 } else if(*(localtdata->tdata->replyctrl) == TRANS_COMMIT) {
1008 if(transComProcess(localtdata) != 0) {
1009 printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
1014 if (localtdata->transinfo->objlocked != NULL) {
1015 free(localtdata->transinfo->objlocked);
1017 if (localtdata->transinfo->objnotfound != NULL) {
1018 free(localtdata->transinfo->objnotfound);
1024 /* This function completes the ABORT process if the transaction is aborting */
1025 int transAbortProcess(local_thread_data_array_t *localtdata) {
1027 unsigned int *objlocked;
1030 numlocked = localtdata->transinfo->numlocked;
1031 objlocked = localtdata->transinfo->objlocked;
1033 for (i = 0; i < numlocked; i++) {
1034 if((header = mhashSearch(objlocked[i])) == NULL) {
1035 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1038 STATUS(((objheader_t *)header)) &= ~(LOCK);
1044 /*This function completes the COMMIT process is the transaction is commiting*/
1045 int transComProcess(local_thread_data_array_t *localtdata) {
1046 objheader_t *header, *tcptr;
1047 int i, nummod, tmpsize, numcreated, numlocked;
1048 unsigned int *oidmod, *oidcreated, *oidlocked;
1051 nummod = localtdata->tdata->buffer->f.nummod;
1052 oidmod = localtdata->tdata->buffer->oidmod;
1053 numcreated = localtdata->tdata->buffer->f.numcreated;
1054 oidcreated = localtdata->tdata->buffer->oidcreated;
1055 numlocked = localtdata->transinfo->numlocked;
1056 oidlocked = localtdata->transinfo->objlocked;
1058 for (i = 0; i < nummod; i++) {
1059 if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
1060 printf("Error: transComProcess() mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1063 /* Copy from transaction cache -> main object store */
1064 if ((tcptr = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidmod[i]))) == NULL) {
1065 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1068 GETSIZE(tmpsize, header);
1069 pthread_mutex_lock(&mainobjstore_mutex);
1070 memcpy((char*)header+sizeof(objheader_t), (char *)tcptr+ sizeof(objheader_t), tmpsize);
1071 header->version += 1;
1072 if(header->notifylist != NULL) {
1073 notifyAll(&header->notifylist, OID(header), header->version);
1075 pthread_mutex_unlock(&mainobjstore_mutex);
1077 /* If object is newly created inside transaction then commit it */
1078 for (i = 0; i < numcreated; i++) {
1079 if ((header = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidcreated[i]))) == NULL) {
1080 printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
1083 GETSIZE(tmpsize, header);
1084 tmpsize += sizeof(objheader_t);
1085 pthread_mutex_lock(&mainobjstore_mutex);
1086 if ((ptrcreate = objstrAlloc(mainobjstore, tmpsize)) == NULL) {
1087 printf("Error: transComProcess() failed objstrAlloc %s, %d\n", __FILE__, __LINE__);
1088 pthread_mutex_unlock(&mainobjstore_mutex);
1091 pthread_mutex_unlock(&mainobjstore_mutex);
1092 memcpy(ptrcreate, header, tmpsize);
1093 mhashInsert(oidcreated[i], ptrcreate);
1094 lhashInsert(oidcreated[i], myIpAddr);
1096 /* Unlock locked objects */
1097 for(i = 0; i < numlocked; i++) {
1098 if((header = (objheader_t *) mhashSearch(oidlocked[i])) == NULL) {
1099 printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1102 STATUS(header) &= ~(LOCK);
1108 /* This function checks if the prefetch oids are same and have same offsets
1109 * for case x.a.b and y.a.b where x and y have same oid's
1110 * or if a.b.c is a subset of x.b.c.d*/
1111 /* check for case where the generated request a.y.z or x.y.z.g then
1112 * prefetch needs to be generated for x.y.z.g if oid of a and x are same*/
1113 void checkPrefetchTuples(prefetchqelem_t *node) {
1114 int i,j, count,k, sindex, index;
1116 int ntuples, slength;
1118 short *endoffsets, *arryfields;
1120 /* Check for the case x.y.z and a.b.c are same oids */
1121 ptr = (char *) node;
1122 ntuples = *(GET_NTUPLES(ptr));
1123 oid = GET_PTR_OID(ptr);
1124 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1125 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1127 /* Find offset length for each tuple */
1128 int numoffset[ntuples];
1129 numoffset[0] = endoffsets[0];
1130 for(i = 1; i<ntuples; i++) {
1131 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1133 /* Check for redundant tuples by comparing oids of each tuple */
1134 for(i = 0; i < ntuples; i++) {
1137 for(j = i+1 ; j < ntuples; j++) {
1140 /*If oids of tuples match */
1141 if (oid[i] == oid[j]) {
1142 /* Find the smallest offset length of two tuples*/
1143 if(numoffset[i] > numoffset[j]){
1144 slength = numoffset[j];
1148 slength = numoffset[i];
1152 /* Compare the offset values based on the current indices
1153 * break if they do not match
1154 * if all offset values match then pick the largest tuple*/
1159 k = endoffsets[i-1];
1161 index = endoffsets[j -1];
1162 for(count = 0; count < slength; count ++) {
1163 if (arryfields[k] != arryfields[index]) {
1169 if(slength == count) {
1176 /* This function makes machine piles to be added into the machine pile queue for each prefetch call */
1177 prefetchpile_t *makePreGroups(prefetchqelem_t *node, int *numoffset) {
1179 int ntuples, i, machinenum, count=0;
1181 short *endoffsets, *arryfields, *offset;
1182 prefetchpile_t *head = NULL, *tmp = NULL;
1184 /* Check for the case x.y.z and a.b.c are same oids */
1185 ptr = (char *) node;
1186 ntuples = *(GET_NTUPLES(ptr));
1187 oid = GET_PTR_OID(ptr);
1188 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1189 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1191 if((head = (prefetchpile_t *) calloc(1, sizeof(prefetchpile_t))) == NULL) {
1192 printf("Calloc error: %s %d\n", __FILE__, __LINE__);
1196 /* Check for redundant tuples by comparing oids of each tuple */
1197 for(i = 0; i < ntuples; i++) {
1199 if(head->next != NULL) {
1200 if((tmp = (prefetchpile_t *) calloc(1, sizeof(prefetchpile_t))) == NULL) {
1201 printf("Calloc error: %s %d\n", __FILE__, __LINE__);
1204 tmp->mid = myIpAddr;
1208 head->mid = myIpAddr;
1212 /* For each tuple make piles */
1213 if ((machinenum = lhashSearch(oid[i])) == 0) {
1214 printf("Error: No such Machine %s, %d\n", __FILE__, __LINE__);
1217 /* Insert into machine pile */
1219 offset = &arryfields[0];
1221 offset = &arryfields[endoffsets[i-1]];
1224 if((head = insertPile(machinenum, oid[i], numoffset[i], offset, head)) == NULL){
1225 printf("Error: Couldn't create a pile %s, %d\n", __FILE__, __LINE__);
1233 prefetchpile_t *foundLocal(prefetchqelem_t *node) {
1234 int ntuples,i, j, k, oidnfound = 0, arryfieldindex,nextarryfieldindex, flag = 0, val;
1236 unsigned int objoid;
1239 objheader_t *objheader;
1240 short *endoffsets, *arryfields;
1241 prefetchpile_t *head = NULL;
1243 ptr = (char *) node;
1244 ntuples = *(GET_NTUPLES(ptr));
1245 oid = GET_PTR_OID(ptr);
1246 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1247 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1249 /* Find offset length for each tuple */
1250 int numoffset[ntuples];//Number of offsets for each tuple
1251 numoffset[0] = endoffsets[0];
1252 for(i = 1; i<ntuples; i++) {
1253 numoffset[i] = endoffsets[i] - endoffsets[i-1];
1255 for(i = 0; i < ntuples; i++) {
1259 nextarryfieldindex = endoffsets[0];
1261 arryfieldindex = endoffsets[i-1];
1262 nextarryfieldindex = endoffsets[i];
1265 endoffsets[0] = val = numoffset[0];
1266 for(k = 1; k < ntuples; k++) {
1267 val = val + numoffset[k];
1268 endoffsets[k] = val;
1271 for(k = 0; k<endoffsets[ntuples-1]; k++) {
1272 arryfields[arryfieldindex+k] = arryfields[nextarryfieldindex+k];
1276 /* If object found locally */
1277 if((objheader = (objheader_t*) mhashSearch(oid[i])) != NULL) {
1278 tmp = (char *) objheader;
1279 int orgnumoffset = numoffset[i];
1283 arryfieldindex = endoffsets[i-1];
1286 for(j = 0; j<orgnumoffset; j++) {
1287 /* Check for arrays */
1288 if(TYPE(objheader) > NUMCLASSES) {
1292 int elementsize = classsize[TYPE(objheader)];
1293 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*arryfields[arryfieldindex])));
1295 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + arryfields[arryfieldindex]));
1297 //Update numoffset array
1298 numoffset[i] = numoffset[i] - 1;
1301 //Update endoffset array
1302 endoffsets[0] = val = numoffset[0];
1303 for(k = 1; k < ntuples; k++) {
1304 val = val + numoffset[k];
1305 endoffsets[k] = val;
1307 //Update arrayfields array
1308 for(k = 0; k < endoffsets[ntuples-1]; k++) {
1309 arryfields[arryfieldindex+k] = arryfields[arryfieldindex+k+1];
1311 if((objheader = (objheader_t*) mhashSearch(oid[i])) == NULL) {
1313 checkPreCache(node, numoffset, oid[i], i);
1316 tmp = (char *) objheader;
1319 /*If all offset oids are found locally,make the prefetch tuple invalid */
1324 /* Look in Prefetch cache */
1325 checkPreCache(node, numoffset, oid[i],i);
1329 /* Make machine groups */
1330 if((head = makePreGroups(node, numoffset)) == NULL) {
1331 printf("Error in makePreGroups() %s %d\n", __FILE__, __LINE__);
1338 void checkPreCache(prefetchqelem_t *node, int *numoffset, unsigned int objoid, int index) {
1340 int ntuples, i, k, flag=0, isArray =0, arryfieldindex, val;
1342 short *endoffsets, *arryfields;
1343 objheader_t *header;
1345 ptr = (char *) node;
1346 ntuples = *(GET_NTUPLES(ptr));
1347 oid = GET_PTR_OID(ptr);
1348 endoffsets = GET_PTR_EOFF(ptr, ntuples);
1349 arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1351 if((header = (objheader_t *) prehashSearch(objoid)) == NULL) {
1353 } else { //Found in Prefetch Cache
1354 //TODO Decide if object is too old, if old remove from cache
1355 tmp = (char *) header;
1356 int loopcount = numoffset[index];
1360 arryfieldindex = endoffsets[(index - 1)];
1361 // Check if any of the offset oid is available in the Prefetch cache
1362 for(i = 0; i < loopcount; i++) {
1363 /* Check for arrays */
1364 if(TYPE(header) > NUMCLASSES) {
1368 int elementsize = classsize[TYPE(header)];
1369 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*arryfields[arryfieldindex])));
1371 objoid = *((unsigned int *)(tmp + sizeof(objheader_t) + arryfields[arryfieldindex]));
1373 //Update numoffset array
1374 numoffset[index] = numoffset[index] - 1;
1376 oid[index] = objoid;
1377 //Update endoffset array
1378 endoffsets[0] = val = numoffset[0];
1379 for(k = 1; k < ntuples; k++) {
1380 val = val + numoffset[k];
1381 endoffsets[k] = val;
1383 //Update arrayfields array
1384 for(k = 0; k < endoffsets[ntuples-1]; k++) {
1385 arryfields[arryfieldindex+k] = arryfields[arryfieldindex+k+1];
1387 if((header = (objheader_t *)prehashSearch(oid[index])) != NULL) {
1388 tmp = (char *) header;
1396 //Found in the prefetch cache
1397 if(flag == 0 && (numoffset[index] == 0)) {
1404 /* This function is called by the thread calling transPrefetch */
1405 void *transPrefetch(void *t) {
1406 prefetchqelem_t *qnode;
1407 prefetchpile_t *pilehead = NULL;
1408 prefetchpile_t *ptr = NULL, *piletail = NULL;
1411 /* lock mutex of primary prefetch queue */
1412 pthread_mutex_lock(&pqueue.qlock);
1413 /* while primary queue is empty, then wait */
1414 while((pqueue.front == NULL) && (pqueue.rear == NULL)) {
1415 pthread_cond_wait(&pqueue.qcond, &pqueue.qlock);
1418 /* dequeue node to create a machine piles and finally unlock mutex */
1419 if((qnode = pre_dequeue()) == NULL) {
1420 printf("Error: No node returned %s, %d\n", __FILE__, __LINE__);
1421 pthread_mutex_unlock(&pqueue.qlock);
1424 pthread_mutex_unlock(&pqueue.qlock);
1426 /* Reduce redundant prefetch requests */
1427 checkPrefetchTuples(qnode);
1428 /* Check if the tuples are found locally, if yes then reduce them further*/
1429 /* and group requests by remote machine ids by calling the makePreGroups() */
1430 if((pilehead = foundLocal(qnode)) == NULL) {
1431 printf("Error: No node created for serving prefetch request %s %d\n", __FILE__, __LINE__);
1436 while(ptr != NULL) {
1437 if(ptr->next == NULL) {
1443 /* Lock mutex of pool queue */
1444 pthread_mutex_lock(&mcqueue.qlock);
1445 /* Update the pool queue with the new remote machine piles generated per prefetch call */
1446 mcpileenqueue(pilehead, piletail);
1447 /* Broadcast signal on machine pile queue */
1448 pthread_cond_broadcast(&mcqueue.qcond);
1449 /* Unlock mutex of machine pile queue */
1450 pthread_mutex_unlock(&mcqueue.qlock);
1451 /* Deallocate the prefetch queue pile node */
1456 /* Each thread in the pool of threads calls this function to establish connection with
1457 * remote machines, send the prefetch requests and process the reponses from
1458 * the remote machines .
1459 * The thread is active throughout the period of runtime */
1461 void *mcqProcess(void *threadid) {
1463 prefetchpile_t *mcpilenode;
1465 tid = (int) threadid;
1467 /* Lock mutex of mc pile queue */
1468 pthread_mutex_lock(&mcqueue.qlock);
1469 /* When mc pile queue is empty, wait */
1470 while((mcqueue.front == NULL) && (mcqueue.rear == NULL)) {
1471 pthread_cond_wait(&mcqueue.qcond, &mcqueue.qlock);
1473 /* Dequeue node to send remote machine connections*/
1474 if((mcpilenode = mcpiledequeue()) == NULL) {
1475 printf("Dequeue Error: No node returned %s %d\n", __FILE__, __LINE__);
1476 pthread_mutex_unlock(&mcqueue.qlock);
1480 pthread_mutex_unlock(&mcqueue.qlock);
1482 /*Initiate connection to remote host and send request */
1483 /* Process Request */
1484 if(mcpilenode->mid != myIpAddr)
1485 sendPrefetchReq(mcpilenode);
1487 /* Deallocate the machine queue pile node */
1488 mcdealloc(mcpilenode);
1492 void sendPrefetchReq(prefetchpile_t *mcpilenode) {
1493 int sd, i, off, len, endpair, count = 0;
1494 struct sockaddr_in serv_addr;
1495 struct hostent *server;
1496 char machineip[16], control;
1499 /* Send Trans Prefetch Request */
1500 if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
1501 perror("Error in socket for SEND_PREFETCH_REQUEST\n");
1505 bzero((char*) &serv_addr, sizeof(serv_addr));
1506 serv_addr.sin_family = AF_INET;
1507 serv_addr.sin_port = htons(LISTEN_PORT);
1508 midtoIP(mcpilenode->mid ,machineip);
1509 machineip[15] = '\0';
1510 serv_addr.sin_addr.s_addr = inet_addr(machineip);
1512 /* Open Connection */
1513 if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
1514 perror("Error in connect for SEND_PREFETCH_REQUEST\n");
1519 /* Send TRANS_PREFETCH control message */
1520 control = TRANS_PREFETCH;
1521 if(send(sd, &control, sizeof(char), MSG_NOSIGNAL) < sizeof(char)) {
1522 perror("Error in sending prefetch control\n");
1527 /* Send Oids and offsets in pairs */
1528 tmp = mcpilenode->objpiles;
1529 while(tmp != NULL) {
1531 count++; /* Keeps track of the number of oid and offset tuples sent per remote machine */
1532 len = sizeof(int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(unsigned short));
1533 char oidnoffset[len];
1534 bzero(oidnoffset, len);
1535 *((unsigned int*)oidnoffset) = len;
1536 //memcpy(oidnoffset, &len, sizeof(int));
1538 *((unsigned int *)((char *)oidnoffset + off)) = tmp->oid;
1539 //memcpy(oidnoffset + off, &tmp->oid, sizeof(unsigned int));
1540 off += sizeof(unsigned int);
1541 for(i = 0; i < tmp->numoffset; i++) {
1542 *((unsigned short*)((char *)oidnoffset + off)) = tmp->offset[i];
1543 //memcpy(oidnoffset + off, &(tmp->offset[i]), sizeof(short));
1544 off+=sizeof(unsigned short);
1547 if (send(sd, oidnoffset, len , MSG_NOSIGNAL) < len) {
1548 perror("Error sending fixed bytes for thread\n");
1556 /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
1558 if (send(sd, &endpair, sizeof(int), MSG_NOSIGNAL) < sizeof(int)) {
1559 perror("Error sending fixed bytes for thread\n");
1564 /* Get Response from the remote machine */
1565 getPrefetchResponse(count,sd);
1570 void getPrefetchResponse(int count, int sd) {
1571 int i = 0, val, n, N, sum, index, objsize;
1572 unsigned int bufsize,oid;
1573 char buffer[RECEIVE_BUFFER_SIZE], control;
1575 void *modptr, *oldptr;
1577 /* Read prefetch response from the Remote machine */
1578 if((val = read(sd, &control, sizeof(char))) <= 0) {
1579 perror("No control response for Prefetch request sent\n");
1583 if(control == TRANS_PREFETCH_RESPONSE) {
1584 /*For each oid and offset tuple sent as prefetch request to remote machine*/
1588 /* Read the size of buffer to be received */
1589 if((N = read(sd, buffer, sizeof(unsigned int))) <= 0) {
1590 perror("Size of buffer not recv\n");
1593 bufsize = *((unsigned int *) buffer);
1594 ptr = buffer + sizeof(unsigned int);
1595 /* Keep receiving the buffer containing oid info */
1597 n = recv((int)sd, (void *)ptr+sum, bufsize-sum, 0);
1599 } while(sum < bufsize && n != 0);
1601 /* Decode the contents of the buffer */
1602 index = sizeof(unsigned int);
1603 while(index < (bufsize - sizeof(unsigned int))) {
1604 if(buffer[index] == OBJECT_FOUND) {
1605 /* Increment it to get the object */
1606 index += sizeof(char);
1607 oid = *((unsigned int *)(buffer+index));
1608 index += sizeof(unsigned int);
1609 /* For each object found add to Prefetch Cache */
1610 objsize = *((int *)(buffer+index));
1612 pthread_mutex_lock(&prefetchcache_mutex);
1613 if ((modptr = objstrAlloc(prefetchcache, objsize)) == NULL) {
1614 printf("Error: objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
1615 pthread_mutex_unlock(&prefetchcache_mutex);
1618 pthread_mutex_unlock(&prefetchcache_mutex);
1619 memcpy(modptr, buffer+index, objsize);
1621 /* Insert the oid and its address into the prefetch hash lookup table */
1622 /* Do a version comparison if the oid exists */
1623 if((oldptr = prehashSearch(oid)) != NULL) {
1624 /* If older version then update with new object ptr */
1625 if(((objheader_t *)oldptr)->version < ((objheader_t *)modptr)->version) {
1627 prehashInsert(oid, modptr);
1628 } else if(((objheader_t *)oldptr)->version == ((objheader_t *)modptr)->version) {
1629 /* Add the new object ptr to hash table */
1631 prehashInsert(oid, modptr);
1632 } else { /* Do nothing: TODO modptr should be reference counted */
1635 } else {/*If doesn't no match found in hashtable, add the object ptr to hash table*/
1636 prehashInsert(oid, modptr);
1638 /* Lock the Prefetch Cache look up table*/
1639 pthread_mutex_lock(&pflookup.lock);
1640 /* Broadcast signal on prefetch cache condition variable */
1641 pthread_cond_broadcast(&pflookup.cond);
1642 /* Unlock the Prefetch Cache look up table*/
1643 pthread_mutex_unlock(&pflookup.lock);
1644 } else if(buffer[index] == OBJECT_NOT_FOUND) {
1645 /* Increment it to get the object */
1646 /* TODO: For each object not found query DHT for new location and retrieve the object */
1647 index += sizeof(char);
1648 oid = *((unsigned int *)(buffer + index));
1649 index += sizeof(unsigned int);
1650 /* Throw an error */
1651 printf("OBJECT NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n");
1654 printf("Error in decoding the index value %s, %d\n",__FILE__, __LINE__);
1662 printf("Error in receving response for prefetch request %s, %d\n",__FILE__, __LINE__);
1666 unsigned short getObjType(unsigned int oid)
1668 objheader_t *objheader;
1669 unsigned short numoffset[] ={0};
1670 short fieldoffset[] ={};
1672 if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL)
1674 if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1676 prefetch(1, &oid, numoffset, fieldoffset);
1677 pthread_mutex_lock(&pflookup.lock);
1678 while ((objheader = (objheader_t *) prehashSearch(oid)) == NULL)
1680 pthread_cond_wait(&pflookup.cond, &pflookup.lock);
1682 pthread_mutex_unlock(&pflookup.lock);
1686 return TYPE(objheader);
1689 int startRemoteThread(unsigned int oid, unsigned int mid)
1692 struct sockaddr_in remoteAddr;
1693 char msg[1 + sizeof(unsigned int)];
1697 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
1699 perror("startRemoteThread():socket()");
1703 bzero(&remoteAddr, sizeof(remoteAddr));
1704 remoteAddr.sin_family = AF_INET;
1705 remoteAddr.sin_port = htons(LISTEN_PORT);
1706 remoteAddr.sin_addr.s_addr = htonl(mid);
1708 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0)
1710 printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
1711 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1716 msg[0] = START_REMOTE_THREAD;
1717 memcpy(&msg[1], &oid, sizeof(unsigned int));
1719 bytesSent = send(sock, msg, 1 + sizeof(unsigned int), 0);
1722 perror("startRemoteThread():send()");
1725 else if (bytesSent != 1 + sizeof(unsigned int))
1727 printf("startRemoteThread(): error, sent %d bytes\n", bytesSent);
1740 //TODO: when reusing oids, make sure they are not already in use!
1741 unsigned int getNewOID(void) {
1742 static unsigned int id = 0xFFFFFFFF;
1745 if (id > oidMax || id < oidMin)
1752 int processConfigFile()
1755 const int maxLineLength = 200;
1756 char lineBuffer[maxLineLength];
1758 const char *delimiters = " \t\n";
1762 configFile = fopen(CONFIG_FILENAME, "r");
1763 if (configFile == NULL)
1765 printf("error opening %s:\n", CONFIG_FILENAME);
1770 numHostsInSystem = 0;
1771 sizeOfHostArray = 8;
1772 hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
1774 while(fgets(lineBuffer, maxLineLength, configFile) != NULL)
1776 commentBegin = strchr(lineBuffer, '#');
1777 if (commentBegin != NULL)
1778 *commentBegin = '\0';
1779 token = strtok(lineBuffer, delimiters);
1780 while (token != NULL)
1782 tmpAddr = inet_addr(token);
1783 if ((int)tmpAddr == -1)
1785 printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
1790 addHost(htonl(tmpAddr));
1791 token = strtok(NULL, delimiters);
1797 if (numHostsInSystem < 1)
1799 printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
1803 myIpAddr = getMyIpAddr("en1");
1805 myIpAddr = getMyIpAddr("eth0");
1807 myIndexInHostArray = findHost(myIpAddr);
1808 if (myIndexInHostArray == -1)
1810 printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
1813 oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
1814 oidMin = oidsPerBlock * myIndexInHostArray;
1815 if (myIndexInHostArray == numHostsInSystem - 1)
1816 oidMax = 0xFFFFFFFF;
1818 oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
1823 void addHost(unsigned int hostIp)
1825 unsigned int *tmpArray;
1827 if (findHost(hostIp) != -1)
1830 if (numHostsInSystem == sizeOfHostArray)
1832 tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
1833 memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
1835 hostIpAddrs = tmpArray;
1838 hostIpAddrs[numHostsInSystem++] = hostIp;
1843 int findHost(unsigned int hostIp)
1846 for (i = 0; i < numHostsInSystem; i++)
1847 if (hostIpAddrs[i] == hostIp)
1854 /* This function sends notification request per thread waiting on object(s) whose version
1856 int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int numoid) {
1858 objheader_t *objheader;
1859 struct sockaddr_in remoteAddr;
1860 char msg[1 + numoid * (sizeof(short) + sizeof(unsigned int)) + 3 * sizeof(unsigned int)];
1864 unsigned short version;
1865 unsigned int oid,mid;
1866 static unsigned int threadid = 0;
1867 pthread_mutex_t threadnotify = PTHREAD_MUTEX_INITIALIZER; //Lock and condition var for threadjoin and notification
1868 pthread_cond_t threadcond = PTHREAD_COND_INITIALIZER;
1869 notifydata_t *ndata;
1871 //FIXME currently all oids belong to one machine
1873 mid = lhashSearch(oid);
1875 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1876 perror("reqNotify():socket()");
1880 bzero(&remoteAddr, sizeof(remoteAddr));
1881 remoteAddr.sin_family = AF_INET;
1882 remoteAddr.sin_port = htons(LISTEN_PORT);
1883 remoteAddr.sin_addr.s_addr = htonl(mid);
1885 /* Generate unique threadid */
1888 /* Save threadid, numoid, oidarray, versionarray, pthread_cond_variable for later processing */
1889 if((ndata = calloc(1, sizeof(notifydata_t))) == NULL) {
1890 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
1893 ndata->numoid = numoid;
1894 ndata->threadid = threadid;
1895 ndata->oidarry = oidarry;
1896 ndata->versionarry = versionarry;
1897 ndata->threadcond = threadcond;
1898 ndata->threadnotify = threadnotify;
1899 if((status = notifyhashInsert(threadid, ndata)) != 0) {
1900 printf("reqNotify(): Insert into notify hash table not successful %s, %d\n", __FILE__, __LINE__);
1905 /* Send number of oids, oidarry, version array, machine id and threadid */
1906 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1907 printf("reqNotify():error %d connecting to %s:%d\n", errno,
1908 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1912 msg[0] = THREAD_NOTIFY_REQUEST;
1913 *((unsigned int *)(&msg[1])) = numoid;
1914 /* Send array of oids */
1915 size = sizeof(unsigned int);
1920 *((unsigned int *)(&msg[1] + size)) = oid;
1921 size += sizeof(unsigned int);
1926 /* Send array of version */
1930 version = versionarry[i];
1931 *((unsigned short *)(&msg[1] + size)) = version;
1932 size += sizeof(unsigned short);
1937 *((unsigned int *)(&msg[1] + size)) = myIpAddr;
1938 size += sizeof(unsigned int);
1939 *((unsigned int *)(&msg[1] + size)) = threadid;
1941 pthread_mutex_lock(&(ndata->threadnotify));
1942 bytesSent = send(sock, msg, 1 + numoid * (sizeof(unsigned int) + sizeof(unsigned short)) + 3 * sizeof(unsigned int) , 0);
1944 perror("reqNotify():send()");
1946 } else if (bytesSent != 1 + numoid*(sizeof(unsigned int) + sizeof(unsigned short)) + 3 * sizeof(unsigned int)){
1947 printf("reNotify(): error, sent %d bytes %s, %d\n", bytesSent, __FILE__, __LINE__);
1953 pthread_cond_wait(&(ndata->threadcond), &(ndata->threadnotify));
1954 pthread_mutex_unlock(&(ndata->threadnotify));
1957 pthread_cond_destroy(&threadcond);
1958 pthread_mutex_destroy(&threadnotify);
1964 void threadNotify(unsigned int oid, unsigned short version, unsigned int tid) {
1965 notifydata_t *ndata;
1966 int i, objIsFound = 0, index;
1969 //Look up the tid and call the corresponding pthread_cond_signal
1970 if((ndata = notifyhashSearch(tid)) == NULL) {
1971 printf("threadnotify(): No such threadid is present %s, %d\n", __FILE__, __LINE__);
1974 for(i = 0; i < ndata->numoid; i++) {
1975 if(ndata->oidarry[i] == oid){
1980 if(objIsFound == 0){
1981 printf("threadNotify(): Oid not found %s, %d\n", __FILE__, __LINE__);
1984 if(version <= ndata->versionarry[index]){
1985 printf("threadNotify(): New version %d has not changed since last version %s, %d\n", version, __FILE__, __LINE__);
1988 /* Clear from prefetch cache and free thread related data structure */
1989 if((ptr = prehashSearch(oid)) != NULL) {
1992 pthread_cond_signal(&(ndata->threadcond));
1999 int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) {
2002 struct sockaddr_in remoteAddr;
2003 char msg[1 + sizeof(unsigned short) + 2*sizeof(unsigned int)];
2004 int sock, status, size, bytesSent;
2006 while(*head != NULL) {
2009 //create a socket connection to that machine
2010 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
2011 perror("notifyAll():socket()");
2015 bzero(&remoteAddr, sizeof(remoteAddr));
2016 remoteAddr.sin_family = AF_INET;
2017 remoteAddr.sin_port = htons(LISTEN_PORT);
2018 remoteAddr.sin_addr.s_addr = htonl(mid);
2019 //send Thread Notify response and threadid to that machine
2020 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
2021 printf("notifyAll():error %d connecting to %s:%d\n", errno,
2022 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
2025 bzero(msg, (1+sizeof(unsigned short) + 2*sizeof(unsigned int)));
2026 msg[0] = THREAD_NOTIFY_RESPONSE;
2027 *((unsigned int *)&msg[1]) = oid;
2028 size = sizeof(unsigned int);
2029 *((unsigned short *)(&msg[1]+ size)) = version;
2030 size+= sizeof(unsigned short);
2031 *((unsigned int *)(&msg[1]+ size)) = ptr->threadid;
2033 bytesSent = send(sock, msg, (1 + 2*sizeof(unsigned int) + sizeof(unsigned short)), 0);
2035 perror("notifyAll():send()");
2037 } else if (bytesSent != 1 + 2*sizeof(unsigned int) + sizeof(unsigned short)){
2038 printf("notifyAll(): error, sent %d bytes %s, %d\n",
2039 bytesSent, __FILE__, __LINE__);
2054 void transAbort(transrecord_t *trans) {
2055 objstrDelete(trans->cache);
2056 chashDelete(trans->lookupTable);