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