65e35371795dfb605fbbe200f806d63d05fc4003
[openafs.git] / src / vol / fssync-server.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  *
9  * Portions Copyright (c) 2006-2008 Sine Nomine Associates
10  */
11
12 /*
13         System:         VICE-TWO
14         Module:         fssync.c
15         Institution:    The Information Technology Center, Carnegie-Mellon University
16
17  */
18 #ifndef AFS_PTHREAD_ENV
19 #define USUAL_PRIORITY (LWP_MAX_PRIORITY - 2)
20
21 /*
22  * stack size increased from 8K because the HP machine seemed to have trouble
23  * with the smaller stack
24  */
25 #define USUAL_STACK_SIZE        (24 * 1024)
26 #endif /* !AFS_PTHREAD_ENV */
27
28 /*
29    fssync-server.c
30    File server synchronization with external volume utilities.
31    server-side implementation
32  */
33
34 /* This controls the size of an fd_set; it must be defined early before
35  * the system headers define that type and the macros that operate on it.
36  * Its value should be as large as the maximum file descriptor limit we
37  * are likely to run into on any platform.  Right now, that is 65536
38  * which is the default hard fd limit on Solaris 9 */
39 #ifndef _WIN32
40 #define FD_SETSIZE 65536
41 #endif
42
43 #include <afsconfig.h>
44 #include <afs/param.h>
45
46
47 #include <sys/types.h>
48 #include <stdio.h>
49 #ifdef AFS_NT40_ENV
50 #include <winsock2.h>
51 #include <time.h>
52 #else
53 #include <sys/param.h>
54 #include <sys/socket.h>
55 #include <netinet/in.h>
56 #include <netdb.h>
57 #include <sys/time.h>
58 #include <unistd.h>
59 #endif
60 #include <errno.h>
61 #ifdef AFS_PTHREAD_ENV
62 #include <assert.h>
63 #else /* AFS_PTHREAD_ENV */
64 #include <afs/assert.h>
65 #endif /* AFS_PTHREAD_ENV */
66 #include <signal.h>
67 #include <string.h>
68
69 #include <rx/xdr.h>
70 #include <afs/afsint.h>
71 #include "nfs.h"
72 #include <afs/errors.h>
73 #include "daemon_com.h"
74 #include "fssync.h"
75 #include "lwp.h"
76 #include "lock.h"
77 #include <afs/afssyscalls.h>
78 #include "ihandle.h"
79 #include "vnode.h"
80 #include "volume.h"
81 #include "volume_inline.h"
82 #include "partition.h"
83
84 #ifdef HAVE_POLL
85 #include <sys/poll.h>
86 #endif /* HAVE_POLL */
87
88 #ifdef USE_UNIX_SOCKETS
89 #include <sys/un.h>
90 #include <afs/afsutil.h>
91 #endif /* USE_UNIX_SOCKETS */
92
93 #ifdef FSSYNC_BUILD_SERVER
94
95 /*@printflike@*/ extern void Log(const char *format, ...);
96
97 int (*V_BreakVolumeCallbacks) (VolumeId volume);
98
99 #define MAXHANDLERS     4       /* Up to 4 clients; must be at least 2, so that
100                                  * move = dump+restore can run on single server */
101 #define MAXOFFLINEVOLUMES 128   /* This needs to be as big as the maximum
102                                  * number that would be offline for 1 operation.
103                                  * Current winner is salvage, which needs all
104                                  * cloned read-only copies offline when salvaging
105                                  * a single read-write volume */
106
107
108
109 static struct offlineInfo OfflineVolumes[MAXHANDLERS][MAXOFFLINEVOLUMES];
110
111 /**
112  * fssync server socket handle.
113  */
114 static SYNC_server_state_t fssync_server_state = 
115     { -1,                       /* file descriptor */
116       FSSYNC_ENDPOINT_DECL,     /* server endpoint */
117       FSYNC_PROTO_VERSION,      /* protocol version */
118       5,                        /* bind() retry limit */
119       100,                      /* listen() queue depth */
120       "FSSYNC",                 /* protocol name string */
121     };
122
123
124 /* Forward declarations */
125 static void * FSYNC_sync(void *);
126 static void FSYNC_newconnection(osi_socket afd);
127 static void FSYNC_com(osi_socket fd);
128 static void FSYNC_Drop(osi_socket fd);
129 static void AcceptOn(void);
130 static void AcceptOff(void);
131 static void InitHandler(void);
132 static int AddHandler(osi_socket fd, void (*aproc)(osi_socket));
133 static int FindHandler(osi_socket afd);
134 static int FindHandler_r(osi_socket afd);
135 static int RemoveHandler(osi_socket afd);
136 #if defined(HAVE_POLL) && defined (AFS_PTHREAD_ENV)
137 static void CallHandler(struct pollfd *fds, int nfds, int mask);
138 static void GetHandler(struct pollfd *fds, int maxfds, int events, int *nfds);
139 #else
140 static void CallHandler(fd_set * fdsetp);
141 static void GetHandler(fd_set * fdsetp, int *maxfdp);
142 #endif
143 extern int LogLevel;
144
145 static afs_int32 FSYNC_com_VolOp(osi_socket fd, SYNC_command * com, SYNC_response * res);
146
147 #ifdef AFS_DEMAND_ATTACH_FS
148 static afs_int32 FSYNC_com_VolError(FSSYNC_VolOp_command * com, SYNC_response * res);
149 #endif
150 static afs_int32 FSYNC_com_VolOn(FSSYNC_VolOp_command * com, SYNC_response * res);
151 static afs_int32 FSYNC_com_VolOff(FSSYNC_VolOp_command * com, SYNC_response * res);
152 static afs_int32 FSYNC_com_VolMove(FSSYNC_VolOp_command * com, SYNC_response * res);
153 static afs_int32 FSYNC_com_VolBreakCBKs(FSSYNC_VolOp_command * com, SYNC_response * res);
154 static afs_int32 FSYNC_com_VolDone(FSSYNC_VolOp_command * com, SYNC_response * res);
155 static afs_int32 FSYNC_com_VolQuery(FSSYNC_VolOp_command * com, SYNC_response * res);
156 static afs_int32 FSYNC_com_VolHdrQuery(FSSYNC_VolOp_command * com, SYNC_response * res);
157 #ifdef AFS_DEMAND_ATTACH_FS
158 static afs_int32 FSYNC_com_VolOpQuery(FSSYNC_VolOp_command * com, SYNC_response * res);
159 #endif /* AFS_DEMAND_ATTACH_FS */
160
161 static afs_int32 FSYNC_com_VnQry(osi_socket fd, SYNC_command * com, SYNC_response * res);
162
163 static afs_int32 FSYNC_com_StatsOp(osi_socket fd, SYNC_command * com, SYNC_response * res);
164
165 static afs_int32 FSYNC_com_StatsOpGeneral(FSSYNC_StatsOp_command * scom, SYNC_response * res);
166
167 #ifdef AFS_DEMAND_ATTACH_FS
168 static afs_int32 FSYNC_com_StatsOpViceP(FSSYNC_StatsOp_command * scom, SYNC_response * res);
169 static afs_int32 FSYNC_com_StatsOpHash(FSSYNC_StatsOp_command * scom, SYNC_response * res);
170 static afs_int32 FSYNC_com_StatsOpHdr(FSSYNC_StatsOp_command * scom, SYNC_response * res);
171 static afs_int32 FSYNC_com_StatsOpVLRU(FSSYNC_StatsOp_command * scom, SYNC_response * res);
172 #endif
173
174 static void FSYNC_com_to_info(FSSYNC_VolOp_command * vcom, FSSYNC_VolOp_info * info);
175
176 static int FSYNC_partMatch(FSSYNC_VolOp_command * vcom, Volume * vp, int match_anon);
177
178
179 /*
180  * This lock controls access to the handler array. The overhead
181  * is minimal in non-preemptive environments.
182  */
183 struct Lock FSYNC_handler_lock;
184
185 void
186 FSYNC_fsInit(void)
187 {
188 #ifdef AFS_PTHREAD_ENV
189     pthread_t tid;
190     pthread_attr_t tattr;
191 #else /* AFS_PTHREAD_ENV */
192     PROCESS pid;
193 #endif /* AFS_PTHREAD_ENV */
194
195     Lock_Init(&FSYNC_handler_lock);
196
197 #ifdef AFS_PTHREAD_ENV
198     assert(pthread_attr_init(&tattr) == 0);
199     assert(pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED) == 0);
200     assert(pthread_create(&tid, &tattr, FSYNC_sync, NULL) == 0);
201 #else /* AFS_PTHREAD_ENV */
202     assert(LWP_CreateProcess
203            (FSYNC_sync, USUAL_STACK_SIZE, USUAL_PRIORITY, (void *)0,
204             "FSYNC_sync", &pid) == LWP_SUCCESS);
205 #endif /* AFS_PTHREAD_ENV */
206 }
207
208 #if defined(HAVE_POLL) && defined(AFS_PTHREAD_ENV)
209 static struct pollfd FSYNC_readfds[MAXHANDLERS];
210 #else
211 static fd_set FSYNC_readfds;
212 #endif
213
214
215 static void *
216 FSYNC_sync(void * args)
217 {
218     extern int VInit;
219     int code;
220 #ifdef AFS_PTHREAD_ENV
221     int tid;
222 #endif
223     SYNC_server_state_t * state = &fssync_server_state;
224 #ifdef AFS_DEMAND_ATTACH_FS
225     VThreadOptions_t * thread_opts;
226     int min_vinit = 2;
227 #else
228     /*
229      * For non-DAFS, only wait until we begin attaching volumes (instead
230      * of waiting until all volumes are attached), since it can take
231      * awhile until VInit == 2.
232      */
233     int min_vinit = 1;
234 #endif /* AFS_DEMAND_ATTACH_FS */
235
236     SYNC_getAddr(&state->endpoint, &state->addr);
237     SYNC_cleanupSock(state);
238
239 #ifndef AFS_NT40_ENV
240     (void)signal(SIGPIPE, SIG_IGN);
241 #endif
242
243 #ifdef AFS_PTHREAD_ENV
244     /* set our 'thread-id' so that the host hold table works */
245     MUTEX_ENTER(&rx_stats_mutex);       /* protects rxi_pthread_hinum */
246     tid = ++rxi_pthread_hinum;
247     MUTEX_EXIT(&rx_stats_mutex);
248     pthread_setspecific(rx_thread_id_key, (void *)(intptr_t)tid);
249     Log("Set thread id %d for FSYNC_sync\n", tid);
250 #endif /* AFS_PTHREAD_ENV */
251
252     while (VInit < min_vinit) {
253         /* Let somebody else run until all volumes have been preattached
254          * (DAFS), or we have started attaching volumes (non-DAFS). This
255          * doesn't mean that all volumes have been attached.
256          */
257 #ifdef AFS_PTHREAD_ENV
258         pthread_yield();
259 #else /* AFS_PTHREAD_ENV */
260         LWP_DispatchProcess();
261 #endif /* AFS_PTHREAD_ENV */
262     }
263     state->fd = SYNC_getSock(&state->endpoint);
264     code = SYNC_bindSock(state);
265     assert(!code);
266
267 #ifdef AFS_DEMAND_ATTACH_FS
268     /*
269      * make sure the volume package is incapable of recursively executing
270      * salvsync calls on this thread, since there is a possibility of
271      * deadlock.
272      */
273     thread_opts = malloc(sizeof(VThreadOptions_t));
274     if (thread_opts == NULL) {
275         Log("failed to allocate memory for thread-specific volume package options structure\n");
276         return NULL;
277     }
278     memcpy(thread_opts, &VThread_defaults, sizeof(VThread_defaults));
279     thread_opts->disallow_salvsync = 1;
280     assert(pthread_setspecific(VThread_key, thread_opts) == 0);
281 #endif
282
283     InitHandler();
284     AcceptOn();
285
286     for (;;) {
287 #if defined(HAVE_POLL) && defined(AFS_PTHREAD_ENV)
288         int nfds;
289         GetHandler(FSYNC_readfds, MAXHANDLERS, POLLIN|POLLPRI, &nfds);
290         if (poll(FSYNC_readfds, nfds, -1) >=1)
291             CallHandler(FSYNC_readfds, nfds, POLLIN|POLLPRI);
292 #else
293         int maxfd;
294         GetHandler(&FSYNC_readfds, &maxfd);
295         /* Note: check for >= 1 below is essential since IOMGR_select
296          * doesn't have exactly same semantics as select.
297          */
298 #ifdef AFS_PTHREAD_ENV
299         if (select(maxfd + 1, &FSYNC_readfds, NULL, NULL, NULL) >= 1)
300 #else /* AFS_PTHREAD_ENV */
301         if (IOMGR_Select(maxfd + 1, &FSYNC_readfds, NULL, NULL, NULL) >= 1)
302 #endif /* AFS_PTHREAD_ENV */
303             CallHandler(&FSYNC_readfds);
304 #endif
305     }
306     return NULL; /* hush now, little gcc */
307 }
308
309 static void
310 FSYNC_newconnection(osi_socket afd)
311 {
312 #ifdef USE_UNIX_SOCKETS
313     struct sockaddr_un other;
314 #else  /* USE_UNIX_SOCKETS */
315     struct sockaddr_in other;
316 #endif
317     osi_socket fd;
318     socklen_t junk;
319     junk = sizeof(other);
320     fd = accept(afd, (struct sockaddr *)&other, &junk);
321     if (fd == -1) {
322         Log("FSYNC_newconnection:  accept failed, errno==%d\n", errno);
323         assert(1 == 2);
324     } else if (!AddHandler(fd, FSYNC_com)) {
325         AcceptOff();
326         assert(AddHandler(fd, FSYNC_com));
327     }
328 }
329
330 /* this function processes commands from an fssync file descriptor (fd) */
331 afs_int32 FS_cnt = 0;
332 static void
333 FSYNC_com(osi_socket fd)
334 {
335     SYNC_command com;
336     SYNC_response res;
337     SYNC_PROTO_BUF_DECL(com_buf);
338     SYNC_PROTO_BUF_DECL(res_buf);
339
340     memset(&res.hdr, 0, sizeof(res.hdr));
341
342     com.payload.buf = (void *)com_buf;
343     com.payload.len = SYNC_PROTO_MAX_LEN;
344     res.hdr.response_len = sizeof(res.hdr);
345     res.payload.len = SYNC_PROTO_MAX_LEN;
346     res.payload.buf = (void *)res_buf;
347
348     FS_cnt++;
349     if (SYNC_getCom(&fssync_server_state, fd, &com)) {
350         Log("FSYNC_com:  read failed; dropping connection (cnt=%d)\n", FS_cnt);
351         FSYNC_Drop(fd);
352         return;
353     }
354
355     if (com.recv_len < sizeof(com.hdr)) {
356         Log("FSSYNC_com:  invalid protocol message length (%u)\n", com.recv_len);
357         res.hdr.response = SYNC_COM_ERROR;
358         res.hdr.reason = SYNC_REASON_MALFORMED_PACKET;
359         res.hdr.flags |= SYNC_FLAG_CHANNEL_SHUTDOWN;
360         goto respond;
361     }
362
363     if (com.hdr.proto_version != FSYNC_PROTO_VERSION) {
364         Log("FSYNC_com:  invalid protocol version (%u)\n", com.hdr.proto_version);
365         res.hdr.response = SYNC_COM_ERROR;
366         res.hdr.flags |= SYNC_FLAG_CHANNEL_SHUTDOWN;
367         goto respond;
368     }
369
370     if (com.hdr.command == SYNC_COM_CHANNEL_CLOSE) {
371         res.hdr.response = SYNC_OK;
372         res.hdr.flags |= SYNC_FLAG_CHANNEL_SHUTDOWN;
373
374         /* don't respond, just drop; senders of SYNC_COM_CHANNEL_CLOSE
375          * never wait for a response. */
376         goto done;
377     }
378
379     res.hdr.com_seq = com.hdr.com_seq;
380
381     VOL_LOCK;
382     switch (com.hdr.command) {
383     case FSYNC_VOL_ON:
384     case FSYNC_VOL_ATTACH:
385     case FSYNC_VOL_LEAVE_OFF:
386     case FSYNC_VOL_OFF:
387     case FSYNC_VOL_FORCE_ERROR:
388     case FSYNC_VOL_LISTVOLUMES:
389     case FSYNC_VOL_NEEDVOLUME:
390     case FSYNC_VOL_MOVE:
391     case FSYNC_VOL_BREAKCBKS:
392     case FSYNC_VOL_DONE:
393     case FSYNC_VOL_QUERY:
394     case FSYNC_VOL_QUERY_HDR:
395     case FSYNC_VOL_QUERY_VOP:
396         res.hdr.response = FSYNC_com_VolOp(fd, &com, &res);
397         break;
398     case FSYNC_VOL_STATS_GENERAL:
399     case FSYNC_VOL_STATS_VICEP:
400     case FSYNC_VOL_STATS_HASH:
401     case FSYNC_VOL_STATS_HDR:
402     case FSYNC_VOL_STATS_VLRU:
403         res.hdr.response = FSYNC_com_StatsOp(fd, &com, &res);
404         break;
405     case FSYNC_VOL_QUERY_VNODE:
406         res.hdr.response = FSYNC_com_VnQry(fd, &com, &res);
407         break;
408     default:
409         res.hdr.response = SYNC_BAD_COMMAND;
410         break;
411     }
412     VOL_UNLOCK;
413
414  respond:
415     SYNC_putRes(&fssync_server_state, fd, &res);
416
417  done:
418     if (res.hdr.flags & SYNC_FLAG_CHANNEL_SHUTDOWN) {
419         FSYNC_Drop(fd);
420     }
421 }
422
423 static afs_int32
424 FSYNC_com_VolOp(osi_socket fd, SYNC_command * com, SYNC_response * res)
425 {
426     int i;
427     afs_int32 code = SYNC_OK;
428     FSSYNC_VolOp_command vcom;
429
430     if (com->recv_len != (sizeof(com->hdr) + sizeof(FSSYNC_VolOp_hdr))) {
431         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
432         res->hdr.flags |= SYNC_FLAG_CHANNEL_SHUTDOWN;
433         return SYNC_COM_ERROR;
434     }
435
436     vcom.hdr = &com->hdr;
437     vcom.vop = (FSSYNC_VolOp_hdr *) com->payload.buf;
438     vcom.com = com;
439
440     vcom.volumes = OfflineVolumes[FindHandler(fd)];
441     for (vcom.v = NULL, i = 0; i < MAXOFFLINEVOLUMES; i++) {
442         if ((vcom.volumes[i].volumeID == vcom.vop->volume) &&
443             (strncmp(vcom.volumes[i].partName, vcom.vop->partName,
444                      sizeof(vcom.volumes[i].partName)) == 0)) {
445             vcom.v = &vcom.volumes[i];
446             break;
447         }
448     }
449
450     switch (com->hdr.command) {
451     case FSYNC_VOL_ON:
452     case FSYNC_VOL_ATTACH:
453     case FSYNC_VOL_LEAVE_OFF:
454         code = FSYNC_com_VolOn(&vcom, res);
455         break;
456     case FSYNC_VOL_OFF:
457     case FSYNC_VOL_NEEDVOLUME:
458         code = FSYNC_com_VolOff(&vcom, res);
459         break;
460     case FSYNC_VOL_LISTVOLUMES:
461         code = SYNC_OK;
462         break;
463     case FSYNC_VOL_MOVE:
464         code = FSYNC_com_VolMove(&vcom, res);
465         break;
466     case FSYNC_VOL_BREAKCBKS:
467         code = FSYNC_com_VolBreakCBKs(&vcom, res);
468         break;
469     case FSYNC_VOL_DONE:
470         code = FSYNC_com_VolDone(&vcom, res);
471         break;
472     case FSYNC_VOL_QUERY:
473         code = FSYNC_com_VolQuery(&vcom, res);
474         break;
475     case FSYNC_VOL_QUERY_HDR:
476         code = FSYNC_com_VolHdrQuery(&vcom, res);
477         break;
478 #ifdef AFS_DEMAND_ATTACH_FS
479     case FSYNC_VOL_FORCE_ERROR:
480         code = FSYNC_com_VolError(&vcom, res);
481         break;
482     case FSYNC_VOL_QUERY_VOP:
483         code = FSYNC_com_VolOpQuery(&vcom, res);
484         break;
485 #endif /* AFS_DEMAND_ATTACH_FS */
486     default:
487         code = SYNC_BAD_COMMAND;
488     }
489
490     return code;
491 }
492
493 /**
494  * service an FSYNC request to bring a volume online.
495  *
496  * @param[in]   vcom  pointer command object
497  * @param[out]  res   object in which to store response packet
498  *
499  * @return operation status
500  *   @retval SYNC_OK volume transitioned online
501  *   @retval SYNC_FAILED invalid command protocol message
502  *   @retval SYNC_DENIED operation could not be completed
503  *
504  * @note this is an FSYNC RPC server stub
505  *
506  * @note this procedure handles the following FSSYNC command codes:
507  *       - FSYNC_VOL_ON
508  *       - FSYNC_VOL_ATTACH
509  *       - FSYNC_VOL_LEAVE_OFF
510  *
511  * @note the supplementary reason code contains additional details.
512  *       When SYNC_DENIED is returned, the specific reason is
513  *       placed in the response packet reason field.
514  *
515  * @internal
516  */
517 static afs_int32
518 FSYNC_com_VolOn(FSSYNC_VolOp_command * vcom, SYNC_response * res)
519 {
520     afs_int32 code = SYNC_OK;
521 #ifndef AFS_DEMAND_ATTACH_FS
522     char tvolName[VMAXPATHLEN];
523 #endif
524     Volume * vp;
525     Error error;
526
527     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
528         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
529         code = SYNC_FAILED;
530         goto done;
531     }
532
533     /* so, we need to attach the volume */
534
535 #ifdef AFS_DEMAND_ATTACH_FS
536     /* check DAFS permissions */
537     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
538     if (vp &&
539         FSYNC_partMatch(vcom, vp, 1) &&
540         vp->pending_vol_op && 
541         (vcom->hdr->programType != vp->pending_vol_op->com.programType)) {
542         /* a different program has this volume checked out. deny. */
543         Log("FSYNC_VolOn: WARNING: program type %u has attempted to manipulate "
544             "state for volume %u using command code %u while the volume is " 
545             "checked out by program type %u for command code %u.\n",
546             vcom->hdr->programType,
547             vcom->vop->volume,
548             vcom->hdr->command,
549             vp->pending_vol_op->com.programType,
550             vp->pending_vol_op->com.command);
551         code = SYNC_DENIED;
552         res->hdr.reason = FSYNC_EXCLUSIVE;
553         goto done;
554     }
555 #endif
556
557     if (vcom->v)
558         vcom->v->volumeID = 0;
559
560
561     if (vcom->hdr->command == FSYNC_VOL_LEAVE_OFF) {
562         /* nothing much to do if we're leaving the volume offline */
563 #ifdef AFS_DEMAND_ATTACH_FS
564         if (vp) {
565             if (FSYNC_partMatch(vcom, vp, 1)) {
566                 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
567                     (V_attachState(vp) == VOL_STATE_PREATTACHED)) {
568                     VChangeState_r(vp, VOL_STATE_UNATTACHED);
569                     VDeregisterVolOp_r(vp);
570                 } else {
571                     code = SYNC_DENIED;
572                     res->hdr.reason = FSYNC_BAD_STATE;
573                 }
574             } else {
575                 code = SYNC_DENIED;
576                 res->hdr.reason = FSYNC_WRONG_PART;
577             }
578         } else {
579             code = SYNC_DENIED;
580             res->hdr.reason = FSYNC_UNKNOWN_VOLID;
581         }
582 #endif
583         goto done;
584     }
585
586 #ifdef AFS_DEMAND_ATTACH_FS
587     /* first, check to see whether we have such a volume defined */
588     vp = VPreAttachVolumeById_r(&error,
589                                 vcom->vop->partName,
590                                 vcom->vop->volume);
591     if (vp) {
592         VDeregisterVolOp_r(vp);
593     }
594 #else /* !AFS_DEMAND_ATTACH_FS */
595     tvolName[0] = '/';
596     snprintf(&tvolName[1], sizeof(tvolName)-1, VFORMAT, afs_printable_uint32_lu(vcom->vop->volume));
597     tvolName[sizeof(tvolName)-1] = '\0';
598
599     vp = VAttachVolumeByName_r(&error, vcom->vop->partName, tvolName,
600                                V_VOLUPD);
601     if (vp)
602         VPutVolume_r(vp);
603     if (error) {
604         code = SYNC_DENIED;
605         res->hdr.reason = error;
606     }
607 #endif /* !AFS_DEMAND_ATTACH_FS */
608
609  done:
610     return code;
611 }
612
613 /**
614  * service an FSYNC request to take a volume offline.
615  *
616  * @param[in]   vcom  pointer command object
617  * @param[out]  res   object in which to store response packet
618  *
619  * @return operation status
620  *   @retval SYNC_OK volume transitioned offline
621  *   @retval SYNC_FAILED invalid command protocol message
622  *   @retval SYNC_DENIED operation could not be completed
623  *
624  * @note this is an FSYNC RPC server stub
625  *
626  * @note this procedure handles the following FSSYNC command codes:
627  *       - FSYNC_VOL_OFF 
628  *       - FSYNC_VOL_NEEDVOLUME
629  *
630  * @note the supplementary reason code contains additional details.
631  *       When SYNC_DENIED is returned, the specific reason is
632  *       placed in the response packet reason field.
633  *
634  * @internal
635  */
636 static afs_int32
637 FSYNC_com_VolOff(FSSYNC_VolOp_command * vcom, SYNC_response * res)
638 {
639     FSSYNC_VolOp_info info;
640     afs_int32 code = SYNC_OK;
641     int i;
642     Volume * vp;
643     Error error;
644 #ifdef AFS_DEMAND_ATTACH_FS
645     Volume *nvp;
646 #endif
647
648     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
649         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
650         code = SYNC_FAILED;
651         goto done;
652     }
653
654     /* not already offline, we need to find a slot for newly offline volume */
655     if (vcom->hdr->programType == debugUtility) {
656         /* debug utilities do not have their operations tracked */
657         vcom->v = NULL;
658     } else {
659         if (!vcom->v) {
660             for (i = 0; i < MAXOFFLINEVOLUMES; i++) {
661                 if (vcom->volumes[i].volumeID == 0) {
662                     vcom->v = &vcom->volumes[i];
663                     break;
664                 }
665             }
666         }
667         if (!vcom->v) {
668             goto deny;
669         }
670     }
671
672     FSYNC_com_to_info(vcom, &info);
673
674 #ifdef AFS_DEMAND_ATTACH_FS
675     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
676 #else
677     vp = VGetVolume_r(&error, vcom->vop->volume);
678 #endif
679
680     if (vp) {
681             if (!FSYNC_partMatch(vcom, vp, 1)) {
682             /* volume on desired partition is not online, so we
683              * should treat this as an offline volume.
684              */
685 #ifndef AFS_DEMAND_ATTACH_FS
686             VPutVolume_r(vp);
687 #endif
688             vp = NULL;
689             goto done;
690         }
691     }
692
693 #ifdef AFS_DEMAND_ATTACH_FS
694     if (vp) {
695         ProgramType type = (ProgramType) vcom->hdr->programType;
696
697         /* do initial filtering of requests */
698
699         /* enforce mutual exclusion for volume ops */
700         if (vp->pending_vol_op) {
701             if (vp->pending_vol_op->com.programType != type) {
702                 Log("volume %u already checked out\n", vp->hashid);
703                 /* XXX debug */
704                 Log("vp->vop = { com = { ver=%u, prog=%d, com=%d, reason=%d, len=%u, flags=0x%x }, vop = { vol=%u, part='%s' } }\n",
705                     vp->pending_vol_op->com.proto_version, 
706                     vp->pending_vol_op->com.programType,
707                     vp->pending_vol_op->com.command,
708                     vp->pending_vol_op->com.reason,
709                     vp->pending_vol_op->com.command_len,
710                     vp->pending_vol_op->com.flags,
711                     vp->pending_vol_op->vop.volume,
712                     vp->pending_vol_op->vop.partName );
713                 Log("vcom = { com = { ver=%u, prog=%d, com=%d, reason=%d, len=%u, flags=0x%x } , vop = { vol=%u, part='%s' } }\n",
714                     vcom->hdr->proto_version,
715                     vcom->hdr->programType,
716                     vcom->hdr->command,
717                     vcom->hdr->reason,
718                     vcom->hdr->command_len,
719                     vcom->hdr->flags,
720                     vcom->vop->volume,
721                     vcom->vop->partName);
722                 res->hdr.reason = FSYNC_EXCLUSIVE;
723                 goto deny;
724             } else {
725                 Log("warning: volume %u recursively checked out by programType id %d\n",
726                     vp->hashid, vcom->hdr->programType);
727             }
728         }
729
730         /* filter based upon requestor
731          *
732          * volume utilities are not allowed to check out volumes
733          * which are in an error state
734          *
735          * unknown utility programs will be denied on principal
736          */
737         switch (type) {
738         case salvageServer:
739             /* it is possible for the salvageserver to checkout a 
740              * volume for salvage before its scheduling request
741              * has been sent to the salvageserver */
742             if (vp->salvage.requested && !vp->salvage.scheduled) {
743                 vp->salvage.scheduled = 1;
744             }
745         case debugUtility:
746             break;
747
748         case volumeUtility:
749             if (VIsErrorState(V_attachState(vp))) {
750                 goto deny;
751             }
752             if (vp->salvage.requested) {
753                 goto deny;
754             }
755             break;
756
757         default:
758             Log("bad program type passed to FSSYNC\n");
759             goto deny;
760         }
761
762         /* short circuit for offline volume states
763          * so we can avoid I/O penalty of attachment */
764         switch (V_attachState(vp)) {
765         case VOL_STATE_UNATTACHED:
766         case VOL_STATE_PREATTACHED:
767         case VOL_STATE_SALVAGING:
768         case VOL_STATE_ERROR:
769             /* register the volume operation metadata with the volume
770              *
771              * if the volume is currently pre-attached, attach2()
772              * will evaluate the vol op metadata to determine whether
773              * attaching the volume would be safe */
774             VRegisterVolOp_r(vp, &info);
775             vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningUnknown;
776             goto done;
777         default:
778             break;
779         }
780
781         /* convert to heavyweight ref */
782         nvp = VGetVolumeByVp_r(&error, vp);
783
784         if (!nvp) {
785             Log("FSYNC_com_VolOff: failed to get heavyweight reference to volume %u\n",
786                 vcom->vop->volume);
787             res->hdr.reason = FSYNC_VOL_PKG_ERROR;
788             goto deny;
789         } else if (nvp != vp) {
790             /* i don't think this should ever happen, but just in case... */
791             Log("FSYNC_com_VolOff: warning: potentially dangerous race detected\n");
792             vp = nvp;
793         }
794
795         /* register the volume operation metadata with the volume */
796         VRegisterVolOp_r(vp, &info);
797
798     }
799 #endif /* AFS_DEMAND_ATTACH_FS */
800
801     if (vp) {
802         if (VVolOpLeaveOnline_r(vp, &info)) {
803             VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);       /* At least get volume stats right */
804             if (LogLevel) {
805                 Log("FSYNC: Volume %u (%s) was left on line for an external %s request\n", 
806                     V_id(vp), V_name(vp), 
807                     vcom->hdr->reason == V_CLONE ? "clone" : 
808                     vcom->hdr->reason == V_READONLY ? "readonly" : 
809                     vcom->hdr->reason == V_DUMP ? "dump" : 
810                     "UNKNOWN");
811             }
812 #ifdef AFS_DEMAND_ATTACH_FS
813             vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
814 #endif
815             VPutVolume_r(vp);
816         } else {
817             if (VVolOpSetVBusy_r(vp, &info)) {
818                 vp->specialStatus = VBUSY;
819             }
820
821             /* remember what volume we got, so we can keep track of how
822              * many volumes the volserver or whatever is using.  Note that
823              * vp is valid since leaveonline is only set when vp is valid.
824              */
825             if (vcom->v) {
826                 vcom->v->volumeID = vcom->vop->volume;
827                 strlcpy(vcom->v->partName, vp->partition->name, sizeof(vcom->v->partName));
828             }
829
830 #ifdef AFS_DEMAND_ATTACH_FS
831             VOfflineForVolOp_r(&error, vp, "A volume utility is running.");
832             if (error==0) {
833                 assert(vp->nUsers==0);
834                 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline; 
835             }
836             else {
837                 VDeregisterVolOp_r(vp);
838                 code = SYNC_DENIED;
839             }
840 #else
841             VOffline_r(vp, "A volume utility is running.");
842 #endif
843             vp = NULL;
844         }
845     }
846
847  done:
848     return code;
849
850  deny:
851     return SYNC_DENIED;
852 }
853
854 /**
855  * service an FSYNC request to mark a volume as moved.
856  *
857  * @param[in]   vcom  pointer command object
858  * @param[out]  res   object in which to store response packet
859  *
860  * @return operation status
861  *   @retval SYNC_OK volume marked as moved to a remote server
862  *   @retval SYNC_FAILED invalid command protocol message
863  *   @retval SYNC_DENIED current volume state does not permit this operation
864  *
865  * @note this is an FSYNC RPC server stub
866  *
867  * @note this operation also breaks all callbacks for the given volume
868  *
869  * @note this procedure handles the following FSSYNC command codes:
870  *       - FSYNC_VOL_MOVE
871  *
872  * @note the supplementary reason code contains additional details.  For
873  *       instance, SYNC_OK is still returned when the partition specified
874  *       does not match the one registered in the volume object -- reason
875  *       will be FSYNC_WRONG_PART in this case.
876  *
877  * @internal
878  */
879 static afs_int32
880 FSYNC_com_VolMove(FSSYNC_VolOp_command * vcom, SYNC_response * res)
881 {
882     afs_int32 code = SYNC_DENIED;
883     Error error;
884     Volume * vp;
885
886     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
887         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
888         code = SYNC_FAILED;
889         goto done;
890     }
891
892     /* Yuch:  the "reason" for the move is the site it got moved to... */
893     /* still set specialStatus so we stop sending back VBUSY.
894      * also should still break callbacks.  Note that I don't know
895      * how to tell if we should break all or not, so we just do it
896      * since it doesn't matter much if we do an extra break
897      * volume callbacks on a volume move within the same server */
898 #ifdef AFS_DEMAND_ATTACH_FS
899     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
900 #else
901     vp = VGetVolume_r(&error, vcom->vop->volume);
902 #endif
903     if (vp) {
904         if (FSYNC_partMatch(vcom, vp, 1)) {
905 #ifdef AFS_DEMAND_ATTACH_FS
906             if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
907                 (V_attachState(vp) == VOL_STATE_PREATTACHED)) {
908 #endif
909                 code = SYNC_OK;
910                 vp->specialStatus = VMOVED;
911 #ifdef AFS_DEMAND_ATTACH_FS
912             } else {
913                 res->hdr.reason = FSYNC_BAD_STATE;
914             }
915 #endif
916         } else {
917             res->hdr.reason = FSYNC_WRONG_PART;
918         }
919 #ifndef AFS_DEMAND_ATTACH_FS
920         VPutVolume_r(vp);
921 #endif /* !AFS_DEMAND_ATTACH_FS */
922     } else {
923         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
924     }
925
926     if ((code == SYNC_OK) && (V_BreakVolumeCallbacks != NULL)) {
927         Log("fssync: volume %u moved to %x; breaking all call backs\n",
928             vcom->vop->volume, vcom->hdr->reason);
929         VOL_UNLOCK;
930         (*V_BreakVolumeCallbacks) (vcom->vop->volume);
931         VOL_LOCK;
932     }
933
934
935  done:
936     return code;
937 }
938
939 /**
940  * service an FSYNC request to mark a volume as destroyed.
941  *
942  * @param[in]   vcom  pointer command object
943  * @param[out]  res   object in which to store response packet
944  *
945  * @return operation status
946  *   @retval SYNC_OK volume marked as destroyed
947  *   @retval SYNC_FAILED invalid command protocol message
948  *   @retval SYNC_DENIED current volume state does not permit this operation
949  *
950  * @note this is an FSYNC RPC server stub
951  *
952  * @note this procedure handles the following FSSYNC command codes:
953  *       - FSYNC_VOL_DONE
954  *
955  * @note the supplementary reason code contains additional details.  For
956  *       instance, SYNC_OK is still returned when the partition specified
957  *       does not match the one registered in the volume object -- reason
958  *       will be FSYNC_WRONG_PART in this case.
959  *
960  * @internal
961  */
962 static afs_int32
963 FSYNC_com_VolDone(FSSYNC_VolOp_command * vcom, SYNC_response * res)
964 {
965     afs_int32 code = SYNC_FAILED;
966 #ifdef AFS_DEMAND_ATTACH_FS
967     Error error;
968     Volume * vp;
969 #endif
970
971     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
972         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
973         goto done;
974     }
975
976     /* don't try to put online, this call is made only after deleting
977      * a volume, in which case we want to remove the vol # from the
978      * OfflineVolumes array only */
979     if (vcom->v)
980         vcom->v->volumeID = 0;
981
982 #ifdef AFS_DEMAND_ATTACH_FS
983     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
984     if (vp) {
985         if (FSYNC_partMatch(vcom, vp, 1)) {
986             if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
987                 (V_attachState(vp) == VOL_STATE_PREATTACHED)) {
988                 VChangeState_r(vp, VOL_STATE_UNATTACHED);
989                 VDeregisterVolOp_r(vp);
990                 code = SYNC_OK;
991             } else {
992                 code = SYNC_DENIED;
993                 res->hdr.reason = FSYNC_BAD_STATE;
994             }
995         } else {
996             code = SYNC_OK; /* XXX is this really a good idea? */
997             res->hdr.reason = FSYNC_WRONG_PART;
998         }
999     } else {
1000         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1001     }
1002 #endif
1003
1004  done:
1005     return code;
1006 }
1007
1008 #ifdef AFS_DEMAND_ATTACH_FS
1009 /**
1010  * service an FSYNC request to transition a volume to the hard error state.
1011  *
1012  * @param[in]   vcom  pointer command object
1013  * @param[out]  res   object in which to store response packet
1014  *
1015  * @return operation status
1016  *   @retval SYNC_OK volume transitioned to hard error state
1017  *   @retval SYNC_FAILED invalid command protocol message
1018  *   @retval SYNC_DENIED (see note)
1019  *
1020  * @note this is an FSYNC RPC server stub
1021  *
1022  * @note this procedure handles the following FSSYNC command codes:
1023  *       - FSYNC_VOL_FORCE_ERROR
1024  *
1025  * @note SYNC_DENIED is returned in the following cases:
1026  *        - no partition name is specified (reason field set to
1027  *          FSYNC_WRONG_PART).
1028  *        - volume id not known to fileserver (reason field set
1029  *          to FSYNC_UNKNOWN_VOLID).
1030  *
1031  * @note demand attach fileserver only
1032  *
1033  * @internal
1034  */
1035 static afs_int32
1036 FSYNC_com_VolError(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1037 {
1038     Error error;
1039     Volume * vp;
1040     afs_int32 code = SYNC_FAILED;
1041
1042     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
1043         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1044         goto done;
1045     }
1046
1047     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
1048     if (vp) {
1049         if (FSYNC_partMatch(vcom, vp, 0)) {
1050             /* null out salvsync control state, as it's no longer relevant */
1051             memset(&vp->salvage, 0, sizeof(vp->salvage));
1052             VChangeState_r(vp, VOL_STATE_ERROR);
1053             code = SYNC_OK;
1054         } else {
1055             res->hdr.reason = FSYNC_WRONG_PART;
1056         }
1057     } else {
1058         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1059     }
1060
1061  done:
1062     return code;
1063 }
1064 #endif /* AFS_DEMAND_ATTACH_FS */
1065
1066 /**
1067  * service an FSYNC request to break all callbacks for this volume.
1068  *
1069  * @param[in]   vcom  pointer command object
1070  * @param[out]  res   object in which to store response packet
1071  *
1072  * @return operation status
1073  *   @retval SYNC_OK callback breaks scheduled for volume
1074  *
1075  * @note this is an FSYNC RPC server stub
1076  *
1077  * @note this procedure handles the following FSSYNC command codes:
1078  *       - FSYNC_VOL_BREAKCBKS
1079  *
1080  * @note demand attach fileserver only
1081  *
1082  * @todo should do partition matching
1083  *
1084  * @internal
1085  */
1086 static afs_int32
1087 FSYNC_com_VolBreakCBKs(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1088 {
1089     /* if the volume is being restored, break all callbacks on it */
1090     if (V_BreakVolumeCallbacks) {
1091         Log("fssync: breaking all call backs for volume %u\n",
1092             vcom->vop->volume);
1093         VOL_UNLOCK;
1094         (*V_BreakVolumeCallbacks) (vcom->vop->volume);
1095         VOL_LOCK;
1096     }
1097     return SYNC_OK;
1098 }
1099
1100 /**
1101  * service an FSYNC request to return the Volume object.
1102  *
1103  * @param[in]   vcom  pointer command object
1104  * @param[out]  res   object in which to store response packet
1105  *
1106  * @return operation status
1107  *   @retval SYNC_OK      volume object returned to caller
1108  *   @retval SYNC_FAILED  bad command packet, or failed to locate volume object
1109  *
1110  * @note this is an FSYNC RPC server stub
1111  *
1112  * @note this procedure handles the following FSSYNC command codes:
1113  *       - FSYNC_VOL_QUERY
1114  *
1115  * @internal
1116  */
1117 static afs_int32
1118 FSYNC_com_VolQuery(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1119 {
1120     afs_int32 code = SYNC_FAILED;
1121     Error error;
1122     Volume * vp;
1123
1124     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
1125         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1126         goto done;
1127     }
1128
1129 #ifdef AFS_DEMAND_ATTACH_FS
1130     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
1131 #else /* !AFS_DEMAND_ATTACH_FS */
1132     vp = VGetVolume_r(&error, vcom->vop->volume);
1133 #endif /* !AFS_DEMAND_ATTACH_FS */
1134
1135     if (vp) {
1136         if (FSYNC_partMatch(vcom, vp, 1)) {
1137             if (res->payload.len >= sizeof(Volume)) {
1138                 memcpy(res->payload.buf, vp, sizeof(Volume));
1139                 res->hdr.response_len += sizeof(Volume);
1140                 code = SYNC_OK;
1141             } else {
1142                 res->hdr.reason = SYNC_REASON_PAYLOAD_TOO_BIG;
1143             }
1144         } else {
1145             res->hdr.reason = FSYNC_WRONG_PART;
1146         }
1147 #ifndef AFS_DEMAND_ATTACH_FS
1148         VPutVolume_r(vp);
1149 #endif
1150     } else {
1151         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1152     }
1153
1154  done:
1155     return code;
1156 }
1157
1158 /**
1159  * service an FSYNC request to return the Volume header.
1160  *
1161  * @param[in]   vcom  pointer command object
1162  * @param[out]  res   object in which to store response packet
1163  *
1164  * @return operation status
1165  *   @retval SYNC_OK volume header returned to caller
1166  *   @retval SYNC_FAILED  bad command packet, or failed to locate volume header
1167  *
1168  * @note this is an FSYNC RPC server stub
1169  *
1170  * @note this procedure handles the following FSSYNC command codes:
1171  *       - FSYNC_VOL_QUERY_HDR
1172  *
1173  * @internal
1174  */
1175 static afs_int32
1176 FSYNC_com_VolHdrQuery(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1177 {
1178     afs_int32 code = SYNC_FAILED;
1179     Error error;
1180     Volume * vp;
1181
1182     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
1183         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1184         goto done;
1185     }
1186     if (res->payload.len < sizeof(VolumeDiskData)) {
1187         res->hdr.reason = SYNC_REASON_PAYLOAD_TOO_BIG;
1188         goto done;
1189     }
1190
1191 #ifdef AFS_DEMAND_ATTACH_FS
1192     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
1193 #else /* !AFS_DEMAND_ATTACH_FS */
1194     vp = VGetVolume_r(&error, vcom->vop->volume);
1195 #endif
1196
1197     if (vp) {
1198         if (FSYNC_partMatch(vcom, vp, 1)) {
1199 #ifdef AFS_DEMAND_ATTACH_FS
1200             if ((vp->header == NULL) ||
1201                 !(V_attachFlags(vp) & VOL_HDR_ATTACHED) ||
1202                 !(V_attachFlags(vp) & VOL_HDR_LOADED)) {
1203                 res->hdr.reason = FSYNC_HDR_NOT_ATTACHED;
1204                 goto cleanup;
1205             }
1206 #else /* !AFS_DEMAND_ATTACH_FS */
1207             if (!vp || !vp->header) {
1208                 res->hdr.reason = FSYNC_HDR_NOT_ATTACHED;
1209                 goto cleanup;
1210             }
1211 #endif /* !AFS_DEMAND_ATTACH_FS */
1212         } else {
1213             res->hdr.reason = FSYNC_WRONG_PART;
1214             goto cleanup;
1215         }
1216     } else {
1217         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1218         goto done;
1219     }
1220
1221     memcpy(res->payload.buf, &V_disk(vp), sizeof(VolumeDiskData));
1222     res->hdr.response_len += sizeof(VolumeDiskData);
1223     code = SYNC_OK;
1224
1225  cleanup:
1226 #ifndef AFS_DEMAND_ATTACH_FS
1227     VPutVolume_r(vp);
1228 #endif
1229
1230  done:
1231     return code;
1232 }
1233
1234 #ifdef AFS_DEMAND_ATTACH_FS
1235 static afs_int32
1236 FSYNC_com_VolOpQuery(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1237 {
1238     afs_int32 code = SYNC_OK;
1239     Error error;
1240     Volume * vp;
1241
1242     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
1243
1244     if (vp && vp->pending_vol_op) {
1245         assert(sizeof(FSSYNC_VolOp_info) <= res->payload.len);
1246         memcpy(res->payload.buf, vp->pending_vol_op, sizeof(FSSYNC_VolOp_info));
1247         res->hdr.response_len += sizeof(FSSYNC_VolOp_info);
1248     } else {
1249         if (vp) {
1250             res->hdr.reason = FSYNC_NO_PENDING_VOL_OP;
1251         } else {
1252             res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1253         }
1254         code = SYNC_FAILED;
1255     }
1256     return code;
1257 }
1258 #endif /* AFS_DEMAND_ATTACH_FS */
1259
1260 static afs_int32
1261 FSYNC_com_VnQry(osi_socket fd, SYNC_command * com, SYNC_response * res)
1262 {
1263     afs_int32 code = SYNC_OK;
1264     FSSYNC_VnQry_hdr * qry = com->payload.buf;
1265     Volume * vp;
1266     Vnode * vnp;
1267     Error error;
1268
1269     if (com->recv_len != (sizeof(com->hdr) + sizeof(FSSYNC_VnQry_hdr))) {
1270         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1271         res->hdr.flags |= SYNC_FLAG_CHANNEL_SHUTDOWN;
1272         return SYNC_COM_ERROR;
1273     }
1274
1275 #ifdef AFS_DEMAND_ATTACH_FS
1276     vp = VLookupVolume_r(&error, qry->volume, NULL);
1277 #else /* !AFS_DEMAND_ATTACH_FS */
1278     vp = VGetVolume_r(&error, qry->volume);
1279 #endif /* !AFS_DEMAND_ATTACH_FS */
1280
1281     if (!vp) {
1282         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1283         code = SYNC_FAILED;
1284         goto done;
1285     }
1286
1287     vnp = VLookupVnode(vp, qry->vnode);
1288     if (!vnp) {
1289         res->hdr.reason = FSYNC_UNKNOWN_VNID;
1290         code = SYNC_FAILED;
1291         goto cleanup;
1292     }
1293
1294     if (Vn_class(vnp)->residentSize > res->payload.len) {
1295         res->hdr.reason = SYNC_REASON_ENCODING_ERROR;
1296         code = SYNC_FAILED;
1297         goto cleanup;
1298     }
1299
1300     memcpy(res->payload.buf, vnp, Vn_class(vnp)->residentSize);
1301     res->hdr.response_len += Vn_class(vnp)->residentSize;
1302
1303  cleanup:
1304 #ifndef AFS_DEMAND_ATTACH_FS
1305     VPutVolume_r(vp);
1306 #endif
1307
1308  done:
1309     return code;
1310 }
1311
1312 static afs_int32
1313 FSYNC_com_StatsOp(osi_socket fd, SYNC_command * com, SYNC_response * res)
1314 {
1315     afs_int32 code = SYNC_OK;
1316     FSSYNC_StatsOp_command scom;
1317
1318     if (com->recv_len != (sizeof(com->hdr) + sizeof(FSSYNC_StatsOp_hdr))) {
1319         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1320         res->hdr.flags |= SYNC_FLAG_CHANNEL_SHUTDOWN;
1321         return SYNC_COM_ERROR;
1322     }
1323
1324     scom.hdr = &com->hdr;
1325     scom.sop = (FSSYNC_StatsOp_hdr *) com->payload.buf;
1326     scom.com = com;
1327
1328     switch (com->hdr.command) {
1329     case FSYNC_VOL_STATS_GENERAL:
1330         code = FSYNC_com_StatsOpGeneral(&scom, res);
1331         break;
1332 #ifdef AFS_DEMAND_ATTACH_FS
1333         /* statistics for the following subsystems are only tracked
1334          * for demand attach fileservers */
1335     case FSYNC_VOL_STATS_VICEP:
1336         code = FSYNC_com_StatsOpViceP(&scom, res);
1337         break;
1338     case FSYNC_VOL_STATS_HASH:
1339         code = FSYNC_com_StatsOpHash(&scom, res);
1340         break;
1341     case FSYNC_VOL_STATS_HDR:
1342         code = FSYNC_com_StatsOpHdr(&scom, res);
1343         break;
1344     case FSYNC_VOL_STATS_VLRU:
1345         code = FSYNC_com_StatsOpVLRU(&scom, res);
1346         break;
1347 #endif /* AFS_DEMAND_ATTACH_FS */
1348     default:
1349         code = SYNC_BAD_COMMAND;
1350     }
1351
1352     return code;
1353 }
1354
1355 static afs_int32
1356 FSYNC_com_StatsOpGeneral(FSSYNC_StatsOp_command * scom, SYNC_response * res)
1357 {
1358     afs_int32 code = SYNC_OK;
1359
1360     memcpy(res->payload.buf, &VStats, sizeof(VStats));
1361     res->hdr.response_len += sizeof(VStats);
1362
1363     return code;
1364 }
1365
1366 #ifdef AFS_DEMAND_ATTACH_FS
1367 static afs_int32
1368 FSYNC_com_StatsOpViceP(FSSYNC_StatsOp_command * scom, SYNC_response * res)
1369 {
1370     afs_int32 code = SYNC_OK;
1371     struct DiskPartition64 * dp;
1372     struct DiskPartitionStats64 * stats;
1373
1374     if (SYNC_verifyProtocolString(scom->sop->args.partName, sizeof(scom->sop->args.partName))) {
1375         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1376         code = SYNC_FAILED;
1377         goto done;
1378     }
1379
1380     dp = VGetPartition_r(scom->sop->args.partName, 0);
1381     if (!dp) {
1382         code = SYNC_FAILED;
1383     } else {
1384         stats = (struct DiskPartitionStats64 *) res->payload.buf;
1385         stats->free = dp->free;
1386         stats->totalUsable = dp->totalUsable;
1387         stats->minFree = dp->minFree;
1388         stats->f_files = dp->f_files;
1389         stats->vol_list_len = dp->vol_list.len;
1390         
1391         res->hdr.response_len += sizeof(struct DiskPartitionStats64);
1392     }
1393
1394  done:
1395     return code;
1396 }
1397
1398 static afs_int32
1399 FSYNC_com_StatsOpHash(FSSYNC_StatsOp_command * scom, SYNC_response * res)
1400 {
1401     afs_int32 code = SYNC_OK;
1402     struct VolumeHashChainStats * stats;
1403     struct VolumeHashChainHead * head;
1404
1405     if (scom->sop->args.hash_bucket >= VolumeHashTable.Size) {
1406         return SYNC_FAILED;
1407     }
1408
1409     head = &VolumeHashTable.Table[scom->sop->args.hash_bucket];
1410     stats = (struct VolumeHashChainStats *) res->payload.buf;
1411     stats->table_size = VolumeHashTable.Size;
1412     stats->chain_len = head->len;
1413     stats->chain_cacheCheck = head->cacheCheck;
1414     stats->chain_busy = head->busy;
1415     AssignInt64(head->looks, &stats->chain_looks);
1416     AssignInt64(head->gets, &stats->chain_gets);
1417     AssignInt64(head->reorders, &stats->chain_reorders);
1418
1419     res->hdr.response_len += sizeof(struct VolumeHashChainStats);
1420     
1421     return code;
1422 }
1423
1424 static afs_int32
1425 FSYNC_com_StatsOpHdr(FSSYNC_StatsOp_command * scom, SYNC_response * res)
1426 {
1427     afs_int32 code = SYNC_OK;
1428
1429     memcpy(res->payload.buf, &volume_hdr_LRU.stats, sizeof(volume_hdr_LRU.stats));
1430     res->hdr.response_len += sizeof(volume_hdr_LRU.stats);
1431
1432     return code;
1433 }
1434
1435 static afs_int32
1436 FSYNC_com_StatsOpVLRU(FSSYNC_StatsOp_command * scom, SYNC_response * res)
1437 {
1438     afs_int32 code = SYNC_OK;
1439
1440     code = SYNC_BAD_COMMAND;
1441
1442     return code;
1443 }
1444 #endif /* AFS_DEMAND_ATTACH_FS */
1445
1446 /**
1447  * populate an FSSYNC_VolOp_info object from a command packet object.
1448  *
1449  * @param[in]   vcom  pointer to command packet
1450  * @param[out]  info  pointer to info object which will be populated
1451  *
1452  * @note FSSYNC_VolOp_info objects are attached to Volume objects when
1453  *       a volume operation is commenced.
1454  *
1455  * @internal
1456  */
1457 static void
1458 FSYNC_com_to_info(FSSYNC_VolOp_command * vcom, FSSYNC_VolOp_info * info)
1459 {
1460     memcpy(&info->com, vcom->hdr, sizeof(SYNC_command_hdr));
1461     memcpy(&info->vop, vcom->vop, sizeof(FSSYNC_VolOp_hdr));
1462     info->vol_op_state = FSSYNC_VolOpPending;
1463 }
1464
1465 /**
1466  * check whether command packet partition name matches volume 
1467  * object's partition name.
1468  *
1469  * @param[in] vcom        pointer to command packet
1470  * @param[in] vp          pointer to volume object
1471  * @param[in] match_anon  anon matching control flag (see note below)
1472  *
1473  * @return whether partitions match
1474  *   @retval 0  partitions do NOT match
1475  *   @retval 1  partitions match
1476  *
1477  * @note if match_anon is non-zero, then this function will return a
1478  *       positive match for a zero-length partition string in the
1479  *       command packet.
1480  *
1481  * @internal
1482  */
1483 static int 
1484 FSYNC_partMatch(FSSYNC_VolOp_command * vcom, Volume * vp, int match_anon)
1485 {
1486     return ((match_anon && vcom->vop->partName[0] == 0) ||
1487             (strncmp(vcom->vop->partName, V_partition(vp)->name, 
1488                      sizeof(vcom->vop->partName)) == 0));
1489 }
1490
1491
1492 static void
1493 FSYNC_Drop(osi_socket fd)
1494 {
1495     struct offlineInfo *p;
1496     int i;
1497     Error error;
1498     char tvolName[VMAXPATHLEN];
1499
1500     VOL_LOCK;
1501     p = OfflineVolumes[FindHandler(fd)];
1502     for (i = 0; i < MAXOFFLINEVOLUMES; i++) {
1503         if (p[i].volumeID) {
1504
1505             Volume *vp;
1506
1507             tvolName[0] = '/';
1508             sprintf(&tvolName[1], VFORMAT, afs_printable_uint32_lu(p[i].volumeID));
1509             vp = VAttachVolumeByName_r(&error, p[i].partName, tvolName,
1510                                        V_VOLUPD);
1511             if (vp)
1512                 VPutVolume_r(vp);
1513             p[i].volumeID = 0;
1514         }
1515     }
1516     VOL_UNLOCK;
1517     RemoveHandler(fd);
1518 #ifdef AFS_NT40_ENV
1519     closesocket(fd);
1520 #else
1521     close(fd);
1522 #endif
1523     AcceptOn();
1524 }
1525
1526 static int AcceptHandler = -1;  /* handler id for accept, if turned on */
1527
1528 static void
1529 AcceptOn(void)
1530 {
1531     if (AcceptHandler == -1) {
1532         assert(AddHandler(fssync_server_state.fd, FSYNC_newconnection));
1533         AcceptHandler = FindHandler(fssync_server_state.fd);
1534     }
1535 }
1536
1537 static void
1538 AcceptOff(void)
1539 {
1540     if (AcceptHandler != -1) {
1541         assert(RemoveHandler(fssync_server_state.fd));
1542         AcceptHandler = -1;
1543     }
1544 }
1545
1546 /* The multiple FD handling code. */
1547
1548 static osi_socket HandlerFD[MAXHANDLERS];
1549 static void (*HandlerProc[MAXHANDLERS]) (osi_socket);
1550
1551 static void
1552 InitHandler(void)
1553 {
1554     register int i;
1555     ObtainWriteLock(&FSYNC_handler_lock);
1556     for (i = 0; i < MAXHANDLERS; i++) {
1557         HandlerFD[i] = -1;
1558         HandlerProc[i] = 0;
1559     }
1560     ReleaseWriteLock(&FSYNC_handler_lock);
1561 }
1562
1563 #if defined(HAVE_POLL) && defined(AFS_PTHREAD_ENV)
1564 static void
1565 CallHandler(struct pollfd *fds, int nfds, int mask)
1566 {
1567     int i;
1568     int handler;
1569     ObtainReadLock(&FSYNC_handler_lock);
1570     for (i = 0; i < nfds; i++) {
1571         if (fds[i].revents & mask) {
1572             handler = FindHandler_r(fds[i].fd);
1573             ReleaseReadLock(&FSYNC_handler_lock);
1574             (*HandlerProc[handler]) (fds[i].fd);
1575             ObtainReadLock(&FSYNC_handler_lock);
1576         }
1577     }
1578     ReleaseReadLock(&FSYNC_handler_lock);
1579 }
1580 #else
1581 static void
1582 CallHandler(fd_set * fdsetp)
1583 {
1584     register int i;
1585     ObtainReadLock(&FSYNC_handler_lock);
1586     for (i = 0; i < MAXHANDLERS; i++) {
1587         if (HandlerFD[i] >= 0 && FD_ISSET(HandlerFD[i], fdsetp)) {
1588             ReleaseReadLock(&FSYNC_handler_lock);
1589             (*HandlerProc[i]) (HandlerFD[i]);
1590             ObtainReadLock(&FSYNC_handler_lock);
1591         }
1592     }
1593     ReleaseReadLock(&FSYNC_handler_lock);
1594 }
1595 #endif
1596
1597 static int
1598 AddHandler(osi_socket afd, void (*aproc) (osi_socket))
1599 {
1600     register int i;
1601     ObtainWriteLock(&FSYNC_handler_lock);
1602     for (i = 0; i < MAXHANDLERS; i++)
1603         if (HandlerFD[i] == -1)
1604             break;
1605     if (i >= MAXHANDLERS) {
1606         ReleaseWriteLock(&FSYNC_handler_lock);
1607         return 0;
1608     }
1609     HandlerFD[i] = afd;
1610     HandlerProc[i] = aproc;
1611     ReleaseWriteLock(&FSYNC_handler_lock);
1612     return 1;
1613 }
1614
1615 static int
1616 FindHandler(register osi_socket afd)
1617 {
1618     register int i;
1619     ObtainReadLock(&FSYNC_handler_lock);
1620     for (i = 0; i < MAXHANDLERS; i++)
1621         if (HandlerFD[i] == afd) {
1622             ReleaseReadLock(&FSYNC_handler_lock);
1623             return i;
1624         }
1625     ReleaseReadLock(&FSYNC_handler_lock);       /* just in case */
1626     assert(1 == 2);
1627     return -1;                  /* satisfy compiler */
1628 }
1629
1630 static int
1631 FindHandler_r(register osi_socket afd)
1632 {
1633     register int i;
1634     for (i = 0; i < MAXHANDLERS; i++)
1635         if (HandlerFD[i] == afd) {
1636             return i;
1637         }
1638     assert(1 == 2);
1639     return -1;                  /* satisfy compiler */
1640 }
1641
1642 static int
1643 RemoveHandler(register osi_socket afd)
1644 {
1645     ObtainWriteLock(&FSYNC_handler_lock);
1646     HandlerFD[FindHandler_r(afd)] = -1;
1647     ReleaseWriteLock(&FSYNC_handler_lock);
1648     return 1;
1649 }
1650
1651 #if defined(HAVE_POLL) && defined(AFS_PTHREAD_ENV)
1652 static void
1653 GetHandler(struct pollfd *fds, int maxfds, int events, int *nfds)
1654 {
1655     int i;
1656     int fdi = 0;
1657     ObtainReadLock(&FSYNC_handler_lock);
1658     for (i = 0; i < MAXHANDLERS; i++)
1659         if (HandlerFD[i] != -1) {
1660             assert(fdi<maxfds);
1661             fds[fdi].fd = HandlerFD[i];
1662             fds[fdi].events = events;
1663             fds[fdi].revents = 0;
1664             fdi++;
1665         }
1666     *nfds = fdi;
1667     ReleaseReadLock(&FSYNC_handler_lock);
1668 }
1669 #else
1670 static void
1671 GetHandler(fd_set * fdsetp, int *maxfdp)
1672 {
1673     register int i;
1674     register int maxfd = -1;
1675     FD_ZERO(fdsetp);
1676     ObtainReadLock(&FSYNC_handler_lock);        /* just in case */
1677     for (i = 0; i < MAXHANDLERS; i++)
1678         if (HandlerFD[i] != -1) {
1679             FD_SET(HandlerFD[i], fdsetp);
1680 #ifndef AFS_NT40_ENV
1681             /* On Windows the nfds parameter to select() is ignored */
1682             if (maxfd < HandlerFD[i] || maxfd == (int)-1)
1683                 maxfd = HandlerFD[i];
1684 #endif /* AFS_NT40_ENV */
1685         }
1686     *maxfdp = maxfd;
1687     ReleaseReadLock(&FSYNC_handler_lock);       /* just in case */
1688 }
1689 #endif /* HAVE_POLL && AFS_PTHREAD_ENV */
1690
1691 #endif /* FSSYNC_BUILD_SERVER */