vol-salvage: VOL_DONE deleted volumes
[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-2010 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 #include <roken.h>
47
48 #include <sys/types.h>
49 #include <stdio.h>
50 #ifdef HAVE_STDINT_H
51 # include <stdint.h>
52 #endif
53 #ifdef AFS_NT40_ENV
54 #include <winsock2.h>
55 #include <time.h>
56 #else
57 #include <sys/param.h>
58 #include <sys/socket.h>
59 #include <netinet/in.h>
60 #include <netdb.h>
61 #include <sys/time.h>
62 #include <unistd.h>
63 #endif
64 #include <errno.h>
65 #include <afs/afs_assert.h>
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 "daemon_com_inline.h"
75 #include "fssync.h"
76 #include "fssync_inline.h"
77 #include "salvsync.h"
78 #include "lwp.h"
79 #include "lock.h"
80 #include <afs/afssyscalls.h>
81 #include "ihandle.h"
82 #include "vnode.h"
83 #include "volume.h"
84 #include "volume_inline.h"
85 #include "partition.h"
86 #include "vg_cache.h"
87 #include "common.h"
88
89 #ifdef HAVE_POLL
90 #include <sys/poll.h>
91 #endif /* HAVE_POLL */
92
93 #ifdef USE_UNIX_SOCKETS
94 #include <sys/un.h>
95 #include <afs/afsutil.h>
96 #endif /* USE_UNIX_SOCKETS */
97
98 #ifdef FSSYNC_BUILD_SERVER
99
100 int (*V_BreakVolumeCallbacks) (VolumeId volume);
101
102 #define MAXHANDLERS     4       /* Up to 4 clients; must be at least 2, so that
103                                  * move = dump+restore can run on single server */
104 #define MAXOFFLINEVOLUMES 128   /* This needs to be as big as the maximum
105                                  * number that would be offline for 1 operation.
106                                  * Current winner is salvage, which needs all
107                                  * cloned read-only copies offline when salvaging
108                                  * a single read-write volume */
109
110
111
112 static struct offlineInfo OfflineVolumes[MAXHANDLERS][MAXOFFLINEVOLUMES];
113
114 /**
115  * fssync server socket handle.
116  */
117 static SYNC_server_state_t fssync_server_state =
118     { OSI_NULLSOCKET,                       /* file descriptor */
119       FSSYNC_ENDPOINT_DECL,     /* server endpoint */
120       FSYNC_PROTO_VERSION,      /* protocol version */
121       5,                        /* bind() retry limit */
122       100,                      /* listen() queue depth */
123       "FSSYNC",                 /* protocol name string */
124     };
125
126 #ifdef AFS_DEMAND_ATTACH_FS
127 /**
128  * a queue of volume pointers to salvage in the background.
129  */
130 struct fsync_salv_node {
131     struct rx_queue q;
132     Volume *vp;                     /**< volume to salvage */
133     unsigned char update_salv_prio; /**< whether we should update the salvage priority or not */
134 };
135 static struct {
136     struct rx_queue head;
137     pthread_cond_t cv;
138 } fsync_salv;
139
140 static void * FSYNC_salvageThread(void *);
141 static void FSYNC_backgroundSalvage(Volume *vp);
142 #endif /* AFS_DEMAND_ATTACH_FS */
143
144 /* Forward declarations */
145 static void * FSYNC_sync(void *);
146 static void FSYNC_newconnection(osi_socket afd);
147 static void FSYNC_com(osi_socket fd);
148 static void FSYNC_Drop(osi_socket fd);
149 static void AcceptOn(void);
150 static void AcceptOff(void);
151 static void InitHandler(void);
152 static int AddHandler(osi_socket fd, void (*aproc)(osi_socket));
153 static int FindHandler(osi_socket afd);
154 static int FindHandler_r(osi_socket afd);
155 static int RemoveHandler(osi_socket afd);
156 #if defined(HAVE_POLL) && defined (AFS_PTHREAD_ENV)
157 static void CallHandler(struct pollfd *fds, int nfds, int mask);
158 static void GetHandler(struct pollfd *fds, int maxfds, int events, int *nfds);
159 #else
160 static void CallHandler(fd_set * fdsetp);
161 static void GetHandler(fd_set * fdsetp, int *maxfdp);
162 #endif
163 extern int LogLevel;
164
165 static afs_int32 FSYNC_com_VolOp(osi_socket fd, SYNC_command * com, SYNC_response * res);
166
167 #ifdef AFS_DEMAND_ATTACH_FS
168 static afs_int32 FSYNC_com_VolError(FSSYNC_VolOp_command * com, SYNC_response * res);
169 #endif
170 static afs_int32 FSYNC_com_VolOn(FSSYNC_VolOp_command * com, SYNC_response * res);
171 static afs_int32 FSYNC_com_VolOff(FSSYNC_VolOp_command * com, SYNC_response * res);
172 static afs_int32 FSYNC_com_VolMove(FSSYNC_VolOp_command * com, SYNC_response * res);
173 static afs_int32 FSYNC_com_VolBreakCBKs(FSSYNC_VolOp_command * com, SYNC_response * res);
174 static afs_int32 FSYNC_com_VolDone(FSSYNC_VolOp_command * com, SYNC_response * res);
175 static afs_int32 FSYNC_com_VolQuery(FSSYNC_VolOp_command * com, SYNC_response * res);
176 static afs_int32 FSYNC_com_VolHdrQuery(FSSYNC_VolOp_command * com, SYNC_response * res);
177 #ifdef AFS_DEMAND_ATTACH_FS
178 static afs_int32 FSYNC_com_VGUpdate(osi_socket fd, SYNC_command * com, SYNC_response * res);
179 static afs_int32 FSYNC_com_VolOpQuery(FSSYNC_VolOp_command * com, SYNC_response * res);
180 static afs_int32 FSYNC_com_VGQuery(FSSYNC_VolOp_command * com, SYNC_response * res);
181 static afs_int32 FSYNC_com_VGScan(FSSYNC_VolOp_command * com, SYNC_response * res);
182 static afs_int32 FSYNC_com_VGScanAll(FSSYNC_VolOp_command * com, SYNC_response * res);
183 #endif /* AFS_DEMAND_ATTACH_FS */
184
185 static afs_int32 FSYNC_com_VnQry(osi_socket fd, SYNC_command * com, SYNC_response * res);
186
187 static afs_int32 FSYNC_com_StatsOp(osi_socket fd, SYNC_command * com, SYNC_response * res);
188
189 static afs_int32 FSYNC_com_StatsOpGeneral(FSSYNC_StatsOp_command * scom, SYNC_response * res);
190
191 #ifdef AFS_DEMAND_ATTACH_FS
192 static afs_int32 FSYNC_com_StatsOpViceP(FSSYNC_StatsOp_command * scom, SYNC_response * res);
193 static afs_int32 FSYNC_com_StatsOpHash(FSSYNC_StatsOp_command * scom, SYNC_response * res);
194 static afs_int32 FSYNC_com_StatsOpHdr(FSSYNC_StatsOp_command * scom, SYNC_response * res);
195 static afs_int32 FSYNC_com_StatsOpVLRU(FSSYNC_StatsOp_command * scom, SYNC_response * res);
196 #endif
197
198 static void FSYNC_com_to_info(FSSYNC_VolOp_command * vcom, FSSYNC_VolOp_info * info);
199
200 static int FSYNC_partMatch(FSSYNC_VolOp_command * vcom, Volume * vp, int match_anon);
201
202
203 /*
204  * This lock controls access to the handler array. The overhead
205  * is minimal in non-preemptive environments.
206  */
207 struct Lock FSYNC_handler_lock;
208
209 void
210 FSYNC_fsInit(void)
211 {
212 #ifdef AFS_PTHREAD_ENV
213     pthread_t tid;
214     pthread_attr_t tattr;
215 #else /* AFS_PTHREAD_ENV */
216     PROCESS pid;
217 #endif /* AFS_PTHREAD_ENV */
218
219     Lock_Init(&FSYNC_handler_lock);
220
221 #ifdef AFS_PTHREAD_ENV
222     osi_Assert(pthread_attr_init(&tattr) == 0);
223     osi_Assert(pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED) == 0);
224     osi_Assert(pthread_create(&tid, &tattr, FSYNC_sync, NULL) == 0);
225 #else /* AFS_PTHREAD_ENV */
226     osi_Assert(LWP_CreateProcess
227            (FSYNC_sync, USUAL_STACK_SIZE, USUAL_PRIORITY, (void *)0,
228             "FSYNC_sync", &pid) == LWP_SUCCESS);
229 #endif /* AFS_PTHREAD_ENV */
230
231 #ifdef AFS_DEMAND_ATTACH_FS
232     queue_Init(&fsync_salv.head);
233     CV_INIT(&fsync_salv.cv, "fsync salv", CV_DEFAULT, 0);
234     osi_Assert(pthread_create(&tid, &tattr, FSYNC_salvageThread, NULL) == 0);
235 #endif /* AFS_DEMAND_ATTACH_FS */
236 }
237
238 #if defined(HAVE_POLL) && defined(AFS_PTHREAD_ENV)
239 static struct pollfd FSYNC_readfds[MAXHANDLERS];
240 #else
241 static fd_set FSYNC_readfds;
242 #endif
243
244
245 static void *
246 FSYNC_sync(void * args)
247 {
248     extern int VInit;
249     int code;
250 #ifdef AFS_PTHREAD_ENV
251     int tid;
252 #endif
253     SYNC_server_state_t * state = &fssync_server_state;
254 #ifdef AFS_DEMAND_ATTACH_FS
255     VThreadOptions_t * thread_opts;
256     int min_vinit = 2;
257 #else
258     /*
259      * For non-DAFS, only wait until we begin attaching volumes (instead
260      * of waiting until all volumes are attached), since it can take
261      * awhile until VInit == 2.
262      */
263     int min_vinit = 1;
264 #endif /* AFS_DEMAND_ATTACH_FS */
265
266     /* we must not be called before vol package initialization, since we use
267      * vol package mutexes and conds etc */
268     osi_Assert(VInit);
269
270     SYNC_getAddr(&state->endpoint, &state->addr);
271     SYNC_cleanupSock(state);
272
273 #ifndef AFS_NT40_ENV
274     (void)signal(SIGPIPE, SIG_IGN);
275 #endif
276
277 #ifdef AFS_PTHREAD_ENV
278     /* set our 'thread-id' so that the host hold table works */
279     tid = rx_NewThreadId();
280     pthread_setspecific(rx_thread_id_key, (void *)(intptr_t)tid);
281     Log("Set thread id %d for FSYNC_sync\n", tid);
282 #endif /* AFS_PTHREAD_ENV */
283
284     VOL_LOCK;
285
286     while (VInit < min_vinit) {
287         /* Let somebody else run until all volumes have been preattached
288          * (DAFS), or we have started attaching volumes (non-DAFS). This
289          * doesn't mean that all volumes have been attached.
290          */
291 #ifdef AFS_PTHREAD_ENV
292         VOL_CV_WAIT(&vol_vinit_cond);
293 #else /* AFS_PTHREAD_ENV */
294         LWP_DispatchProcess();
295 #endif /* AFS_PTHREAD_ENV */
296     }
297
298     VOL_UNLOCK;
299
300     state->fd = SYNC_getSock(&state->endpoint);
301     code = SYNC_bindSock(state);
302     osi_Assert(!code);
303
304 #ifdef AFS_DEMAND_ATTACH_FS
305     /*
306      * make sure the volume package is incapable of recursively executing
307      * salvsync calls on this thread, since there is a possibility of
308      * deadlock.
309      */
310     thread_opts = malloc(sizeof(VThreadOptions_t));
311     if (thread_opts == NULL) {
312         Log("failed to allocate memory for thread-specific volume package options structure\n");
313         return NULL;
314     }
315     memcpy(thread_opts, &VThread_defaults, sizeof(VThread_defaults));
316     thread_opts->disallow_salvsync = 1;
317     osi_Assert(pthread_setspecific(VThread_key, thread_opts) == 0);
318
319     code = VVGCache_PkgInit();
320     osi_Assert(code == 0);
321 #endif
322
323     InitHandler();
324     AcceptOn();
325
326     for (;;) {
327 #if defined(HAVE_POLL) && defined(AFS_PTHREAD_ENV)
328         int nfds;
329         GetHandler(FSYNC_readfds, MAXHANDLERS, POLLIN|POLLPRI, &nfds);
330         if (poll(FSYNC_readfds, nfds, -1) >=1)
331             CallHandler(FSYNC_readfds, nfds, POLLIN|POLLPRI);
332 #else
333         int maxfd;
334         GetHandler(&FSYNC_readfds, &maxfd);
335         /* Note: check for >= 1 below is essential since IOMGR_select
336          * doesn't have exactly same semantics as select.
337          */
338 #ifdef AFS_PTHREAD_ENV
339         if (select(maxfd + 1, &FSYNC_readfds, NULL, NULL, NULL) >= 1)
340 #else /* AFS_PTHREAD_ENV */
341         if (IOMGR_Select(maxfd + 1, &FSYNC_readfds, NULL, NULL, NULL) >= 1)
342 #endif /* AFS_PTHREAD_ENV */
343             CallHandler(&FSYNC_readfds);
344 #endif
345     }
346     return NULL; /* hush now, little gcc */
347 }
348
349 #ifdef AFS_DEMAND_ATTACH_FS
350 /**
351  * thread for salvaging volumes in the background.
352  *
353  * Since FSSYNC handlers cannot issue SALVSYNC requests in order to avoid
354  * deadlock issues, this thread exists so code in the FSSYNC handler thread
355  * can hand off volumes to be salvaged in the background.
356  *
357  * @param[in] args  unused
358  *
359  * @note DEMAND_ATTACH_FS only
360  */
361 static void *
362 FSYNC_salvageThread(void * args)
363 {
364     Volume *vp;
365     struct fsync_salv_node *node;
366
367     VOL_LOCK;
368
369     for (;;) {
370         while (queue_IsEmpty(&fsync_salv.head)) {
371             VOL_CV_WAIT(&fsync_salv.cv);
372         }
373
374         node = queue_First(&fsync_salv.head, fsync_salv_node);
375         queue_Remove(node);
376
377         vp = node->vp;
378         if (node->update_salv_prio) {
379             if (VUpdateSalvagePriority_r(vp)) {
380                 ViceLog(0, ("FSYNC_salvageThread: unable to raise salvage priority "
381                             "for volume %lu\n", afs_printable_uint32_lu(vp->hashid)));
382             }
383         }
384
385         free(node);
386         node = NULL;
387
388         VCancelReservation_r(vp);
389     }
390
391     VOL_UNLOCK;
392
393     return NULL;
394 }
395
396 /**
397  * salvage a volume in the background.
398  *
399  * Salvages cannot be scheduled directly from the main FSYNC thread, so
400  * instead call this function to schedule a salvage asynchronously in the
401  * FSYNC_salvageThread thread.
402  *
403  * @param[in] vp  volume to pointer to salvage
404  *
405  * @pre VOL_LOCK held
406  *
407  * @note DEMAND_ATTACH_FS only
408  */
409 static void
410 FSYNC_backgroundSalvage(Volume *vp)
411 {
412     struct fsync_salv_node *node;
413     Error ec;
414
415     VCreateReservation_r(vp);
416
417     node = malloc(sizeof(struct fsync_salv_node));
418     node->vp = vp;
419
420     /* Save this value, to know if we should VUpdateSalvagePriority_r.
421      * We need to save it here, snce VRequestSalvage_r will change it. */
422     node->update_salv_prio = vp->salvage.requested;
423
424     if (VRequestSalvage_r(&ec, vp, SALVSYNC_ERROR, 0)) {
425         ViceLog(0, ("FSYNC_backgroundSalvage: unable to request salvage for volume %lu\n",
426                     afs_printable_uint32_lu(vp->hashid)));
427     }
428
429     queue_Append(&fsync_salv.head, node);
430     CV_BROADCAST(&fsync_salv.cv);
431 }
432 #endif /* AFS_DEMAND_ATTACH_FS */
433
434 static void
435 FSYNC_newconnection(osi_socket afd)
436 {
437 #ifdef USE_UNIX_SOCKETS
438     struct sockaddr_un other;
439 #else  /* USE_UNIX_SOCKETS */
440     struct sockaddr_in other;
441 #endif
442     osi_socket fd;
443     socklen_t junk;
444     junk = sizeof(other);
445     fd = accept(afd, (struct sockaddr *)&other, &junk);
446     if (fd == OSI_NULLSOCKET) {
447         Log("FSYNC_newconnection:  accept failed, errno==%d\n", errno);
448         osi_Assert(1 == 2);
449     } else if (!AddHandler(fd, FSYNC_com)) {
450         AcceptOff();
451         osi_Assert(AddHandler(fd, FSYNC_com));
452     }
453 }
454
455 /* this function processes commands from an fssync file descriptor (fd) */
456 afs_int32 FS_cnt = 0;
457 static void
458 FSYNC_com(osi_socket fd)
459 {
460     SYNC_command com;
461     SYNC_response res;
462     SYNC_PROTO_BUF_DECL(com_buf);
463     SYNC_PROTO_BUF_DECL(res_buf);
464
465     memset(&res.hdr, 0, sizeof(res.hdr));
466
467     com.payload.buf = (void *)com_buf;
468     com.payload.len = SYNC_PROTO_MAX_LEN;
469     res.hdr.response_len = sizeof(res.hdr);
470     res.payload.len = SYNC_PROTO_MAX_LEN;
471     res.payload.buf = (void *)res_buf;
472
473     FS_cnt++;
474     if (SYNC_getCom(&fssync_server_state, fd, &com)) {
475         Log("FSYNC_com:  read failed; dropping connection (cnt=%d)\n", FS_cnt);
476         FSYNC_Drop(fd);
477         return;
478     }
479
480     if (com.recv_len < sizeof(com.hdr)) {
481         Log("FSSYNC_com:  invalid protocol message length (%u)\n", com.recv_len);
482         res.hdr.response = SYNC_COM_ERROR;
483         res.hdr.reason = SYNC_REASON_MALFORMED_PACKET;
484         res.hdr.flags |= SYNC_FLAG_CHANNEL_SHUTDOWN;
485         goto respond;
486     }
487
488     if (com.hdr.proto_version != FSYNC_PROTO_VERSION) {
489         Log("FSYNC_com:  invalid protocol version (%u)\n", com.hdr.proto_version);
490         res.hdr.response = SYNC_COM_ERROR;
491         res.hdr.flags |= SYNC_FLAG_CHANNEL_SHUTDOWN;
492         goto respond;
493     }
494
495     if (com.hdr.command == SYNC_COM_CHANNEL_CLOSE) {
496         res.hdr.response = SYNC_OK;
497         res.hdr.flags |= SYNC_FLAG_CHANNEL_SHUTDOWN;
498
499         /* don't respond, just drop; senders of SYNC_COM_CHANNEL_CLOSE
500          * never wait for a response. */
501         goto done;
502     }
503
504     ViceLog(125, ("FSYNC_com: from fd %d got command %ld (%s) reason %ld (%s) "
505                   "pt %ld (%s) pid %ld\n", (int)fd,
506                   afs_printable_int32_ld(com.hdr.command),
507                   FSYNC_com2string(com.hdr.command),
508                   afs_printable_int32_ld(com.hdr.reason),
509                   FSYNC_reason2string(com.hdr.reason),
510                   afs_printable_int32_ld(com.hdr.programType),
511                   VPTypeToString(com.hdr.programType),
512                   afs_printable_int32_ld(com.hdr.pid)));
513
514     res.hdr.com_seq = com.hdr.com_seq;
515
516     VOL_LOCK;
517     switch (com.hdr.command) {
518     case FSYNC_VOL_ON:
519     case FSYNC_VOL_ATTACH:
520     case FSYNC_VOL_LEAVE_OFF:
521     case FSYNC_VOL_OFF:
522     case FSYNC_VOL_FORCE_ERROR:
523     case FSYNC_VOL_LISTVOLUMES:
524     case FSYNC_VOL_NEEDVOLUME:
525     case FSYNC_VOL_MOVE:
526     case FSYNC_VOL_BREAKCBKS:
527     case FSYNC_VOL_DONE:
528     case FSYNC_VOL_QUERY:
529     case FSYNC_VOL_QUERY_HDR:
530 #ifdef AFS_DEMAND_ATTACH_FS
531     case FSYNC_VOL_QUERY_VOP:
532     case FSYNC_VG_QUERY:
533     case FSYNC_VG_SCAN:
534     case FSYNC_VG_SCAN_ALL:
535 #endif
536         res.hdr.response = FSYNC_com_VolOp(fd, &com, &res);
537         break;
538     case FSYNC_VOL_STATS_GENERAL:
539     case FSYNC_VOL_STATS_VICEP:
540     case FSYNC_VOL_STATS_HASH:
541     case FSYNC_VOL_STATS_HDR:
542     case FSYNC_VOL_STATS_VLRU:
543         res.hdr.response = FSYNC_com_StatsOp(fd, &com, &res);
544         break;
545     case FSYNC_VOL_QUERY_VNODE:
546         res.hdr.response = FSYNC_com_VnQry(fd, &com, &res);
547         break;
548 #ifdef AFS_DEMAND_ATTACH_FS
549     case FSYNC_VG_ADD:
550     case FSYNC_VG_DEL:
551         res.hdr.response = FSYNC_com_VGUpdate(fd, &com, &res);
552         break;
553 #endif
554     default:
555         res.hdr.response = SYNC_BAD_COMMAND;
556         break;
557     }
558     VOL_UNLOCK;
559
560     ViceLog(125, ("FSYNC_com: fd %d responding with code %ld (%s) reason %ld "
561                   "(%s)\n", (int)fd,
562                   afs_printable_int32_ld(res.hdr.response),
563                   SYNC_res2string(res.hdr.response),
564                   afs_printable_int32_ld(res.hdr.reason),
565                   FSYNC_reason2string(res.hdr.reason)));
566
567  respond:
568     SYNC_putRes(&fssync_server_state, fd, &res);
569
570  done:
571     if (res.hdr.flags & SYNC_FLAG_CHANNEL_SHUTDOWN) {
572         FSYNC_Drop(fd);
573     }
574 }
575
576 static afs_int32
577 FSYNC_com_VolOp(osi_socket fd, SYNC_command * com, SYNC_response * res)
578 {
579     int i;
580     afs_int32 code = SYNC_OK;
581     FSSYNC_VolOp_command vcom;
582
583     if (com->recv_len != (sizeof(com->hdr) + sizeof(FSSYNC_VolOp_hdr))) {
584         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
585         res->hdr.flags |= SYNC_FLAG_CHANNEL_SHUTDOWN;
586         return SYNC_COM_ERROR;
587     }
588
589     vcom.hdr = &com->hdr;
590     vcom.vop = (FSSYNC_VolOp_hdr *) com->payload.buf;
591     vcom.com = com;
592
593     vcom.volumes = OfflineVolumes[FindHandler(fd)];
594     for (vcom.v = NULL, i = 0; i < MAXOFFLINEVOLUMES; i++) {
595         if ((vcom.volumes[i].volumeID == vcom.vop->volume) &&
596             (strncmp(vcom.volumes[i].partName, vcom.vop->partName,
597                      sizeof(vcom.volumes[i].partName)) == 0)) {
598             vcom.v = &vcom.volumes[i];
599             break;
600         }
601     }
602
603     ViceLog(125, ("FSYNC_com_VolOp: fd %d got command for vol %lu part %.16s\n",
604                   (int)fd, afs_printable_uint32_lu(vcom.vop->volume),
605                   vcom.vop->partName));
606
607     switch (com->hdr.command) {
608     case FSYNC_VOL_ON:
609     case FSYNC_VOL_ATTACH:
610     case FSYNC_VOL_LEAVE_OFF:
611         code = FSYNC_com_VolOn(&vcom, res);
612         break;
613     case FSYNC_VOL_OFF:
614     case FSYNC_VOL_NEEDVOLUME:
615         code = FSYNC_com_VolOff(&vcom, res);
616         break;
617     case FSYNC_VOL_LISTVOLUMES:
618         code = SYNC_OK;
619         break;
620     case FSYNC_VOL_MOVE:
621         code = FSYNC_com_VolMove(&vcom, res);
622         break;
623     case FSYNC_VOL_BREAKCBKS:
624         code = FSYNC_com_VolBreakCBKs(&vcom, res);
625         break;
626     case FSYNC_VOL_DONE:
627         code = FSYNC_com_VolDone(&vcom, res);
628         break;
629     case FSYNC_VOL_QUERY:
630         code = FSYNC_com_VolQuery(&vcom, res);
631         break;
632     case FSYNC_VOL_QUERY_HDR:
633         code = FSYNC_com_VolHdrQuery(&vcom, res);
634         break;
635 #ifdef AFS_DEMAND_ATTACH_FS
636     case FSYNC_VOL_FORCE_ERROR:
637         code = FSYNC_com_VolError(&vcom, res);
638         break;
639     case FSYNC_VOL_QUERY_VOP:
640         code = FSYNC_com_VolOpQuery(&vcom, res);
641         break;
642     case FSYNC_VG_QUERY:
643         code = FSYNC_com_VGQuery(&vcom, res);
644         break;
645     case FSYNC_VG_SCAN:
646         code = FSYNC_com_VGScan(&vcom, res);
647         break;
648     case FSYNC_VG_SCAN_ALL:
649         code = FSYNC_com_VGScanAll(&vcom, res);
650         break;
651 #endif /* AFS_DEMAND_ATTACH_FS */
652     default:
653         code = SYNC_BAD_COMMAND;
654     }
655
656     return code;
657 }
658
659 /**
660  * service an FSYNC request to bring a volume online.
661  *
662  * @param[in]   vcom  pointer command object
663  * @param[out]  res   object in which to store response packet
664  *
665  * @return operation status
666  *   @retval SYNC_OK volume transitioned online
667  *   @retval SYNC_FAILED invalid command protocol message
668  *   @retval SYNC_DENIED operation could not be completed
669  *
670  * @note this is an FSYNC RPC server stub
671  *
672  * @note this procedure handles the following FSSYNC command codes:
673  *       - FSYNC_VOL_ON
674  *       - FSYNC_VOL_ATTACH
675  *       - FSYNC_VOL_LEAVE_OFF
676  *
677  * @note the supplementary reason code contains additional details.
678  *       When SYNC_DENIED is returned, the specific reason is
679  *       placed in the response packet reason field.
680  *
681  * @internal
682  */
683 static afs_int32
684 FSYNC_com_VolOn(FSSYNC_VolOp_command * vcom, SYNC_response * res)
685 {
686     afs_int32 code = SYNC_OK;
687 #ifndef AFS_DEMAND_ATTACH_FS
688     char tvolName[VMAXPATHLEN];
689 #endif
690     Volume * vp;
691     Error error;
692
693     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
694         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
695         code = SYNC_FAILED;
696         goto done;
697     }
698
699     /* so, we need to attach the volume */
700
701 #ifdef AFS_DEMAND_ATTACH_FS
702     /* check DAFS permissions */
703     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
704     if (vp &&
705         FSYNC_partMatch(vcom, vp, 1) &&
706         vp->pending_vol_op &&
707         (vcom->hdr->programType != vp->pending_vol_op->com.programType)) {
708         /* a different program has this volume checked out. deny. */
709         Log("FSYNC_VolOn: WARNING: program type %u has attempted to manipulate "
710             "state for volume %u using command code %u while the volume is "
711             "checked out by program type %u for command code %u.\n",
712             vcom->hdr->programType,
713             vcom->vop->volume,
714             vcom->hdr->command,
715             vp->pending_vol_op->com.programType,
716             vp->pending_vol_op->com.command);
717         code = SYNC_DENIED;
718         res->hdr.reason = FSYNC_EXCLUSIVE;
719         goto done;
720     }
721 #endif
722
723     if (vcom->v)
724         vcom->v->volumeID = 0;
725
726
727     if (vcom->hdr->command == FSYNC_VOL_LEAVE_OFF) {
728         /* nothing much to do if we're leaving the volume offline */
729 #ifdef AFS_DEMAND_ATTACH_FS
730         if (vp && V_attachState(vp) != VOL_STATE_DELETED) {
731             if (FSYNC_partMatch(vcom, vp, 1)) {
732                 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
733                     (V_attachState(vp) == VOL_STATE_PREATTACHED)) {
734                     VChangeState_r(vp, VOL_STATE_UNATTACHED);
735                     VDeregisterVolOp_r(vp);
736                 } else {
737                     code = SYNC_DENIED;
738                     res->hdr.reason = FSYNC_BAD_STATE;
739                 }
740             } else {
741                 code = SYNC_DENIED;
742                 res->hdr.reason = FSYNC_WRONG_PART;
743             }
744         } else {
745             code = SYNC_FAILED;
746             res->hdr.reason = FSYNC_UNKNOWN_VOLID;
747         }
748 #endif
749         goto done;
750     }
751
752 #ifdef AFS_DEMAND_ATTACH_FS
753     /* first, check to see whether we have such a volume defined */
754     vp = VPreAttachVolumeById_r(&error,
755                                 vcom->vop->partName,
756                                 vcom->vop->volume);
757     if (vp) {
758         VDeregisterVolOp_r(vp);
759     }
760 #else /* !AFS_DEMAND_ATTACH_FS */
761     tvolName[0] = OS_DIRSEPC;
762     snprintf(&tvolName[1], sizeof(tvolName)-1, VFORMAT, afs_printable_uint32_lu(vcom->vop->volume));
763     tvolName[sizeof(tvolName)-1] = '\0';
764
765     vp = VAttachVolumeByName_r(&error, vcom->vop->partName, tvolName,
766                                V_VOLUPD);
767     if (vp)
768         VPutVolume_r(vp);
769     if (error) {
770         code = SYNC_DENIED;
771         res->hdr.reason = error;
772     }
773 #endif /* !AFS_DEMAND_ATTACH_FS */
774
775  done:
776     return code;
777 }
778
779 /**
780  * service an FSYNC request to take a volume offline.
781  *
782  * @param[in]   vcom  pointer command object
783  * @param[out]  res   object in which to store response packet
784  *
785  * @return operation status
786  *   @retval SYNC_OK volume transitioned offline
787  *   @retval SYNC_FAILED invalid command protocol message
788  *   @retval SYNC_DENIED operation could not be completed
789  *
790  * @note this is an FSYNC RPC server stub
791  *
792  * @note this procedure handles the following FSSYNC command codes:
793  *       - FSYNC_VOL_OFF
794  *       - FSYNC_VOL_NEEDVOLUME
795  *
796  * @note the supplementary reason code contains additional details.
797  *       When SYNC_DENIED is returned, the specific reason is
798  *       placed in the response packet reason field.
799  *
800  * @internal
801  */
802 static afs_int32
803 FSYNC_com_VolOff(FSSYNC_VolOp_command * vcom, SYNC_response * res)
804 {
805     FSSYNC_VolOp_info info;
806     afs_int32 code = SYNC_OK;
807     int i;
808     Volume * vp;
809     Error error;
810 #ifdef AFS_DEMAND_ATTACH_FS
811     Volume *nvp, *rvp = NULL;
812 #endif
813
814     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
815         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
816         code = SYNC_FAILED;
817         goto done;
818     }
819
820     /* not already offline, we need to find a slot for newly offline volume */
821     if (vcom->hdr->programType == debugUtility) {
822         /* debug utilities do not have their operations tracked */
823         vcom->v = NULL;
824     } else {
825         if (!vcom->v) {
826             for (i = 0; i < MAXOFFLINEVOLUMES; i++) {
827                 if (vcom->volumes[i].volumeID == 0) {
828                     vcom->v = &vcom->volumes[i];
829                     break;
830                 }
831             }
832         }
833         if (!vcom->v) {
834             goto deny;
835         }
836     }
837
838     FSYNC_com_to_info(vcom, &info);
839
840 #ifdef AFS_DEMAND_ATTACH_FS
841     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
842 #else
843     vp = VGetVolume_r(&error, vcom->vop->volume);
844 #endif
845
846     if (vp) {
847             if (!FSYNC_partMatch(vcom, vp, 1)) {
848             /* volume on desired partition is not online, so we
849              * should treat this as an offline volume.
850              */
851 #ifndef AFS_DEMAND_ATTACH_FS
852             VPutVolume_r(vp);
853 #endif
854             vp = NULL;
855             goto done;
856         }
857     }
858
859 #ifdef AFS_DEMAND_ATTACH_FS
860     if (vp) {
861         ProgramType type = (ProgramType) vcom->hdr->programType;
862
863         /* do initial filtering of requests */
864
865         /* enforce mutual exclusion for volume ops */
866         if (vp->pending_vol_op) {
867             if (vp->pending_vol_op->com.programType != type) {
868                 if (vp->pending_vol_op->com.command == FSYNC_VOL_OFF &&
869                     vp->pending_vol_op->com.reason == FSYNC_SALVAGE) {
870
871                     Log("denying offline request for volume %lu; volume is salvaging\n",
872                         afs_printable_uint32_lu(vp->hashid));
873
874                     res->hdr.reason = FSYNC_SALVAGE;
875                     goto deny;
876                 }
877                 Log("volume %u already checked out\n", vp->hashid);
878                 /* XXX debug */
879                 Log("vp->vop = { com = { ver=%u, prog=%d, com=%d, reason=%d, len=%u, flags=0x%x }, vop = { vol=%u, part='%s' } }\n",
880                     vp->pending_vol_op->com.proto_version,
881                     vp->pending_vol_op->com.programType,
882                     vp->pending_vol_op->com.command,
883                     vp->pending_vol_op->com.reason,
884                     vp->pending_vol_op->com.command_len,
885                     vp->pending_vol_op->com.flags,
886                     vp->pending_vol_op->vop.volume,
887                     vp->pending_vol_op->vop.partName );
888                 Log("vcom = { com = { ver=%u, prog=%d, com=%d, reason=%d, len=%u, flags=0x%x } , vop = { vol=%u, part='%s' } }\n",
889                     vcom->hdr->proto_version,
890                     vcom->hdr->programType,
891                     vcom->hdr->command,
892                     vcom->hdr->reason,
893                     vcom->hdr->command_len,
894                     vcom->hdr->flags,
895                     vcom->vop->volume,
896                     vcom->vop->partName);
897                 res->hdr.reason = FSYNC_EXCLUSIVE;
898                 goto deny;
899             } else {
900                 Log("warning: volume %u recursively checked out by programType id %d\n",
901                     vp->hashid, vcom->hdr->programType);
902             }
903         }
904
905         /* wait for exclusive ops, so we have an accurate picture of the
906          * vol attach state */
907         VCreateReservation_r(vp);
908         VWaitExclusiveState_r(vp);
909         rvp = vp;
910
911         /* filter based upon requestor
912          *
913          * volume utilities / volserver are not allowed to check out
914          * volumes which are in an error state
915          *
916          * unknown utility programs will be denied on principal
917          */
918         switch (type) {
919         case salvageServer:
920             /* it is possible for the salvageserver to checkout a
921              * volume for salvage before its scheduling request
922              * has been sent to the salvageserver */
923             if (vp->salvage.requested && !vp->salvage.scheduled) {
924                 vp->salvage.scheduled = 1;
925             }
926
927             /* If the volume is in VOL_STATE_SALVAGE_REQ, we need to wait
928              * for the vol to go offline before we can give it away. Also
929              * make sure we don't come out with vp in an excl state. */
930             while (V_attachState(vp) == VOL_STATE_SALVAGE_REQ ||
931                    VIsExclusiveState(V_attachState(vp))) {
932
933                 VOL_CV_WAIT(&V_attachCV(vp));
934             }
935
936         case debugUtility:
937             break;
938
939         case volumeUtility:
940         case volumeServer:
941             if (VIsSalvaging(vp)) {
942                 Log("denying offline request for volume %lu; volume is in salvaging state\n",
943                     afs_printable_uint32_lu(vp->hashid));
944                 res->hdr.reason = FSYNC_SALVAGE;
945
946                 /* the volume hasn't been checked out yet by the salvager,
947                  * but we think the volume is salvaging; schedule a
948                  * a salvage to update the salvage priority */
949                 FSYNC_backgroundSalvage(vp);
950
951                 goto deny;
952             }
953             if (VIsErrorState(V_attachState(vp))) {
954                 goto deny;
955             }
956             break;
957
958         default:
959             Log("bad program type passed to FSSYNC\n");
960             goto deny;
961         }
962
963         /* short circuit for offline volume states
964          * so we can avoid I/O penalty of attachment */
965         switch (V_attachState(vp)) {
966         case VOL_STATE_UNATTACHED:
967         case VOL_STATE_PREATTACHED:
968         case VOL_STATE_SALVAGING:
969         case VOL_STATE_ERROR:
970         case VOL_STATE_DELETED:
971             /* register the volume operation metadata with the volume
972              *
973              * if the volume is currently pre-attached, attach2()
974              * will evaluate the vol op metadata to determine whether
975              * attaching the volume would be safe */
976             VRegisterVolOp_r(vp, &info);
977             vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningUnknown;
978             goto done;
979         default:
980             break;
981         }
982
983         /* convert to heavyweight ref */
984         nvp = VGetVolumeByVp_r(&error, vp);
985         if (!nvp) {
986             /*
987              * It's possible for VGetVolumeByVp_r to have dropped and
988              * re-acquired VOL_LOCK, so volume state may have changed
989              * back to one of the states we tested for above. Since
990              * GetVolume can return NULL in some of those states, just
991              * test for the states again here.
992              */
993             switch (V_attachState(vp)) {
994             case VOL_STATE_UNATTACHED:
995             case VOL_STATE_PREATTACHED:
996             case VOL_STATE_SALVAGING:
997             case VOL_STATE_ERROR:
998             case VOL_STATE_DELETED:
999                 /* register the volume operation metadata with the volume
1000                  *
1001                  * if the volume is currently pre-attached, attach2()
1002                  * will evaluate the vol op metadata to determine whether
1003                  * attaching the volume would be safe */
1004                 VRegisterVolOp_r(vp, &info);
1005                 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningUnknown;
1006                 goto done;
1007             default:
1008                 break;
1009             }
1010
1011             Log("FSYNC_com_VolOff: failed to get heavyweight reference to volume %u (state=%u, flags=0x%x)\n",
1012                 vcom->vop->volume, V_attachState(vp), V_attachFlags(vp));
1013             res->hdr.reason = FSYNC_VOL_PKG_ERROR;
1014             goto deny;
1015         } else if (nvp != vp) {
1016             /* i don't think this should ever happen, but just in case... */
1017             Log("FSYNC_com_VolOff: warning: potentially dangerous race detected\n");
1018             vp = nvp;
1019         }
1020
1021         /* kill off lightweight ref to ensure we can't deadlock against ourselves later... */
1022         VCancelReservation_r(rvp);
1023         rvp = NULL;
1024
1025         /* register the volume operation metadata with the volume */
1026         VRegisterVolOp_r(vp, &info);
1027
1028     }
1029 #endif /* AFS_DEMAND_ATTACH_FS */
1030
1031     if (vp) {
1032         if (VVolOpLeaveOnline_r(vp, &info)) {
1033             VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);       /* At least get volume stats right */
1034             if (LogLevel) {
1035                 Log("FSYNC: Volume %u (%s) was left on line for an external %s request\n",
1036                     V_id(vp), V_name(vp),
1037                     vcom->hdr->reason == V_CLONE ? "clone" :
1038                     vcom->hdr->reason == V_READONLY ? "readonly" :
1039                     vcom->hdr->reason == V_DUMP ? "dump" :
1040                     vcom->hdr->reason == FSYNC_SALVAGE ? "salvage" :
1041                     "UNKNOWN");
1042             }
1043 #ifdef AFS_DEMAND_ATTACH_FS
1044             vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
1045 #endif
1046             VPutVolume_r(vp);
1047         } else {
1048             if (VVolOpSetVBusy_r(vp, &info)) {
1049                 vp->specialStatus = VBUSY;
1050             }
1051
1052             /* remember what volume we got, so we can keep track of how
1053              * many volumes the volserver or whatever is using.  Note that
1054              * vp is valid since leaveonline is only set when vp is valid.
1055              */
1056             if (vcom->v) {
1057                 vcom->v->volumeID = vcom->vop->volume;
1058                 strlcpy(vcom->v->partName, vp->partition->name, sizeof(vcom->v->partName));
1059             }
1060
1061 #ifdef AFS_DEMAND_ATTACH_FS
1062             VOfflineForVolOp_r(&error, vp, "A volume utility is running.");
1063             if (error==0) {
1064                 osi_Assert(vp->nUsers==0);
1065                 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
1066             }
1067             else {
1068                 VDeregisterVolOp_r(vp);
1069                 code = SYNC_DENIED;
1070             }
1071 #else
1072             VOffline_r(vp, "A volume utility is running.");
1073 #endif
1074             vp = NULL;
1075         }
1076     }
1077     goto done;
1078
1079  deny:
1080     code = SYNC_DENIED;
1081
1082  done:
1083 #ifdef AFS_DEMAND_ATTACH_FS
1084     if (rvp) {
1085         VCancelReservation_r(rvp);
1086     }
1087 #endif
1088     return code;
1089 }
1090
1091 /**
1092  * service an FSYNC request to mark a volume as moved.
1093  *
1094  * @param[in]   vcom  pointer command object
1095  * @param[out]  res   object in which to store response packet
1096  *
1097  * @return operation status
1098  *   @retval SYNC_OK volume marked as moved to a remote server
1099  *   @retval SYNC_FAILED invalid command protocol message
1100  *   @retval SYNC_DENIED current volume state does not permit this operation
1101  *
1102  * @note this is an FSYNC RPC server stub
1103  *
1104  * @note this operation also breaks all callbacks for the given volume
1105  *
1106  * @note this procedure handles the following FSSYNC command codes:
1107  *       - FSYNC_VOL_MOVE
1108  *
1109  * @note the supplementary reason code contains additional details.  For
1110  *       instance, SYNC_OK is still returned when the partition specified
1111  *       does not match the one registered in the volume object -- reason
1112  *       will be FSYNC_WRONG_PART in this case.
1113  *
1114  * @internal
1115  */
1116 static afs_int32
1117 FSYNC_com_VolMove(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1118 {
1119     afs_int32 code = SYNC_DENIED;
1120     Error error;
1121     Volume * vp;
1122
1123     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
1124         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1125         code = SYNC_FAILED;
1126         goto done;
1127     }
1128
1129     /* Yuch:  the "reason" for the move is the site it got moved to... */
1130     /* still set specialStatus so we stop sending back VBUSY.
1131      * also should still break callbacks.  Note that I don't know
1132      * how to tell if we should break all or not, so we just do it
1133      * since it doesn't matter much if we do an extra break
1134      * volume callbacks on a volume move within the same server */
1135 #ifdef AFS_DEMAND_ATTACH_FS
1136     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
1137 #else
1138     vp = VGetVolume_r(&error, vcom->vop->volume);
1139 #endif
1140     if (vp) {
1141         if (FSYNC_partMatch(vcom, vp, 1)) {
1142 #ifdef AFS_DEMAND_ATTACH_FS
1143             if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
1144                 (V_attachState(vp) == VOL_STATE_PREATTACHED)) {
1145 #endif
1146                 code = SYNC_OK;
1147                 vp->specialStatus = VMOVED;
1148 #ifdef AFS_DEMAND_ATTACH_FS
1149             } else {
1150                 res->hdr.reason = FSYNC_BAD_STATE;
1151             }
1152 #endif
1153         } else {
1154             res->hdr.reason = FSYNC_WRONG_PART;
1155         }
1156 #ifndef AFS_DEMAND_ATTACH_FS
1157         VPutVolume_r(vp);
1158 #endif /* !AFS_DEMAND_ATTACH_FS */
1159     } else {
1160         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1161     }
1162
1163     if ((code == SYNC_OK) && (V_BreakVolumeCallbacks != NULL)) {
1164         Log("fssync: volume %u moved to %x; breaking all call backs\n",
1165             vcom->vop->volume, vcom->hdr->reason);
1166         VOL_UNLOCK;
1167         (*V_BreakVolumeCallbacks) (vcom->vop->volume);
1168         VOL_LOCK;
1169     }
1170
1171
1172  done:
1173     return code;
1174 }
1175
1176 /**
1177  * service an FSYNC request to mark a volume as destroyed.
1178  *
1179  * @param[in]   vcom  pointer command object
1180  * @param[out]  res   object in which to store response packet
1181  *
1182  * @return operation status
1183  *   @retval SYNC_OK volume marked as destroyed
1184  *   @retval SYNC_FAILED invalid command protocol message
1185  *   @retval SYNC_DENIED current volume state does not permit this operation
1186  *
1187  * @note this is an FSYNC RPC server stub
1188  *
1189  * @note this procedure handles the following FSSYNC command codes:
1190  *       - FSYNC_VOL_DONE
1191  *
1192  * @note the supplementary reason code contains additional details.  For
1193  *       instance, SYNC_OK is still returned when the partition specified
1194  *       does not match the one registered in the volume object -- reason
1195  *       will be FSYNC_WRONG_PART in this case.
1196  *
1197  * @internal
1198  */
1199 static afs_int32
1200 FSYNC_com_VolDone(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1201 {
1202     afs_int32 code = SYNC_FAILED;
1203     Error error;
1204     Volume * vp;
1205
1206     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
1207         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1208         goto done;
1209     }
1210
1211     /* don't try to put online, this call is made only after deleting
1212      * a volume, in which case we want to remove the vol # from the
1213      * OfflineVolumes array only */
1214     if (vcom->v)
1215         vcom->v->volumeID = 0;
1216
1217     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
1218     if (vp) {
1219         if (FSYNC_partMatch(vcom, vp, 1)) {
1220 #ifdef AFS_DEMAND_ATTACH_FS
1221             if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
1222                 (V_attachState(vp) == VOL_STATE_PREATTACHED) ||
1223                 VIsErrorState(V_attachState(vp))) {
1224
1225                 /* Change state to DELETED, not UNATTACHED, so clients get
1226                  * a VNOVOL error when they try to access from now on. */
1227
1228                 VChangeState_r(vp, VOL_STATE_DELETED);
1229                 VDeregisterVolOp_r(vp);
1230
1231                 /* Volume is gone; clear out old salvage stats */
1232                 memset(&vp->salvage, 0, sizeof(vp->salvage));
1233
1234                 /* Someday we should free the vp, too, after about 2 hours,
1235                  * possibly by putting the vp back on the VLRU. */
1236
1237                 code = SYNC_OK;
1238             } else {
1239                 code = SYNC_DENIED;
1240                 res->hdr.reason = FSYNC_BAD_STATE;
1241             }
1242 #else /* AFS_DEMAND_ATTACH_FS */
1243             if (!vp->specialStatus) {
1244                 vp->specialStatus = VNOVOL;
1245             }
1246             code = SYNC_OK;
1247 #endif /* !AFS_DEMAND_ATTACH_FS */
1248         } else {
1249             code = SYNC_OK; /* XXX is this really a good idea? */
1250             res->hdr.reason = FSYNC_WRONG_PART;
1251         }
1252     } else {
1253         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1254     }
1255
1256  done:
1257     return code;
1258 }
1259
1260 #ifdef AFS_DEMAND_ATTACH_FS
1261 /**
1262  * service an FSYNC request to transition a volume to the hard error state.
1263  *
1264  * @param[in]   vcom  pointer command object
1265  * @param[out]  res   object in which to store response packet
1266  *
1267  * @return operation status
1268  *   @retval SYNC_OK volume transitioned to hard error state
1269  *   @retval SYNC_FAILED invalid command protocol message
1270  *   @retval SYNC_DENIED (see note)
1271  *
1272  * @note this is an FSYNC RPC server stub
1273  *
1274  * @note this procedure handles the following FSSYNC command codes:
1275  *       - FSYNC_VOL_FORCE_ERROR
1276  *
1277  * @note SYNC_DENIED is returned in the following cases:
1278  *        - no partition name is specified (reason field set to
1279  *          FSYNC_WRONG_PART).
1280  *        - volume id not known to fileserver (reason field set
1281  *          to FSYNC_UNKNOWN_VOLID).
1282  *
1283  * @note demand attach fileserver only
1284  *
1285  * @internal
1286  */
1287 static afs_int32
1288 FSYNC_com_VolError(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1289 {
1290     Error error;
1291     Volume * vp;
1292     afs_int32 code = SYNC_FAILED;
1293
1294     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
1295         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1296         goto done;
1297     }
1298
1299     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
1300
1301     if (!vp && vcom->hdr->reason == FSYNC_SALVAGE) {
1302         /* The requested volume doesn't seem to exist. However, it is possible
1303          * that this is triggered by trying to create or clone a volume that
1304          * was prevented from succeeding by a half-created volume in the way.
1305          * (e.g. we tried to create volume X, but volume X exists except that
1306          * its .vol header was deleted for some reason) So, still try to
1307          * a salvage for that volume ID. */
1308
1309         Log("FSYNC_com_VolError: attempting to schedule salvage for unknown "
1310             "volume %lu part %s\n", afs_printable_uint32_lu(vcom->vop->volume),
1311             vcom->vop->partName);
1312         vp = VPreAttachVolumeById_r(&error, vcom->vop->partName,
1313                                     vcom->vop->volume);
1314     }
1315
1316     if (vp) {
1317         if (FSYNC_partMatch(vcom, vp, 0)) {
1318             /* null out salvsync control state, as it's no longer relevant */
1319             memset(&vp->salvage, 0, sizeof(vp->salvage));
1320             VDeregisterVolOp_r(vp);
1321
1322             if (vcom->hdr->reason == FSYNC_SALVAGE) {
1323                 FSYNC_backgroundSalvage(vp);
1324             } else {
1325                 VChangeState_r(vp, VOL_STATE_ERROR);
1326             }
1327
1328             code = SYNC_OK;
1329         } else {
1330             res->hdr.reason = FSYNC_WRONG_PART;
1331         }
1332     } else {
1333         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1334     }
1335
1336  done:
1337     return code;
1338 }
1339 #endif /* AFS_DEMAND_ATTACH_FS */
1340
1341 /**
1342  * service an FSYNC request to break all callbacks for this volume.
1343  *
1344  * @param[in]   vcom  pointer command object
1345  * @param[out]  res   object in which to store response packet
1346  *
1347  * @return operation status
1348  *   @retval SYNC_OK callback breaks scheduled for volume
1349  *
1350  * @note this is an FSYNC RPC server stub
1351  *
1352  * @note this procedure handles the following FSSYNC command codes:
1353  *       - FSYNC_VOL_BREAKCBKS
1354  *
1355  * @note demand attach fileserver only
1356  *
1357  * @todo should do partition matching
1358  *
1359  * @internal
1360  */
1361 static afs_int32
1362 FSYNC_com_VolBreakCBKs(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1363 {
1364     /* if the volume is being restored, break all callbacks on it */
1365     if (V_BreakVolumeCallbacks) {
1366         Log("fssync: breaking all call backs for volume %u\n",
1367             vcom->vop->volume);
1368         VOL_UNLOCK;
1369         (*V_BreakVolumeCallbacks) (vcom->vop->volume);
1370         VOL_LOCK;
1371     }
1372     return SYNC_OK;
1373 }
1374
1375 /**
1376  * service an FSYNC request to return the Volume object.
1377  *
1378  * @param[in]   vcom  pointer command object
1379  * @param[out]  res   object in which to store response packet
1380  *
1381  * @return operation status
1382  *   @retval SYNC_OK      volume object returned to caller
1383  *   @retval SYNC_FAILED  bad command packet, or failed to locate volume object
1384  *
1385  * @note this is an FSYNC RPC server stub
1386  *
1387  * @note this procedure handles the following FSSYNC command codes:
1388  *       - FSYNC_VOL_QUERY
1389  *
1390  * @internal
1391  */
1392 static afs_int32
1393 FSYNC_com_VolQuery(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1394 {
1395     afs_int32 code = SYNC_FAILED;
1396     Error error;
1397     Volume * vp;
1398
1399     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
1400         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1401         goto done;
1402     }
1403
1404 #ifdef AFS_DEMAND_ATTACH_FS
1405     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
1406 #else /* !AFS_DEMAND_ATTACH_FS */
1407     vp = VGetVolume_r(&error, vcom->vop->volume);
1408 #endif /* !AFS_DEMAND_ATTACH_FS */
1409
1410     if (vp) {
1411         if (FSYNC_partMatch(vcom, vp, 1)) {
1412             if (res->payload.len >= sizeof(Volume)) {
1413                 memcpy(res->payload.buf, vp, sizeof(Volume));
1414                 res->hdr.response_len += sizeof(Volume);
1415                 code = SYNC_OK;
1416             } else {
1417                 res->hdr.reason = SYNC_REASON_PAYLOAD_TOO_BIG;
1418             }
1419         } else {
1420             res->hdr.reason = FSYNC_WRONG_PART;
1421         }
1422 #ifndef AFS_DEMAND_ATTACH_FS
1423         VPutVolume_r(vp);
1424 #endif
1425     } else {
1426         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1427     }
1428
1429  done:
1430     return code;
1431 }
1432
1433 /**
1434  * service an FSYNC request to return the Volume header.
1435  *
1436  * @param[in]   vcom  pointer command object
1437  * @param[out]  res   object in which to store response packet
1438  *
1439  * @return operation status
1440  *   @retval SYNC_OK volume header returned to caller
1441  *   @retval SYNC_FAILED  bad command packet, or failed to locate volume header
1442  *
1443  * @note this is an FSYNC RPC server stub
1444  *
1445  * @note this procedure handles the following FSSYNC command codes:
1446  *       - FSYNC_VOL_QUERY_HDR
1447  *
1448  * @internal
1449  */
1450 static afs_int32
1451 FSYNC_com_VolHdrQuery(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1452 {
1453     afs_int32 code = SYNC_FAILED;
1454     Error error;
1455     Volume * vp;
1456
1457     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
1458         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1459         goto done;
1460     }
1461     if (res->payload.len < sizeof(VolumeDiskData)) {
1462         res->hdr.reason = SYNC_REASON_PAYLOAD_TOO_BIG;
1463         goto done;
1464     }
1465
1466 #ifdef AFS_DEMAND_ATTACH_FS
1467     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
1468 #else /* !AFS_DEMAND_ATTACH_FS */
1469     vp = VGetVolume_r(&error, vcom->vop->volume);
1470 #endif
1471
1472     if (vp) {
1473         if (FSYNC_partMatch(vcom, vp, 1)) {
1474 #ifdef AFS_DEMAND_ATTACH_FS
1475             if ((vp->header == NULL) ||
1476                 !(V_attachFlags(vp) & VOL_HDR_ATTACHED) ||
1477                 !(V_attachFlags(vp) & VOL_HDR_LOADED)) {
1478                 res->hdr.reason = FSYNC_HDR_NOT_ATTACHED;
1479                 goto cleanup;
1480             }
1481 #else /* !AFS_DEMAND_ATTACH_FS */
1482             if (!vp || !vp->header) {
1483                 res->hdr.reason = FSYNC_HDR_NOT_ATTACHED;
1484                 goto cleanup;
1485             }
1486 #endif /* !AFS_DEMAND_ATTACH_FS */
1487         } else {
1488             res->hdr.reason = FSYNC_WRONG_PART;
1489             goto cleanup;
1490         }
1491     } else {
1492         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1493         goto done;
1494     }
1495
1496     memcpy(res->payload.buf, &V_disk(vp), sizeof(VolumeDiskData));
1497     res->hdr.response_len += sizeof(VolumeDiskData);
1498     code = SYNC_OK;
1499
1500  cleanup:
1501 #ifndef AFS_DEMAND_ATTACH_FS
1502     VPutVolume_r(vp);
1503 #endif
1504
1505  done:
1506     return code;
1507 }
1508
1509 #ifdef AFS_DEMAND_ATTACH_FS
1510 static afs_int32
1511 FSYNC_com_VolOpQuery(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1512 {
1513     afs_int32 code = SYNC_OK;
1514     Error error;
1515     Volume * vp;
1516
1517     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
1518
1519     if (vp && vp->pending_vol_op) {
1520         osi_Assert(sizeof(FSSYNC_VolOp_info) <= res->payload.len);
1521         memcpy(res->payload.buf, vp->pending_vol_op, sizeof(FSSYNC_VolOp_info));
1522         res->hdr.response_len += sizeof(FSSYNC_VolOp_info);
1523     } else {
1524         if (!vp || V_attachState(vp) == VOL_STATE_DELETED) {
1525             res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1526         } else if (!FSYNC_partMatch(vcom, vp, 1)) {
1527             res->hdr.reason = FSYNC_WRONG_PART;
1528         } else {
1529             res->hdr.reason = FSYNC_NO_PENDING_VOL_OP;
1530         }
1531         code = SYNC_FAILED;
1532     }
1533     return code;
1534 }
1535
1536 static afs_int32
1537 FSYNC_com_VGQuery(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1538 {
1539     afs_int32 code = SYNC_FAILED;
1540     int rc;
1541     struct DiskPartition64 * dp;
1542
1543     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
1544         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1545         goto done;
1546     }
1547
1548     dp = VGetPartition_r(vcom->vop->partName, 0);
1549     if (dp == NULL) {
1550         res->hdr.reason = FSYNC_BAD_PART;
1551         goto done;
1552     }
1553
1554     osi_Assert(sizeof(FSSYNC_VGQry_response_t) <= res->payload.len);
1555
1556     rc = VVGCache_query_r(dp, vcom->vop->volume, res->payload.buf);
1557     switch (rc) {
1558     case 0:
1559         res->hdr.response_len += sizeof(FSSYNC_VGQry_response_t);
1560         code = SYNC_OK;
1561         break;
1562     case EAGAIN:
1563         res->hdr.reason = FSYNC_PART_SCANNING;
1564         break;
1565     case ENOENT:
1566         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1567         break;
1568     default:
1569         break;
1570     }
1571
1572  done:
1573     return code;
1574 }
1575
1576 static afs_int32
1577 FSYNC_com_VGUpdate(osi_socket fd, SYNC_command * com, SYNC_response * res)
1578 {
1579     afs_int32 code = SYNC_FAILED;
1580     struct DiskPartition64 * dp;
1581     FSSYNC_VGUpdate_command_t * vgucom;
1582     int rc;
1583
1584     if (com->recv_len != (sizeof(com->hdr) + sizeof(*vgucom))) {
1585         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1586         res->hdr.flags |= SYNC_FLAG_CHANNEL_SHUTDOWN;
1587         code = SYNC_COM_ERROR;
1588         goto done;
1589     }
1590
1591     vgucom = com->payload.buf;
1592
1593     ViceLog(125, ("FSYNC_com_VGUpdate: fd %d got command for parent %lu child "
1594                   "%lu partName %.16s\n", (int)fd,
1595                   afs_printable_uint32_lu(vgucom->parent),
1596                   afs_printable_uint32_lu(vgucom->child),
1597                   vgucom->partName));
1598
1599     if (SYNC_verifyProtocolString(vgucom->partName, sizeof(vgucom->partName))) {
1600         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1601         goto done;
1602     }
1603
1604     dp = VGetPartition_r(vgucom->partName, 0);
1605     if (dp == NULL) {
1606         res->hdr.reason = FSYNC_BAD_PART;
1607         goto done;
1608     }
1609
1610     switch(com->hdr.command) {
1611     case FSYNC_VG_ADD:
1612         rc = VVGCache_entry_add_r(dp, vgucom->parent, vgucom->child, NULL);
1613         break;
1614
1615     case FSYNC_VG_DEL:
1616         rc = VVGCache_entry_del_r(dp, vgucom->parent, vgucom->child);
1617         break;
1618
1619     default:
1620         Log("FSYNC_com_VGUpdate called improperly\n");
1621         rc = -1;
1622         break;
1623     }
1624
1625     /* EINVAL means the partition VGC doesn't exist at all; not really
1626      * an error */
1627     if (rc == 0 || rc == EINVAL) {
1628         code = SYNC_OK;
1629     }
1630
1631     if (rc == ENOENT) {
1632         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1633     } else {
1634         res->hdr.reason = FSYNC_WHATEVER;
1635     }
1636
1637  done:
1638     return code;
1639 }
1640
1641 static afs_int32
1642 FSYNC_com_VGScan(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1643 {
1644     afs_int32 code = SYNC_FAILED;
1645     struct DiskPartition64 * dp;
1646
1647     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
1648         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1649         goto done;
1650     }
1651
1652     dp = VGetPartition_r(vcom->vop->partName, 0);
1653     if (dp == NULL) {
1654         res->hdr.reason = FSYNC_BAD_PART;
1655         goto done;
1656     }
1657
1658     if (VVGCache_scanStart_r(dp) == 0) {
1659         code = SYNC_OK;
1660     }
1661
1662  done:
1663     return code;
1664 }
1665
1666 static afs_int32
1667 FSYNC_com_VGScanAll(FSSYNC_VolOp_command * com, SYNC_response * res)
1668 {
1669     afs_int32 code = SYNC_FAILED;
1670
1671     if (VVGCache_scanStart_r(NULL) == 0) {
1672         code = SYNC_OK;
1673     }
1674
1675     return code;
1676 }
1677 #endif /* AFS_DEMAND_ATTACH_FS */
1678
1679 static afs_int32
1680 FSYNC_com_VnQry(osi_socket fd, SYNC_command * com, SYNC_response * res)
1681 {
1682     afs_int32 code = SYNC_OK;
1683     FSSYNC_VnQry_hdr * qry = com->payload.buf;
1684     Volume * vp;
1685     Vnode * vnp;
1686     Error error;
1687
1688     if (com->recv_len != (sizeof(com->hdr) + sizeof(FSSYNC_VnQry_hdr))) {
1689         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1690         res->hdr.flags |= SYNC_FLAG_CHANNEL_SHUTDOWN;
1691         return SYNC_COM_ERROR;
1692     }
1693
1694     ViceLog(125, ("FSYNC_com_VnQry: fd %d got command for vol %lu vnode %lu "
1695                   "uniq %lu spare %lu partName %.16s\n", (int)fd,
1696                   afs_printable_uint32_lu(qry->volume),
1697                   afs_printable_uint32_lu(qry->vnode),
1698                   afs_printable_uint32_lu(qry->unique),
1699                   afs_printable_uint32_lu(qry->spare),
1700                   qry->partName));
1701
1702 #ifdef AFS_DEMAND_ATTACH_FS
1703     vp = VLookupVolume_r(&error, qry->volume, NULL);
1704 #else /* !AFS_DEMAND_ATTACH_FS */
1705     vp = VGetVolume_r(&error, qry->volume);
1706 #endif /* !AFS_DEMAND_ATTACH_FS */
1707
1708     if (!vp) {
1709         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1710         code = SYNC_FAILED;
1711         goto done;
1712     }
1713
1714     vnp = VLookupVnode(vp, qry->vnode);
1715     if (!vnp) {
1716         res->hdr.reason = FSYNC_UNKNOWN_VNID;
1717         code = SYNC_FAILED;
1718         goto cleanup;
1719     }
1720
1721     if (Vn_class(vnp)->residentSize > res->payload.len) {
1722         res->hdr.reason = SYNC_REASON_ENCODING_ERROR;
1723         code = SYNC_FAILED;
1724         goto cleanup;
1725     }
1726
1727     memcpy(res->payload.buf, vnp, Vn_class(vnp)->residentSize);
1728     res->hdr.response_len += Vn_class(vnp)->residentSize;
1729
1730  cleanup:
1731 #ifndef AFS_DEMAND_ATTACH_FS
1732     VPutVolume_r(vp);
1733 #endif
1734
1735  done:
1736     return code;
1737 }
1738
1739 static afs_int32
1740 FSYNC_com_StatsOp(osi_socket fd, SYNC_command * com, SYNC_response * res)
1741 {
1742     afs_int32 code = SYNC_OK;
1743     FSSYNC_StatsOp_command scom;
1744
1745     if (com->recv_len != (sizeof(com->hdr) + sizeof(FSSYNC_StatsOp_hdr))) {
1746         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1747         res->hdr.flags |= SYNC_FLAG_CHANNEL_SHUTDOWN;
1748         return SYNC_COM_ERROR;
1749     }
1750
1751     scom.hdr = &com->hdr;
1752     scom.sop = (FSSYNC_StatsOp_hdr *) com->payload.buf;
1753     scom.com = com;
1754
1755     ViceLog(125, ("FSYNC_com_StatsOp: fd %d got command for stats: "
1756                   "{vlru_generation = %lu, hash_bucket = %lu, partName = "
1757                   "%.16s}\n", (int)fd,
1758                   afs_printable_uint32_lu(scom.sop->args.vlru_generation),
1759                   afs_printable_uint32_lu(scom.sop->args.hash_bucket),
1760                   scom.sop->args.partName));
1761
1762     switch (com->hdr.command) {
1763     case FSYNC_VOL_STATS_GENERAL:
1764         code = FSYNC_com_StatsOpGeneral(&scom, res);
1765         break;
1766 #ifdef AFS_DEMAND_ATTACH_FS
1767         /* statistics for the following subsystems are only tracked
1768          * for demand attach fileservers */
1769     case FSYNC_VOL_STATS_VICEP:
1770         code = FSYNC_com_StatsOpViceP(&scom, res);
1771         break;
1772     case FSYNC_VOL_STATS_HASH:
1773         code = FSYNC_com_StatsOpHash(&scom, res);
1774         break;
1775     case FSYNC_VOL_STATS_HDR:
1776         code = FSYNC_com_StatsOpHdr(&scom, res);
1777         break;
1778     case FSYNC_VOL_STATS_VLRU:
1779         code = FSYNC_com_StatsOpVLRU(&scom, res);
1780         break;
1781 #endif /* AFS_DEMAND_ATTACH_FS */
1782     default:
1783         code = SYNC_BAD_COMMAND;
1784     }
1785
1786     return code;
1787 }
1788
1789 static afs_int32
1790 FSYNC_com_StatsOpGeneral(FSSYNC_StatsOp_command * scom, SYNC_response * res)
1791 {
1792     afs_int32 code = SYNC_OK;
1793
1794     memcpy(res->payload.buf, &VStats, sizeof(VStats));
1795     res->hdr.response_len += sizeof(VStats);
1796
1797     return code;
1798 }
1799
1800 #ifdef AFS_DEMAND_ATTACH_FS
1801 static afs_int32
1802 FSYNC_com_StatsOpViceP(FSSYNC_StatsOp_command * scom, SYNC_response * res)
1803 {
1804     afs_int32 code = SYNC_OK;
1805     struct DiskPartition64 * dp;
1806     struct DiskPartitionStats64 * stats;
1807
1808     if (SYNC_verifyProtocolString(scom->sop->args.partName, sizeof(scom->sop->args.partName))) {
1809         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1810         code = SYNC_FAILED;
1811         goto done;
1812     }
1813
1814     dp = VGetPartition_r(scom->sop->args.partName, 0);
1815     if (!dp) {
1816         code = SYNC_FAILED;
1817     } else {
1818         stats = (struct DiskPartitionStats64 *) res->payload.buf;
1819         stats->free = dp->free;
1820         stats->totalUsable = dp->totalUsable;
1821         stats->minFree = dp->minFree;
1822         stats->f_files = dp->f_files;
1823         stats->vol_list_len = dp->vol_list.len;
1824
1825         res->hdr.response_len += sizeof(struct DiskPartitionStats64);
1826     }
1827
1828  done:
1829     return code;
1830 }
1831
1832 static afs_int32
1833 FSYNC_com_StatsOpHash(FSSYNC_StatsOp_command * scom, SYNC_response * res)
1834 {
1835     afs_int32 code = SYNC_OK;
1836     struct VolumeHashChainStats * stats;
1837     struct VolumeHashChainHead * head;
1838
1839     if (scom->sop->args.hash_bucket >= VolumeHashTable.Size) {
1840         return SYNC_FAILED;
1841     }
1842
1843     head = &VolumeHashTable.Table[scom->sop->args.hash_bucket];
1844     stats = (struct VolumeHashChainStats *) res->payload.buf;
1845     stats->table_size = VolumeHashTable.Size;
1846     stats->chain_len = head->len;
1847     stats->chain_cacheCheck = head->cacheCheck;
1848     stats->chain_busy = head->busy;
1849     AssignInt64(head->looks, &stats->chain_looks);
1850     AssignInt64(head->gets, &stats->chain_gets);
1851     AssignInt64(head->reorders, &stats->chain_reorders);
1852
1853     res->hdr.response_len += sizeof(struct VolumeHashChainStats);
1854
1855     return code;
1856 }
1857
1858 static afs_int32
1859 FSYNC_com_StatsOpHdr(FSSYNC_StatsOp_command * scom, SYNC_response * res)
1860 {
1861     afs_int32 code = SYNC_OK;
1862
1863     memcpy(res->payload.buf, &volume_hdr_LRU.stats, sizeof(volume_hdr_LRU.stats));
1864     res->hdr.response_len += sizeof(volume_hdr_LRU.stats);
1865
1866     return code;
1867 }
1868
1869 static afs_int32
1870 FSYNC_com_StatsOpVLRU(FSSYNC_StatsOp_command * scom, SYNC_response * res)
1871 {
1872     afs_int32 code = SYNC_OK;
1873
1874     code = SYNC_BAD_COMMAND;
1875
1876     return code;
1877 }
1878 #endif /* AFS_DEMAND_ATTACH_FS */
1879
1880 /**
1881  * populate an FSSYNC_VolOp_info object from a command packet object.
1882  *
1883  * @param[in]   vcom  pointer to command packet
1884  * @param[out]  info  pointer to info object which will be populated
1885  *
1886  * @note FSSYNC_VolOp_info objects are attached to Volume objects when
1887  *       a volume operation is commenced.
1888  *
1889  * @internal
1890  */
1891 static void
1892 FSYNC_com_to_info(FSSYNC_VolOp_command * vcom, FSSYNC_VolOp_info * info)
1893 {
1894     memcpy(&info->com, vcom->hdr, sizeof(SYNC_command_hdr));
1895     memcpy(&info->vop, vcom->vop, sizeof(FSSYNC_VolOp_hdr));
1896     info->vol_op_state = FSSYNC_VolOpPending;
1897 }
1898
1899 /**
1900  * check whether command packet partition name matches volume
1901  * object's partition name.
1902  *
1903  * @param[in] vcom        pointer to command packet
1904  * @param[in] vp          pointer to volume object
1905  * @param[in] match_anon  anon matching control flag (see note below)
1906  *
1907  * @return whether partitions match
1908  *   @retval 0  partitions do NOT match
1909  *   @retval 1  partitions match
1910  *
1911  * @note if match_anon is non-zero, then this function will return a
1912  *       positive match for a zero-length partition string in the
1913  *       command packet.
1914  *
1915  * @internal
1916  */
1917 static int
1918 FSYNC_partMatch(FSSYNC_VolOp_command * vcom, Volume * vp, int match_anon)
1919 {
1920     return ((match_anon && vcom->vop->partName[0] == 0) ||
1921             (strncmp(vcom->vop->partName, V_partition(vp)->name,
1922                      sizeof(vcom->vop->partName)) == 0));
1923 }
1924
1925
1926 static void
1927 FSYNC_Drop(osi_socket fd)
1928 {
1929     struct offlineInfo *p;
1930     int i;
1931     Error error;
1932     char tvolName[VMAXPATHLEN];
1933
1934     VOL_LOCK;
1935     p = OfflineVolumes[FindHandler(fd)];
1936     for (i = 0; i < MAXOFFLINEVOLUMES; i++) {
1937         if (p[i].volumeID) {
1938
1939             Volume *vp;
1940
1941             tvolName[0] = OS_DIRSEPC;
1942             sprintf(&tvolName[1], VFORMAT, afs_printable_uint32_lu(p[i].volumeID));
1943             vp = VAttachVolumeByName_r(&error, p[i].partName, tvolName,
1944                                        V_VOLUPD);
1945             if (vp)
1946                 VPutVolume_r(vp);
1947             p[i].volumeID = 0;
1948         }
1949     }
1950     VOL_UNLOCK;
1951     RemoveHandler(fd);
1952 #ifdef AFS_NT40_ENV
1953     closesocket(fd);
1954 #else
1955     close(fd);
1956 #endif
1957     AcceptOn();
1958 }
1959
1960 static int AcceptHandler = -1;  /* handler id for accept, if turned on */
1961
1962 static void
1963 AcceptOn(void)
1964 {
1965     if (AcceptHandler == -1) {
1966         osi_Assert(AddHandler(fssync_server_state.fd, FSYNC_newconnection));
1967         AcceptHandler = FindHandler(fssync_server_state.fd);
1968     }
1969 }
1970
1971 static void
1972 AcceptOff(void)
1973 {
1974     if (AcceptHandler != -1) {
1975         osi_Assert(RemoveHandler(fssync_server_state.fd));
1976         AcceptHandler = -1;
1977     }
1978 }
1979
1980 /* The multiple FD handling code. */
1981
1982 static osi_socket HandlerFD[MAXHANDLERS];
1983 static void (*HandlerProc[MAXHANDLERS]) (osi_socket);
1984
1985 static void
1986 InitHandler(void)
1987 {
1988     int i;
1989     ObtainWriteLock(&FSYNC_handler_lock);
1990     for (i = 0; i < MAXHANDLERS; i++) {
1991         HandlerFD[i] = OSI_NULLSOCKET;
1992         HandlerProc[i] = 0;
1993     }
1994     ReleaseWriteLock(&FSYNC_handler_lock);
1995 }
1996
1997 #if defined(HAVE_POLL) && defined(AFS_PTHREAD_ENV)
1998 static void
1999 CallHandler(struct pollfd *fds, int nfds, int mask)
2000 {
2001     int i;
2002     int handler;
2003     ObtainReadLock(&FSYNC_handler_lock);
2004     for (i = 0; i < nfds; i++) {
2005         if (fds[i].revents & mask) {
2006             handler = FindHandler_r(fds[i].fd);
2007             ReleaseReadLock(&FSYNC_handler_lock);
2008             (*HandlerProc[handler]) (fds[i].fd);
2009             ObtainReadLock(&FSYNC_handler_lock);
2010         }
2011     }
2012     ReleaseReadLock(&FSYNC_handler_lock);
2013 }
2014 #else
2015 static void
2016 CallHandler(fd_set * fdsetp)
2017 {
2018     int i;
2019     ObtainReadLock(&FSYNC_handler_lock);
2020     for (i = 0; i < MAXHANDLERS; i++) {
2021         if (HandlerFD[i] >= 0 && FD_ISSET(HandlerFD[i], fdsetp)) {
2022             ReleaseReadLock(&FSYNC_handler_lock);
2023             (*HandlerProc[i]) (HandlerFD[i]);
2024             ObtainReadLock(&FSYNC_handler_lock);
2025         }
2026     }
2027     ReleaseReadLock(&FSYNC_handler_lock);
2028 }
2029 #endif
2030
2031 static int
2032 AddHandler(osi_socket afd, void (*aproc) (osi_socket))
2033 {
2034     int i;
2035     ObtainWriteLock(&FSYNC_handler_lock);
2036     for (i = 0; i < MAXHANDLERS; i++)
2037         if (HandlerFD[i] == OSI_NULLSOCKET)
2038             break;
2039     if (i >= MAXHANDLERS) {
2040         ReleaseWriteLock(&FSYNC_handler_lock);
2041         return 0;
2042     }
2043     HandlerFD[i] = afd;
2044     HandlerProc[i] = aproc;
2045     ReleaseWriteLock(&FSYNC_handler_lock);
2046     return 1;
2047 }
2048
2049 static int
2050 FindHandler(osi_socket afd)
2051 {
2052     int i;
2053     ObtainReadLock(&FSYNC_handler_lock);
2054     for (i = 0; i < MAXHANDLERS; i++)
2055         if (HandlerFD[i] == afd) {
2056             ReleaseReadLock(&FSYNC_handler_lock);
2057             return i;
2058         }
2059     ReleaseReadLock(&FSYNC_handler_lock);       /* just in case */
2060     osi_Assert(1 == 2);
2061     return -1;                  /* satisfy compiler */
2062 }
2063
2064 static int
2065 FindHandler_r(osi_socket afd)
2066 {
2067     int i;
2068     for (i = 0; i < MAXHANDLERS; i++)
2069         if (HandlerFD[i] == afd) {
2070             return i;
2071         }
2072     osi_Assert(1 == 2);
2073     return -1;                  /* satisfy compiler */
2074 }
2075
2076 static int
2077 RemoveHandler(osi_socket afd)
2078 {
2079     ObtainWriteLock(&FSYNC_handler_lock);
2080     HandlerFD[FindHandler_r(afd)] = OSI_NULLSOCKET;
2081     ReleaseWriteLock(&FSYNC_handler_lock);
2082     return 1;
2083 }
2084
2085 #if defined(HAVE_POLL) && defined(AFS_PTHREAD_ENV)
2086 static void
2087 GetHandler(struct pollfd *fds, int maxfds, int events, int *nfds)
2088 {
2089     int i;
2090     int fdi = 0;
2091     ObtainReadLock(&FSYNC_handler_lock);
2092     for (i = 0; i < MAXHANDLERS; i++)
2093         if (HandlerFD[i] != OSI_NULLSOCKET) {
2094             osi_Assert(fdi<maxfds);
2095             fds[fdi].fd = HandlerFD[i];
2096             fds[fdi].events = events;
2097             fds[fdi].revents = 0;
2098             fdi++;
2099         }
2100     *nfds = fdi;
2101     ReleaseReadLock(&FSYNC_handler_lock);
2102 }
2103 #else
2104 static void
2105 GetHandler(fd_set * fdsetp, int *maxfdp)
2106 {
2107     int i;
2108     int maxfd = -1;
2109     FD_ZERO(fdsetp);
2110     ObtainReadLock(&FSYNC_handler_lock);        /* just in case */
2111     for (i = 0; i < MAXHANDLERS; i++)
2112         if (HandlerFD[i] != OSI_NULLSOCKET) {
2113             FD_SET(HandlerFD[i], fdsetp);
2114 #ifndef AFS_NT40_ENV
2115             /* On Windows the nfds parameter to select() is ignored */
2116             if (maxfd < HandlerFD[i] || maxfd == (int)-1)
2117                 maxfd = HandlerFD[i];
2118 #endif /* AFS_NT40_ENV */
2119         }
2120     *maxfdp = maxfd;
2121     ReleaseReadLock(&FSYNC_handler_lock);       /* just in case */
2122 }
2123 #endif /* HAVE_POLL && AFS_PTHREAD_ENV */
2124
2125 #endif /* FSSYNC_BUILD_SERVER */