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