completed and tested socket reuse code for trans read and trans prefetch() messages
[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             do {
154                 /* Read oid requested and search if available */
155                 recv_data((int)acceptfd, &oid, sizeof(unsigned int));
156                 if((srcObj = mhashSearch(oid)) == NULL) {
157                     printf("Error: Object 0x%x is not found in Main Object Store %s, %d\n", oid, __FILE__, __LINE__);
158                     break;
159                 }
160                 h = (objheader_t *) srcObj;
161                 GETSIZE(size, h);
162                 size += sizeof(objheader_t);
163                 sockid = (int) acceptfd;
164
165                 if (h == NULL) {
166                     ctrl = OBJECT_NOT_FOUND;
167                     send_data(sockid, &ctrl, sizeof(char));
168                 } else {
169                     /* Type */
170                     char msg[]={OBJECT_FOUND, 0, 0, 0, 0};
171                     *((int *)&msg[1])=size;
172                     send_data(sockid, &msg, sizeof(msg));
173                     send_data(sockid, h, size);
174                 }
175                                 recv_data((int)acceptfd, &control, sizeof(char));
176             } while(control == READ_REQUEST);
177                         break;
178                 
179                 case READ_MULT_REQUEST:
180                         break;
181         
182                 case MOVE_REQUEST:
183                         break;
184
185                 case MOVE_MULT_REQUEST:
186                         break;
187
188                 case TRANS_REQUEST:
189                         /* Read transaction request */
190                         if((val = readClientReq(&transinfo, (int)acceptfd)) != 0) {
191                                 printf("Error: In readClientReq() %s, %d\n", __FILE__, __LINE__);
192                                 pthread_exit(NULL);
193                         }
194                         break;
195                 case TRANS_PREFETCH:
196                         do {
197                                 if((val = prefetchReq((int)acceptfd)) != 0) {
198                                         printf("Error: In prefetchReq() %s, %d\n", __FILE__, __LINE__);
199                                         break;
200                                 }
201                                 recv_data((int)acceptfd, &control, sizeof(char));
202                         } while (control == TRANS_PREFETCH);
203                         break;
204                 case TRANS_PREFETCH_RESPONSE:
205                         do {
206                                 if((val = getPrefetchResponse((int) acceptfd)) != 0) {
207                                         printf("Error: In getPrefetchResponse() %s, %d\n", __FILE__, __LINE__);
208                                         break;
209                                 }
210                                 recv_data((int)acceptfd, &control, sizeof(char));
211                         } while (control == TRANS_PREFETCH_RESPONSE);
212                         break;
213                 case START_REMOTE_THREAD:
214                         recv_data((int)acceptfd, &oid, sizeof(unsigned int));
215                         objType = getObjType(oid);
216                         startDSMthread(oid, objType);
217                         break;
218
219                 case THREAD_NOTIFY_REQUEST:
220                         recv_data((int)acceptfd, &numoid, sizeof(unsigned int));
221                         size = (sizeof(unsigned int) + sizeof(unsigned short)) * numoid + 2 * sizeof(unsigned int);
222                         if((buffer = calloc(1,size)) == NULL) {
223                                 printf("%s() Calloc error at %s, %d\n", __func__, __FILE__, __LINE__);
224                                 pthread_exit(NULL);
225                         }
226
227                         recv_data((int)acceptfd, buffer, size);
228
229                         oidarry = calloc(numoid, sizeof(unsigned int)); 
230                         memcpy(oidarry, buffer, sizeof(unsigned int) * numoid);
231                         size = sizeof(unsigned int) * numoid;
232                         versionarry = calloc(numoid, sizeof(unsigned short));
233                         memcpy(versionarry, buffer+size, sizeof(unsigned short) * numoid);
234                         size += sizeof(unsigned short) * numoid;
235                         mid = *((unsigned int *)(buffer+size));
236                         size += sizeof(unsigned int);
237                         threadid = *((unsigned int *)(buffer+size));
238                         processReqNotify(numoid, oidarry, versionarry, mid, threadid);
239                         free(buffer);
240
241                         break;
242
243                 case THREAD_NOTIFY_RESPONSE:
244                         size = sizeof(unsigned short) + 2 * sizeof(unsigned int);
245                         if((buffer = calloc(1,size)) == NULL) {
246                                 printf("%s() Calloc error at %s, %d\n", __func__, __FILE__, __LINE__);
247                                 pthread_exit(NULL);
248                         }
249
250                         recv_data((int)acceptfd, buffer, size);
251
252                         oid = *((unsigned int *)buffer);
253                         size = sizeof(unsigned int);
254                         version = *((unsigned short *)(buffer+size));
255                         size += sizeof(unsigned short);
256                         threadid = *((unsigned int *)(buffer+size));
257                         threadNotify(oid,version,threadid);
258                         free(buffer);
259
260                         break;
261                 default:
262                         printf("Error: dstmAccept() Unknown opcode %d at %s, %d\n", control, __FILE__, __LINE__);
263         }
264
265         /* Close connection */
266         if (close((int)acceptfd) == -1)
267                 perror("close");
268         pthread_exit(NULL);
269 }
270
271 /* This function reads the information available in a transaction request
272  * and makes a function call to process the request */
273 int readClientReq(trans_commit_data_t *transinfo, int acceptfd) {
274         char *ptr;
275         void *modptr;
276         unsigned int *oidmod, oid;
277         fixed_data_t fixed;
278         objheader_t *headaddr;
279         int sum, i, size, n, val;
280
281         oidmod = NULL;
282
283         /* Read fixed_data_t data structure */ 
284         size = sizeof(fixed) - 1;
285         ptr = (char *)&fixed;;
286         fixed.control = TRANS_REQUEST;
287         recv_data((int)acceptfd, ptr+1, size);
288
289         /* Read list of mids */
290         int mcount = fixed.mcount;
291         size = mcount * sizeof(unsigned int);
292         unsigned int listmid[mcount];
293         ptr = (char *) listmid;
294         recv_data((int)acceptfd, ptr, size);
295         
296         /* Read oid and version tuples for those objects that are not modified in the transaction */
297         int numread = fixed.numread;
298         size = numread * (sizeof(unsigned int) + sizeof(unsigned short));
299         char objread[size];
300         if(numread != 0) { //If pile contains more than one object to be read, 
301                           // keep reading all objects
302                 recv_data((int)acceptfd, objread, size);        
303         }
304         
305         /* Read modified objects */
306         if(fixed.nummod != 0) {
307                 if ((modptr = calloc(1, fixed.sum_bytes)) == NULL) {
308                         printf("calloc error for modified objects %s, %d\n", __FILE__, __LINE__);
309                         return 1;
310                 }
311                 size = fixed.sum_bytes;
312                 recv_data((int)acceptfd, modptr, size); 
313         }
314
315         /* Create an array of oids for modified objects */
316         oidmod = (unsigned int *) calloc(fixed.nummod, sizeof(unsigned int));
317         if (oidmod == NULL)
318         {
319                 printf("calloc error %s, %d\n", __FILE__, __LINE__);
320                 return 1;
321         }
322         ptr = (char *) modptr;
323         for(i = 0 ; i < fixed.nummod; i++) {
324           int tmpsize;
325           headaddr = (objheader_t *) ptr;
326           oid = OID(headaddr);
327           oidmod[i] = oid;
328           GETSIZE(tmpsize, headaddr);
329           ptr += sizeof(objheader_t) + tmpsize;
330         }
331         
332         /*Process the information read */
333         if((val = processClientReq(&fixed, transinfo, listmid, objread, modptr, oidmod, acceptfd)) != 0) {
334                 printf("Error: In processClientReq() %s, %d\n", __FILE__, __LINE__);
335                 /* Free resources */
336                 if(oidmod != NULL) {
337                         free(oidmod);
338                 }
339                 return 1;
340         }
341
342         /* Free resources */
343         if(oidmod != NULL) {
344                 free(oidmod);
345         }
346
347         return 0;
348 }
349
350 /* This function processes the Coordinator's transaction request using "handleTransReq" 
351  * function and sends a reply to the co-ordinator.
352  * Following this it also receives a new control message from the co-ordinator and processes this message*/
353 int processClientReq(fixed_data_t *fixed, trans_commit_data_t *transinfo,
354                 unsigned int *listmid, char *objread, void *modptr, unsigned int *oidmod, int acceptfd) {
355         char control, sendctrl, retval;
356         objheader_t *tmp_header;
357         void *header;
358         int  i = 0, val;
359
360         /* Send reply to the Coordinator */
361         if((retval = handleTransReq(fixed, transinfo, listmid, objread, modptr,acceptfd)) == 0 ) {
362                 printf("Error: In handleTransReq() %s, %d\n", __FILE__, __LINE__);
363                 return 1;
364         }
365
366         recv_data((int)acceptfd, &control, sizeof(char));
367         
368         /* Process the new control message */
369         switch(control) {
370                 case TRANS_ABORT:
371                         if (fixed->nummod > 0)
372                                 free(modptr);
373                         /* Unlock objects that was locked due to this transaction */
374                         for(i = 0; i< transinfo->numlocked; i++) {
375                                 if((header = mhashSearch(transinfo->objlocked[i])) == NULL) {
376                                         printf("mhashSearch returns NULL at %s, %d\n", __FILE__, __LINE__);// find the header address
377                                         return 1;
378                                 }
379                                 STATUS(((objheader_t *)header)) &= ~(LOCK);             
380                         }
381
382                         /* Send ack to Coordinator */
383                         sendctrl = TRANS_UNSUCESSFUL;
384                         send_data((int)acceptfd, &sendctrl, sizeof(char));
385                         break;
386
387                 case TRANS_COMMIT:
388                         /* Invoke the transCommit process() */
389                         if((val = transCommitProcess(modptr, oidmod, transinfo->objlocked, fixed->nummod, transinfo->numlocked, (int)acceptfd)) != 0) {
390                                 printf("Error: In transCommitProcess() %s, %d\n", __FILE__, __LINE__);
391                                 /* Free memory */
392                                 if (transinfo->objlocked != NULL) {
393                                         free(transinfo->objlocked);
394                                 }
395                                 if (transinfo->objnotfound != NULL) {
396                                         free(transinfo->objnotfound);
397                                 }
398                                 return 1;
399                         }
400                         break;
401
402                 case TRANS_ABORT_BUT_RETRY_COMMIT_WITH_RELOCATING:
403                         break;
404                 default:
405                         printf("Error: No response to TRANS_AGREE OR DISAGREE protocol %s, %d\n", __FILE__, __LINE__);
406                         //TODO Use fixed.trans_id  TID since Client may have died
407                         break;
408         }
409
410         /* Free memory */
411         if (transinfo->objlocked != NULL) {
412                 free(transinfo->objlocked);
413         }
414         if (transinfo->objnotfound != NULL) {
415                 free(transinfo->objnotfound);
416         }
417
418         return 0;
419 }
420
421 /* This function increments counters while running a voting decision on all objects involved 
422  * in TRANS_REQUEST and If a TRANS_DISAGREE sends the response immediately back to the coordinator */
423 char handleTransReq(fixed_data_t *fixed, trans_commit_data_t *transinfo, unsigned int *listmid, char *objread, void *modptr, int acceptfd) {
424         int val, i = 0, j;
425         unsigned short version;
426         char control = 0, *ptr;
427         unsigned int oid;
428         unsigned int *oidnotfound, *oidlocked;
429         void *mobj;
430         objheader_t *headptr;
431
432         /* Counters and arrays to formulate decision on control message to be sent */
433         oidnotfound = (unsigned int *) calloc(fixed->numread + fixed->nummod, sizeof(unsigned int)); 
434         oidlocked = (unsigned int *) calloc(fixed->numread + fixed->nummod, sizeof(unsigned int)); 
435         int objnotfound = 0, objlocked = 0;
436         int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0;
437
438         /* modptr points to the beginning of the object store 
439          * created at the Pariticipant. 
440          * Object store holds the modified objects involved in the transaction request */ 
441         ptr = (char *) modptr;
442         
443         /* Process each oid in the machine pile/ group per thread */
444         for (i = 0; i < fixed->numread + fixed->nummod; i++) {
445                 if (i < fixed->numread) {//Objs only read and not modified
446                         int incr = sizeof(unsigned int) + sizeof(unsigned short);// Offset that points to next position in the objread array
447                         incr *= i;
448                         oid = *((unsigned int *)(objread + incr));
449                         incr += sizeof(unsigned int);
450                         version = *((unsigned short *)(objread + incr));
451                 } else {//Objs modified
452                   int tmpsize;
453                   headptr = (objheader_t *) ptr;
454                   oid = OID(headptr);
455                   version = headptr->version;
456                   GETSIZE(tmpsize, headptr);
457                   ptr += sizeof(objheader_t) + tmpsize;
458                 }
459                 
460                 /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */
461
462                 if ((mobj = mhashSearch(oid)) == NULL) {/* Obj not found */
463                         /* Save the oids not found and number of oids not found for later use */
464                         oidnotfound[objnotfound] = oid;
465                         objnotfound++;
466                 } else { /* If Obj found in machine (i.e. has not moved) */
467                         /* Check if Obj is locked by any previous transaction */
468                         if ((STATUS(((objheader_t *)mobj)) & LOCK) == LOCK) {           
469                                 if (version == ((objheader_t *)mobj)->version) {      /* If locked then match versions */
470                                         v_matchlock++;
471                                 } else {/* If versions don't match ...HARD ABORT */
472                                         v_nomatch++;
473                                         /* Send TRANS_DISAGREE to Coordinator */
474                                         control = TRANS_DISAGREE;
475                                         if (objlocked > 0) {
476                                           for(j = 0; j < objlocked; j++) {
477                                                         if((headptr = mhashSearch(oidlocked[j])) == NULL) {
478                                                                 printf("mhashSearch returns NULL at %s, %d\n", __FILE__, __LINE__);
479                                                                 return 0;
480                                                         }
481                                                         STATUS(headptr) &= ~(LOCK);
482                                                 }
483                                                 free(oidlocked);
484                                         }
485                                         send_data(acceptfd, &control, sizeof(char));
486                                         return control;
487                                 }
488                         } else {/* If Obj is not locked then lock object */
489                                 STATUS(((objheader_t *)mobj)) |= LOCK;
490                                 /* Save all object oids that are locked on this machine during this transaction request call */
491                                 oidlocked[objlocked] = OID(((objheader_t *)mobj));
492                                 objlocked++;
493                                 if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
494                                         v_matchnolock++;
495                                 } else { /* If versions don't match ...HARD ABORT */
496                                         v_nomatch++;
497                                         control = TRANS_DISAGREE;
498                                         if (objlocked > 0) {
499                                                 for(j = 0; j < objlocked; j++) {
500                                                         if((headptr = mhashSearch(oidlocked[j])) == NULL) {
501                                                                 printf("mhashSearch returns NULL at %s, %d\n", __FILE__, __LINE__);
502                                                                 return 0;
503                                                         }
504                                                         STATUS(headptr) &= ~(LOCK);
505                                                 }
506                                                 free(oidlocked);
507                                         }
508
509                                         /* Send TRANS_DISAGREE to Coordinator */
510                                         send_data(acceptfd, &control, sizeof(char));
511                                         return control;
512                                 }
513                         }
514                 }
515         }
516         
517         /* Decide what control message to send to Coordinator */
518         if ((control = decideCtrlMessage(fixed, transinfo, &v_matchnolock, &v_matchlock, &v_nomatch, &objnotfound, &objlocked,
519                                         modptr, oidnotfound, oidlocked, acceptfd)) == 0) {
520                 printf("Error: In decideCtrlMessage() %s, %d\n", __FILE__, __LINE__);
521                 return 0;
522         }
523         
524         return control;
525
526 }
527 /* This function decides what control message such as TRANS_AGREE, TRANS_DISAGREE or TRANS_SOFT_ABORT
528  * to send to Coordinator based on the votes of oids involved in the transaction */
529 char decideCtrlMessage(fixed_data_t *fixed, trans_commit_data_t *transinfo, int *v_matchnolock, int *v_matchlock, 
530                 int *v_nomatch, int *objnotfound, int *objlocked, void *modptr, 
531                 unsigned int *oidnotfound, unsigned int *oidlocked, int acceptfd) {
532         int val;
533         char control = 0;
534
535         /* Condition to send TRANS_AGREE */
536         if(*(v_matchnolock) == fixed->numread + fixed->nummod) {
537                 control = TRANS_AGREE;
538                 /* Send control message */
539                 send_data(acceptfd, &control, sizeof(char));
540         }
541         /* Condition to send TRANS_SOFT_ABORT */
542         if((*(v_matchlock) > 0 && *(v_nomatch) == 0) || (*(objnotfound) > 0 && *(v_nomatch) == 0)) {
543                 control = TRANS_SOFT_ABORT;
544
545                 /* Send control message */
546                 send_data(acceptfd, &control, sizeof(char));
547         
548                 /* Send number of oids not found and the missing oids if objects are missing in the machine */
549                 if(*(objnotfound) != 0) { 
550                         int msg[1];
551                         msg[0] = *(objnotfound);
552                         send_data(acceptfd, &msg, sizeof(int));
553                         int size = sizeof(unsigned int)* *(objnotfound);
554                         send_data(acceptfd, oidnotfound, size);
555                 }
556         }
557
558         /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process
559          * if Participant receives a TRANS_COMMIT */
560         transinfo->objlocked = oidlocked;
561         transinfo->objnotfound = oidnotfound;
562         transinfo->modptr = modptr;
563         transinfo->numlocked = *(objlocked);
564         transinfo->numnotfound = *(objnotfound);
565         
566         return control;
567 }
568
569 /* This function processes all modified objects involved in a TRANS_COMMIT and updates pointer 
570  * addresses in lookup table and also changes version number
571  * Sends an ACK back to Coordinator */
572 int transCommitProcess(void *modptr, unsigned int *oidmod, unsigned int *oidlocked, int nummod, int numlocked, int acceptfd) {
573         objheader_t *header;
574         objheader_t *newheader;
575         int i = 0, offset = 0;
576         char control;
577         int tmpsize;
578
579         /* Process each modified object saved in the mainobject store */
580         for(i = 0; i < nummod; i++) {
581                 if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) {
582                         printf("Error: mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
583                         return 1;
584                 }
585                 GETSIZE(tmpsize,header);
586                 pthread_mutex_lock(&mainobjstore_mutex);
587                 memcpy((char*)header + sizeof(objheader_t), ((char *)modptr + sizeof(objheader_t) + offset), tmpsize);
588                 header->version += 1; 
589                 /* If threads are waiting on this object to be updated, notify them */
590                 if(header->notifylist != NULL) {
591                         notifyAll(&header->notifylist, OID(header), header->version);
592                 }
593                 pthread_mutex_unlock(&mainobjstore_mutex);
594                 offset += sizeof(objheader_t) + tmpsize;
595         }
596
597         if (nummod > 0)
598                 free(modptr);
599
600         /* Unlock locked objects */
601         for(i = 0; i < numlocked; i++) {
602                 if((header = (objheader_t *) mhashSearch(oidlocked[i])) == NULL) {
603                         printf("Error: mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
604                         return 1;
605                 }
606                 STATUS(header) &= ~(LOCK);
607         }
608         //TODO Update location lookup table
609
610         /* Send ack to coordinator */
611         control = TRANS_SUCESSFUL;
612         send_data((int)acceptfd, &control, sizeof(char));
613         return 0;
614 }
615
616 /* This function recevies the oid and offset tuples from the Coordinator's prefetch call.
617  * Looks for the objects to be prefetched in the main object store.
618  * If objects are not found then record those and if objects are found
619  * then use offset values to prefetch references to other objects */
620
621 int prefetchReq(int acceptfd) {
622         int i, size, objsize, numbytes = 0, isArray = 0, numoffset = 0;
623         int length, sd = -1;
624         char *recvbuffer, *sendbuffer, control;
625         unsigned int oid, mid;
626         short *offsetarry;
627         objheader_t *header;
628         struct sockaddr_in remoteAddr;
629
630         do {
631                 recv_data((int)acceptfd, &length, sizeof(int));
632                 if(length != -1) {
633                         size = length - sizeof(int);
634                         if((recvbuffer = calloc(1, size)) == NULL) {
635                                 printf("Calloc error at %s,%d\n", __FILE__, __LINE__);
636                                 return -1;
637                         }
638                         recv_data((int)acceptfd, recvbuffer, size);
639                         oid = *((unsigned int *) recvbuffer);
640                         mid = *((unsigned int *) (recvbuffer + sizeof(unsigned int)));
641                         size = size - (2 * sizeof(unsigned int));
642                         numoffset = size / sizeof(short);
643                         if((offsetarry = calloc(numoffset, sizeof(short))) == NULL) {
644                                 printf("Calloc error at %s,%d\n", __FILE__, __LINE__);
645                                 free(recvbuffer);
646                                 return -1;
647                         }
648                         memcpy(offsetarry, recvbuffer + (2 * sizeof(unsigned int)), size);
649                         free(recvbuffer);
650                         pthread_mutex_lock(&sockLock);
651                         sockIdFound = 0;
652                         pthread_mutex_unlock(&sockLock);
653             /* If socket is already established then send data reusing socket */
654                         for(i = 0; i < NUM_MACHINES; i++) {
655                                 if(sockArray[i].mid == mid) {
656                                         sd = sockArray[i].sockid;
657                                         pthread_mutex_lock(&sockLock);
658                                         sockIdFound = 1;
659                                         pthread_mutex_unlock(&sockLock);
660                                         break;
661                                 }
662                         }
663
664                         if(sockIdFound == 0) {
665                                 if(sockCount < NUM_MACHINES) {
666                                         /* Create socket to send information */
667                                         if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
668                                                 perror("prefetchReq():socket()");
669                                                 return -1;
670                                         }
671                                         bzero(&remoteAddr, sizeof(remoteAddr));
672                                         remoteAddr.sin_family = AF_INET;
673                                         remoteAddr.sin_port = htons(LISTEN_PORT);
674                                         remoteAddr.sin_addr.s_addr = htonl(mid);
675
676                                         if (connect(sd, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
677                                                 perror("connect");
678                                                 printf("Error: prefetchReq():error %d connecting to %s:%d\n", errno,
679                                                                 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
680                                                 close(sd);
681                                                 return -1;
682                                         }
683                                         sockArray[sockCount].mid = mid;
684                                         sockArray[sockCount].sockid = sd;
685                                         pthread_mutex_lock(&sockLock);
686                                         sockCount++;
687                                         pthread_mutex_unlock(&sockLock);
688                                 } else {
689                                         //TODO Fix for connecting to more than 2 machines && close socket
690                                         printf("%s(): Error: Currently works for only 2 machines\n", __func__);
691                                         return -1;
692                                 }
693                         }
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                 }
816         } while (length != -1);
817         return 0;
818 }
819
820 int sendPrefetchResponse(int sd, char *control, char *sendbuffer, int *size) {
821         int numbytes = 0;
822
823         send_data(sd, control, sizeof(char));
824         /* Send the buffer with its size */
825         int length = *(size);
826         send_data(sd, sendbuffer, length);
827         free(sendbuffer);
828         return 0;
829 }
830
831 void processReqNotify(unsigned int numoid, unsigned int *oidarry, unsigned short *versionarry, unsigned int mid, unsigned int threadid) {
832         objheader_t *header;
833         unsigned int oid;
834         unsigned short newversion;
835         char msg[1+  2 * sizeof(unsigned int) + sizeof(unsigned short)];
836         int sd;
837         struct sockaddr_in remoteAddr;
838         int bytesSent;
839         int size;
840
841         int i = 0;
842         while(i < numoid) {
843                 oid = *(oidarry + i);
844                 if((header = (objheader_t *) mhashSearch(oid)) == NULL) {
845                         printf("Error: mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__);
846                         return;
847                 } else {
848                         /* Check to see if versions are same */
849 checkversion:
850                         if ((STATUS(header) & LOCK) != LOCK) {          
851                                 //FIXME make locking atomic
852                                 STATUS(header) |= LOCK;
853                                 newversion = header->version;
854                                 if(newversion == *(versionarry + i)) {
855                                         //Add to the notify list 
856                                         if((header->notifylist = insNode(header->notifylist, threadid, mid)) == NULL) {
857                                                 printf("Error: Obj notify list points to NULL %s, %d\n", __FILE__, __LINE__); 
858                                                 return;
859                                         }
860                                         STATUS(header) &= ~(LOCK);              
861                                 } else {
862                                         STATUS(header) &= ~(LOCK);              
863                                         if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
864                                                 perror("processReqNotify():socket()");
865                                                 return;
866                                         }
867                                         bzero(&remoteAddr, sizeof(remoteAddr));
868                                         remoteAddr.sin_family = AF_INET;
869                                         remoteAddr.sin_port = htons(LISTEN_PORT);
870                                         remoteAddr.sin_addr.s_addr = htonl(mid);
871
872                                         if (connect(sd, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){
873                                                 printf("Error: processReqNotify():error %d connecting to %s:%d\n", errno,
874                                                                 inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
875                                                 close(sd);
876                                                 return;
877                                         } else {
878                                                 //Send Update notification
879                                                 msg[0] = THREAD_NOTIFY_RESPONSE;
880                                                 *((unsigned int *)&msg[1]) = oid;
881                                                 size = sizeof(unsigned int);
882                                                 *((unsigned short *)(&msg[1]+size)) = newversion;
883                                                 size += sizeof(unsigned short);
884                                                 *((unsigned int *)(&msg[1]+size)) = threadid;
885                                                 size = 1+ 2*sizeof(unsigned int) + sizeof(unsigned short);
886                                                 send_data(sd, msg, size);
887                                         }
888                                         close(sd);
889                                 }
890                         } else {
891                                 randomdelay();
892                                 goto checkversion;
893                         }
894                 }
895                 i++;
896         }
897         free(oidarry);
898         free(versionarry);
899 }