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