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