check LOCK versions
[IRC.git] / Robust / src / Runtime / DSTM / interface / trans.c
1 #include "dstm.h"
2 #include "ip.h"
3 #include "clookup.h"
4 #include "machinepile.h"
5 #include "mlookup.h"
6 #include "llookup.h"
7 #include "plookup.h"
8 #include "prelookup.h"
9 #include "threadnotify.h"
10 #include "queue.h"
11 #ifdef COMPILER
12 #include "thread.h"
13 #endif
14
15 #define NUM_THREADS 1
16 #define PREFETCH_CACHE_SIZE 1048576 //1MB
17 #define CONFIG_FILENAME "dstm.conf"
18
19 /* Global Variables */
20 extern int classsize[];
21 extern primarypfq_t pqueue; //Shared prefetch queue
22 objstr_t *prefetchcache; //Global Prefetch cache
23 pthread_mutex_t prefetchcache_mutex;// Mutex to lock Prefetch Cache
24 pthread_mutexattr_t prefetchcache_mutex_attr; /* Attribute for lock to make it a recursive lock */
25 extern pthread_mutex_t mainobjstore_mutex;// Mutex to lock main Object store
26 extern prehashtable_t pflookup; //Global Prefetch cache's lookup table
27 pthread_t wthreads[NUM_THREADS]; //Worker threads for working on the prefetch queue
28 pthread_t tPrefetch;            /* Primary Prefetch thread that processes the prefetch queue */
29 extern objstr_t *mainobjstore;
30 unsigned int myIpAddr;
31 unsigned int *hostIpAddrs;
32 int sizeOfHostArray;
33 int numHostsInSystem;
34 int myIndexInHostArray;
35 unsigned int oidsPerBlock;
36 unsigned int oidMin;
37 unsigned int oidMax;
38
39 sockPoolHashTable_t *transReadSockPool;
40 sockPoolHashTable_t *transPrefetchSockPool;
41 pthread_mutex_t notifymutex;
42 pthread_mutex_t atomicObjLock;
43
44 void printhex(unsigned char *, int);
45 plistnode_t *createPiles(transrecord_t *);
46
47 /*******************************
48  * Send and Recv function calls 
49  *******************************/
50 void send_data(int fd , void *buf, int buflen) {
51   char *buffer = (char *)(buf); 
52   int size = buflen;
53   int numbytes; 
54   while (size > 0) {
55     numbytes = send(fd, buffer, size, MSG_NOSIGNAL);
56     if (numbytes == -1) {
57       perror("send");
58       exit(-1);
59     }
60     buffer += numbytes;
61     size -= numbytes;
62   }
63 }
64
65 void recv_data(int fd , void *buf, int buflen) {
66   char *buffer = (char *)(buf); 
67   int size = buflen;
68   int numbytes; 
69   while (size > 0) {
70     numbytes = recv(fd, buffer, size, 0);
71     if (numbytes == -1) {
72       perror("recv");
73       exit(-1);
74     }
75     buffer += numbytes;
76     size -= numbytes;
77   }
78 }
79
80 int recv_data_errorcode(int fd , void *buf, int buflen) {
81   char *buffer = (char *)(buf); 
82   int size = buflen;
83   int numbytes; 
84   while (size > 0) {
85     numbytes = recv(fd, buffer, size, 0);
86     if (numbytes == -1) {
87       return -1;
88     }
89     buffer += numbytes;
90     size -= numbytes;
91   }
92   return 0;
93 }
94
95 void printhex(unsigned char *ptr, int numBytes) {
96   int i;
97   for (i = 0; i < numBytes; i++) {
98     if (ptr[i] < 16)
99       printf("0%x ", ptr[i]);
100     else
101       printf("%x ", ptr[i]);
102   }
103   printf("\n");
104   return;
105 }
106
107 inline int arrayLength(int *array) {
108   int i;
109   for(i=0 ;array[i] != -1; i++)
110     ;
111   return i;
112 }
113
114 inline int findmax(int *array, int arraylength) {
115   int max, i;
116   max = array[0];
117   for(i = 0; i < arraylength; i++){
118     if(array[i] > max) {
119       max = array[i];
120     }
121   }
122   return max;
123 }
124
125 /* This function is a prefetch call generated by the compiler that
126  * populates the shared primary prefetch queue*/
127 void prefetch(int ntuples, unsigned int *oids, unsigned short *endoffsets, short *arrayfields) {
128   /* Allocate for the queue node*/
129   int qnodesize = sizeof(prefetchqelem_t) + sizeof(int) + ntuples * (sizeof(unsigned short) + sizeof(unsigned int)) + endoffsets[ntuples - 1] * sizeof(short);
130   char * node= malloc(qnodesize);
131   /* Set queue node values */
132   int len = sizeof(prefetchqelem_t);
133   int top=endoffsets[ntuples-1];
134   *((int *)(node+len))=ntuples;
135   len += sizeof(int);
136   memcpy(node+len, oids, ntuples*sizeof(unsigned int));
137   memcpy(node+len+ntuples*sizeof(unsigned int), endoffsets, ntuples*sizeof(unsigned short));
138   memcpy(node+len+ntuples*(sizeof(unsigned int)+sizeof(short)), arrayfields, top*sizeof(short));
139
140   /* Lock and insert into primary prefetch queue */
141   pthread_mutex_lock(&pqueue.qlock);
142   pre_enqueue((prefetchqelem_t *)node);
143   pthread_cond_signal(&pqueue.qcond);
144   pthread_mutex_unlock(&pqueue.qlock);
145 }
146
147 /* This function starts up the transaction runtime. */
148 int dstmStartup(const char * option) {
149   pthread_t thread_Listen;
150   pthread_attr_t attr;
151   int master=option!=NULL && strcmp(option, "master")==0;
152   
153   if (processConfigFile() != 0)
154     return 0; //TODO: return error value, cause main program to exit
155 #ifdef COMPILER
156   if (!master)
157     threadcount--;
158 #endif
159   
160   //Initialize socket pool
161   transReadSockPool = createSockPool(transReadSockPool, 2*numHostsInSystem+1);
162   transPrefetchSockPool = createSockPool(transPrefetchSockPool, 2*numHostsInSystem+1);
163   
164   dstmInit();
165   transInit();
166   
167   if (master) {
168     pthread_attr_init(&attr);
169     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
170     pthread_create(&thread_Listen, &attr, dstmListen, NULL);
171     return 1;
172   } else {
173     dstmListen();
174     return 0;
175   }
176 }
177
178 //TODO Use this later
179 void *pCacheAlloc(objstr_t *store, unsigned int size) {
180   void *tmp;
181   objstr_t *ptr;
182   ptr = store;
183   int success = 0;
184   
185   while(ptr->next != NULL) {
186     /* check if store is empty */
187     if(((unsigned int)ptr->top - (unsigned int)ptr - sizeof(objstr_t) + size) <= ptr->size) {
188       tmp = ptr->top;
189       ptr->top += size;
190       success = 1;
191       return tmp;
192     } else {
193       ptr = ptr-> next;
194     }
195   }
196   
197   if(success == 0) {
198     return NULL;
199   }
200 }
201
202 /* This function initiates the prefetch thread A queue is shared
203  * between the main thread of execution and the prefetch thread to
204  * process the prefetch call Call from compiler populates the shared
205  * queue with prefetch requests while prefetch thread processes the
206  * prefetch requests */
207
208 void transInit() {
209   int t, rc;
210   int retval;
211   //Create and initialize prefetch cache structure
212   prefetchcache = objstrCreate(PREFETCH_CACHE_SIZE);
213   
214   /* Initialize attributes for mutex */
215   pthread_mutexattr_init(&prefetchcache_mutex_attr);
216   pthread_mutexattr_settype(&prefetchcache_mutex_attr, PTHREAD_MUTEX_RECURSIVE_NP);
217   
218   pthread_mutex_init(&prefetchcache_mutex, &prefetchcache_mutex_attr);
219   
220   pthread_mutex_init(&notifymutex, NULL);
221   pthread_mutex_init(&atomicObjLock, NULL);
222   //Create prefetch cache lookup table
223   if(prehashCreate(HASH_SIZE, LOADFACTOR)) {
224     printf("ERROR\n");
225     return; //Failure
226   }
227   
228   //Initialize primary shared queue
229   queueInit();
230   //Initialize machine pile w/prefetch oids and offsets shared queue
231   mcpileqInit();
232   
233   //Create the primary prefetch thread 
234   do {
235     retval=pthread_create(&tPrefetch, NULL, transPrefetch, NULL);
236   } while(retval!=0);
237   pthread_detach(tPrefetch);
238 }
239
240 /* This function stops the threads spawned */
241 void transExit() {
242   int t;
243   pthread_cancel(tPrefetch);
244   for(t = 0; t < NUM_THREADS; t++)
245     pthread_cancel(wthreads[t]);
246   
247   return;
248 }
249
250 /* This functions inserts randowm wait delays in the order of msec
251  * Mostly used when transaction commits retry*/
252 void randomdelay() {
253   struct timespec req;
254   time_t t;
255   
256   t = time(NULL);
257   req.tv_sec = 0;
258   req.tv_nsec = (long)(1000000 + (t%10000000)); //1-11 msec
259   nanosleep(&req, NULL);
260   return;
261 }
262
263 /* This function initializes things required in the transaction start*/
264 transrecord_t *transStart() {
265   transrecord_t *tmp;
266   if((tmp = calloc(1, sizeof(transrecord_t))) == NULL){
267     printf("%s() Calloc error at line %d, %s\n", __func__, __LINE__, __FILE__);
268     return NULL;
269   }
270   tmp->cache = objstrCreate(1048576);
271   tmp->lookupTable = chashCreate(HASH_SIZE, LOADFACTOR);
272 #ifdef COMPILER
273   tmp->revertlist=NULL;
274 #endif
275   return tmp;
276 }
277
278 /* This function finds the location of the objects involved in a transaction
279  * and returns the pointer to the object if found in a remote location */
280 objheader_t *transRead(transrecord_t *record, unsigned int oid) {
281   unsigned int machinenumber;
282   objheader_t *tmp, *objheader;
283   objheader_t *objcopy;
284   int size, found = 0;
285   void *buf;
286   
287   if(oid == 0) {
288     return NULL;
289   }
290   
291   if((objheader = (objheader_t *)chashSearch(record->lookupTable, oid)) != NULL){
292     /* Search local transaction cache */
293 #ifdef COMPILER
294     return &objheader[1];
295 #else
296     return objheader;
297 #endif
298   } else if ((objheader = (objheader_t *) mhashSearch(oid)) != NULL) {
299     /* Look up in machine lookup table  and copy  into cache*/
300     GETSIZE(size, objheader);
301     size += sizeof(objheader_t);
302     objcopy = (objheader_t *) objstrAlloc(record->cache, size);
303     memcpy(objcopy, objheader, size);
304     /* Insert into cache's lookup table */
305     chashInsert(record->lookupTable, OID(objheader), objcopy); 
306 #ifdef COMPILER
307     return &objcopy[1];
308 #else
309     return objcopy;
310 #endif
311   } else if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) { 
312     /* Look up in prefetch cache */
313     GETSIZE(size, tmp);
314     size+=sizeof(objheader_t);
315     objcopy = (objheader_t *) objstrAlloc(record->cache, size);
316     memcpy(objcopy, tmp, size);
317     /* Insert into cache's lookup table */
318     chashInsert(record->lookupTable, OID(tmp), objcopy); 
319 #ifdef COMPILER
320     return &objcopy[1];
321 #else
322     return objcopy;
323 #endif
324   } else {
325     /* Get the object from the remote location */
326     if((machinenumber = lhashSearch(oid)) == 0) {
327       printf("Error: %s() No machine found for oid =% %s,%dx\n",__func__, machinenumber, __FILE__, __LINE__);
328       return NULL;
329     }
330     objcopy = getRemoteObj(record, machinenumber, oid);
331     
332     if(objcopy == NULL) {
333       printf("Error: Object not found in Remote location %s, %d\n", __FILE__, __LINE__);
334       return NULL;
335     } else {
336       
337 #ifdef COMPILER
338       return &objcopy[1];
339 #else
340       return objcopy;
341 #endif
342     }
343   }
344 }
345
346 /* This function creates objects in the transaction record */
347 objheader_t *transCreateObj(transrecord_t *record, unsigned int size) {
348   objheader_t *tmp = (objheader_t *) objstrAlloc(record->cache, (sizeof(objheader_t) + size));
349   tmp->notifylist = NULL;
350   OID(tmp) = getNewOID();
351   tmp->version = 1;
352   tmp->rcount = 1;
353   STATUS(tmp) = NEW;
354   chashInsert(record->lookupTable, OID(tmp), tmp);
355   
356 #ifdef COMPILER
357   return &tmp[1]; //want space after object header
358 #else
359   return tmp;
360 #endif
361 }
362
363 /* This function creates machine piles based on all machines involved in a
364  * transaction commit request */
365 plistnode_t *createPiles(transrecord_t *record) {
366   int i;
367   plistnode_t *pile = NULL;
368   unsigned int machinenum;
369   objheader_t *headeraddr;
370   chashlistnode_t * ptr = record->lookupTable->table;
371   /* Represents number of bins in the chash table */
372   unsigned int size = record->lookupTable->size;
373   
374   for(i = 0; i < size ; i++) {
375     chashlistnode_t * curr = &ptr[i];
376     /* Inner loop to traverse the linked list of the cache lookupTable */
377     while(curr != NULL) {
378       //if the first bin in hash table is empty
379       if(curr->key == 0)
380         break;
381       
382       if ((headeraddr = chashSearch(record->lookupTable, curr->key)) == NULL) {
383         printf("Error: No such oid %s, %d\n", __FILE__, __LINE__);
384         return NULL;
385       }
386       
387       //Get machine location for object id (and whether local or not)
388       if (STATUS(headeraddr) & NEW || (mhashSearch(curr->key) != NULL)) {
389         machinenum = myIpAddr;
390       } else if ((machinenum = lhashSearch(curr->key)) == 0) {
391         printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
392         return NULL;
393       }
394       
395       //Make machine groups
396       pile = pInsert(pile, headeraddr, machinenum, record->lookupTable->numelements);
397       curr = curr->next;
398     }
399   }
400   return pile; 
401 }
402
403 /* This function initiates the transaction commit process
404  * Spawns threads for each of the new connections with Participants 
405  * and creates new piles by calling the createPiles(), 
406  * Sends a transrequest() to each remote machines for objects found remotely 
407  * and calls handleLocalReq() to process objects found locally */
408 int transCommit(transrecord_t *record) {        
409   unsigned int tot_bytes_mod, *listmid;
410   plistnode_t *pile, *pile_ptr;
411   int i, j, rc, val;
412   int pilecount, offset, threadnum = 0, trecvcount = 0;
413   char control;
414   char transid[TID_LEN];
415   trans_req_data_t *tosend;
416   trans_commit_data_t transinfo;
417   static int newtid = 0;
418   char treplyctrl = 0, treplyretry = 0; /* keeps track of the common response that needs to be sent */
419   char localstat = 0;
420   thread_data_array_t *thread_data_array;
421   local_thread_data_array_t *ltdata;
422   
423   do { 
424     trecvcount = 0; 
425     threadnum = 0; 
426     treplyretry = 0;
427     thread_data_array = NULL;
428     ltdata = NULL;
429     
430     /* Look through all the objects in the transaction record and make piles 
431      * for each machine involved in the transaction*/
432     pile_ptr = pile = createPiles(record);
433     
434     /* Create the packet to be sent in TRANS_REQUEST */
435     
436     /* Count the number of participants */
437     pilecount = pCount(pile);
438     
439     /* Create a list of machine ids(Participants) involved in transaction       */
440     listmid = calloc(pilecount, sizeof(unsigned int));
441     pListMid(pile, listmid);
442     
443     
444     /* Initialize thread variables,
445      * Spawn a thread for each Participant involved in a transaction */
446     pthread_t thread[pilecount];
447     pthread_attr_t attr;                        
448     pthread_cond_t tcond;
449     pthread_mutex_t tlock;
450     pthread_mutex_t tlshrd;
451     
452     thread_data_array = (thread_data_array_t *) calloc(pilecount, sizeof(thread_data_array_t));
453     
454     ltdata = calloc(1, sizeof(local_thread_data_array_t));
455     
456     thread_response_t rcvd_control_msg[pilecount];      /* Shared thread array that keeps track of responses of participants */
457     
458     /* Initialize and set thread detach attribute */
459     pthread_attr_init(&attr);
460     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
461     pthread_mutex_init(&tlock, NULL);
462     pthread_cond_init(&tcond, NULL);
463     
464     /* Process each machine pile */
465     while(pile != NULL) {
466       //Create transaction id
467       newtid++;
468       tosend = calloc(1, sizeof(trans_req_data_t));
469       tosend->f.control = TRANS_REQUEST;
470       sprintf(tosend->f.trans_id, "%x_%d", pile->mid, newtid);
471       tosend->f.mcount = pilecount;
472       tosend->f.numread = pile->numread;
473       tosend->f.nummod = pile->nummod;
474       tosend->f.numcreated = pile->numcreated;
475       tosend->f.sum_bytes = pile->sum_bytes;
476       tosend->listmid = listmid;
477       tosend->objread = pile->objread;
478       tosend->oidmod = pile->oidmod;
479       tosend->oidcreated = pile->oidcreated;
480       thread_data_array[threadnum].thread_id = threadnum;
481       thread_data_array[threadnum].mid = pile->mid;
482       thread_data_array[threadnum].buffer = tosend;
483       thread_data_array[threadnum].recvmsg = rcvd_control_msg;
484       thread_data_array[threadnum].threshold = &tcond;
485       thread_data_array[threadnum].lock = &tlock;
486       thread_data_array[threadnum].count = &trecvcount;
487       thread_data_array[threadnum].replyctrl = &treplyctrl;
488       thread_data_array[threadnum].replyretry = &treplyretry;
489       thread_data_array[threadnum].rec = record;
490       /* If local do not create any extra connection */
491       if(pile->mid != myIpAddr) { /* Not local */
492         do {
493           rc = pthread_create(&thread[threadnum], &attr, transRequest, (void *) &thread_data_array[threadnum]);  
494         } while(rc!=0);
495         if(rc) {
496           perror("Error in pthread create\n");
497           pthread_cond_destroy(&tcond);
498           pthread_mutex_destroy(&tlock);
499           pDelete(pile_ptr);
500           free(listmid);
501           for (i = 0; i < threadnum; i++)
502             free(thread_data_array[i].buffer);
503           free(thread_data_array);
504           free(ltdata);
505           return 1;
506         }
507       } else { /*Local*/
508         ltdata->tdata = &thread_data_array[threadnum];
509         ltdata->transinfo = &transinfo;
510         do {
511           val = pthread_create(&thread[threadnum], &attr, handleLocalReq, (void *) ltdata);
512         } while(val!=0);
513         if(val) {
514           perror("Error in pthread create\n");
515           pthread_cond_destroy(&tcond);
516           pthread_mutex_destroy(&tlock);
517           pDelete(pile_ptr);
518           free(listmid);
519           for (i = 0; i < threadnum; i++)
520             free(thread_data_array[i].buffer);
521           free(thread_data_array);
522           free(ltdata);
523           return 1;
524         }
525       }
526       
527       threadnum++;              
528       pile = pile->next;
529     }
530     /* Free attribute and wait for the other threads */
531     pthread_attr_destroy(&attr);
532     
533     for (i = 0; i < threadnum; i++) {
534       rc = pthread_join(thread[i], NULL);
535       if(rc)
536         {
537           printf("Error: return code from pthread_join() is %d\n", rc);
538           pthread_cond_destroy(&tcond);
539           pthread_mutex_destroy(&tlock);
540           pDelete(pile_ptr);
541           free(listmid);
542           for (j = i; j < threadnum; j++) {
543             free(thread_data_array[j].buffer);
544           }
545           return 1;
546         }
547       free(thread_data_array[i].buffer);
548     }
549
550     /* Free resources */        
551     pthread_cond_destroy(&tcond);
552     pthread_mutex_destroy(&tlock);
553     free(listmid);
554     pDelete(pile_ptr);
555     
556     /* wait a random amount of time before retrying to commit transaction*/
557     if(treplyretry) {
558       free(thread_data_array);
559       free(ltdata);
560       randomdelay();
561     }
562     
563     /* Retry trans commit procedure during soft_abort case */
564   } while (treplyretry);
565   
566   if(treplyctrl == TRANS_ABORT) {
567     /* Free Resources */
568     objstrDelete(record->cache);
569     chashDelete(record->lookupTable);
570     free(record);
571     free(thread_data_array);
572     free(ltdata);
573     return TRANS_ABORT;
574   } else if(treplyctrl == TRANS_COMMIT) {
575     /* Free Resources */
576     objstrDelete(record->cache);
577     chashDelete(record->lookupTable);
578     free(record);
579     free(thread_data_array);
580     free(ltdata);
581     return 0;
582   } else {
583     //TODO Add other cases
584     printf("Error: in %s() THIS SHOULD NOT HAPPEN.....EXIT PROGRAM\n", __func__);
585     exit(-1);
586   }
587   return 0;
588 }
589
590 /* This function sends information involved in the transaction request 
591  * to participants and accepts a response from particpants.
592  * It calls decideresponse() to decide on what control message 
593  * to send next to participants and sends the message using sendResponse()*/
594 void *transRequest(void *threadarg) {
595   int sd, i, n;
596   struct sockaddr_in serv_addr;
597   thread_data_array_t *tdata;
598   objheader_t *headeraddr;
599   char control, recvcontrol;
600   char machineip[16], retval;
601   
602   tdata = (thread_data_array_t *) threadarg;
603   
604   /* Send Trans Request */
605   if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
606     perror("Error in socket for TRANS_REQUEST\n");
607     pthread_exit(NULL);
608   }
609   bzero((char*) &serv_addr, sizeof(serv_addr));
610   serv_addr.sin_family = AF_INET;
611   serv_addr.sin_port = htons(LISTEN_PORT);
612   midtoIP(tdata->mid,machineip);
613   machineip[15] = '\0';
614   serv_addr.sin_addr.s_addr = inet_addr(machineip);
615   /* Open Connection */
616   if (connect(sd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) {
617     perror("Error in connect for TRANS_REQUEST\n");
618     close(sd);
619     pthread_exit(NULL);
620   }
621   
622   /* Send bytes of data with TRANS_REQUEST control message */
623   send_data(sd, &(tdata->buffer->f), sizeof(fixed_data_t));
624   
625   /* Send list of machines involved in the transaction */
626   {
627     int size=sizeof(unsigned int)*tdata->buffer->f.mcount;
628     send_data(sd, tdata->buffer->listmid, size);
629   }
630   
631   /* Send oids and version number tuples for objects that are read */
632   {
633     int size=(sizeof(unsigned int)+sizeof(unsigned short))*tdata->buffer->f.numread;
634     send_data(sd, tdata->buffer->objread, size);
635   }
636   
637   /* Send objects that are modified */
638   for(i = 0; i < tdata->buffer->f.nummod ; i++) {
639     int size;
640     headeraddr = chashSearch(tdata->rec->lookupTable, tdata->buffer->oidmod[i]);
641     GETSIZE(size,headeraddr);
642     size+=sizeof(objheader_t);
643     send_data(sd, headeraddr, size);
644   }
645   
646   /* Read control message from Participant */
647   recv_data(sd, &control, sizeof(char));
648   recvcontrol = control;
649   
650   /* Update common data structure and increment count */
651   tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol;
652   
653   /* Lock and update count */
654   /* Thread sleeps until all messages from pariticipants are received by coordinator */
655   pthread_mutex_lock(tdata->lock);
656   
657   (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */
658   
659   /* Wake up the threads and invoke decideResponse (once) */
660   if(*(tdata->count) == tdata->buffer->f.mcount) {
661     decideResponse(tdata); 
662     pthread_cond_broadcast(tdata->threshold);
663   } else {
664     pthread_cond_wait(tdata->threshold, tdata->lock);
665   }
666   pthread_mutex_unlock(tdata->lock);
667   
668   /* Send the final response such as TRANS_COMMIT or TRANS_ABORT t
669    * to all participants in their respective socket */
670   if (sendResponse(tdata, sd) == 0) { 
671     printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__);
672     close(sd);
673     pthread_exit(NULL);
674   }
675   
676   recv_data((int)sd, &control, sizeof(char)); 
677   
678   if(control == TRANS_UNSUCESSFUL) {
679     //printf("DEBUG-> TRANS_ABORTED\n");
680   } else if(control == TRANS_SUCESSFUL) {
681     //printf("DEBUG-> TRANS_SUCCESSFUL\n");
682   } else {
683     //printf("DEBUG-> Error: Incorrect Transaction End Message %d\n", control);
684   }
685   
686   /* Close connection */
687   close(sd);
688   pthread_exit(NULL);
689 }
690
691 /* This function decides the reponse that needs to be sent to 
692  * all Participant machines after the TRANS_REQUEST protocol */
693 void decideResponse(thread_data_array_t *tdata) {
694   char control;
695   int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
696                                                                    message to send */
697   
698   for (i = 0 ; i < tdata->buffer->f.mcount; i++) {
699     control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses
700                                                written onto the shared array */
701     switch(control) {
702     default:
703       printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__);
704       /* treat as disagree, pass thru */
705     case TRANS_DISAGREE:
706       transdisagree++;
707       break;
708       
709     case TRANS_AGREE:
710       transagree++;
711       break;
712       
713     case TRANS_SOFT_ABORT:
714       transsoftabort++;
715       break;
716     }
717   }
718   
719   if(transdisagree > 0) {
720     /* Send Abort */
721     *(tdata->replyctrl) = TRANS_ABORT;
722     *(tdata->replyretry) = 0;
723     /* clear objects from prefetch cache */
724     for (i = 0; i < tdata->buffer->f.numread; i++)
725       prehashRemove(*((unsigned int *)(((char *)tdata->buffer->objread) + (sizeof(unsigned int) + sizeof(unsigned short))*i)));
726     for (i = 0; i < tdata->buffer->f.nummod; i++)
727       prehashRemove(tdata->buffer->oidmod[i]);
728   } else if(transagree == tdata->buffer->f.mcount){
729     /* Send Commit */
730     *(tdata->replyctrl) = TRANS_COMMIT;
731     *(tdata->replyretry) = 0;
732   } else { 
733     /* Send Abort in soft abort case followed by retry commiting transaction again*/
734     *(tdata->replyctrl) = TRANS_ABORT;
735     *(tdata->replyretry) = 1;
736   }
737   
738   return;
739 }
740
741 /* This function sends the final response to remote machines per
742  * thread in their respective socket id It returns a char that is only
743  * needed to check the correctness of execution of this function
744  * inside transRequest()*/
745
746 char sendResponse(thread_data_array_t *tdata, int sd) {
747   int n, size, sum, oidcount = 0, control;
748   char *ptr, retval = 0;
749   unsigned int *oidnotfound;
750   
751   control = *(tdata->replyctrl);
752   send_data(sd, &control, sizeof(char));
753   
754   //TODO read missing objects during object migration
755   /* If response is a soft abort due to missing objects at the
756      Participant's side */
757   
758   /* If the decided response is TRANS_ABORT */
759   if(*(tdata->replyctrl) == TRANS_ABORT) {
760     retval = TRANS_ABORT;
761   } else if(*(tdata->replyctrl) == TRANS_COMMIT) { 
762     /* If the decided response is TRANS_COMMIT */ 
763     retval = TRANS_COMMIT;
764   }
765   
766   return retval;
767 }
768
769 /* This function opens a connection, places an object read request to
770  * the remote machine, reads the control message and object if
771  * available and copies the object and its header to the local
772  * cache. */ 
773
774 void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) {
775   int size, val;
776   struct sockaddr_in serv_addr;
777   char machineip[16];
778   char control;
779   objheader_t *h;
780   void *objcopy = NULL;
781   
782   int sd = getSock2(transReadSockPool, mnum);
783   char readrequest[sizeof(char)+sizeof(unsigned int)];
784   readrequest[0] = READ_REQUEST;
785   *((unsigned int *)(&readrequest[1])) = oid;
786   send_data(sd, readrequest, sizeof(readrequest));
787   
788   /* Read response from the Participant */
789   recv_data(sd, &control, sizeof(char));
790   
791   if (control==OBJECT_NOT_FOUND) {
792     objcopy = NULL;
793   } else {
794     /* Read object if found into local cache */
795     recv_data(sd, &size, sizeof(int));
796     objcopy = objstrAlloc(record->cache, size);
797     recv_data(sd, objcopy, size);
798     
799     /* Insert into cache's lookup table */
800     chashInsert(record->lookupTable, oid, objcopy); 
801   }
802   
803   return objcopy;
804 }
805
806 /* This function handles the local objects involved in a transaction
807  * commiting process.  It also makes a decision if this local machine
808  * sends AGREE or DISAGREE or SOFT_ABORT to coordinator.  Note
809  * Coordinator = local machine It wakes up the other threads from
810  * remote participants that are waiting for the coordinator's decision
811  * and based on common agreement it either commits or aborts the
812  * transaction.  It also frees the memory resources */
813
814 void *handleLocalReq(void *threadarg) {
815   unsigned int *oidnotfound = NULL, *oidlocked = NULL;
816   local_thread_data_array_t *localtdata;
817   int objnotfound = 0, objlocked = 0; 
818   int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
819   int numread, i;
820   unsigned int oid;
821   unsigned short version;
822   void *mobj;
823   objheader_t *headptr;
824   
825   localtdata = (local_thread_data_array_t *) threadarg;
826   
827   /* Counters and arrays to formulate decision on control message to be sent */
828   oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
829   oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int));
830   
831   numread = localtdata->tdata->buffer->f.numread;
832   /* Process each oid in the machine pile/ group per thread */
833   for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) {
834     if (i < localtdata->tdata->buffer->f.numread) {
835       int incr = sizeof(unsigned int) + sizeof(unsigned short);// Offset that points to next position in the objread array
836       incr *= i;
837       oid = *((unsigned int *)(((char *)localtdata->tdata->buffer->objread) + incr));
838       version = *((unsigned short *)(((char *)localtdata->tdata->buffer->objread) + incr + sizeof(unsigned int)));
839     } else { // Objects Modified
840       int tmpsize;
841       headptr = (objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidmod[i-numread]);
842       if (headptr == NULL) {
843         printf("Error: handleLocalReq() returning NULL %s, %d\n", __FILE__, __LINE__);
844         return NULL;
845       }
846       oid = OID(headptr);
847       version = headptr->version;
848     }
849     /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
850     
851     /* Save the oids not found and number of oids not found for later use */
852     if ((mobj = mhashSearch(oid)) == NULL) { /* Obj not found */
853       /* Save the oids not found and number of oids not found for later use */
854       oidnotfound[objnotfound] = oid;
855       objnotfound++;
856     } else { /* If Obj found in machine (i.e. has not moved) */
857       /* Check if Obj is locked by any previous transaction */
858       pthread_mutex_lock(&atomicObjLock);
859       if ((STATUS((objheader_t *)mobj) & LOCK) == LOCK) {
860         pthread_mutex_unlock(&atomicObjLock);
861         if (version == ((objheader_t *)mobj)->version) {      /* If locked then match versions */ 
862           v_matchlock++;
863         } else {/* If versions don't match ...HARD ABORT */
864           v_nomatch++;
865           /* Send TRANS_DISAGREE to Coordinator */
866           localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
867         }
868       } else {/* If Obj is not locked then lock object */
869         STATUS(((objheader_t *)mobj)) |= LOCK;
870         pthread_mutex_unlock(&atomicObjLock);
871         /* Save all object oids that are locked on this machine during this transaction request call */
872         oidlocked[objlocked] = OID(((objheader_t *)mobj));
873         objlocked++;
874         if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
875           v_matchnolock++;
876         } else { /* If versions don't match ...HARD ABORT */
877           v_nomatch++;
878           /* Send TRANS_DISAGREE to Coordinator */
879           localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE;
880         }
881       }
882     }
883   } // End for
884   /* Condition to send TRANS_AGREE */
885   if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) {
886     localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE;
887   }
888   /* Condition to send TRANS_SOFT_ABORT */
889   if((v_matchlock > 0 && v_nomatch == 0) || (objnotfound > 0 && v_nomatch == 0)) {
890     localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT;
891   }
892   
893   /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
894    * if Participant receives a TRANS_COMMIT */
895   localtdata->transinfo->objlocked = oidlocked;
896   localtdata->transinfo->objnotfound = oidnotfound;
897   localtdata->transinfo->modptr = NULL;
898   localtdata->transinfo->numlocked = objlocked;
899   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 */
904   
905   /* Wake up the threads and invoke decideResponse (once) */
906   if(*(localtdata->tdata->count) == localtdata->tdata->buffer->f.mcount) {
907     decideResponse(localtdata->tdata); 
908     pthread_cond_broadcast(localtdata->tdata->threshold);
909   } else {
910     pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock);
911   }
912   pthread_mutex_unlock(localtdata->tdata->lock);
913   if(*(localtdata->tdata->replyctrl) == TRANS_ABORT){
914     if(transAbortProcess(localtdata) != 0) {
915       printf("Error in transAbortProcess() %s,%d\n", __FILE__, __LINE__);
916       pthread_exit(NULL);
917     }
918   } else if(*(localtdata->tdata->replyctrl) == TRANS_COMMIT) {
919     if(transComProcess(localtdata) != 0) {
920       printf("Error in transComProcess() %s,%d\n", __FILE__, __LINE__);
921       pthread_exit(NULL);
922     }
923   }
924   /* Free memory */
925   if (localtdata->transinfo->objlocked != NULL) {
926     free(localtdata->transinfo->objlocked);
927   }
928   if (localtdata->transinfo->objnotfound != NULL) {
929     free(localtdata->transinfo->objnotfound);
930   }
931   
932   pthread_exit(NULL);
933 }
934
935 /* This function completes the ABORT process if the transaction is aborting */
936 int transAbortProcess(local_thread_data_array_t  *localtdata) {
937   int i, numlocked;
938   unsigned int *objlocked;
939   void *header;
940   
941   numlocked = localtdata->transinfo->numlocked;
942   objlocked = localtdata->transinfo->objlocked;
943   
944   for (i = 0; i < numlocked; i++) {
945     if((header = mhashSearch(objlocked[i])) == NULL) {
946       printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
947       return 1;
948     }
949     STATUS(((objheader_t *)header)) &= ~(LOCK);
950   }
951   
952   return 0;
953 }
954
955 /*This function completes the COMMIT process is the transaction is commiting*/
956 int transComProcess(local_thread_data_array_t  *localtdata) {
957         objheader_t *header, *tcptr;
958         int i, nummod, tmpsize, numcreated, numlocked;
959         unsigned int *oidmod, *oidcreated, *oidlocked;
960         void *ptrcreate;
961
962         nummod = localtdata->tdata->buffer->f.nummod;
963         oidmod = localtdata->tdata->buffer->oidmod;
964         numcreated = localtdata->tdata->buffer->f.numcreated;
965         oidcreated = localtdata->tdata->buffer->oidcreated;
966         numlocked = localtdata->transinfo->numlocked;
967         oidlocked = localtdata->transinfo->objlocked;
968
969         for (i = 0; i < nummod; i++) {
970                 if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
971                         printf("Error: transComProcess() mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
972                         return 1;
973                 }
974                 /* Copy from transaction cache -> main object store */
975                 if ((tcptr = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidmod[i]))) == NULL) {
976                         printf("Error: transComProcess() chashSearch returned NULL at %s, %d\n", __FILE__, __LINE__);
977                         return 1;
978                 }
979                 GETSIZE(tmpsize, header);
980                 pthread_mutex_lock(&mainobjstore_mutex);
981         char *tmptcptr = (char *) tcptr;
982                 memcpy((char*)header+sizeof(objheader_t), (char *)tmptcptr+ sizeof(objheader_t), tmpsize);
983                 header->version += 1;
984         pthread_mutex_lock(&notifymutex);
985                 if(header->notifylist != NULL) {
986                         notifyAll(&header->notifylist, OID(header), header->version);
987                 }
988         pthread_mutex_unlock(&notifymutex);
989                 pthread_mutex_unlock(&mainobjstore_mutex);
990         }
991         /* If object is newly created inside transaction then commit it */
992         for (i = 0; i < numcreated; i++) {
993                 if ((header = ((objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, oidcreated[i]))) == NULL) {
994                         printf("Error: transComProcess() chashSearch returned NULL for oid = %x at %s, %d\n", oidcreated[i], __FILE__, __LINE__);
995                         return 1;
996                 }
997                 GETSIZE(tmpsize, header);
998                 tmpsize += sizeof(objheader_t);
999                 pthread_mutex_lock(&mainobjstore_mutex);
1000                 if ((ptrcreate = objstrAlloc(mainobjstore, tmpsize)) == NULL) {
1001                         printf("Error: transComProcess() failed objstrAlloc %s, %d\n", __FILE__, __LINE__);
1002                         pthread_mutex_unlock(&mainobjstore_mutex);
1003                         return 1;
1004                 }
1005                 pthread_mutex_unlock(&mainobjstore_mutex);
1006                 memcpy(ptrcreate, header, tmpsize);
1007                 mhashInsert(oidcreated[i], ptrcreate);
1008                 lhashInsert(oidcreated[i], myIpAddr);
1009         }
1010         /* Unlock locked objects */
1011         for(i = 0; i < numlocked; i++) {
1012                 if((header = (objheader_t *) mhashSearch(oidlocked[i])) == NULL) {
1013                         printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
1014                         return 1;
1015                 }
1016                 STATUS(header) &= ~(LOCK);
1017         }
1018
1019         return 0;
1020 }
1021
1022 prefetchpile_t *foundLocal(prefetchqelem_t *node) {
1023   char * ptr = (char *) node;
1024   int ntuples = *(GET_NTUPLES(ptr));
1025   unsigned int * oidarray = GET_PTR_OID(ptr);
1026   unsigned short * endoffsets = GET_PTR_EOFF(ptr, ntuples); 
1027   short * arryfields = GET_PTR_ARRYFLD(ptr, ntuples);
1028   prefetchpile_t * head=NULL;
1029   
1030   int i;
1031   for(i=0;i<ntuples; i++) {
1032     unsigned short baseindex=(i==0)?0:endoffsets[i-1];
1033     unsigned short endindex=endoffsets[i];
1034     unsigned int oid=oidarray[i];
1035     int newbase;
1036     int machinenum;
1037     if (oid==0)
1038       continue;
1039     //Look up fields locally
1040     for(newbase=baseindex;newbase<endindex;newbase++) {
1041       if (!lookupObject(&oid, arryfields[newbase]))
1042         break;
1043       //Ended in a null pointer...
1044       if (oid==0)
1045         goto tuple;
1046     }
1047     //Entire prefetch is local
1048     if (newbase==endindex&&checkoid(oid))
1049       goto tuple;
1050     //Add to remote requests
1051     machinenum=lhashSearch(oid);
1052     insertPile(machinenum, oid, endindex-newbase, &arryfields[newbase], &head);
1053   tuple:
1054     ;
1055   }
1056   return head;
1057 }
1058
1059 int checkoid(unsigned int oid) {
1060   objheader_t *header;
1061   if ((header=mhashSearch(oid))!=NULL) {
1062     //Found on machine
1063     return 1;
1064   } else if ((header=prehashSearch(oid))!=NULL) {
1065     //Found in cache
1066     return 1;
1067   } else {
1068     return 0;
1069   }
1070 }
1071
1072 int lookupObject(unsigned int * oid, short offset) {
1073   objheader_t *header;
1074   if ((header=mhashSearch(*oid))!=NULL) {
1075     //Found on machine
1076     ;
1077   } else if ((header=prehashSearch(*oid))!=NULL) {
1078     //Found in cache
1079     ;
1080   } else {
1081     return 0;
1082   }
1083
1084   if(TYPE(header) > NUMCLASSES) {
1085     int elementsize = classsize[TYPE(header)];
1086     struct ArrayObject *ao = (struct ArrayObject *) (((char *)header) + sizeof(objheader_t));
1087     int length = ao->___length___;
1088     /* Check if array out of bounds */
1089     if(offset < 0 || offset >= length) {
1090       //if yes treat the object as found
1091       (*oid)=0;
1092       return 1;
1093     }
1094     (*oid) = *((unsigned int *)(((char *)ao) + sizeof(struct ArrayObject) + (elementsize*offset)));
1095     return 1;
1096   } else {
1097     (*oid) = *((unsigned int *)(((char *)header) + sizeof(objheader_t) + offset));
1098     return 1;
1099   }
1100 }
1101
1102
1103 /* This function is called by the thread calling transPrefetch */
1104 void *transPrefetch(void *t) {
1105   while(1) {
1106     /* lock mutex of primary prefetch queue */
1107     pthread_mutex_lock(&pqueue.qlock);
1108     /* while primary queue is empty, then wait */
1109     while(pqueue.front == NULL) {
1110       pthread_cond_wait(&pqueue.qcond, &pqueue.qlock);
1111     }
1112     
1113     /* dequeue node to create a machine piles and  finally unlock mutex */
1114     prefetchqelem_t *qnode = pre_dequeue();
1115     pthread_mutex_unlock(&pqueue.qlock);
1116     
1117     /* Check if the tuples are found locally, if yes then reduce them further*/ 
1118     /* and group requests by remote machine ids by calling the makePreGroups() */
1119     prefetchpile_t *pilehead = foundLocal(qnode);
1120
1121     if (pilehead!=NULL) {
1122       // Get sock from shared pool 
1123       int sd = getSock2(transPrefetchSockPool, pilehead->mid);
1124       
1125       /* Send  Prefetch Request */
1126       prefetchpile_t *ptr = pilehead;
1127       while(ptr != NULL) {
1128         sendPrefetchReq(ptr, sd);
1129         ptr = ptr->next; 
1130       }
1131       
1132       /* Release socket */
1133       //        freeSock(transPrefetchSockPool, pilehead->mid, sd);
1134       
1135       /* Deallocated pilehead */
1136       mcdealloc(pilehead);
1137       
1138     }
1139     // Deallocate the prefetch queue pile node
1140     predealloc(qnode);
1141   }
1142 }
1143
1144 void sendPrefetchReqnew(prefetchpile_t *mcpilenode, int sd) {
1145   objpile_t *tmp;
1146   
1147   int size=sizeof(char)+sizeof(int);
1148   for(tmp=mcpilenode->objpiles;tmp!=NULL;tmp=tmp->next) {
1149     size += sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1150   }
1151   
1152   char buft[size];
1153   char *buf=buft;
1154   *buf=TRANS_PREFETCH;
1155   buf+=sizeof(char);
1156   
1157   for(tmp=mcpilenode->objpiles;tmp!=NULL;tmp=tmp->next) {
1158     int len = sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1159     *((int*)buf)=len;
1160     buf+=sizeof(int);
1161     *((unsigned int *)buf)=tmp->oid;
1162     buf+=sizeof(unsigned int);
1163     *((unsigned int *)(buf)) = myIpAddr; 
1164     buf+=sizeof(unsigned int);
1165     memcpy(buf, tmp->offset, tmp->numoffset*sizeof(short));
1166     buf+=tmp->numoffset*sizeof(short);
1167   }
1168   *((int *)buf)=-1;
1169   send_data(sd, buft, size);
1170   return;
1171 }
1172
1173 void sendPrefetchReq(prefetchpile_t *mcpilenode, int sd) {
1174   int len, endpair;
1175   char control;
1176   objpile_t *tmp;
1177   
1178   /* Send TRANS_PREFETCH control message */
1179   control = TRANS_PREFETCH;
1180   send_data(sd, &control, sizeof(char));
1181   
1182   /* Send Oids and offsets in pairs */
1183   tmp = mcpilenode->objpiles;
1184   while(tmp != NULL) {
1185     len = sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short));
1186     char oidnoffset[len];
1187     char *buf=oidnoffset;
1188     *((int*)buf) = tmp->numoffset;
1189     buf+=sizeof(int);
1190     *((unsigned int *)buf) = tmp->oid;
1191     buf+=sizeof(unsigned int);
1192     *((unsigned int *)buf) = myIpAddr; 
1193     buf += sizeof(unsigned int);
1194     memcpy(buf, tmp->offset, tmp->numoffset*sizeof(short));
1195     send_data(sd, oidnoffset, len);
1196     tmp = tmp->next;
1197   }
1198   
1199   /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */
1200   endpair = -1;
1201   send_data(sd, &endpair, sizeof(int));
1202   
1203   return;
1204 }
1205
1206 int getPrefetchResponse(int sd) {
1207   int length = 0, size = 0;
1208   char control;
1209   unsigned int oid;
1210   void *modptr, *oldptr;
1211   
1212   recv_data((int)sd, &length, sizeof(int)); 
1213   size = length - sizeof(int);
1214   char recvbuffer[size];
1215
1216   recv_data((int)sd, recvbuffer, size);
1217   control = *((char *) recvbuffer);
1218   if(control == OBJECT_FOUND) {
1219     oid = *((unsigned int *)(recvbuffer + sizeof(char)));
1220     size = size - (sizeof(char) + sizeof(unsigned int));
1221     pthread_mutex_lock(&prefetchcache_mutex);
1222     if ((modptr = objstrAlloc(prefetchcache, size)) == NULL) {
1223       printf("Error: objstrAlloc error for copying into prefetch cache %s, %d\n", __FILE__, __LINE__);
1224       pthread_mutex_unlock(&prefetchcache_mutex);
1225       return -1;
1226     }
1227     pthread_mutex_unlock(&prefetchcache_mutex);
1228     memcpy(modptr, recvbuffer + sizeof(char) + sizeof(unsigned int), size);
1229     
1230     /* Insert the oid and its address into the prefetch hash lookup table */
1231     /* Do a version comparison if the oid exists */
1232     if((oldptr = prehashSearch(oid)) != NULL) {
1233       /* If older version then update with new object ptr */
1234       if(((objheader_t *)oldptr)->version <= ((objheader_t *)modptr)->version) {
1235         prehashRemove(oid);
1236         prehashInsert(oid, modptr);
1237       }
1238     } else {/* Else add the object ptr to hash table*/
1239       prehashInsert(oid, modptr);
1240     }
1241     /* Lock the Prefetch Cache look up table*/
1242     pthread_mutex_lock(&pflookup.lock);
1243     /* Broadcast signal on prefetch cache condition variable */ 
1244     pthread_cond_broadcast(&pflookup.cond);
1245     /* Unlock the Prefetch Cache look up table*/
1246     pthread_mutex_unlock(&pflookup.lock);
1247   } else if(control == OBJECT_NOT_FOUND) {
1248     oid = *((unsigned int *)(recvbuffer + sizeof(char)));
1249     /* TODO: For each object not found query DHT for new location and retrieve the object */
1250     /* Throw an error */
1251     printf("OBJECT %x NOT FOUND.... THIS SHOULD NOT HAPPEN...TERMINATE PROGRAM\n", oid);
1252     //    exit(-1);
1253   } else {
1254     printf("Error: in decoding the control value %d, %s, %d\n",control, __FILE__, __LINE__);
1255   }
1256   
1257   return 0;
1258 }
1259
1260 unsigned short getObjType(unsigned int oid) {
1261   objheader_t *objheader;
1262   unsigned short numoffset[] ={0};
1263   short fieldoffset[] ={};
1264   
1265   if ((objheader = (objheader_t *) mhashSearch(oid)) == NULL) {
1266       if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL) {
1267         prefetch(1, &oid, numoffset, fieldoffset);
1268         pthread_mutex_lock(&pflookup.lock);
1269         while ((objheader = (objheader_t *) prehashSearch(oid)) == NULL) {
1270           pthread_cond_wait(&pflookup.cond, &pflookup.lock);
1271         }
1272         pthread_mutex_unlock(&pflookup.lock);
1273       }
1274   }
1275   
1276   return TYPE(objheader);
1277 }
1278
1279 int startRemoteThread(unsigned int oid, unsigned int mid)
1280 {
1281         int sock;
1282         struct sockaddr_in remoteAddr;
1283         char msg[1 + sizeof(unsigned int)];
1284         int bytesSent;
1285         int status;
1286
1287         if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
1288         {
1289                 perror("startRemoteThread():socket()");
1290                 return -1;
1291         }
1292
1293         bzero(&remoteAddr, sizeof(remoteAddr));
1294         remoteAddr.sin_family = AF_INET;
1295         remoteAddr.sin_port = htons(LISTEN_PORT);
1296         remoteAddr.sin_addr.s_addr = htonl(mid);
1297         
1298         if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0)
1299         {
1300                 printf("startRemoteThread():error %d connecting to %s:%d\n", errno,
1301                         inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1302                 status = -1;
1303         }
1304         else
1305         {
1306                 msg[0] = START_REMOTE_THREAD;
1307         *((unsigned int *) &msg[1]) = oid;
1308                 send_data(sock, msg, 1 + sizeof(unsigned int));
1309         }
1310
1311         close(sock);
1312         return status;
1313 }
1314
1315 //TODO: when reusing oids, make sure they are not already in use!
1316 static unsigned int id = 0xFFFFFFFF;
1317 unsigned int getNewOID(void) {
1318         id += 2;
1319         if (id > oidMax || id < oidMin)
1320         {
1321                 id = (oidMin | 1);
1322         }
1323         return id;
1324 }
1325
1326 int processConfigFile()
1327 {
1328         FILE *configFile;
1329         const int maxLineLength = 200;
1330         char lineBuffer[maxLineLength];
1331         char *token;
1332         const char *delimiters = " \t\n";
1333         char *commentBegin;
1334         in_addr_t tmpAddr;
1335         
1336         configFile = fopen(CONFIG_FILENAME, "r");
1337         if (configFile == NULL)
1338         {
1339                 printf("error opening %s:\n", CONFIG_FILENAME);
1340                 perror("");
1341                 return -1;
1342         }
1343
1344         numHostsInSystem = 0;
1345         sizeOfHostArray = 8;
1346         hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int));
1347         
1348         while(fgets(lineBuffer, maxLineLength, configFile) != NULL)
1349         {
1350                 commentBegin = strchr(lineBuffer, '#');
1351                 if (commentBegin != NULL)
1352                         *commentBegin = '\0';
1353                 token = strtok(lineBuffer, delimiters);
1354                 while (token != NULL)
1355                 {
1356                         tmpAddr = inet_addr(token);
1357                         if ((int)tmpAddr == -1)
1358                         {
1359                                 printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
1360                                 fclose(configFile);
1361                                 return -1;
1362                         }
1363                         else
1364                                 addHost(htonl(tmpAddr));
1365                         token = strtok(NULL, delimiters);
1366                 }
1367         }
1368
1369         fclose(configFile);
1370         
1371         if (numHostsInSystem < 1)
1372         {
1373                 printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME);
1374                 return -1;
1375         }
1376 #ifdef MAC
1377         myIpAddr = getMyIpAddr("en1");
1378 #else
1379         myIpAddr = getMyIpAddr("eth0");
1380 #endif
1381         myIndexInHostArray = findHost(myIpAddr);
1382         if (myIndexInHostArray == -1)
1383         {
1384                 printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME);
1385                 return -1;
1386         }
1387         oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1;
1388         oidMin = oidsPerBlock * myIndexInHostArray;
1389         if (myIndexInHostArray == numHostsInSystem - 1)
1390                 oidMax = 0xFFFFFFFF;
1391         else
1392                 oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1;
1393
1394         return 0;
1395 }
1396
1397 void addHost(unsigned int hostIp)
1398 {
1399         unsigned int *tmpArray;
1400
1401         if (findHost(hostIp) != -1)
1402                 return;
1403
1404         if (numHostsInSystem == sizeOfHostArray)
1405         {
1406                 tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int));
1407                 memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem);
1408                 free(hostIpAddrs);
1409                 hostIpAddrs = tmpArray;
1410         }
1411
1412         hostIpAddrs[numHostsInSystem++] = hostIp;
1413
1414         return;
1415 }
1416
1417 int findHost(unsigned int hostIp)
1418 {
1419         int i;
1420         for (i = 0; i < numHostsInSystem; i++)
1421                 if (hostIpAddrs[i] == hostIp)
1422                         return i;
1423
1424         //not found
1425         return -1;
1426 }
1427
1428 /* This function sends notification request per thread waiting on object(s) whose version 
1429  * changes */
1430 int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int numoid) {
1431         int sock,i;
1432         objheader_t *objheader;
1433         struct sockaddr_in remoteAddr;
1434         char msg[1 + numoid * (sizeof(unsigned short) + sizeof(unsigned int)) +  3 * sizeof(unsigned int)];
1435         char *ptr;
1436         int bytesSent;
1437         int status, size;
1438         unsigned short version;
1439         unsigned int oid,mid;
1440         static unsigned int threadid = 0;
1441         pthread_mutex_t threadnotify = PTHREAD_MUTEX_INITIALIZER; //Lock and condition var for threadjoin and notification
1442         pthread_cond_t threadcond = PTHREAD_COND_INITIALIZER;
1443         notifydata_t *ndata;
1444
1445         oid = oidarry[0];
1446         if((mid = lhashSearch(oid)) == 0) {
1447                 printf("Error: %s() No such machine found for oid =%x\n",__func__, oid);
1448                 return;
1449         }
1450
1451         if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1452                 perror("reqNotify():socket()");
1453                 return -1;
1454         }
1455
1456         bzero(&remoteAddr, sizeof(remoteAddr));
1457         remoteAddr.sin_family = AF_INET;
1458         remoteAddr.sin_port = htons(LISTEN_PORT);
1459         remoteAddr.sin_addr.s_addr = htonl(mid);
1460
1461         /* Generate unique threadid */
1462         threadid++;
1463
1464         /* Save threadid, numoid, oidarray, versionarray, pthread_cond_variable for later processing */
1465         if((ndata = calloc(1, sizeof(notifydata_t))) == NULL) {
1466                 printf("Calloc Error %s, %d\n", __FILE__, __LINE__);
1467                 return -1;
1468         }
1469         ndata->numoid = numoid;
1470         ndata->threadid = threadid;
1471         ndata->oidarry = oidarry;
1472         ndata->versionarry = versionarry;
1473         ndata->threadcond = threadcond;
1474         ndata->threadnotify = threadnotify;
1475         if((status = notifyhashInsert(threadid, ndata)) != 0) {
1476                 printf("reqNotify(): Insert into notify hash table not successful %s, %d\n", __FILE__, __LINE__);
1477                 free(ndata);
1478                 return -1; 
1479         }
1480         
1481         /* Send  number of oids, oidarry, version array, machine id and threadid */     
1482         if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1483                 printf("reqNotify():error %d connecting to %s:%d\n", errno,
1484                                 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1485                 free(ndata);
1486                 return -1;
1487         } else {
1488                 msg[0] = THREAD_NOTIFY_REQUEST;
1489                 *((unsigned int *)(&msg[1])) = numoid;
1490                 /* Send array of oids  */
1491                 size = sizeof(unsigned int);
1492                 {
1493                         i = 0;
1494                         while(i < numoid) {
1495                                 oid = oidarry[i];
1496                                 *((unsigned int *)(&msg[1] + size)) = oid;
1497                                 size += sizeof(unsigned int);
1498                                 i++;
1499                         }
1500                 }
1501
1502                 /* Send array of version  */
1503                 {
1504                         i = 0;
1505                         while(i < numoid) {
1506                                 version = versionarry[i];
1507                                 *((unsigned short *)(&msg[1] + size)) = version;
1508                                 size += sizeof(unsigned short);
1509                                 i++;
1510                         }
1511                 }
1512
1513                 *((unsigned int *)(&msg[1] + size)) = myIpAddr;
1514                 size += sizeof(unsigned int);
1515                 *((unsigned int *)(&msg[1] + size)) = threadid;
1516                 pthread_mutex_lock(&(ndata->threadnotify));
1517                 size = 1 + numoid * (sizeof(unsigned int) + sizeof(unsigned short)) + 3 * sizeof(unsigned int);
1518                 send_data(sock, msg, size);
1519                 pthread_cond_wait(&(ndata->threadcond), &(ndata->threadnotify));
1520                 pthread_mutex_unlock(&(ndata->threadnotify));
1521         }
1522
1523         pthread_cond_destroy(&threadcond);
1524         pthread_mutex_destroy(&threadnotify);
1525         free(ndata);
1526         close(sock);
1527         return status;
1528 }
1529
1530 void threadNotify(unsigned int oid, unsigned short version, unsigned int tid) {
1531         notifydata_t *ndata;
1532         int i, objIsFound = 0, index;
1533         void *ptr;
1534
1535         //Look up the tid and call the corresponding pthread_cond_signal
1536         if((ndata = notifyhashSearch(tid)) == NULL) {
1537                 printf("threadnotify(): No such threadid is present %s, %d\n", __FILE__, __LINE__);
1538                 return;
1539         } else  {
1540                 for(i = 0; i < ndata->numoid; i++) {
1541                         if(ndata->oidarry[i] == oid){
1542                                 objIsFound = 1;
1543                                 index = i;
1544                         }
1545                 }
1546                 if(objIsFound == 0){
1547                         printf("threadNotify(): Oid not found %s, %d\n", __FILE__, __LINE__);
1548                         return;
1549                 } else {
1550                         if(version <= ndata->versionarry[index]){
1551                                 printf("threadNotify(): New version %d has not changed since last version %s, %d\n", version, __FILE__, __LINE__);
1552                                 return;
1553                         } else {
1554                                 /* Clear from prefetch cache and free thread related data structure */
1555                                 if((ptr = prehashSearch(oid)) != NULL) {
1556                                         prehashRemove(oid);
1557                                 }
1558                                 pthread_cond_signal(&(ndata->threadcond));
1559                         }
1560                 }
1561         }
1562         return;
1563 }
1564
1565 int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) {
1566         threadlist_t *ptr;
1567         unsigned int mid;
1568         struct sockaddr_in remoteAddr;
1569         char msg[1 + sizeof(unsigned short) + 2*sizeof(unsigned int)];
1570         int sock, status, size, bytesSent;
1571
1572         while(*head != NULL) {
1573                 ptr = *head;
1574                 mid = ptr->mid; 
1575                 //create a socket connection to that machine
1576                 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
1577                         perror("notifyAll():socket()");
1578                         return -1;
1579                 }
1580
1581                 bzero(&remoteAddr, sizeof(remoteAddr));
1582                 remoteAddr.sin_family = AF_INET;
1583                 remoteAddr.sin_port = htons(LISTEN_PORT);
1584                 remoteAddr.sin_addr.s_addr = htonl(mid);
1585                 //send Thread Notify response and threadid to that machine
1586                 if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
1587                         printf("notifyAll():error %d connecting to %s:%d\n", errno,
1588                                         inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
1589                         status = -1;
1590             fflush(stdout);
1591                 } else {
1592                         bzero(msg, (1+sizeof(unsigned short) + 2*sizeof(unsigned int)));
1593                         msg[0] = THREAD_NOTIFY_RESPONSE;
1594                         *((unsigned int *)&msg[1]) = oid;
1595                         size = sizeof(unsigned int);
1596                         *((unsigned short *)(&msg[1]+ size)) = version;
1597                         size+= sizeof(unsigned short);
1598                         *((unsigned int *)(&msg[1]+ size)) = ptr->threadid;
1599
1600                         size = 1 + 2*sizeof(unsigned int) + sizeof(unsigned short);
1601                         send_data(sock, msg, size);
1602                 }
1603                 //close socket
1604                 close(sock);
1605                 // Update head
1606                 *head = ptr->next;
1607                 free(ptr);
1608         }
1609         return status;
1610 }
1611
1612 void transAbort(transrecord_t *trans) {
1613   objstrDelete(trans->cache);
1614   chashDelete(trans->lookupTable);
1615   free(trans);
1616 }