Changes to increase garbage collector heap
[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
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
358   recv_data((int)acceptfd, &control, sizeof(char));
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     break;
382
383   case TRANS_COMMIT:
384     /* Invoke the transCommit process() */
385     if((val = transCommitProcess(modptr, oidmod, transinfo->objlocked, fixed->nummod, transinfo->numlocked, (int)acceptfd)) != 0) {
386       printf("Error: In transCommitProcess() %s, %d\n", __FILE__, __LINE__);
387       /* Free memory */
388       if (transinfo->objlocked != NULL) {
389         free(transinfo->objlocked);
390       }
391       if (transinfo->objnotfound != NULL) {
392         free(transinfo->objnotfound);
393       }
394       return 1;
395     }
396     break;
397
398   case TRANS_ABORT_BUT_RETRY_COMMIT_WITH_RELOCATING:
399     break;
400
401   default:
402     printf("Error: No response to TRANS_AGREE OR DISAGREE protocol %s, %d\n", __FILE__, __LINE__);
403     //TODO Use fixed.trans_id  TID since Client may have died
404     break;
405   }
406
407   /* Free memory */
408   if (transinfo->objlocked != NULL) {
409     free(transinfo->objlocked);
410   }
411   if (transinfo->objnotfound != NULL) {
412     free(transinfo->objnotfound);
413   }
414
415   return 0;
416 }
417
418 /* This function increments counters while running a voting decision on all objects involved
419  * in TRANS_REQUEST and If a TRANS_DISAGREE sends the response immediately back to the coordinator */
420 char handleTransReq(fixed_data_t *fixed, trans_commit_data_t *transinfo, unsigned int *listmid, char *objread, void *modptr, int acceptfd) {
421   int val, i = 0, j;
422   unsigned short version;
423   char control = 0, *ptr;
424   unsigned int oid;
425   unsigned int *oidnotfound, *oidlocked, *oidvernotmatch;
426   objheader_t *headptr;
427
428   /* Counters and arrays to formulate decision on control message to be sent */
429   oidnotfound = (unsigned int *) calloc(fixed->numread + fixed->nummod, sizeof(unsigned int));
430   oidlocked = (unsigned int *) calloc(fixed->numread + fixed->nummod + 1, sizeof(unsigned int));
431   oidvernotmatch = (unsigned int *) calloc(fixed->numread + fixed->nummod, sizeof(unsigned int));
432   int objnotfound = 0, objlocked = 0, objvernotmatch = 0;
433   int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
434   int numBytes = 0;
435   /* modptr points to the beginning of the object store
436    * created at the Pariticipant.
437    * Object store holds the modified objects involved in the transaction request */
438   ptr = (char *) modptr;
439
440   /* Process each oid in the machine pile/ group per thread */
441   for (i = 0; i < fixed->numread + fixed->nummod; i++) {
442     if (i < fixed->numread) { //Objs only read and not modified
443       int incr = sizeof(unsigned int) + sizeof(unsigned short); // Offset that points to next position in the objread array
444       incr *= i;
445       oid = *((unsigned int *)(objread + incr));
446       incr += sizeof(unsigned int);
447       version = *((unsigned short *)(objread + incr));
448       getCommitCountForObjRead(oidnotfound, oidlocked, oidvernotmatch, &objnotfound, &objlocked, &objvernotmatch,
449                                &v_matchnolock, &v_matchlock, &v_nomatch, &numBytes, &control, oid, version);
450     } else {  //Objs modified
451       if(i == fixed->numread) {
452         oidlocked[objlocked] = -1;
453         objlocked++;
454       }
455       int tmpsize;
456       headptr = (objheader_t *) ptr;
457       oid = OID(headptr);
458       version = headptr->version;
459       GETSIZE(tmpsize, headptr);
460       ptr += sizeof(objheader_t) + tmpsize;
461       getCommitCountForObjMod(oidnotfound, oidlocked, oidvernotmatch, &objnotfound,
462                               &objlocked, &objvernotmatch, &v_matchnolock, &v_matchlock, &v_nomatch,
463                               &numBytes, &control, oid, version);
464     }
465   }
466
467   /* send TRANS_DISAGREE and objs*/
468   if(v_nomatch > 0) {
469 #ifdef CACHE
470     char *objs = calloc(1, numBytes);
471     int j, offset = 0;
472     for(j = 0; j<objvernotmatch; j++) {
473       objheader_t *header = mhashSearch(oidvernotmatch[j]);
474       int size = 0;
475       GETSIZE(size, header);
476       size += sizeof(objheader_t);
477       memcpy(objs+offset, header, size);
478       offset += size;
479     }
480 #endif
481     if (objlocked > 0) {
482       int useWriteUnlock = 0;
483       for(j = 0; j < objlocked; j++) {
484         if(oidlocked[j] == -1) {
485           useWriteUnlock = 1;
486           continue;
487         }
488         if((headptr = mhashSearch(oidlocked[j])) == NULL) {
489           printf("mhashSearch returns NULL at %s, %d\n", __FILE__, __LINE__);
490           return 0;
491         }
492         if(useWriteUnlock) {
493           write_unlock(STATUSPTR(headptr));
494         } else {
495           read_unlock(STATUSPTR(headptr));
496         }
497       }
498       free(oidlocked);
499     }
500     send_data(acceptfd, &control, sizeof(char));
501 #ifdef CACHE
502     send_data(acceptfd, &numBytes, sizeof(int));
503     send_data(acceptfd, objs, numBytes);
504     transinfo->objvernotmatch = oidvernotmatch;
505     transinfo->numvernotmatch = objvernotmatch;
506     free(objs);
507     free(transinfo->objvernotmatch);
508 #endif
509     return control;
510   }
511
512   /* Decide what control message to send to Coordinator */
513   if ((control = decideCtrlMessage(fixed, transinfo, &v_matchnolock, &v_matchlock, &v_nomatch, &objnotfound, &objlocked,
514                                    modptr, oidnotfound, oidlocked, acceptfd)) == 0) {
515     printf("Error: In decideCtrlMessage() %s, %d\n", __FILE__, __LINE__);
516     return 0;
517   }
518   return control;
519 }
520
521 /* Update Commit info for objects that are read */
522 void getCommitCountForObjMod(unsigned int *oidnotfound, unsigned int *oidlocked,
523                              unsigned int *oidvernotmatch, int *objnotfound, int *objlocked, int *objvernotmatch,
524                              int *v_matchnolock, int *v_matchlock, int *v_nomatch, int *numBytes,
525                              char *control, unsigned int oid, unsigned short version) {
526   void *mobj;
527   /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
528
529   if ((mobj = mhashSearch(oid)) == NULL) {    /* Obj not found */
530     /* Save the oids not found and number of oids not found for later use */
531     oidnotfound[*objnotfound] = oid;
532     (*objnotfound)++;
533   } else {     /* If Obj found in machine (i.e. has not moved) */
534     /* Check if Obj is locked by any previous transaction */
535     if (write_trylock(STATUSPTR(mobj))) { // Can acquire write lock
536       if (version == ((objheader_t *)mobj)->version) { /* match versions */
537         (*v_matchnolock)++;
538       } else { /* If versions don't match ...HARD ABORT */
539         (*v_nomatch)++;
540         oidvernotmatch[*objvernotmatch] = oid;
541         (*objvernotmatch)++;
542         int size;
543         GETSIZE(size, mobj);
544         size += sizeof(objheader_t);
545         *numBytes += size;
546         /* Send TRANS_DISAGREE to Coordinator */
547         *control = TRANS_DISAGREE;
548         //printf("%s() oid = %d, type = %d\t", __func__, OID(mobj), TYPE((objheader_t *)mobj));
549       }
550       //Keep track of oid locked
551       oidlocked[*objlocked] = OID(((objheader_t *)mobj));
552       (*objlocked)++;
553     } else {  //we are locked
554       if (version == ((objheader_t *)mobj)->version) {     /* Check if versions match */
555         (*v_matchlock)++;
556       } else { /* If versions don't match ...HARD ABORT */
557         (*v_nomatch)++;
558         oidvernotmatch[*objvernotmatch] = oid;
559         (*objvernotmatch)++;
560         int size;
561         GETSIZE(size, mobj);
562         size += sizeof(objheader_t);
563         *numBytes += size;
564         *control = TRANS_DISAGREE;
565         //printf("%s() oid = %d, type = %d\t", __func__, OID(mobj), TYPE((objheader_t *)mobj));
566       }
567     }
568   }
569 }
570
571 /* Update Commit info for objects that are read */
572 void getCommitCountForObjRead(unsigned int *oidnotfound, unsigned int *oidlocked, unsigned int *oidvernotmatch,
573                               int *objnotfound, int *objlocked, int * objvernotmatch, int *v_matchnolock, int *v_matchlock,
574                               int *v_nomatch, int *numBytes, char *control, unsigned int oid, unsigned short version) {
575   void *mobj;
576   /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
577   if ((mobj = mhashSearch(oid)) == NULL) {    /* Obj not found */
578     /* Save the oids not found and number of oids not found for later use */
579     oidnotfound[*objnotfound] = oid;
580     (*objnotfound)++;
581   } else {     /* If Obj found in machine (i.e. has not moved) */
582     /* Check if Obj is locked by any previous transaction */
583     if (read_trylock(STATUSPTR(mobj))) { //Can further acquire read locks
584       if (version == ((objheader_t *)mobj)->version) { /* match versions */
585         (*v_matchnolock)++;
586       } else { /* If versions don't match ...HARD ABORT */
587         (*v_nomatch)++;
588         oidvernotmatch[*objvernotmatch] = oid;
589         (*objvernotmatch)++;
590         int size;
591         GETSIZE(size, mobj);
592         size += sizeof(objheader_t);
593         *numBytes += size;
594         /* Send TRANS_DISAGREE to Coordinator */
595         *control = TRANS_DISAGREE;
596         //printf("%s() oid = %d, type = %d\t", __func__, OID(mobj), TYPE((objheader_t *)mobj));
597       }
598       //Keep track of oid locked
599       oidlocked[*objlocked] = OID(((objheader_t *)mobj));
600       (*objlocked)++;
601     } else { /* Some other transaction has aquired a write lock on this object */
602       if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
603         (*v_matchlock)++;
604       } else { /* If versions don't match ...HARD ABORT */
605         (*v_nomatch)++;
606         oidvernotmatch[*objvernotmatch] = oid;
607         (*objvernotmatch)++;
608         int size;
609         GETSIZE(size, mobj);
610         size += sizeof(objheader_t);
611         *numBytes += size;
612         *control = TRANS_DISAGREE;
613         //printf("%s() oid = %d, type = %d\t", __func__, OID(mobj), TYPE((objheader_t *)mobj));
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   return control;
658 }
659
660 /* This function processes all modified objects involved in a TRANS_COMMIT and updates pointer
661  * addresses in lookup table and also changes version number
662  * Sends an ACK back to Coordinator */
663 int transCommitProcess(void *modptr, unsigned int *oidmod, unsigned int *oidlocked, int nummod, int numlocked, int acceptfd) {
664   objheader_t *header;
665   objheader_t *newheader;
666   int i = 0, offset = 0;
667   char control;
668   int tmpsize;
669
670   /* Process each modified object saved in the mainobject store */
671   for(i = 0; i < nummod; i++) {
672     if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
673       printf("Error: mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
674       return 1;
675     }
676     GETSIZE(tmpsize,header);
677     memcpy((char*)header + sizeof(objheader_t), ((char *)modptr + sizeof(objheader_t) + offset), tmpsize);
678     header->version += 1;
679     /* If threads are waiting on this object to be updated, notify them */
680     if(header->notifylist != NULL) {
681       notifyAll(&header->notifylist, OID(header), header->version);
682     }
683     offset += sizeof(objheader_t) + tmpsize;
684   }
685
686   if (nummod > 0)
687     free(modptr);
688
689   /* Unlock locked objects */
690   int useWriteUnlock = 0;
691   for(i = 0; i < numlocked; i++) {
692     if(oidlocked[i] == -1) {
693       useWriteUnlock = 1;
694       continue;
695     }
696     if((header = (objheader_t *) mhashSearch(oidlocked[i])) == NULL) {
697       printf("Error: mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
698       return 1;
699     }
700
701     if(useWriteUnlock) {
702       write_unlock(STATUSPTR(header));
703     } else {
704       read_unlock(STATUSPTR(header));
705     }
706   }
707   //TODO Update location lookup table
708   return 0;
709 }
710
711 /* This function recevies the oid and offset tuples from the Coordinator's prefetch call.
712  * Looks for the objects to be prefetched in the main object store.
713  * If objects are not found then record those and if objects are found
714  * then use offset values to prefetch references to other objects */
715
716 int prefetchReq(int acceptfd) {
717   int i, size, objsize, numoffset = 0;
718   int length;
719   char *recvbuffer, control;
720   unsigned int oid, mid=-1;
721   objheader_t *header;
722   oidmidpair_t oidmid;
723   int sd = -1;
724
725   while(1) {
726     recv_data((int)acceptfd, &numoffset, sizeof(int));
727     if(numoffset == -1)
728       break;
729     recv_data((int)acceptfd, &oidmid, 2*sizeof(unsigned int));
730     oid = oidmid.oid;
731     if (mid != oidmid.mid) {
732       if (mid!=-1) {
733         freeSockWithLock(transPResponseSocketPool, mid, sd);
734       }
735       mid=oidmid.mid;
736       sd = getSockWithLock(transPResponseSocketPool, mid);
737     }
738     short offsetarry[numoffset];
739     recv_data((int) acceptfd, offsetarry, numoffset*sizeof(short));
740
741     /*Process each oid */
742     if ((header = mhashSearch(oid)) == NULL) { /* Obj not found */
743       /* Save the oids not found in buffer for later use */
744       size = sizeof(int) + sizeof(char) + sizeof(unsigned int) ;
745       char sendbuffer[size];
746       *((int *) sendbuffer) = size;
747       *((char *)(sendbuffer + sizeof(int))) = OBJECT_NOT_FOUND;
748       *((unsigned int *)(sendbuffer + sizeof(int) + sizeof(char))) = oid;
749       control = TRANS_PREFETCH_RESPONSE;
750       sendPrefetchResponse(sd, &control, sendbuffer, &size);
751     } else { /* Object Found */
752       int incr = 0;
753       GETSIZE(objsize, header);
754       size = sizeof(int) + sizeof(char) + sizeof(unsigned int) + sizeof(objheader_t) + objsize;
755       char sendbuffer[size];
756       *((int *)(sendbuffer + incr)) = size;
757       incr += sizeof(int);
758       *((char *)(sendbuffer + incr)) = OBJECT_FOUND;
759       incr += sizeof(char);
760       *((unsigned int *)(sendbuffer+incr)) = oid;
761       incr += sizeof(unsigned int);
762       memcpy(sendbuffer + incr, header, objsize + sizeof(objheader_t));
763
764       control = TRANS_PREFETCH_RESPONSE;
765       sendPrefetchResponse(sd, &control, sendbuffer, &size);
766
767       /* Calculate the oid corresponding to the offset value */
768       for(i = 0 ; i< numoffset ; i++) {
769         /* Check for arrays  */
770         if(TYPE(header) > NUMCLASSES) {
771           int elementsize = classsize[TYPE(header)];
772           struct ArrayObject *ao = (struct ArrayObject *) (((char *)header) + sizeof(objheader_t));
773           unsigned short length = ao->___length___;
774           /* Check if array out of bounds */
775           if(offsetarry[i]< 0 || offsetarry[i] >= length) {
776             break;
777           }
778           oid = *((unsigned int *)(((char *)header) + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*offsetarry[i])));
779         } else {
780           oid = *((unsigned int *)(((char *)header) + sizeof(objheader_t) + offsetarry[i]));
781         }
782
783         /* Don't continue if we hit a NULL pointer */
784         if (oid==0)
785           break;
786
787         if((header = mhashSearch(oid)) == NULL) {
788           size = sizeof(int) + sizeof(char) + sizeof(unsigned int) ;
789           char sendbuffer[size];
790           *((int *) sendbuffer) = size;
791           *((char *)(sendbuffer + sizeof(int))) = OBJECT_NOT_FOUND;
792           *((unsigned int *)(sendbuffer + sizeof(int) + sizeof(char))) = oid;
793
794           control = TRANS_PREFETCH_RESPONSE;
795           sendPrefetchResponse(sd, &control, sendbuffer, &size);
796           break;
797         } else { /* Obj Found */
798           int incr = 0;
799           GETSIZE(objsize, header);
800           size = sizeof(int) + sizeof(char) + sizeof(unsigned int) + sizeof(objheader_t) + objsize;
801           char sendbuffer[size];
802           *((int *)(sendbuffer + incr)) = size;
803           incr += sizeof(int);
804           *((char *)(sendbuffer + incr)) = OBJECT_FOUND;
805           incr += sizeof(char);
806           *((unsigned int *)(sendbuffer+incr)) = oid;
807           incr += sizeof(unsigned int);
808           memcpy(sendbuffer + incr, header, objsize + sizeof(objheader_t));
809
810           control = TRANS_PREFETCH_RESPONSE;
811           sendPrefetchResponse(sd, &control, sendbuffer, &size);
812         }
813       }
814     }
815   }
816   //Release socket
817   if (mid!=-1)
818     freeSockWithLock(transPResponseSocketPool, mid, sd);
819
820   return 0;
821 }
822
823 void sendPrefetchResponse(int sd, char *control, char *sendbuffer, int *size) {
824   send_data(sd, control, sizeof(char));
825   /* Send the buffer with its size */
826   int length = *(size);
827   send_data(sd, sendbuffer, length);
828 }
829
830 void processReqNotify(unsigned int numoid, unsigned int *oidarry, unsigned short *versionarry, unsigned int mid, unsigned int threadid) {
831   objheader_t *header;
832   unsigned int oid;
833   unsigned short newversion;
834   char msg[1+  2 * sizeof(unsigned int) + sizeof(unsigned short)];
835   int sd;
836   struct sockaddr_in remoteAddr;
837   int bytesSent;
838   int size;
839   int i = 0;
840
841   while(i < numoid) {
842     oid = *(oidarry + i);
843     if((header = (objheader_t *) mhashSearch(oid)) == NULL) {
844       printf("Error: mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
845       return;
846     } else {
847       /* Check to see if versions are same */
848 checkversion:
849       if (write_trylock(STATUSPTR(header))) { // Can acquire write lock
850         newversion = header->version;
851         if(newversion == *(versionarry + i)) {
852           //Add to the notify list
853           if((header->notifylist = insNode(header->notifylist, threadid, mid)) == NULL) {
854             printf("Error: Obj notify list points to NULL %s, %d\n", __FILE__, __LINE__);
855             return;
856           }
857           write_unlock(STATUSPTR(header));
858         } else {
859           write_unlock(STATUSPTR(header));
860           if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
861             perror("processReqNotify():socket()");
862             return;
863           }
864           bzero(&remoteAddr, sizeof(remoteAddr));
865           remoteAddr.sin_family = AF_INET;
866           remoteAddr.sin_port = htons(LISTEN_PORT);
867           remoteAddr.sin_addr.s_addr = htonl(mid);
868
869           if (connect(sd, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0) {
870             printf("Error: processReqNotify():error %d connecting to %s:%d\n", errno,
871                    inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
872             close(sd);
873             return;
874           } else {
875             //Send Update notification
876             msg[0] = THREAD_NOTIFY_RESPONSE;
877             *((unsigned int *)&msg[1]) = oid;
878             size = sizeof(unsigned int);
879             *((unsigned short *)(&msg[1]+size)) = newversion;
880             size += sizeof(unsigned short);
881             *((unsigned int *)(&msg[1]+size)) = threadid;
882             size = 1+ 2*sizeof(unsigned int) + sizeof(unsigned short);
883             send_data(sd, msg, size);
884           }
885           close(sd);
886         }
887       } else {
888         randomdelay();
889         goto checkversion;
890       }
891     }
892     i++;
893   }
894   free(oidarry);
895   free(versionarry);
896 }