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