bug fix
[IRC.git] / Robust / src / Runtime / DSTM / interface / dstmserver.c
1 /* Coordinator => Machine that initiates the transaction request call for commiting a transaction
2  * Participant => Machines that host the objects involved in a transaction commit */
3
4 #include <netinet/tcp.h>
5 #include "dstm.h"
6 #include "mlookup.h"
7 #include "llookup.h"
8 #include "threadnotify.h"
9 #include "prefetch.h"
10 #include <sched.h>
11 #ifdef COMPILER
12 #include "thread.h"
13 #endif
14 #include "gCollect.h"
15 #include "readstruct.h"
16
17 #define BACKLOG 10 //max pending connections
18 #define RECEIVE_BUFFER_SIZE 2048
19
20 extern int classsize[];
21 extern int numHostsInSystem;
22 extern pthread_mutex_t notifymutex;
23
24 objstr_t *mainobjstore;
25 pthread_mutex_t mainobjstore_mutex;
26 pthread_mutex_t lockObjHeader;
27 pthread_mutexattr_t mainobjstore_mutex_attr; /* Attribute for lock to make it a recursive lock */
28
29 sockPoolHashTable_t *transPResponseSocketPool;
30
31 /* This function initializes the main objects store and creates the
32  * global machine and location lookup table */
33
34 int dstmInit(void) {
35   mainobjstore = objstrCreate(DEFAULT_OBJ_STORE_SIZE);
36   /* Initialize attribute for mutex */
37   pthread_mutexattr_init(&mainobjstore_mutex_attr);
38   pthread_mutexattr_settype(&mainobjstore_mutex_attr, PTHREAD_MUTEX_RECURSIVE_NP);
39   pthread_mutex_init(&mainobjstore_mutex, &mainobjstore_mutex_attr);
40   pthread_mutex_init(&lockObjHeader,NULL);
41   if (mhashCreate(MHASH_SIZE, MLOADFACTOR))
42     return 1;             //failure
43
44   if (lhashCreate(HASH_SIZE, LOADFACTOR))
45     return 1;             //failure
46
47   if (notifyhashCreate(N_HASH_SIZE, N_LOADFACTOR))
48     return 1;             //failure
49
50   //Initialize socket pool
51   if((transPResponseSocketPool = createSockPool(transPResponseSocketPool, DEFAULTSOCKPOOLSIZE)) == NULL) {
52     printf("Error in creating new socket pool at  %s line %d\n", __FILE__, __LINE__);
53     return 0;
54   }
55
56   return 0;
57 }
58
59
60 int startlistening() {
61   int listenfd;
62   struct sockaddr_in my_addr;
63   socklen_t addrlength = sizeof(struct sockaddr);
64   int setsockflag=1;
65
66   listenfd = socket(AF_INET, SOCK_STREAM, 0);
67   if (listenfd == -1) {
68     perror("socket");
69     exit(1);
70   }
71
72   if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &setsockflag, sizeof (setsockflag)) < 0) {
73     perror("socket");
74     exit(1);
75   }
76 #ifdef MAC
77   if (setsockopt(listenfd, SOL_SOCKET, SO_NOSIGPIPE, &setsockflag, sizeof (setsockflag)) < 0) {
78     perror("socket");
79     exit(1);
80   }
81 #endif
82
83   my_addr.sin_family = AF_INET;
84   my_addr.sin_port = htons(LISTEN_PORT);
85   my_addr.sin_addr.s_addr = INADDR_ANY;
86   memset(&(my_addr.sin_zero), '\0', 8);
87
88   if (bind(listenfd, (struct sockaddr *)&my_addr, addrlength) == -1) {
89     perror("bind");
90     exit(1);
91   }
92
93   if (listen(listenfd, BACKLOG) == -1) {
94     perror("listen");
95     exit(1);
96   }
97   return listenfd;
98 }
99
100 /* This function starts the thread to listen on a socket
101  * for tranaction calls */
102 void *dstmListen(void *lfd) {
103   int listenfd=(int)lfd;
104   int acceptfd;
105   struct sockaddr_in client_addr;
106   socklen_t addrlength = sizeof(struct sockaddr);
107   pthread_t thread_dstm_accept;
108
109   printf("Listening on port %d, fd = %d\n", LISTEN_PORT, listenfd);
110   while(1) {
111     int retval;
112     int flag=1;
113     acceptfd = accept(listenfd, (struct sockaddr *)&client_addr, &addrlength);
114     setsockopt(acceptfd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(flag));
115     do {
116       retval=pthread_create(&thread_dstm_accept, NULL, dstmAccept, (void *)acceptfd);
117     } while(retval!=0);
118     pthread_detach(thread_dstm_accept);
119   }
120 }
121 /* This function accepts a new connection request, decodes the control message in the connection
122  * and accordingly calls other functions to process new requests */
123 void *dstmAccept(void *acceptfd) {
124   int val, retval, size, sum, sockid;
125   unsigned int oid;
126   char *buffer;
127   char control,ctrl;
128   char *ptr;
129   void *srcObj;
130   objheader_t *h;
131   trans_commit_data_t transinfo;
132   unsigned short objType, *versionarry, version;
133   unsigned int *oidarry, numoid, mid, threadid;
134   struct readstruct readbuffer;
135   readbuffer.head=0;
136   readbuffer.tail=0;
137
138   /* Receive control messages from other machines */
139   while(1) {
140     int ret=recv_data_errorcode_buf((int)acceptfd, &readbuffer, &control, sizeof(char));
141     if (ret==0)
142       break;
143     if (ret==-1) {
144       printf("DEBUG -> RECV Error!.. retrying\n");
145       break;
146     }
147     switch(control) {
148     case READ_REQUEST:
149       /* Read oid requested and search if available */
150       recv_data_buf((int)acceptfd, &readbuffer, &oid, sizeof(unsigned int));
151       while((srcObj = mhashSearch(oid)) == NULL) {
152         int ret;
153         if((ret = sched_yield()) != 0) {
154           printf("%s(): error no %d in thread yield\n", __func__, errno);
155         }
156       }
157       h = (objheader_t *) srcObj;
158       GETSIZE(size, h);
159       size += sizeof(objheader_t);
160       sockid = (int) acceptfd;
161       if (h == NULL) {
162         ctrl = OBJECT_NOT_FOUND;
163         send_data(sockid, &ctrl, sizeof(char));
164       } else {
165         // Type
166         char msg[]={OBJECT_FOUND, 0, 0, 0, 0};
167         *((int *)&msg[1])=size;
168         send_data(sockid, &msg, sizeof(msg));
169         send_data(sockid, h, size);
170       }
171       break;
172
173     case READ_MULT_REQUEST:
174       break;
175
176     case MOVE_REQUEST:
177       break;
178
179     case MOVE_MULT_REQUEST:
180       break;
181
182     case TRANS_REQUEST:
183       /* Read transaction request */
184       transinfo.objlocked = NULL;
185       transinfo.objnotfound = NULL;
186       transinfo.modptr = NULL;
187       transinfo.numlocked = 0;
188       transinfo.numnotfound = 0;
189       if((val = readClientReq(&transinfo, (int)acceptfd, &readbuffer)) != 0) {
190         printf("Error: In readClientReq() %s, %d\n", __FILE__, __LINE__);
191         pthread_exit(NULL);
192       }
193       break;
194
195     case TRANS_PREFETCH:
196 #ifdef RANGEPREFETCH
197       if((val = rangePrefetchReq((int)acceptfd, &readbuffer)) != 0) {
198         printf("Error: In rangePrefetchReq() %s, %d\n", __FILE__, __LINE__);
199         break;
200       }
201 #else
202       if((val = prefetchReq((int)acceptfd, &readbuffer)) != 0) {
203         printf("Error: In prefetchReq() %s, %d\n", __FILE__, __LINE__);
204         break;
205       }
206 #endif
207       break;
208
209     case TRANS_PREFETCH_RESPONSE:
210 #ifdef RANGEPREFETCH
211       if((val = getRangePrefetchResponse((int)acceptfd, &readbuffer)) != 0) {
212         printf("Error: In getRangePrefetchRespose() %s, %d\n", __FILE__, __LINE__);
213         break;
214       }
215 #else
216       if((val = getPrefetchResponse((int) acceptfd, &readbuffer)) != 0) {
217         printf("Error: In getPrefetchResponse() %s, %d\n", __FILE__, __LINE__);
218         break;
219       }
220 #endif
221       break;
222
223     case START_REMOTE_THREAD:
224       recv_data_buf((int)acceptfd, &readbuffer, &oid, sizeof(unsigned int));
225       objType = getObjType(oid);
226       startDSMthread(oid, objType);
227       break;
228
229     case THREAD_NOTIFY_REQUEST:
230       recv_data_buf((int)acceptfd, &readbuffer, &numoid, sizeof(unsigned int));
231       size = (sizeof(unsigned int) + sizeof(unsigned short)) * numoid + 2 * sizeof(unsigned int);
232       if((buffer = calloc(1,size)) == NULL) {
233         printf("%s() Calloc error at %s, %d\n", __func__, __FILE__, __LINE__);
234         pthread_exit(NULL);
235       }
236
237       recv_data_buf((int)acceptfd, &readbuffer, buffer, size);
238
239       oidarry = calloc(numoid, sizeof(unsigned int));
240       memcpy(oidarry, buffer, sizeof(unsigned int) * numoid);
241       size = sizeof(unsigned int) * numoid;
242       versionarry = calloc(numoid, sizeof(unsigned short));
243       memcpy(versionarry, buffer+size, sizeof(unsigned short) * numoid);
244       size += sizeof(unsigned short) * numoid;
245       mid = *((unsigned int *)(buffer+size));
246       size += sizeof(unsigned int);
247       threadid = *((unsigned int *)(buffer+size));
248       processReqNotify(numoid, oidarry, versionarry, mid, threadid);
249       free(buffer);
250       break;
251
252     case THREAD_NOTIFY_RESPONSE:
253       size = sizeof(unsigned short) + 2 * sizeof(unsigned int);
254       if((buffer = calloc(1,size)) == NULL) {
255         printf("%s() Calloc error at %s, %d\n", __func__, __FILE__, __LINE__);
256         pthread_exit(NULL);
257       }
258
259       recv_data_buf((int)acceptfd, &readbuffer, buffer, size);
260
261       oid = *((unsigned int *)buffer);
262       size = sizeof(unsigned int);
263       version = *((unsigned short *)(buffer+size));
264       size += sizeof(unsigned short);
265       threadid = *((unsigned int *)(buffer+size));
266       threadNotify(oid,version,threadid);
267       free(buffer);
268       break;
269
270     case CLOSE_CONNECTION:
271       goto closeconnection;
272
273     default:
274       printf("Error: dstmAccept() Unknown opcode %d at %s, %d\n", control, __FILE__, __LINE__);
275     }
276   }
277
278 closeconnection:
279   /* Close connection */
280   if (close((int)acceptfd) == -1)
281     perror("close");
282   pthread_exit(NULL);
283 }
284
285 /* This function reads the information available in a transaction request
286  * and makes a function call to process the request */
287 int readClientReq(trans_commit_data_t *transinfo, int acceptfd, struct readstruct * readbuffer) {
288   char *ptr;
289   void *modptr;
290   unsigned int *oidmod, oid;
291   fixed_data_t fixed;
292   objheader_t *headaddr;
293   int sum, i, size, n, val;
294
295   oidmod = NULL;
296
297   /* Read fixed_data_t data structure */
298   size = sizeof(fixed) - 1;
299   ptr = (char *)&fixed;;
300   fixed.control = TRANS_REQUEST;
301   recv_data_buf((int)acceptfd, readbuffer, ptr+1, size);
302
303   /* Read list of mids */
304   int mcount = fixed.mcount;
305   size = mcount * sizeof(unsigned int);
306   unsigned int listmid[mcount];
307   ptr = (char *) listmid;
308   recv_data_buf((int)acceptfd, readbuffer, ptr, size);
309
310   /* Read oid and version tuples for those objects that are not modified in the transaction */
311   int numread = fixed.numread;
312   size = numread * (sizeof(unsigned int) + sizeof(unsigned short));
313   char objread[size];
314   if(numread != 0) { //If pile contains more than one object to be read,
315     // keep reading all objects
316     recv_data_buf((int)acceptfd, readbuffer, objread, size);
317   }
318
319   /* Read modified objects */
320   if(fixed.nummod != 0) {
321     if ((modptr = calloc(1, fixed.sum_bytes)) == NULL) {
322       printf("calloc error for modified objects %s, %d\n", __FILE__, __LINE__);
323       return 1;
324     }
325     size = fixed.sum_bytes;
326     recv_data_buf((int)acceptfd, readbuffer, modptr, size);
327   }
328
329   /* Create an array of oids for modified objects */
330   oidmod = (unsigned int *) calloc(fixed.nummod, sizeof(unsigned int));
331   if (oidmod == NULL) {
332     printf("calloc error %s, %d\n", __FILE__, __LINE__);
333     return 1;
334   }
335   ptr = (char *) modptr;
336   for(i = 0 ; i < fixed.nummod; i++) {
337     int tmpsize;
338     headaddr = (objheader_t *) ptr;
339     oid = OID(headaddr);
340     oidmod[i] = oid;
341     GETSIZE(tmpsize, headaddr);
342     ptr += sizeof(objheader_t) + tmpsize;
343   }
344
345   /*Process the information read */
346   if((val = processClientReq(&fixed, transinfo, listmid, objread, modptr, oidmod, acceptfd, readbuffer)) != 0) {
347     printf("Error: In processClientReq() %s, %d\n", __FILE__, __LINE__);
348     /* Free resources */
349     if(oidmod != NULL) {
350       free(oidmod);
351     }
352     return 1;
353   }
354
355   /* Free resources */
356   if(oidmod != NULL) {
357     free(oidmod);
358   }
359
360   return 0;
361 }
362
363 /* This function processes the Coordinator's transaction request using "handleTransReq"
364  * function and sends a reply to the co-ordinator.
365  * Following this it also receives a new control message from the co-ordinator and processes this message*/
366 int processClientReq(fixed_data_t *fixed, trans_commit_data_t *transinfo,
367                      unsigned int *listmid, char *objread, void *modptr, unsigned int *oidmod, int acceptfd, struct readstruct *readbuffer) {
368
369   char control, sendctrl, retval;
370   objheader_t *tmp_header;
371   void *header;
372   int i = 0, val;
373
374   /* Send reply to the Coordinator */
375   if((retval = handleTransReq(fixed, transinfo, listmid, objread, modptr,acceptfd)) == 0 ) {
376     printf("Error: In handleTransReq() %s, %d\n", __FILE__, __LINE__);
377     return 1;
378   }
379
380   recv_data_buf((int)acceptfd, readbuffer, &control, sizeof(char));
381   /* Process the new control message */
382   switch(control) {
383   case TRANS_ABORT:
384     if (fixed->nummod > 0)
385       free(modptr);
386     /* Unlock objects that was locked due to this transaction */
387     int useWriteUnlock = 0;
388     for(i = 0; i< transinfo->numlocked; i++) {
389       if(transinfo->objlocked[i] == -1) {
390         useWriteUnlock = 1;
391         continue;
392       }
393       if((header = mhashSearch(transinfo->objlocked[i])) == NULL) {
394         printf("mhashSearch returns NULL at %s, %d\n", __FILE__, __LINE__); // find the header address
395         return 1;
396       }
397       if(useWriteUnlock) {
398         write_unlock(STATUSPTR(header));
399       } else {
400         read_unlock(STATUSPTR(header));
401       }
402     }
403     break;
404
405   case TRANS_COMMIT:
406     /* Invoke the transCommit process() */
407     if((val = transCommitProcess(modptr, oidmod, transinfo->objlocked, fixed->nummod, transinfo->numlocked, (int)acceptfd)) != 0) {
408       printf("Error: In transCommitProcess() %s, %d\n", __FILE__, __LINE__);
409       /* Free memory */
410       if (transinfo->objlocked != NULL) {
411         free(transinfo->objlocked);
412       }
413       if (transinfo->objnotfound != NULL) {
414         free(transinfo->objnotfound);
415       }
416       return 1;
417     }
418     break;
419
420   case TRANS_ABORT_BUT_RETRY_COMMIT_WITH_RELOCATING:
421     break;
422
423   default:
424     printf("Error: No response to TRANS_AGREE OR DISAGREE protocol %s, %d\n", __FILE__, __LINE__);
425     //TODO Use fixed.trans_id  TID since Client may have died
426     break;
427   }
428
429   /* Free memory */
430   if (transinfo->objlocked != NULL) {
431     free(transinfo->objlocked);
432   }
433   if (transinfo->objnotfound != NULL) {
434     free(transinfo->objnotfound);
435   }
436
437   return 0;
438 }
439
440 /* This function increments counters while running a voting decision on all objects involved
441  * in TRANS_REQUEST and If a TRANS_DISAGREE sends the response immediately back to the coordinator */
442 char handleTransReq(fixed_data_t *fixed, trans_commit_data_t *transinfo, unsigned int *listmid, char *objread, void *modptr, int acceptfd) {
443   int val, i = 0, j;
444   unsigned short version;
445   char control = 0, *ptr;
446   unsigned int oid;
447   unsigned int *oidnotfound, *oidlocked, *oidvernotmatch;
448   objheader_t *headptr;
449
450   /* Counters and arrays to formulate decision on control message to be sent */
451   oidnotfound = (unsigned int *) calloc(fixed->numread + fixed->nummod, sizeof(unsigned int));
452   oidlocked = (unsigned int *) calloc(fixed->numread + fixed->nummod + 1, sizeof(unsigned int));
453   oidvernotmatch = (unsigned int *) calloc(fixed->numread + fixed->nummod, sizeof(unsigned int));
454   int objnotfound = 0, objlocked = 0, objvernotmatch = 0;
455   int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
456   int numBytes = 0;
457   /* modptr points to the beginning of the object store
458    * created at the Pariticipant.
459    * Object store holds the modified objects involved in the transaction request */
460   ptr = (char *) modptr;
461
462   /* Process each oid in the machine pile/ group per thread */
463   for (i = 0; i < fixed->numread + fixed->nummod; i++) {
464     if (i < fixed->numread) { //Objs only read and not modified
465       int incr = sizeof(unsigned int) + sizeof(unsigned short); // Offset that points to next position in the objread array
466       incr *= i;
467       oid = *((unsigned int *)(objread + incr));
468       incr += sizeof(unsigned int);
469       version = *((unsigned short *)(objread + incr));
470       getCommitCountForObjRead(oidnotfound, oidlocked, oidvernotmatch, &objnotfound, &objlocked, &objvernotmatch,
471                                &v_matchnolock, &v_matchlock, &v_nomatch, &numBytes, &control, oid, version);
472     } else {  //Objs modified
473       if(i == fixed->numread) {
474         oidlocked[objlocked++] = -1;
475       }
476       int tmpsize;
477       headptr = (objheader_t *) ptr;
478       oid = OID(headptr);
479       version = headptr->version;
480       GETSIZE(tmpsize, headptr);
481       ptr += sizeof(objheader_t) + tmpsize;
482       getCommitCountForObjMod(oidnotfound, oidlocked, oidvernotmatch, &objnotfound,
483                               &objlocked, &objvernotmatch, &v_matchnolock, &v_matchlock, &v_nomatch,
484                               &numBytes, &control, oid, version);
485     }
486   }
487
488   /* send TRANS_DISAGREE and objs*/
489   if(v_nomatch > 0) {
490 #ifdef CACHE
491     char *objs = calloc(1, numBytes);
492     int j, offset = 0;
493     for(j = 0; j<objvernotmatch; j++) {
494       objheader_t *header = mhashSearch(oidvernotmatch[j]);
495       int size = 0;
496       GETSIZE(size, header);
497       size += sizeof(objheader_t);
498       memcpy(objs+offset, header, size);
499       offset += size;
500     }
501 #endif
502     if (objlocked > 0) {
503       int useWriteUnlock = 0;
504       for(j = 0; j < objlocked; j++) {
505         if(oidlocked[j] == -1) {
506           useWriteUnlock = 1;
507           continue;
508         }
509         if((headptr = mhashSearch(oidlocked[j])) == NULL) {
510           printf("mhashSearch returns NULL at %s, %d\n", __FILE__, __LINE__);
511           return 0;
512         }
513         if(useWriteUnlock) {
514           write_unlock(STATUSPTR(headptr));
515         } else {
516           read_unlock(STATUSPTR(headptr));
517         }
518       }
519       free(oidlocked);
520     }
521     send_data(acceptfd, &control, sizeof(char));
522 #ifdef CACHE
523     send_data(acceptfd, &numBytes, sizeof(int));
524     send_data(acceptfd, objs, numBytes);
525     transinfo->objvernotmatch = oidvernotmatch;
526     transinfo->numvernotmatch = objvernotmatch;
527     free(objs);
528     free(transinfo->objvernotmatch);
529 #endif
530     return control;
531   }
532
533   /* Decide what control message to send to Coordinator */
534   if ((control = decideCtrlMessage(fixed, transinfo, &v_matchnolock, &v_matchlock, &v_nomatch, &objnotfound, &objlocked,
535                                    modptr, oidnotfound, oidlocked, acceptfd)) == 0) {
536     printf("Error: In decideCtrlMessage() %s, %d\n", __FILE__, __LINE__);
537     return 0;
538   }
539   return control;
540 }
541
542 /* Update Commit info for objects that are read */
543 void getCommitCountForObjMod(unsigned int *oidnotfound, unsigned int *oidlocked,
544                              unsigned int *oidvernotmatch, int *objnotfound, int *objlocked, int *objvernotmatch,
545                              int *v_matchnolock, int *v_matchlock, int *v_nomatch, int *numBytes,
546                              char *control, unsigned int oid, unsigned short version) {
547   void *mobj;
548   /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
549
550   if ((mobj = mhashSearch(oid)) == NULL) {    /* Obj not found */
551     /* Save the oids not found and number of oids not found for later use */
552     oidnotfound[*objnotfound] = oid;
553     (*objnotfound)++;
554   } else {     /* If Obj found in machine (i.e. has not moved) */
555     /* Check if Obj is locked by any previous transaction */
556     if (write_trylock(STATUSPTR(mobj))) { // Can acquire write lock
557       if (version == ((objheader_t *)mobj)->version) { /* match versions */
558         (*v_matchnolock)++;
559       } else { /* If versions don't match ...HARD ABORT */
560         (*v_nomatch)++;
561         oidvernotmatch[*objvernotmatch] = oid;
562         (*objvernotmatch)++;
563         int size;
564         GETSIZE(size, mobj);
565         size += sizeof(objheader_t);
566         *numBytes += size;
567         /* Send TRANS_DISAGREE to Coordinator */
568         *control = TRANS_DISAGREE;
569         //printf("%s() oid = %d, type = %d\t", __func__, OID(mobj), TYPE((objheader_t *)mobj));
570       }
571       //Keep track of oid locked
572       oidlocked[(*objlocked)++] = OID(((objheader_t *)mobj));
573     } else {  //we are locked
574       if (version == ((objheader_t *)mobj)->version) {     /* Check if versions match */
575         (*v_matchlock)++;
576       } else { /* If versions don't match ...HARD ABORT */
577         (*v_nomatch)++;
578         oidvernotmatch[*objvernotmatch] = oid;
579         (*objvernotmatch)++;
580         int size;
581         GETSIZE(size, mobj);
582         size += sizeof(objheader_t);
583         *numBytes += size;
584         *control = TRANS_DISAGREE;
585         //printf("%s() oid = %d, type = %d\t", __func__, OID(mobj), TYPE((objheader_t *)mobj));
586       }
587     }
588   }
589 }
590
591 /* Update Commit info for objects that are read */
592 void getCommitCountForObjRead(unsigned int *oidnotfound, unsigned int *oidlocked, unsigned int *oidvernotmatch,
593                               int *objnotfound, int *objlocked, int * objvernotmatch, int *v_matchnolock, int *v_matchlock,
594                               int *v_nomatch, int *numBytes, char *control, unsigned int oid, unsigned short version) {
595   void *mobj;
596   /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
597   if ((mobj = mhashSearch(oid)) == NULL) {    /* Obj not found */
598     /* Save the oids not found and number of oids not found for later use */
599     oidnotfound[*objnotfound] = oid;
600     (*objnotfound)++;
601   } else {     /* If Obj found in machine (i.e. has not moved) */
602     /* Check if Obj is locked by any previous transaction */
603     if (read_trylock(STATUSPTR(mobj))) { //Can further acquire read locks
604       if (version == ((objheader_t *)mobj)->version) { /* match versions */
605         (*v_matchnolock)++;
606       } else { /* If versions don't match ...HARD ABORT */
607         (*v_nomatch)++;
608         oidvernotmatch[(*objvernotmatch)++] = oid;
609         int size;
610         GETSIZE(size, mobj);
611         size += sizeof(objheader_t);
612         *numBytes += size;
613         /* Send TRANS_DISAGREE to Coordinator */
614         *control = TRANS_DISAGREE;
615         //printf("%s() oid = %d, type = %d\t", __func__, OID(mobj), TYPE((objheader_t *)mobj));
616       }
617       //Keep track of oid locked
618       oidlocked[(*objlocked)++] = OID(((objheader_t *)mobj));
619     } else { /* Some other transaction has aquired a write lock on this object */
620       if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
621         (*v_matchlock)++;
622       } else { /* If versions don't match ...HARD ABORT */
623         (*v_nomatch)++;
624         oidvernotmatch[*objvernotmatch] = oid;
625         (*objvernotmatch)++;
626         int size;
627         GETSIZE(size, mobj);
628         size += sizeof(objheader_t);
629         *numBytes += size;
630         *control = TRANS_DISAGREE;
631         //printf("%s() oid = %d, type = %d\t", __func__, OID(mobj), TYPE((objheader_t *)mobj));
632       }
633     }
634   }
635 }
636
637 /* This function decides what control message such as TRANS_AGREE, TRANS_DISAGREE or TRANS_SOFT_ABORT
638  * to send to Coordinator based on the votes of oids involved in the transaction */
639 char decideCtrlMessage(fixed_data_t *fixed, trans_commit_data_t *transinfo, int *v_matchnolock, int *v_matchlock,
640                        int *v_nomatch, int *objnotfound, int *objlocked, void *modptr,
641                        unsigned int *oidnotfound, unsigned int *oidlocked, int acceptfd) {
642   int val;
643   char control = 0;
644
645   /* Condition to send TRANS_AGREE */
646   if(*(v_matchnolock) == fixed->numread + fixed->nummod) {
647     control = TRANS_AGREE;
648     /* Send control message */
649     send_data(acceptfd, &control, sizeof(char));
650   }
651   /* Condition to send TRANS_SOFT_ABORT */
652   if((*(v_matchlock) > 0 && *(v_nomatch) == 0) || (*(objnotfound) > 0 && *(v_nomatch) == 0)) {
653     control = TRANS_SOFT_ABORT;
654
655     /* Send control message */
656     send_data(acceptfd, &control, sizeof(char));
657
658     /*  FIXME how to send objs Send number of oids not found and the missing oids if objects are missing in the machine */
659     if(*(objnotfound) != 0) {
660       int msg[1];
661       msg[0] = *(objnotfound);
662       send_data(acceptfd, &msg, sizeof(int));
663       int size = sizeof(unsigned int)* *(objnotfound);
664       send_data(acceptfd, oidnotfound, size);
665     }
666   }
667
668   /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
669    * if Participant receives a TRANS_COMMIT */
670   transinfo->objlocked = oidlocked;
671   transinfo->objnotfound = oidnotfound;
672   transinfo->modptr = modptr;
673   transinfo->numlocked = *(objlocked);
674   transinfo->numnotfound = *(objnotfound);
675   return control;
676 }
677
678 /* This function processes all modified objects involved in a TRANS_COMMIT and updates pointer
679  * addresses in lookup table and also changes version number
680  * Sends an ACK back to Coordinator */
681 int transCommitProcess(void *modptr, unsigned int *oidmod, unsigned int *oidlocked, int nummod, int numlocked, int acceptfd) {
682   objheader_t *header;
683   objheader_t *newheader;
684   int i = 0, offset = 0;
685   char control;
686   int tmpsize;
687
688   /* Process each modified object saved in the mainobject store */
689   for(i = 0; i < nummod; i++) {
690     if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
691       printf("Error: mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
692       return 1;
693     }
694     GETSIZE(tmpsize,header);
695
696     {
697       struct ___Object___ *dst=(struct ___Object___*)((char*)header+sizeof(objheader_t));
698       struct ___Object___ *src=(struct ___Object___*)((char*)modptr+sizeof(objheader_t)+offset);
699       dst->type=src->type;
700       dst->___cachedCode___=src->___cachedCode___;
701       dst->___cachedHash___=src->___cachedHash___;
702       memcpy(&dst[1], &src[1], tmpsize-sizeof(struct ___Object___));
703     }
704     header->version += 1;
705     /* If threads are waiting on this object to be updated, notify them */
706     if(header->notifylist != NULL) {
707       notifyAll(&header->notifylist, OID(header), header->version);
708     }
709     offset += sizeof(objheader_t) + tmpsize;
710   }
711
712   if (nummod > 0)
713     free(modptr);
714
715   /* Unlock locked objects */
716   int useWriteUnlock = 0;
717   for(i = 0; i < numlocked; i++) {
718     if(oidlocked[i] == -1) {
719       useWriteUnlock = 1;
720       continue;
721     }
722     if((header = (objheader_t *) mhashSearch(oidlocked[i])) == NULL) {
723       printf("Error: mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
724       return 1;
725     }
726
727     if(useWriteUnlock) {
728       write_unlock(STATUSPTR(header));
729     } else {
730       read_unlock(STATUSPTR(header));
731     }
732   }
733   //TODO Update location lookup table
734   return 0;
735 }
736
737 /* This function recevies the oid and offset tuples from the Coordinator's prefetch call.
738  * Looks for the objects to be prefetched in the main object store.
739  * If objects are not found then record those and if objects are found
740  * then use offset values to prefetch references to other objects */
741
742 int prefetchReq(int acceptfd, struct readstruct * readbuffer) {
743   int i, size, objsize, numoffset = 0;
744   int length;
745   char *recvbuffer, control;
746   unsigned int oid, mid=-1;
747   objheader_t *header;
748   oidmidpair_t oidmid;
749   int sd = -1;
750   while(1) {
751     recv_data_buf((int)acceptfd, readbuffer, &numoffset, sizeof(int));
752     if(numoffset == -1)
753       break;
754     recv_data_buf((int)acceptfd, readbuffer, &oidmid, 2*sizeof(unsigned int));
755     oid = oidmid.oid;
756     if (mid != oidmid.mid) {
757       if (mid!=-1) {
758         freeSockWithLock(transPResponseSocketPool, mid, sd);
759       }
760       mid=oidmid.mid;
761       sd = getSockWithLock(transPResponseSocketPool, mid);
762     }
763     short offsetarry[numoffset];
764     recv_data_buf((int) acceptfd, readbuffer, offsetarry, numoffset*sizeof(short));
765
766     /*Process each oid */
767     if ((header = mhashSearch(oid)) == NULL) { /* Obj not found */
768       /* Save the oids not found in buffer for later use */
769       size = sizeof(int) + sizeof(char) + sizeof(unsigned int) ;
770       char sendbuffer[size+1];
771       sendbuffer[0]=TRANS_PREFETCH_RESPONSE;
772       *((int *) (sendbuffer+sizeof(char))) = size;
773       *((char *)(sendbuffer + sizeof(char)+sizeof(int))) = OBJECT_NOT_FOUND;
774       *((unsigned int *)(sendbuffer + sizeof(int) + sizeof(char)+sizeof(char))) = oid;
775       send_data(sd, sendbuffer, size+1);
776     } else { /* Object Found */
777       int incr = 1;
778       GETSIZE(objsize, header);
779       size = sizeof(int) + sizeof(char) + sizeof(unsigned int) + sizeof(objheader_t) + objsize;
780       char sendbuffer[size+1];
781       sendbuffer[0]=TRANS_PREFETCH_RESPONSE;
782       *((int *)(sendbuffer + incr)) = size;
783       incr += sizeof(int);
784       *((char *)(sendbuffer + incr)) = OBJECT_FOUND;
785       incr += sizeof(char);
786       *((unsigned int *)(sendbuffer+incr)) = oid;
787       incr += sizeof(unsigned int);
788       memcpy(sendbuffer + incr, header, objsize + sizeof(objheader_t));
789       send_data(sd, sendbuffer, size+1);
790
791       /* Calculate the oid corresponding to the offset value */
792       for(i = 0 ; i< numoffset ; i++) {
793         /* Check for arrays  */
794         if(TYPE(header) >= NUMCLASSES) {
795           int elementsize = classsize[TYPE(header)];
796           struct ArrayObject *ao = (struct ArrayObject *) (((char *)header) + sizeof(objheader_t));
797           unsigned short length = ao->___length___;
798           /* Check if array out of bounds */
799           if(offsetarry[i]< 0 || offsetarry[i] >= length) {
800             break;
801           }
802           oid = *((unsigned int *)(((char *)header) + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*offsetarry[i])));
803         } else {
804           oid = *((unsigned int *)(((char *)header) + sizeof(objheader_t) + offsetarry[i]));
805         }
806
807         /* Don't continue if we hit a NULL pointer */
808         if (oid==0)
809           break;
810
811         if((header = mhashSearch(oid)) == NULL) {
812           size = sizeof(int) + sizeof(char) + sizeof(unsigned int) ;
813           char sendbuffer[size+1];
814           sendbuffer[0]=TRANS_PREFETCH_RESPONSE;
815           *((int *) (sendbuffer+1)) = size;
816           *((char *)(sendbuffer + sizeof(char)+sizeof(int))) = OBJECT_NOT_FOUND;
817           *((unsigned int *)(sendbuffer + sizeof(char)+sizeof(int) + sizeof(char))) = oid;
818
819           send_data(sd, sendbuffer, size+1);
820           break;
821         } else { /* Obj Found */
822           int incr = 1;
823           GETSIZE(objsize, header);
824           size = sizeof(int) + sizeof(char) + sizeof(unsigned int) + sizeof(objheader_t) + objsize;
825           char sendbuffer[size+1];
826           sendbuffer[0]=TRANS_PREFETCH_RESPONSE;
827           *((int *)(sendbuffer + incr)) = size;
828           incr += sizeof(int);
829           *((char *)(sendbuffer + incr)) = OBJECT_FOUND;
830           incr += sizeof(char);
831           *((unsigned int *)(sendbuffer+incr)) = oid;
832           incr += sizeof(unsigned int);
833           memcpy(sendbuffer + incr, header, objsize + sizeof(objheader_t));
834           send_data(sd, sendbuffer, size+1);
835         }
836       } //end of for
837     }
838   } //end of while
839     //Release socket
840   if (mid!=-1)
841     freeSockWithLock(transPResponseSocketPool, mid, sd);
842   return 0;
843 }
844
845 void sendPrefetchResponse(int sd, char *control, char *sendbuffer, int *size) {
846   send_data(sd, control, sizeof(char));
847   /* Send the buffer with its size */
848   int length = *(size);
849   send_data(sd, sendbuffer, length);
850 }
851
852 void processReqNotify(unsigned int numoid, unsigned int *oidarry, unsigned short *versionarry, unsigned int mid, unsigned int threadid) {
853   objheader_t *header;
854   unsigned int oid;
855   unsigned short newversion;
856   char msg[1+  2 * sizeof(unsigned int) + sizeof(unsigned short)];
857   int sd;
858   struct sockaddr_in remoteAddr;
859   int bytesSent;
860   int size;
861   int i = 0;
862
863   while(i < numoid) {
864     oid = *(oidarry + i);
865     if((header = (objheader_t *) mhashSearch(oid)) == NULL) {
866       printf("Error: mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
867       return;
868     } else {
869       /* Check to see if versions are same */
870 checkversion:
871       if (write_trylock(STATUSPTR(header))) { // Can acquire write lock
872         newversion = header->version;
873         if(newversion == *(versionarry + i)) {
874           //Add to the notify list
875           if((header->notifylist = insNode(header->notifylist, threadid, mid)) == NULL) {
876             printf("Error: Obj notify list points to NULL %s, %d\n", __FILE__, __LINE__);
877             return;
878           }
879           write_unlock(STATUSPTR(header));
880         } else {
881           write_unlock(STATUSPTR(header));
882           if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
883             perror("processReqNotify():socket()");
884             return;
885           }
886           bzero(&remoteAddr, sizeof(remoteAddr));
887           remoteAddr.sin_family = AF_INET;
888           remoteAddr.sin_port = htons(LISTEN_PORT);
889           remoteAddr.sin_addr.s_addr = htonl(mid);
890
891           if (connect(sd, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0) {
892             printf("Error: processReqNotify():error %d connecting to %s:%d\n", errno,
893                    inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
894             close(sd);
895             return;
896           } else {
897             //Send Update notification
898             msg[0] = THREAD_NOTIFY_RESPONSE;
899             *((unsigned int *)&msg[1]) = oid;
900             size = sizeof(unsigned int);
901             *((unsigned short *)(&msg[1]+size)) = newversion;
902             size += sizeof(unsigned short);
903             *((unsigned int *)(&msg[1]+size)) = threadid;
904             size = 1+ 2*sizeof(unsigned int) + sizeof(unsigned short);
905             send_data(sd, msg, size);
906           }
907           close(sd);
908         }
909       } else {
910         randomdelay();
911         goto checkversion;
912       }
913     }
914     i++;
915   }
916   free(oidarry);
917   free(versionarry);
918 }