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