Implementation for thread join and wait and notify design
[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 <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <pthread.h>
8 #include <netdb.h>
9 #include <fcntl.h>
10 #include <errno.h>
11 #include <string.h>
12 #include "dstm.h"
13 #include "mlookup.h"
14 #include "llookup.h"
15 #include "threadnotify.h"
16 #ifdef COMPILER
17 #include "thread.h"
18 #endif
19
20
21 #define LISTEN_PORT 2156
22 #define BACKLOG 10 //max pending connections
23 #define RECEIVE_BUFFER_SIZE 2048
24 #define PRE_BUF_SIZE 2048
25
26 extern int classsize[];
27
28 objstr_t *mainobjstore;
29 pthread_mutex_t mainobjstore_mutex;
30 pthread_mutexattr_t mainobjstore_mutex_attr; /* Attribute for lock to make it a recursive lock */
31
32 /* This function initializes the main objects store and creates the 
33  * global machine and location lookup table */
34
35 int dstmInit(void)
36 {
37         mainobjstore = objstrCreate(DEFAULT_OBJ_STORE_SIZE);
38         /* Initialize attribute for mutex */
39         pthread_mutexattr_init(&mainobjstore_mutex_attr);
40         pthread_mutexattr_settype(&mainobjstore_mutex_attr, PTHREAD_MUTEX_RECURSIVE_NP);
41         pthread_mutex_init(&mainobjstore_mutex, &mainobjstore_mutex_attr);
42         if (mhashCreate(HASH_SIZE, LOADFACTOR))
43                 return 1; //failure
44         
45         if (lhashCreate(HASH_SIZE, LOADFACTOR))
46                 return 1; //failure
47
48         if (notifyhashCreate(N_HASH_SIZE, N_LOADFACTOR))
49                 return 1; //failure
50         
51         return 0;
52 }
53
54 /* This function starts the thread to listen on a socket 
55  * for tranaction calls */
56 void *dstmListen()
57 {
58         int listenfd, acceptfd;
59         struct sockaddr_in my_addr;
60         struct sockaddr_in client_addr;
61         socklen_t addrlength = sizeof(struct sockaddr);
62         pthread_t thread_dstm_accept;
63         int i;
64         int setsockflag=1;
65
66         listenfd = socket(AF_INET, SOCK_STREAM, 0);
67         if (listenfd == -1)
68         {
69                 perror("socket");
70                 exit(1);
71         }
72
73         if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &setsockflag, sizeof (setsockflag)) < 0) {
74           perror("socket");
75           exit(1);
76         }
77 #ifdef MAC
78         if (setsockopt(listenfd, SOL_SOCKET, SO_NOSIGPIPE, &setsockflag, sizeof (setsockflag)) < 0) {
79           perror("socket");
80           exit(1);
81         }
82 #endif
83
84         my_addr.sin_family = AF_INET;
85         my_addr.sin_port = htons(LISTEN_PORT);
86         my_addr.sin_addr.s_addr = INADDR_ANY;
87         memset(&(my_addr.sin_zero), '\0', 8);
88
89         if (bind(listenfd, (struct sockaddr *)&my_addr, addrlength) == -1)
90         {
91                 perror("bind");
92                 exit(1);
93         }
94         
95         if (listen(listenfd, BACKLOG) == -1)
96         {
97                 perror("listen");
98                 exit(1);
99         }
100
101         printf("Listening on port %d, fd = %d\n", LISTEN_PORT, listenfd);
102         while(1)
103         {
104           int retval;
105           acceptfd = accept(listenfd, (struct sockaddr *)&client_addr, &addrlength);
106           do {
107             retval=pthread_create(&thread_dstm_accept, NULL, dstmAccept, (void *)acceptfd);
108           } while(retval!=0);
109           pthread_detach(thread_dstm_accept);
110         }
111 }
112 /* This function accepts a new connection request, decodes the control message in the connection 
113  * and accordingly calls other functions to process new requests */
114 void *dstmAccept(void *acceptfd)
115 {
116         int val, retval, size;
117         unsigned int oid;
118         char buffer[RECEIVE_BUFFER_SIZE], control,ctrl;
119         char *ptr;
120         void *srcObj;
121         objheader_t *h;
122         trans_commit_data_t transinfo;
123         unsigned short objType, *versionarry, version;
124         unsigned int *oidarry, numoid, mid, threadid;
125
126         transinfo.objlocked = NULL;
127         transinfo.objnotfound = NULL;
128         transinfo.modptr = NULL;
129         transinfo.numlocked = 0;
130         transinfo.numnotfound = 0;
131
132         /* Receive control messages from other machines */
133         if((retval = recv((int)acceptfd, &control, sizeof(char), 0)) <= 0) {
134                 if (retval == 0) {
135                         pthread_exit(NULL); // Testing connection
136                 }
137                 perror("Error in receiving control from coordinator\n");
138                 pthread_exit(NULL);
139         }
140         
141         switch(control) {
142                 case READ_REQUEST:
143                         /* Read oid requested and search if available */
144                         if((retval = recv((int)acceptfd, &oid, sizeof(unsigned int), 0)) <= 0) {
145                                 perror("Error receiving object from cooridnator\n");
146                                 pthread_exit(NULL);
147                         }
148                         if((srcObj = mhashSearch(oid)) == NULL) {
149                                 printf("Object not found in Main Object Store %s %d\n", __FILE__, __LINE__);
150                                 pthread_exit(NULL);
151                         }
152                         h = (objheader_t *) srcObj;
153                         GETSIZE(size, h);
154                         size += sizeof(objheader_t);
155
156                         if (h == NULL) {
157                                 ctrl = OBJECT_NOT_FOUND;
158                                 if(send((int)acceptfd, &ctrl, sizeof(char), MSG_NOSIGNAL) < sizeof(char)) {
159                                         perror("Error sending control msg to coordinator\n");
160                                         pthread_exit(NULL);
161                                 }
162                         } else {
163                                 /* Type */
164                                 char msg[]={OBJECT_FOUND, 0, 0, 0, 0};
165                                 *((int *)&msg[1])=size;
166                                 if(send((int)acceptfd, &msg, sizeof(msg), MSG_NOSIGNAL) < sizeof(msg)) {
167                                         perror("Error sending size of object to coordinator\n");
168                                         pthread_exit(NULL);
169                                 }
170                                 if(send((int)acceptfd, h, size, MSG_NOSIGNAL) < size) {
171                                         perror("Error in sending object\n");
172                                         pthread_exit(NULL);
173                                 }
174                         }
175                         break;
176                 
177                 case READ_MULT_REQUEST:
178                         printf("DEBUG-> READ_MULT_REQUEST\n");
179                         break;
180         
181                 case MOVE_REQUEST:
182                         printf("DEBUG -> MOVE_REQUEST\n");
183                         break;
184
185                 case MOVE_MULT_REQUEST:
186                         printf("DEBUG -> MOVE_MULT_REQUEST\n");
187                         break;
188
189                 case TRANS_REQUEST:
190                         /* Read transaction request */
191                         printf("DEBUG -> Recv TRANS_REQUEST\n");
192                         if((val = readClientReq(&transinfo, (int)acceptfd)) != 0) {
193                                 printf("Error in readClientReq\n");
194                                 pthread_exit(NULL);
195                         }
196                         break;
197                 case TRANS_PREFETCH:
198                         printf("DEBUG -> Recv TRANS_PREFETCH\n");
199                         if((val = prefetchReq((int)acceptfd)) != 0) {
200                                 printf("Error in transPrefetch\n");
201                                 pthread_exit(NULL);
202                         }
203                         break;
204                 case START_REMOTE_THREAD:
205                         retval = recv((int)acceptfd, &oid, sizeof(unsigned int), 0);
206                         if (retval <= 0)
207                                 perror("dstmAccept(): error receiving START_REMOTE_THREAD msg");
208                         else if (retval != sizeof(unsigned int))
209                                 printf("dstmAccept(): incorrect msg size %d for START_REMOTE_THREAD\n",
210                                         retval);
211                         else
212                         {
213                                 objType = getObjType(oid);
214                                 startDSMthread(oid, objType);
215                         }
216                         break;
217
218                 case THREAD_NOTIFY_REQUEST:
219                         size = sizeof(unsigned int);
220                         retval = recv((int)acceptfd, ptr, size, 0);
221                         numoid = *((unsigned int *) ptr);
222                         size = (sizeof(unsigned int) + sizeof(unsigned short)) * numoid + 2 * sizeof(unsigned int);
223                         retval = recv((int)acceptfd, ptr, size, 0);
224                         oidarry = calloc(numoid, sizeof(unsigned int)); 
225                         memcpy(oidarry, ptr, sizeof(unsigned int) * numoid);
226                         size = sizeof(unsigned int) * numoid;
227                         versionarry = calloc(numoid, sizeof(unsigned short));
228                         memcpy(versionarry, ptr+size, sizeof(unsigned short) * numoid);
229                         size += sizeof(unsigned short) * numoid;
230                         mid = *((unsigned int *)(ptr+size));
231                         size += sizeof(unsigned int);
232                         threadid = *((unsigned int *)(ptr+size));
233                         processReqNotify(numoid, oidarry, versionarry, mid, threadid);
234
235                         break;
236
237                 case THREAD_NOTIFY_RESPONSE:
238                         size = sizeof(unsigned short) + 2 * sizeof(unsigned int);
239                         retval = recv((int)acceptfd, ptr, size, 0);
240                         if(retval <= 0) 
241                                 perror("dstmAccept(): error receiving THREAD_NOTIFY_RESPONSE msg");
242                         else if( retval != 2*sizeof(unsigned int) + sizeof(unsigned short))
243                                 printf("dstmAccept(): incorrect smsg size %d for THREAD_NOTIFY_RESPONSE msg\n", retval);
244                         else {
245                                 oid = *((unsigned int *)ptr);
246                                 size = sizeof(unsigned int);
247                                 version = *((unsigned short *)(ptr+size));
248                                 size += sizeof(unsigned short);
249                                 threadid = *((unsigned int *)(ptr+size));
250                                 threadNotify(oid,version,threadid);
251                         }
252
253                         break;
254
255                 default:
256                         printf("DEBUG -> dstmAccept: Error Unknown opcode %d\n", control);
257         }
258
259         /* Close connection */
260         if (close((int)acceptfd) == -1)
261                 perror("close");
262         
263         pthread_exit(NULL);
264 }
265
266 /* This function reads the information available in a transaction request
267  * and makes a function call to process the request */
268 int readClientReq(trans_commit_data_t *transinfo, int acceptfd) {
269         char *ptr;
270         void *modptr;
271         unsigned int *oidmod, oid;
272         fixed_data_t fixed;
273         objheader_t *headaddr;
274         int sum = 0, i, N, n, val;
275
276         oidmod = NULL;
277
278         /* Read fixed_data_t data structure */ 
279         N = sizeof(fixed) - 1;
280         ptr = (char *)&fixed;;
281         fixed.control = TRANS_REQUEST;
282         do {
283                 n = recv((int)acceptfd, (void *) ptr+1+sum, N-sum, 0);
284                 sum += n;
285         } while(sum < N && n != 0); 
286
287         /* Read list of mids */
288         int mcount = fixed.mcount;
289         N = mcount * sizeof(unsigned int);
290         unsigned int listmid[mcount];
291         ptr = (char *) listmid;
292         sum = 0;
293         do {
294                 n = recv((int)acceptfd, (void *) ptr+sum, N-sum, 0);
295                 sum += n;
296         } while(sum < N && n != 0);
297
298         /* Read oid and version tuples for those objects that are not modified in the transaction */
299         int numread = fixed.numread;
300         N = numread * (sizeof(unsigned int) + sizeof(short));
301         char objread[N];
302         if(numread != 0) { //If pile contains more than one object to be read, 
303                           // keep reading all objects
304                 sum = 0;
305                 do {
306                         n = recv((int)acceptfd, (void *) objread, N, 0);
307                         sum += n;
308                 } while(sum < N && n != 0);
309         }
310         
311         /* Read modified objects */
312         if(fixed.nummod != 0) {
313                 if ((modptr = calloc(1, fixed.sum_bytes)) == NULL) {
314                         printf("calloc error for modified objects %s, %d\n", __FILE__, __LINE__);
315                         return 1;
316                 }
317                 sum = 0;
318                 do { // Recv the objs that are modified by the Coordinator
319                         n = recv((int)acceptfd, (char *) modptr+sum, fixed.sum_bytes-sum, 0);
320                         sum += n;
321                 } while (sum < fixed.sum_bytes && n != 0);
322         }
323
324         /* Create an array of oids for modified objects */
325         oidmod = (unsigned int *) calloc(fixed.nummod, sizeof(unsigned int));
326         if (oidmod == NULL)
327         {
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         char *ptr, control, sendctrl;
365         objheader_t *tmp_header;
366         void *header;
367         int  i = 0, val, retval;
368
369         /* Send reply to the Coordinator */
370         if((retval = handleTransReq(fixed, transinfo, listmid, objread, modptr,acceptfd)) == 0 ) {
371                 printf("Handle Trans Req error %s, %d\n", __FILE__, __LINE__);
372                 return 1;
373         }
374
375         /* Read new control message from Coordiator */
376         if((retval = recv((int)acceptfd, &control, sizeof(char), 0)) <= 0 ) {
377                 perror("Error in receiving control message\n");
378                 return 1;
379         }
380
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                         for(i = 0; i< transinfo->numlocked; i++) {
388                                 header = mhashSearch(transinfo->objlocked[i]);// find the header address
389                                 STATUS(((objheader_t *)header)) &= ~(LOCK);             
390                         }
391
392                         /* Send ack to Coordinator */
393                         sendctrl = TRANS_SUCESSFUL;
394                         if(send((int)acceptfd, &sendctrl, sizeof(char), MSG_NOSIGNAL) < sizeof(char)) {
395                                 perror("Error sending ACK to coordinator\n");
396                                 if (transinfo->objlocked != NULL) {
397                                         free(transinfo->objlocked);
398                                 }
399                                 if (transinfo->objnotfound != NULL) {
400                                         free(transinfo->objnotfound);
401                                 }
402
403                                 return 1;
404                         }
405                         ptr = NULL;
406                         break;
407
408                 case TRANS_COMMIT:
409                         /* Invoke the transCommit process() */
410                         if((val = transCommitProcess(modptr, oidmod, transinfo->objlocked, fixed->nummod, transinfo->numlocked, (int)acceptfd)) != 0) {
411                                 printf("Error in transCommitProcess %s, %d\n", __FILE__, __LINE__);
412                                 /* Free memory */
413                                 if (transinfo->objlocked != NULL) {
414                                         free(transinfo->objlocked);
415                                 }
416                                 if (transinfo->objnotfound != NULL) {
417                                         free(transinfo->objnotfound);
418                                 }
419                                 return 1;
420                         }
421                         break;
422
423                 case TRANS_ABORT_BUT_RETRY_COMMIT_WITH_RELOCATING:
424                         //TODO expect another transrequest from client
425                         printf("DEBUG -> Recv TRANS_ABORT_BUT_RETRY_COMMIT_WITH_RELOCATING\n");
426                         break;
427                 default:
428                         printf("No response to TRANS_AGREE OR DISAGREE protocol\n");
429                         //TODO Use fixed.trans_id  TID since Client may have died
430                         break;
431         }
432
433         /* Free memory */
434         if (transinfo->objlocked != NULL) {
435                 free(transinfo->objlocked);
436         }
437         if (transinfo->objnotfound != NULL) {
438                 free(transinfo->objnotfound);
439         }
440
441         return 0;
442 }
443
444 /* This function increments counters while running a voting decision on all objects involved 
445  * in TRANS_REQUEST and If a TRANS_DISAGREE sends the response immediately back to the coordinator */
446 char handleTransReq(fixed_data_t *fixed, trans_commit_data_t *transinfo, unsigned int *listmid, char *objread, void *modptr, int acceptfd) {
447         int val, i = 0;
448         unsigned short version;
449         char control = 0, *ptr;
450         unsigned int oid;
451         unsigned int *oidnotfound, *oidlocked;
452         void *mobj;
453         objheader_t *headptr;
454
455         /* Counters and arrays to formulate decision on control message to be sent */
456         oidnotfound = (unsigned int *) calloc(fixed->numread + fixed->nummod, sizeof(unsigned int)); 
457         oidlocked = (unsigned int *) calloc(fixed->numread + fixed->nummod, sizeof(unsigned int)); 
458         int objnotfound = 0, objlocked = 0;
459         int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
460
461         /* modptr points to the beginning of the object store 
462          * created at the Pariticipant. 
463          * Object store holds the modified objects involved in the transaction request */ 
464         ptr = (char *) modptr;
465         
466         /* Process each oid in the machine pile/ group per thread */
467         for (i = 0; i < fixed->numread + fixed->nummod; i++) {
468                 if (i < fixed->numread) {//Objs only read and not modified
469                         int incr = sizeof(unsigned int) + sizeof(short);// Offset that points to next position in the objread array
470                         incr *= i;
471                         oid = *((unsigned int *)(objread + incr));
472                         incr += sizeof(unsigned int);
473                         version = *((unsigned short *)(objread + incr));
474                 } else {//Objs modified
475                   int tmpsize;
476                   headptr = (objheader_t *) ptr;
477                   oid = OID(headptr);
478                   version = headptr->version;
479                   GETSIZE(tmpsize, headptr);
480                   ptr += sizeof(objheader_t) + tmpsize;
481                 }
482                 
483                 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
484
485                 if ((mobj = mhashSearch(oid)) == NULL) {/* Obj not found */
486                         /* Save the oids not found and number of oids not found for later use */
487                         oidnotfound[objnotfound] = oid;
488                         objnotfound++;
489                 } else { /* If Obj found in machine (i.e. has not moved) */
490                         /* Check if Obj is locked by any previous transaction */
491                         if ((STATUS(((objheader_t *)mobj)) & LOCK) == LOCK) {           
492                                 if (version == ((objheader_t *)mobj)->version) {      /* If locked then match versions */
493                                         v_matchlock++;
494                                 } else {/* If versions don't match ...HARD ABORT */
495                                         v_nomatch++;
496                                         /* Send TRANS_DISAGREE to Coordinator */
497                                         control = TRANS_DISAGREE;
498                                         if((val = send(acceptfd, &control, sizeof(char), MSG_NOSIGNAL)) < sizeof(char)) {
499                                                 perror("Error in sending control to the Coordinator\n");
500                                                 return 0;
501                                         }
502                                         return control;
503                                 }
504                         } else {/* If Obj is not locked then lock object */
505                                 STATUS(((objheader_t *)mobj)) |= LOCK;
506                                 /* Save all object oids that are locked on this machine during this transaction request call */
507                                 oidlocked[objlocked] = OID(((objheader_t *)mobj));
508                                 objlocked++;
509                                 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
510                                         v_matchnolock++;
511                                 } else { /* If versions don't match ...HARD ABORT */
512                                         v_nomatch++;
513                                         control = TRANS_DISAGREE;
514                                         /* Send TRANS_DISAGREE to Coordinator */
515                                         if((val = send(acceptfd, &control, sizeof(char), MSG_NOSIGNAL)) < sizeof(char)) {
516                                                 perror("Error in sending control to the Coordinator\n");
517                                                 return 0;
518                                         }
519                                         if (objlocked > 0) {
520                                                 STATUS(((objheader_t *)mobj)) &= ~(LOCK);
521                                                 free(oidlocked);
522                                         }
523                                         return control;
524                                 }
525                         }
526                 }
527         }
528         
529         /* Decide what control message to send to Coordinator */
530         if ((val = 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         
536         return val;
537
538 }
539 /* This function decides what control message such as TRANS_AGREE, TRANS_DISAGREE or TRANS_SOFT_ABORT
540  * to send to Coordinator based on the votes of oids involved in the transaction */
541 int decideCtrlMessage(fixed_data_t *fixed, trans_commit_data_t *transinfo, int *v_matchnolock, int *v_matchlock, 
542                 int *v_nomatch, int *objnotfound, int *objlocked, void *modptr, 
543                 unsigned int *oidnotfound, unsigned int *oidlocked, int acceptfd) {
544         int val;
545         char control = 0;
546         /* Condition to send TRANS_AGREE */
547         if(*(v_matchnolock) == fixed->numread + fixed->nummod) {
548                 control = TRANS_AGREE;
549                 /* Send control message */
550                 if((val = send(acceptfd, &control, sizeof(char), MSG_NOSIGNAL)) < sizeof(char)) {
551                         perror("Error in sending control to Coordinator\n");
552                         return 0;
553                 }
554         }
555         /* Condition to send TRANS_SOFT_ABORT */
556         if((*(v_matchlock) > 0 && *(v_nomatch) == 0) || (*(objnotfound) > 0 && *(v_nomatch) == 0)) {
557                 control = TRANS_SOFT_ABORT;
558                 char msg[]={TRANS_SOFT_ABORT, 0,0,0,0};
559                 *((int*)&msg[1])= *(objnotfound);
560
561                 /* Send control message */
562                 if((val = send(acceptfd, &msg, sizeof(msg),MSG_NOSIGNAL)) < sizeof(msg)) {
563                         perror("Error in sending no of objects that are not found\n");
564                         return 0;
565                 }
566                 /* Send number of oids not found and the missing oids if objects are missing in the machine */
567                 if(*(objnotfound) != 0) { 
568                         int size = sizeof(unsigned int)* *(objnotfound);
569                         if((val = send(acceptfd, oidnotfound, size ,MSG_NOSIGNAL)) < size) {
570                                 perror("Error in sending objects that are not found\n");
571                                 return 0;
572                         }
573                 }
574         }
575
576         /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
577          * if Participant receives a TRANS_COMMIT */
578         transinfo->objlocked = oidlocked;
579         transinfo->objnotfound = oidnotfound;
580         transinfo->modptr = modptr;
581         transinfo->numlocked = *(objlocked);
582         transinfo->numnotfound = *(objnotfound);
583         
584         return control;
585 }
586
587 /* This function processes all modified objects involved in a TRANS_COMMIT and updates pointer 
588  * addresses in lookup table and also changes version number
589  * Sends an ACK back to Coordinator */
590 int transCommitProcess(void *modptr, unsigned int *oidmod, unsigned int *oidlocked, int nummod, int numlocked, int acceptfd) {
591         objheader_t *header;
592         objheader_t *newheader;
593         int i = 0, offset = 0;
594         char control;
595         int tmpsize;
596
597         /* Process each modified object saved in the mainobject store */
598         for(i = 0; i < nummod; i++) {
599                 if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
600                         printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
601                         return 1;
602                 }
603                 GETSIZE(tmpsize,header);
604                 pthread_mutex_lock(&mainobjstore_mutex);
605                 memcpy(header, (char *)modptr + offset, tmpsize + sizeof(objheader_t));
606                 header->version += 1; 
607                 /* If threads are waiting on this object to be updated, notify them */
608                 if(header->notifylist != NULL) {
609                         notifyAll(&header->notifylist, OID(header), header->version);
610                 }
611                 pthread_mutex_unlock(&mainobjstore_mutex);
612                 offset += sizeof(objheader_t) + tmpsize;
613         }
614
615         if (nummod > 0)
616                 free(modptr);
617
618         /* Unlock locked objects */
619         for(i = 0; i < numlocked; i++) {
620                 if((header = (objheader_t *) mhashSearch(oidlocked[i])) == NULL) {
621                         printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
622                         return 1;
623                 }
624                 STATUS(header) &= ~(LOCK);
625         }
626         //TODO Update location lookup table
627
628         /* Send ack to coordinator */
629         control = TRANS_SUCESSFUL;
630         if(send((int)acceptfd, &control, sizeof(char), MSG_NOSIGNAL) < sizeof(char)) {
631                 perror("Error sending ACK to coordinator\n");
632         }
633         
634         return 0;
635 }
636
637 /* This function recevies the oid and offset tuples from the Coordinator's prefetch call.
638  * Looks for the objects to be prefetched in the main object store.
639  * If objects are not found then record those and if objects are found
640  * then use offset values to prefetch references to other objects */
641
642 int prefetchReq(int acceptfd) {
643   int i, length, sum, n, numbytes, numoffset, N, objnotfound = 0, size, count = 0;
644   int isArray = 0;
645   unsigned int oid, index = 0;
646   char *ptr, buffer[PRE_BUF_SIZE];
647   void *mobj;
648   unsigned int objoid;
649   char control;
650   objheader_t * header;
651   int bytesRecvd;
652   
653   /* Repeatedly recv the oid and offset pairs sent for prefetch */
654   while(numbytes = recv((int)acceptfd, &length, sizeof(int), 0) != 0) {
655     count++;
656     if(length == -1)
657       break;
658     sum = 0;
659     index = sizeof(unsigned int); // Index starts with sizeof  unsigned int because the 
660     // first 4 bytes are saved to send the
661     // size of the buffer (that is computed at the end of the loop)
662     bytesRecvd = 0;
663     do {
664       bytesRecvd += recv((int)acceptfd, (char *)&oid +bytesRecvd,
665                          sizeof(unsigned int) - bytesRecvd, 0);
666     } while (bytesRecvd < sizeof(unsigned int));
667     numoffset = (length - (sizeof(int) + sizeof(unsigned int)))/ sizeof(short);
668     N = numoffset * sizeof(short);
669     short offset[numoffset];
670     ptr = (char *)&offset;
671     /* Recv the offset values per oid */ 
672     do {
673       n = recv((int)acceptfd, (void *)ptr+sum, N-sum, 0); 
674       sum += n; 
675     } while(sum < N && n != 0); 
676     
677     /* Process each oid */
678     printf("Oid 0x%x is being searched\n", oid);
679     if ((mobj = mhashSearch(oid)) == NULL) {/* Obj not found */
680       /* Save the oids not found in buffer for later use */
681       *(buffer + index) = OBJECT_NOT_FOUND;
682       index += sizeof(char);
683       memcpy(buffer+index, &oid, sizeof(unsigned int));
684       index += sizeof(unsigned int);
685     } else { /* If Obj found in machine (i.e. has not moved) */
686       /* send the oid, it's size, it's header and data */
687       header = mobj;
688       GETSIZE(size, header);
689       size += sizeof(objheader_t);
690       *(buffer + index) = OBJECT_FOUND;
691       index += sizeof(char);
692       memcpy(buffer+index, &oid, sizeof(unsigned int));
693       index += sizeof(unsigned int);
694       memcpy(buffer+index, &size, sizeof(int));
695       index += sizeof(int);
696       memcpy(buffer + index, header, size);
697       index += size;
698       /* Calculate the oid corresponding to the offset value */
699       for(i = 0 ; i< numoffset ; i++) {
700               /* Check for arrays  */
701               if(TYPE(header) > NUMCLASSES) {
702                       isArray = 1;
703               }
704               if(isArray == 1) {
705                       int elementsize = classsize[TYPE(header)];
706                       objoid = *((unsigned int *)(((char *)header) + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*offset[i])));
707               } else {
708                       objoid = *((unsigned int *)(((char *)header) + sizeof(objheader_t) + offset[i]));
709               }
710               if((header = mhashSearch(objoid)) == NULL) {
711                       /* Obj not found, send oid */
712                       *(buffer + index) = OBJECT_NOT_FOUND;
713                       index += sizeof(char);
714                       memcpy(buffer+index, &oid, sizeof(unsigned int));
715                       index += sizeof(unsigned int);
716                       break;
717               } else {/* Obj Found */
718                       /* send the oid, it's size, it's header and data */
719                       GETSIZE(size, header);
720                       size+=sizeof(objheader_t);
721                       *(buffer + index) = OBJECT_FOUND;
722                       index += sizeof(char);
723                       memcpy(buffer+index, &oid, sizeof(unsigned int));
724                       index += sizeof(unsigned int);
725                       memcpy(buffer+index, &size, sizeof(int));
726                       index += sizeof(int);
727                       memcpy(buffer+index, header, size);
728                       index += size;
729                       isArray = 0;
730                       continue;
731               }
732       }
733     }
734     /* Check for overflow in the buffer */
735     if (index >= PRE_BUF_SIZE) {
736       printf("Char buffer is overflowing\n");
737       return 1;
738     }
739     /* Send Prefetch response control message only once*/
740     if(count == 1) {
741       control = TRANS_PREFETCH_RESPONSE;
742       if((numbytes = send(acceptfd, &control, sizeof(char), MSG_NOSIGNAL)) < sizeof(char)) {
743         perror("Error in sending PREFETCH RESPONSE to Coordinator\n");
744         return 1;
745       }
746     }
747     
748     /* Add the buffer size into buffer as a parameter */
749     *((unsigned int *)buffer)=index;
750     /* Send the entire buffer with its size and oids found and not found */
751     if(send((int)acceptfd, &buffer, index, MSG_NOSIGNAL) < sizeof(index -1)) {
752       perror("Error sending oids found\n");
753       return 1;
754     }
755   }
756   return 0;
757 }
758
759 void processReqNotify(unsigned int numoid, unsigned int *oidarry, unsigned short *versionarry, unsigned int mid, unsigned int threadid) {
760         objheader_t *header;
761         unsigned int oid;
762         unsigned short newversion;
763         char msg[1+ sizeof(unsigned int)];
764         int sd;
765         struct sockaddr_in remoteAddr;
766         int bytesSent;
767         int status, size, retry = 0;
768
769         int i = 0;
770         while(i < numoid) {
771                 oid = *(oidarry + i);
772                 if((header = (objheader_t *) mhashSearch(oid)) == NULL) {
773                         printf("processReqNotify(): Object is not found in mlookup %s, %d\n", __FILE__, __LINE__);
774                         return;
775                 } else {
776                         /* Check to see if versions are same */
777 checkversion:
778                         if ((STATUS(header) & LOCK) != LOCK) {          
779                                 STATUS(header) |= LOCK;
780                                 if(header->version == *(versionarry + i)) {
781                                         //Add to the notify list 
782                                         insNode(header->notifylist, threadid, mid); 
783                                 } else {
784                                         if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
785                                                 perror("processReqNotify():socket()");
786                                                 return;
787                                         }
788                                         bzero(&remoteAddr, sizeof(remoteAddr));
789                                         remoteAddr.sin_family = AF_INET;
790                                         remoteAddr.sin_port = htons(LISTEN_PORT);
791                                         remoteAddr.sin_addr.s_addr = htonl(mid);
792
793                                         if (connect(sd, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
794                                                 printf("processReqNotify():error %d connecting to %s:%d\n", errno,
795                                                                 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
796                                                 status = -1;
797                                         } else {
798                                                 //Send Update notification
799                                                 msg[0] = THREAD_NOTIFY_RESPONSE;
800                                                 msg[1] = oid;
801                                                 size = sizeof(unsigned int);
802                                                 memcpy(&msg[1] + size, &newversion, sizeof(unsigned short)); 
803                                                 size += sizeof(unsigned short);
804                                                 memcpy(&msg[1] + size, &threadid, sizeof(unsigned int)); 
805                                                 bytesSent = send(sd, msg, 1+sizeof(unsigned int), 0);
806                                                 if (bytesSent < 0){
807                                                         perror("processReqNotify():send()");
808                                                         status = -1;
809                                                 } else if (bytesSent != 1 + sizeof(unsigned short) + 2*sizeof(unsigned int)){
810                                                         printf("processReqNotify(): error, sent %d bytes\n", bytesSent);
811                                                         status = -1;
812                                                 } else {
813                                                         status = 0;
814                                                 }
815
816                                         }
817                                         close(sd);
818                                 }
819                                 STATUS(header) &= ~(LOCK);              
820                         } else {
821                                 randomdelay();
822                                 printf("DEBUG-> processReqNotify() Object is still locked\n");
823                                 goto checkversion;
824                         }
825                 }
826         }
827         free(oidarry);
828         free(versionarry);
829 }
830