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