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