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