DAFS: Avoid unnecessary preattach on FSYNC_VOL_ON
[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     /* Verify the partition name is null terminated. */
678     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
679         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
680         code = SYNC_FAILED;
681         goto done;
682     }
683
684     /* so, we need to attach the volume */
685
686 #ifdef AFS_DEMAND_ATTACH_FS
687     /* Verify the partition name is not empty. */
688     if (*vcom->vop->partName == 0) {
689         res->hdr.reason = FSYNC_BAD_PART;
690         code = SYNC_FAILED;
691         goto done;
692     }
693
694     /* check DAFS permissions */
695     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
696     if (vp &&
697         FSYNC_partMatch(vcom, vp, 1) &&
698         vp->pending_vol_op &&
699         (vcom->hdr->programType != vp->pending_vol_op->com.programType)) {
700         /* a different program has this volume checked out. deny. */
701         Log("FSYNC_VolOn: WARNING: program type %u has attempted to manipulate "
702             "state for volume %u using command code %u while the volume is "
703             "checked out by program type %u for command code %u.\n",
704             vcom->hdr->programType,
705             vcom->vop->volume,
706             vcom->hdr->command,
707             vp->pending_vol_op->com.programType,
708             vp->pending_vol_op->com.command);
709         code = SYNC_DENIED;
710         res->hdr.reason = FSYNC_EXCLUSIVE;
711         goto done;
712     }
713 #endif
714
715     if (vcom->v)
716         vcom->v->volumeID = 0;
717
718
719     if (vcom->hdr->command == FSYNC_VOL_LEAVE_OFF) {
720         /* nothing much to do if we're leaving the volume offline */
721 #ifdef AFS_DEMAND_ATTACH_FS
722         if (vp) {
723             VCreateReservation_r(vp);
724             VWaitExclusiveState_r(vp);
725         }
726         if (vp && V_attachState(vp) != VOL_STATE_DELETED) {
727             if (FSYNC_partMatch(vcom, vp, 1)) {
728                 if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
729                     (V_attachState(vp) == VOL_STATE_PREATTACHED)) {
730                     VChangeState_r(vp, VOL_STATE_UNATTACHED);
731                     VDeregisterVolOp_r(vp);
732                 } else {
733                     code = SYNC_DENIED;
734                     res->hdr.reason = FSYNC_BAD_STATE;
735                 }
736             } else {
737                 code = SYNC_DENIED;
738                 res->hdr.reason = FSYNC_WRONG_PART;
739             }
740         } else {
741             code = SYNC_FAILED;
742             res->hdr.reason = FSYNC_UNKNOWN_VOLID;
743         }
744
745         if (vp) {
746             VCancelReservation_r(vp);
747             vp = NULL;
748         }
749 #endif
750         goto done;
751     }
752
753 #ifdef AFS_DEMAND_ATTACH_FS
754
755     if (vp &&
756         FSYNC_partMatch(vcom, vp, 0) &&
757         vp->pending_vol_op &&
758         vp->pending_vol_op->vol_op_state == FSSYNC_VolOpRunningOnline &&
759         V_attachState(vp) == VOL_STATE_ATTACHED) {
760
761         /* noop; the volume stayed online for the volume operation and we were
762          * simply told that the vol op is done. The vp we already have is fine,
763          * so avoid confusing volume routines with trying to preattach an
764          * attached volume. */
765
766     } else {
767         /* first, check to see whether we have such a volume defined */
768         vp = VPreAttachVolumeById_r(&error,
769                                     vcom->vop->partName,
770                                     vcom->vop->volume);
771     }
772
773     if (vp) {
774         VCreateReservation_r(vp);
775         VWaitExclusiveState_r(vp);
776         VDeregisterVolOp_r(vp);
777         VCancelReservation_r(vp);
778         vp = NULL;
779     }
780 #else /* !AFS_DEMAND_ATTACH_FS */
781     tvolName[0] = OS_DIRSEPC;
782     snprintf(&tvolName[1], sizeof(tvolName)-1, VFORMAT, afs_printable_uint32_lu(vcom->vop->volume));
783     tvolName[sizeof(tvolName)-1] = '\0';
784
785     vp = VAttachVolumeByName_r(&error, vcom->vop->partName, tvolName,
786                                V_VOLUPD);
787     if (vp)
788         VPutVolume_r(vp);
789 #endif /* !AFS_DEMAND_ATTACH_FS */
790     if (error) {
791         code = SYNC_DENIED;
792         res->hdr.reason = error;
793     }
794
795  done:
796     return code;
797 }
798
799 /**
800  * service an FSYNC request to take a volume offline.
801  *
802  * @param[in]   vcom  pointer command object
803  * @param[out]  res   object in which to store response packet
804  *
805  * @return operation status
806  *   @retval SYNC_OK volume transitioned offline
807  *   @retval SYNC_FAILED invalid command protocol message
808  *   @retval SYNC_DENIED operation could not be completed
809  *
810  * @note this is an FSYNC RPC server stub
811  *
812  * @note this procedure handles the following FSSYNC command codes:
813  *       - FSYNC_VOL_OFF
814  *       - FSYNC_VOL_NEEDVOLUME
815  *
816  * @note the supplementary reason code contains additional details.
817  *       When SYNC_DENIED is returned, the specific reason is
818  *       placed in the response packet reason field.
819  *
820  * @internal
821  */
822 static afs_int32
823 FSYNC_com_VolOff(FSSYNC_VolOp_command * vcom, SYNC_response * res)
824 {
825     FSSYNC_VolOp_info info;
826     afs_int32 code = SYNC_OK;
827     int i;
828     Volume * vp;
829     Error error;
830 #ifdef AFS_DEMAND_ATTACH_FS
831     Volume *nvp, *rvp = NULL;
832 #endif
833
834     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
835         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
836         code = SYNC_FAILED;
837         goto done;
838     }
839
840     /* not already offline, we need to find a slot for newly offline volume */
841     if (vcom->hdr->programType == debugUtility) {
842         /* debug utilities do not have their operations tracked */
843         vcom->v = NULL;
844     } else {
845         if (!vcom->v) {
846             for (i = 0; i < MAXOFFLINEVOLUMES; i++) {
847                 if (vcom->volumes[i].volumeID == 0) {
848                     vcom->v = &vcom->volumes[i];
849                     break;
850                 }
851             }
852         }
853         if (!vcom->v) {
854             goto deny;
855         }
856     }
857
858     FSYNC_com_to_info(vcom, &info);
859
860 #ifdef AFS_DEMAND_ATTACH_FS
861     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
862 #else
863     vp = VGetVolume_r(&error, vcom->vop->volume);
864 #endif
865
866     if (vp) {
867             if (!FSYNC_partMatch(vcom, vp, 1)) {
868             /* volume on desired partition is not online, so we
869              * should treat this as an offline volume.
870              */
871 #ifndef AFS_DEMAND_ATTACH_FS
872             VPutVolume_r(vp);
873 #endif
874             vp = NULL;
875             goto done;
876         }
877     }
878
879 #ifdef AFS_DEMAND_ATTACH_FS
880     if (vp) {
881         ProgramType type = (ProgramType) vcom->hdr->programType;
882
883         /* do initial filtering of requests */
884
885         /* enforce mutual exclusion for volume ops */
886         if (vp->pending_vol_op) {
887             if (vp->pending_vol_op->com.programType != type) {
888                 if (vp->pending_vol_op->com.command == FSYNC_VOL_OFF &&
889                     vp->pending_vol_op->com.reason == FSYNC_SALVAGE) {
890
891                     Log("denying offline request for volume %lu; volume is salvaging\n",
892                         afs_printable_uint32_lu(vp->hashid));
893
894                     res->hdr.reason = FSYNC_SALVAGE;
895                     goto deny;
896                 }
897                 Log("volume %u already checked out\n", vp->hashid);
898                 /* XXX debug */
899                 Log("vp->vop = { com = { ver=%u, prog=%d, com=%d, reason=%d, len=%u, flags=0x%x }, vop = { vol=%u, part='%s' } }\n",
900                     vp->pending_vol_op->com.proto_version,
901                     vp->pending_vol_op->com.programType,
902                     vp->pending_vol_op->com.command,
903                     vp->pending_vol_op->com.reason,
904                     vp->pending_vol_op->com.command_len,
905                     vp->pending_vol_op->com.flags,
906                     vp->pending_vol_op->vop.volume,
907                     vp->pending_vol_op->vop.partName );
908                 Log("vcom = { com = { ver=%u, prog=%d, com=%d, reason=%d, len=%u, flags=0x%x } , vop = { vol=%u, part='%s' } }\n",
909                     vcom->hdr->proto_version,
910                     vcom->hdr->programType,
911                     vcom->hdr->command,
912                     vcom->hdr->reason,
913                     vcom->hdr->command_len,
914                     vcom->hdr->flags,
915                     vcom->vop->volume,
916                     vcom->vop->partName);
917                 res->hdr.reason = FSYNC_EXCLUSIVE;
918                 goto deny;
919             } else {
920                 Log("warning: volume %u recursively checked out by programType id %d\n",
921                     vp->hashid, vcom->hdr->programType);
922             }
923         }
924
925         /* wait for exclusive ops, so we have an accurate picture of the
926          * vol attach state */
927         VCreateReservation_r(vp);
928         VWaitExclusiveState_r(vp);
929         rvp = vp;
930
931         /* filter based upon requestor
932          *
933          * volume utilities / volserver are not allowed to check out
934          * volumes which are in an error state
935          *
936          * unknown utility programs will be denied on principal
937          */
938         switch (type) {
939         case salvageServer:
940         case volumeSalvager:
941             /* it is possible for the salvageserver to checkout a
942              * volume for salvage before its scheduling request
943              * has been sent to the salvageserver */
944             if (vp->salvage.requested && !vp->salvage.scheduled) {
945                 vp->salvage.scheduled = 1;
946             }
947
948             /* If the volume is in VOL_STATE_SALVAGE_REQ, we need to wait
949              * for the vol to go offline before we can give it away. Also
950              * make sure we don't come out with vp in an excl state. */
951             while (V_attachState(vp) == VOL_STATE_SALVAGE_REQ ||
952                    VIsExclusiveState(V_attachState(vp))) {
953
954                 VOL_CV_WAIT(&V_attachCV(vp));
955             }
956
957         case debugUtility:
958             break;
959
960         case volumeUtility:
961         case volumeServer:
962             if (VIsSalvaging(vp)) {
963                 Log("denying offline request for volume %lu; volume is in salvaging state\n",
964                     afs_printable_uint32_lu(vp->hashid));
965                 res->hdr.reason = FSYNC_SALVAGE;
966
967                 /* the volume hasn't been checked out yet by the salvager,
968                  * but we think the volume is salvaging; schedule a
969                  * a salvage to update the salvage priority */
970                 FSYNC_backgroundSalvage(vp);
971
972                 goto deny;
973             }
974             if (VIsErrorState(V_attachState(vp))) {
975                 goto deny;
976             }
977             break;
978
979         default:
980             Log("bad program type passed to FSSYNC\n");
981             goto deny;
982         }
983
984         /* short circuit for offline volume states
985          * so we can avoid I/O penalty of attachment */
986         switch (V_attachState(vp)) {
987         case VOL_STATE_UNATTACHED:
988         case VOL_STATE_PREATTACHED:
989         case VOL_STATE_SALVAGING:
990         case VOL_STATE_ERROR:
991             /* register the volume operation metadata with the volume
992              *
993              * if the volume is currently pre-attached, attach2()
994              * will evaluate the vol op metadata to determine whether
995              * attaching the volume would be safe */
996             VRegisterVolOp_r(vp, &info);
997             vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningUnknown;
998             /* fall through */
999
1000         case VOL_STATE_DELETED:
1001             goto done;
1002         default:
1003             break;
1004         }
1005
1006         /* convert to heavyweight ref */
1007         nvp = VGetVolumeByVp_r(&error, vp);
1008         if (!nvp) {
1009             /*
1010              * It's possible for VGetVolumeByVp_r to have dropped and
1011              * re-acquired VOL_LOCK, so volume state may have changed
1012              * back to one of the states we tested for above. Since
1013              * GetVolume can return NULL in some of those states, just
1014              * test for the states again here.
1015              */
1016             switch (V_attachState(vp)) {
1017             case VOL_STATE_UNATTACHED:
1018             case VOL_STATE_PREATTACHED:
1019             case VOL_STATE_SALVAGING:
1020             case VOL_STATE_ERROR:
1021                 /* register the volume operation metadata with the volume
1022                  *
1023                  * if the volume is currently pre-attached, attach2()
1024                  * will evaluate the vol op metadata to determine whether
1025                  * attaching the volume would be safe */
1026                 VRegisterVolOp_r(vp, &info);
1027                 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningUnknown;
1028                 /* fall through */
1029
1030             case VOL_STATE_DELETED:
1031                 goto done;
1032             default:
1033                 break;
1034             }
1035
1036             Log("FSYNC_com_VolOff: failed to get heavyweight reference to volume %u (state=%u, flags=0x%x)\n",
1037                 vcom->vop->volume, V_attachState(vp), V_attachFlags(vp));
1038             res->hdr.reason = FSYNC_VOL_PKG_ERROR;
1039             goto deny;
1040         } else if (nvp != vp) {
1041             /* i don't think this should ever happen, but just in case... */
1042             Log("FSYNC_com_VolOff: warning: potentially dangerous race detected\n");
1043             vp = nvp;
1044         }
1045
1046         /* kill off lightweight ref to ensure we can't deadlock against ourselves later... */
1047         VCancelReservation_r(rvp);
1048         rvp = NULL;
1049
1050         /* register the volume operation metadata with the volume */
1051         VRegisterVolOp_r(vp, &info);
1052
1053     }
1054 #endif /* AFS_DEMAND_ATTACH_FS */
1055
1056     if (vp) {
1057         if (VVolOpLeaveOnline_r(vp, &info)) {
1058             VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);       /* At least get volume stats right */
1059             if (LogLevel) {
1060                 Log("FSYNC: Volume %u (%s) was left on line for an external %s request\n",
1061                     V_id(vp), V_name(vp),
1062                     vcom->hdr->reason == V_CLONE ? "clone" :
1063                     vcom->hdr->reason == V_READONLY ? "readonly" :
1064                     vcom->hdr->reason == V_DUMP ? "dump" :
1065                     vcom->hdr->reason == FSYNC_SALVAGE ? "salvage" :
1066                     "UNKNOWN");
1067             }
1068 #ifdef AFS_DEMAND_ATTACH_FS
1069             vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
1070 #endif
1071             VPutVolume_r(vp);
1072         } else {
1073             if (VVolOpSetVBusy_r(vp, &info)) {
1074                 vp->specialStatus = VBUSY;
1075             }
1076
1077             /* remember what volume we got, so we can keep track of how
1078              * many volumes the volserver or whatever is using.  Note that
1079              * vp is valid since leaveonline is only set when vp is valid.
1080              */
1081             if (vcom->v) {
1082                 vcom->v->volumeID = vcom->vop->volume;
1083                 strlcpy(vcom->v->partName, vp->partition->name, sizeof(vcom->v->partName));
1084             }
1085
1086 #ifdef AFS_DEMAND_ATTACH_FS
1087             VCreateReservation_r(vp);
1088             VOfflineForVolOp_r(&error, vp, "A volume utility is running.");
1089             if (error==0) {
1090                 osi_Assert(vp->nUsers==0);
1091                 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
1092             }
1093             else {
1094                 VWaitExclusiveState_r(vp);
1095                 VDeregisterVolOp_r(vp);
1096                 code = SYNC_DENIED;
1097             }
1098             VCancelReservation_r(vp);
1099 #else
1100             VOffline_r(vp, "A volume utility is running.");
1101 #endif
1102             vp = NULL;
1103         }
1104     }
1105     goto done;
1106
1107  deny:
1108     code = SYNC_DENIED;
1109
1110  done:
1111 #ifdef AFS_DEMAND_ATTACH_FS
1112     if (rvp) {
1113         VCancelReservation_r(rvp);
1114     }
1115 #endif
1116     return code;
1117 }
1118
1119 /**
1120  * service an FSYNC request to mark a volume as moved.
1121  *
1122  * @param[in]   vcom  pointer command object
1123  * @param[out]  res   object in which to store response packet
1124  *
1125  * @return operation status
1126  *   @retval SYNC_OK volume marked as moved to a remote server
1127  *   @retval SYNC_FAILED invalid command protocol message
1128  *   @retval SYNC_DENIED current volume state does not permit this operation
1129  *
1130  * @note this is an FSYNC RPC server stub
1131  *
1132  * @note this operation also breaks all callbacks for the given volume
1133  *
1134  * @note this procedure handles the following FSSYNC command codes:
1135  *       - FSYNC_VOL_MOVE
1136  *
1137  * @note the supplementary reason code contains additional details.  For
1138  *       instance, SYNC_OK is still returned when the partition specified
1139  *       does not match the one registered in the volume object -- reason
1140  *       will be FSYNC_WRONG_PART in this case.
1141  *
1142  * @internal
1143  */
1144 static afs_int32
1145 FSYNC_com_VolMove(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1146 {
1147     afs_int32 code = SYNC_DENIED;
1148     Error error;
1149     Volume * vp;
1150
1151     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
1152         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1153         code = SYNC_FAILED;
1154         goto done;
1155     }
1156
1157     /* Yuch:  the "reason" for the move is the site it got moved to... */
1158     /* still set specialStatus so we stop sending back VBUSY.
1159      * also should still break callbacks.  Note that I don't know
1160      * how to tell if we should break all or not, so we just do it
1161      * since it doesn't matter much if we do an extra break
1162      * volume callbacks on a volume move within the same server */
1163 #ifdef AFS_DEMAND_ATTACH_FS
1164     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
1165 #else
1166     vp = VGetVolume_r(&error, vcom->vop->volume);
1167 #endif
1168     if (vp) {
1169         if (FSYNC_partMatch(vcom, vp, 1)) {
1170 #ifdef AFS_DEMAND_ATTACH_FS
1171             if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
1172                 (V_attachState(vp) == VOL_STATE_PREATTACHED)) {
1173 #endif
1174                 code = SYNC_OK;
1175                 vp->specialStatus = VMOVED;
1176 #ifdef AFS_DEMAND_ATTACH_FS
1177             } else {
1178                 res->hdr.reason = FSYNC_BAD_STATE;
1179             }
1180 #endif
1181         } else {
1182             res->hdr.reason = FSYNC_WRONG_PART;
1183         }
1184 #ifndef AFS_DEMAND_ATTACH_FS
1185         VPutVolume_r(vp);
1186 #endif /* !AFS_DEMAND_ATTACH_FS */
1187     } else {
1188         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1189     }
1190
1191     if ((code == SYNC_OK) && (V_BreakVolumeCallbacks != NULL)) {
1192         Log("fssync: volume %u moved to %x; breaking all call backs\n",
1193             vcom->vop->volume, vcom->hdr->reason);
1194         VOL_UNLOCK;
1195         (*V_BreakVolumeCallbacks) (vcom->vop->volume);
1196         VOL_LOCK;
1197     }
1198
1199
1200  done:
1201     return code;
1202 }
1203
1204 /**
1205  * service an FSYNC request to mark a volume as destroyed.
1206  *
1207  * @param[in]   vcom  pointer command object
1208  * @param[out]  res   object in which to store response packet
1209  *
1210  * @return operation status
1211  *   @retval SYNC_OK volume marked as destroyed
1212  *   @retval SYNC_FAILED invalid command protocol message
1213  *   @retval SYNC_DENIED current volume state does not permit this operation
1214  *
1215  * @note this is an FSYNC RPC server stub
1216  *
1217  * @note this procedure handles the following FSSYNC command codes:
1218  *       - FSYNC_VOL_DONE
1219  *
1220  * @note the supplementary reason code contains additional details.  For
1221  *       instance, SYNC_OK is still returned when the partition specified
1222  *       does not match the one registered in the volume object -- reason
1223  *       will be FSYNC_WRONG_PART in this case.
1224  *
1225  * @internal
1226  */
1227 static afs_int32
1228 FSYNC_com_VolDone(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1229 {
1230     afs_int32 code = SYNC_FAILED;
1231     Error error;
1232     Volume * vp;
1233
1234     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
1235         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1236         goto done;
1237     }
1238
1239     /* don't try to put online, this call is made only after deleting
1240      * a volume, in which case we want to remove the vol # from the
1241      * OfflineVolumes array only */
1242     if (vcom->v)
1243         vcom->v->volumeID = 0;
1244
1245     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
1246     if (vp) {
1247         if (FSYNC_partMatch(vcom, vp, 1)) {
1248 #ifdef AFS_DEMAND_ATTACH_FS
1249             VCreateReservation_r(vp);
1250             VWaitExclusiveState_r(vp);
1251
1252             if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
1253                 (V_attachState(vp) == VOL_STATE_PREATTACHED) ||
1254                 VIsErrorState(V_attachState(vp))) {
1255
1256                 /* Change state to DELETED, not UNATTACHED, so clients get
1257                  * a VNOVOL error when they try to access from now on. */
1258
1259                 VChangeState_r(vp, VOL_STATE_DELETED);
1260                 VDeregisterVolOp_r(vp);
1261
1262                 /* Volume is gone; clear out old salvage stats */
1263                 memset(&vp->salvage, 0, sizeof(vp->salvage));
1264
1265                 /* Someday we should free the vp, too, after about 2 hours,
1266                  * possibly by putting the vp back on the VLRU. */
1267
1268                 code = SYNC_OK;
1269             } else if (V_attachState(vp) == VOL_STATE_DELETED) {
1270                 VDeregisterVolOp_r(vp);
1271                 res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1272
1273             } else {
1274                 code = SYNC_DENIED;
1275                 res->hdr.reason = FSYNC_BAD_STATE;
1276             }
1277
1278             VCancelReservation_r(vp);
1279             vp = NULL;
1280 #else /* AFS_DEMAND_ATTACH_FS */
1281             if (!vp->specialStatus) {
1282                 vp->specialStatus = VNOVOL;
1283             }
1284             code = SYNC_OK;
1285 #endif /* !AFS_DEMAND_ATTACH_FS */
1286         } else {
1287             code = SYNC_OK; /* XXX is this really a good idea? */
1288             res->hdr.reason = FSYNC_WRONG_PART;
1289         }
1290     } else {
1291         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1292     }
1293
1294  done:
1295     return code;
1296 }
1297
1298 #ifdef AFS_DEMAND_ATTACH_FS
1299 /**
1300  * service an FSYNC request to transition a volume to the hard error state.
1301  *
1302  * @param[in]   vcom  pointer command object
1303  * @param[out]  res   object in which to store response packet
1304  *
1305  * @return operation status
1306  *   @retval SYNC_OK volume transitioned to hard error state
1307  *   @retval SYNC_FAILED invalid command protocol message
1308  *   @retval SYNC_DENIED (see note)
1309  *
1310  * @note this is an FSYNC RPC server stub
1311  *
1312  * @note this procedure handles the following FSSYNC command codes:
1313  *       - FSYNC_VOL_FORCE_ERROR
1314  *
1315  * @note SYNC_DENIED is returned in the following cases:
1316  *        - no partition name is specified (reason field set to
1317  *          FSYNC_WRONG_PART).
1318  *        - volume id not known to fileserver (reason field set
1319  *          to FSYNC_UNKNOWN_VOLID).
1320  *
1321  * @note demand attach fileserver only
1322  *
1323  * @internal
1324  */
1325 static afs_int32
1326 FSYNC_com_VolError(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1327 {
1328     Error error;
1329     Volume * vp;
1330     afs_int32 code = SYNC_FAILED;
1331
1332     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
1333         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1334         goto done;
1335     }
1336
1337     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
1338
1339     if (!vp && vcom->hdr->reason == FSYNC_SALVAGE) {
1340         /* The requested volume doesn't seem to exist. However, it is possible
1341          * that this is triggered by trying to create or clone a volume that
1342          * was prevented from succeeding by a half-created volume in the way.
1343          * (e.g. we tried to create volume X, but volume X exists except that
1344          * its .vol header was deleted for some reason) So, still try to
1345          * a salvage for that volume ID. */
1346
1347         Log("FSYNC_com_VolError: attempting to schedule salvage for unknown "
1348             "volume %lu part %s\n", afs_printable_uint32_lu(vcom->vop->volume),
1349             vcom->vop->partName);
1350         vp = VPreAttachVolumeById_r(&error, vcom->vop->partName,
1351                                     vcom->vop->volume);
1352     }
1353
1354     if (vp) {
1355         if (FSYNC_partMatch(vcom, vp, 0)) {
1356             VCreateReservation_r(vp);
1357             VWaitExclusiveState_r(vp);
1358             VDeregisterVolOp_r(vp);
1359
1360             if (vcom->hdr->reason == FSYNC_SALVAGE) {
1361                 FSYNC_backgroundSalvage(vp);
1362             } else {
1363                 /* null out salvsync control state, as it's no longer relevant */
1364                 memset(&vp->salvage, 0, sizeof(vp->salvage));
1365                 VChangeState_r(vp, VOL_STATE_ERROR);
1366             }
1367
1368             VCancelReservation_r(vp);
1369             vp = NULL;
1370
1371             code = SYNC_OK;
1372         } else {
1373             res->hdr.reason = FSYNC_WRONG_PART;
1374         }
1375     } else {
1376         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1377     }
1378
1379  done:
1380     return code;
1381 }
1382 #endif /* AFS_DEMAND_ATTACH_FS */
1383
1384 /**
1385  * service an FSYNC request to break all callbacks for this volume.
1386  *
1387  * @param[in]   vcom  pointer command object
1388  * @param[out]  res   object in which to store response packet
1389  *
1390  * @return operation status
1391  *   @retval SYNC_OK callback breaks scheduled for volume
1392  *
1393  * @note this is an FSYNC RPC server stub
1394  *
1395  * @note this procedure handles the following FSSYNC command codes:
1396  *       - FSYNC_VOL_BREAKCBKS
1397  *
1398  * @note demand attach fileserver only
1399  *
1400  * @todo should do partition matching
1401  *
1402  * @internal
1403  */
1404 static afs_int32
1405 FSYNC_com_VolBreakCBKs(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1406 {
1407     /* if the volume is being restored, break all callbacks on it */
1408     if (V_BreakVolumeCallbacks) {
1409         Log("fssync: breaking all call backs for volume %u\n",
1410             vcom->vop->volume);
1411         VOL_UNLOCK;
1412         (*V_BreakVolumeCallbacks) (vcom->vop->volume);
1413         VOL_LOCK;
1414     }
1415     return SYNC_OK;
1416 }
1417
1418 /**
1419  * service an FSYNC request to return the Volume object.
1420  *
1421  * @param[in]   vcom  pointer command object
1422  * @param[out]  res   object in which to store response packet
1423  *
1424  * @return operation status
1425  *   @retval SYNC_OK      volume object returned to caller
1426  *   @retval SYNC_FAILED  bad command packet, or failed to locate volume object
1427  *
1428  * @note this is an FSYNC RPC server stub
1429  *
1430  * @note this procedure handles the following FSSYNC command codes:
1431  *       - FSYNC_VOL_QUERY
1432  *
1433  * @internal
1434  */
1435 static afs_int32
1436 FSYNC_com_VolQuery(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1437 {
1438     afs_int32 code = SYNC_FAILED;
1439     Error error;
1440     Volume * vp;
1441
1442     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
1443         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1444         goto done;
1445     }
1446
1447 #ifdef AFS_DEMAND_ATTACH_FS
1448     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
1449 #else /* !AFS_DEMAND_ATTACH_FS */
1450     vp = VGetVolume_r(&error, vcom->vop->volume);
1451 #endif /* !AFS_DEMAND_ATTACH_FS */
1452
1453     if (vp) {
1454         if (FSYNC_partMatch(vcom, vp, 1)) {
1455             if (res->payload.len >= sizeof(Volume)) {
1456                 memcpy(res->payload.buf, vp, sizeof(Volume));
1457                 res->hdr.response_len += sizeof(Volume);
1458                 code = SYNC_OK;
1459             } else {
1460                 res->hdr.reason = SYNC_REASON_PAYLOAD_TOO_BIG;
1461             }
1462         } else {
1463             res->hdr.reason = FSYNC_WRONG_PART;
1464         }
1465 #ifndef AFS_DEMAND_ATTACH_FS
1466         VPutVolume_r(vp);
1467 #endif
1468     } else {
1469         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1470     }
1471
1472  done:
1473     return code;
1474 }
1475
1476 /**
1477  * service an FSYNC request to return the Volume header.
1478  *
1479  * @param[in]   vcom  pointer command object
1480  * @param[out]  res   object in which to store response packet
1481  *
1482  * @return operation status
1483  *   @retval SYNC_OK volume header returned to caller
1484  *   @retval SYNC_FAILED  bad command packet, or failed to locate volume header
1485  *
1486  * @note this is an FSYNC RPC server stub
1487  *
1488  * @note this procedure handles the following FSSYNC command codes:
1489  *       - FSYNC_VOL_QUERY_HDR
1490  *
1491  * @internal
1492  */
1493 static afs_int32
1494 FSYNC_com_VolHdrQuery(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1495 {
1496     afs_int32 code = SYNC_FAILED;
1497     Error error;
1498     Volume * vp;
1499
1500     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
1501         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1502         goto done;
1503     }
1504     if (res->payload.len < sizeof(VolumeDiskData)) {
1505         res->hdr.reason = SYNC_REASON_PAYLOAD_TOO_BIG;
1506         goto done;
1507     }
1508
1509 #ifdef AFS_DEMAND_ATTACH_FS
1510     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
1511 #else /* !AFS_DEMAND_ATTACH_FS */
1512     vp = VGetVolume_r(&error, vcom->vop->volume);
1513 #endif
1514
1515     if (vp) {
1516         if (FSYNC_partMatch(vcom, vp, 1)) {
1517 #ifdef AFS_DEMAND_ATTACH_FS
1518             if ((vp->header == NULL) ||
1519                 !(V_attachFlags(vp) & VOL_HDR_ATTACHED) ||
1520                 !(V_attachFlags(vp) & VOL_HDR_LOADED)) {
1521                 res->hdr.reason = FSYNC_HDR_NOT_ATTACHED;
1522                 goto cleanup;
1523             }
1524 #else /* !AFS_DEMAND_ATTACH_FS */
1525             if (!vp || !vp->header) {
1526                 res->hdr.reason = FSYNC_HDR_NOT_ATTACHED;
1527                 goto cleanup;
1528             }
1529 #endif /* !AFS_DEMAND_ATTACH_FS */
1530         } else {
1531             res->hdr.reason = FSYNC_WRONG_PART;
1532             goto cleanup;
1533         }
1534     } else {
1535         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1536         goto done;
1537     }
1538
1539     memcpy(res->payload.buf, &V_disk(vp), sizeof(VolumeDiskData));
1540     res->hdr.response_len += sizeof(VolumeDiskData);
1541     code = SYNC_OK;
1542
1543  cleanup:
1544 #ifndef AFS_DEMAND_ATTACH_FS
1545     VPutVolume_r(vp);
1546 #endif
1547
1548  done:
1549     return code;
1550 }
1551
1552 #ifdef AFS_DEMAND_ATTACH_FS
1553 static afs_int32
1554 FSYNC_com_VolOpQuery(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1555 {
1556     afs_int32 code = SYNC_OK;
1557     Error error;
1558     Volume * vp;
1559
1560     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
1561
1562     if (vp) {
1563         VCreateReservation_r(vp);
1564         VWaitExclusiveState_r(vp);
1565     }
1566
1567     if (vp && vp->pending_vol_op) {
1568         if (!FSYNC_partMatch(vcom, vp, 1)) {
1569             res->hdr.reason = FSYNC_WRONG_PART;
1570             code = SYNC_FAILED;
1571         } else {
1572             osi_Assert(sizeof(FSSYNC_VolOp_info) <= res->payload.len);
1573             memcpy(res->payload.buf, vp->pending_vol_op, sizeof(FSSYNC_VolOp_info));
1574             res->hdr.response_len += sizeof(FSSYNC_VolOp_info);
1575         }
1576     } else {
1577         if (!vp || V_attachState(vp) == VOL_STATE_DELETED) {
1578             res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1579         } else if (!FSYNC_partMatch(vcom, vp, 1)) {
1580             res->hdr.reason = FSYNC_WRONG_PART;
1581         } else {
1582             res->hdr.reason = FSYNC_NO_PENDING_VOL_OP;
1583         }
1584         code = SYNC_FAILED;
1585     }
1586
1587     if (vp) {
1588         VCancelReservation_r(vp);
1589     }
1590     return code;
1591 }
1592
1593 static afs_int32
1594 FSYNC_com_VGQuery(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1595 {
1596     afs_int32 code = SYNC_FAILED;
1597     int rc;
1598     struct DiskPartition64 * dp;
1599
1600     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
1601         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1602         goto done;
1603     }
1604
1605     dp = VGetPartition_r(vcom->vop->partName, 0);
1606     if (dp == NULL) {
1607         res->hdr.reason = FSYNC_BAD_PART;
1608         goto done;
1609     }
1610
1611     osi_Assert(sizeof(FSSYNC_VGQry_response_t) <= res->payload.len);
1612
1613     rc = VVGCache_query_r(dp, vcom->vop->volume, res->payload.buf);
1614     switch (rc) {
1615     case 0:
1616         res->hdr.response_len += sizeof(FSSYNC_VGQry_response_t);
1617         code = SYNC_OK;
1618         break;
1619     case EAGAIN:
1620         res->hdr.reason = FSYNC_PART_SCANNING;
1621         break;
1622     case ENOENT:
1623         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1624         break;
1625     default:
1626         break;
1627     }
1628
1629  done:
1630     return code;
1631 }
1632
1633 static afs_int32
1634 FSYNC_com_VGUpdate(osi_socket fd, SYNC_command * com, SYNC_response * res)
1635 {
1636     afs_int32 code = SYNC_FAILED;
1637     struct DiskPartition64 * dp;
1638     FSSYNC_VGUpdate_command_t * vgucom;
1639     int rc;
1640
1641     if (com->recv_len != (sizeof(com->hdr) + sizeof(*vgucom))) {
1642         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1643         res->hdr.flags |= SYNC_FLAG_CHANNEL_SHUTDOWN;
1644         code = SYNC_COM_ERROR;
1645         goto done;
1646     }
1647
1648     vgucom = com->payload.buf;
1649
1650     ViceLog(125, ("FSYNC_com_VGUpdate: fd %d got command for parent %lu child "
1651                   "%lu partName %.16s\n", (int)fd,
1652                   afs_printable_uint32_lu(vgucom->parent),
1653                   afs_printable_uint32_lu(vgucom->child),
1654                   vgucom->partName));
1655
1656     if (SYNC_verifyProtocolString(vgucom->partName, sizeof(vgucom->partName))) {
1657         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1658         goto done;
1659     }
1660
1661     dp = VGetPartition_r(vgucom->partName, 0);
1662     if (dp == NULL) {
1663         res->hdr.reason = FSYNC_BAD_PART;
1664         goto done;
1665     }
1666
1667     switch(com->hdr.command) {
1668     case FSYNC_VG_ADD:
1669         rc = VVGCache_entry_add_r(dp, vgucom->parent, vgucom->child, NULL);
1670         break;
1671
1672     case FSYNC_VG_DEL:
1673         rc = VVGCache_entry_del_r(dp, vgucom->parent, vgucom->child);
1674         break;
1675
1676     default:
1677         Log("FSYNC_com_VGUpdate called improperly\n");
1678         rc = -1;
1679         break;
1680     }
1681
1682     /* EINVAL means the partition VGC doesn't exist at all; not really
1683      * an error */
1684     if (rc == 0 || rc == EINVAL) {
1685         code = SYNC_OK;
1686     }
1687
1688     if (rc == ENOENT) {
1689         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1690     } else {
1691         res->hdr.reason = FSYNC_WHATEVER;
1692     }
1693
1694  done:
1695     return code;
1696 }
1697
1698 static afs_int32
1699 FSYNC_com_VGScan(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1700 {
1701     afs_int32 code = SYNC_FAILED;
1702     struct DiskPartition64 * dp;
1703
1704     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
1705         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1706         goto done;
1707     }
1708
1709     dp = VGetPartition_r(vcom->vop->partName, 0);
1710     if (dp == NULL) {
1711         res->hdr.reason = FSYNC_BAD_PART;
1712         goto done;
1713     }
1714
1715     if (VVGCache_scanStart_r(dp) == 0) {
1716         code = SYNC_OK;
1717     }
1718
1719  done:
1720     return code;
1721 }
1722
1723 static afs_int32
1724 FSYNC_com_VGScanAll(FSSYNC_VolOp_command * com, SYNC_response * res)
1725 {
1726     afs_int32 code = SYNC_FAILED;
1727
1728     if (VVGCache_scanStart_r(NULL) == 0) {
1729         code = SYNC_OK;
1730     }
1731
1732     return code;
1733 }
1734 #endif /* AFS_DEMAND_ATTACH_FS */
1735
1736 static afs_int32
1737 FSYNC_com_VnQry(osi_socket fd, SYNC_command * com, SYNC_response * res)
1738 {
1739     afs_int32 code = SYNC_OK;
1740     FSSYNC_VnQry_hdr * qry = com->payload.buf;
1741     Volume * vp;
1742     Vnode * vnp;
1743     Error error;
1744
1745     if (com->recv_len != (sizeof(com->hdr) + sizeof(FSSYNC_VnQry_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     ViceLog(125, ("FSYNC_com_VnQry: fd %d got command for vol %lu vnode %lu "
1752                   "uniq %lu spare %lu partName %.16s\n", (int)fd,
1753                   afs_printable_uint32_lu(qry->volume),
1754                   afs_printable_uint32_lu(qry->vnode),
1755                   afs_printable_uint32_lu(qry->unique),
1756                   afs_printable_uint32_lu(qry->spare),
1757                   qry->partName));
1758
1759 #ifdef AFS_DEMAND_ATTACH_FS
1760     vp = VLookupVolume_r(&error, qry->volume, NULL);
1761 #else /* !AFS_DEMAND_ATTACH_FS */
1762     vp = VGetVolume_r(&error, qry->volume);
1763 #endif /* !AFS_DEMAND_ATTACH_FS */
1764
1765     if (!vp) {
1766         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1767         code = SYNC_FAILED;
1768         goto done;
1769     }
1770
1771     vnp = VLookupVnode(vp, qry->vnode);
1772     if (!vnp) {
1773         res->hdr.reason = FSYNC_UNKNOWN_VNID;
1774         code = SYNC_FAILED;
1775         goto cleanup;
1776     }
1777
1778     if (Vn_class(vnp)->residentSize > res->payload.len) {
1779         res->hdr.reason = SYNC_REASON_ENCODING_ERROR;
1780         code = SYNC_FAILED;
1781         goto cleanup;
1782     }
1783
1784     memcpy(res->payload.buf, vnp, Vn_class(vnp)->residentSize);
1785     res->hdr.response_len += Vn_class(vnp)->residentSize;
1786
1787  cleanup:
1788 #ifndef AFS_DEMAND_ATTACH_FS
1789     VPutVolume_r(vp);
1790 #endif
1791
1792  done:
1793     return code;
1794 }
1795
1796 static afs_int32
1797 FSYNC_com_StatsOp(osi_socket fd, SYNC_command * com, SYNC_response * res)
1798 {
1799     afs_int32 code = SYNC_OK;
1800     FSSYNC_StatsOp_command scom;
1801
1802     if (com->recv_len != (sizeof(com->hdr) + sizeof(FSSYNC_StatsOp_hdr))) {
1803         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1804         res->hdr.flags |= SYNC_FLAG_CHANNEL_SHUTDOWN;
1805         return SYNC_COM_ERROR;
1806     }
1807
1808     scom.hdr = &com->hdr;
1809     scom.sop = (FSSYNC_StatsOp_hdr *) com->payload.buf;
1810     scom.com = com;
1811
1812     ViceLog(125, ("FSYNC_com_StatsOp: fd %d got command for stats: "
1813                   "{vlru_generation = %lu, hash_bucket = %lu, partName = "
1814                   "%.16s}\n", (int)fd,
1815                   afs_printable_uint32_lu(scom.sop->args.vlru_generation),
1816                   afs_printable_uint32_lu(scom.sop->args.hash_bucket),
1817                   scom.sop->args.partName));
1818
1819     switch (com->hdr.command) {
1820     case FSYNC_VOL_STATS_GENERAL:
1821         code = FSYNC_com_StatsOpGeneral(&scom, res);
1822         break;
1823 #ifdef AFS_DEMAND_ATTACH_FS
1824         /* statistics for the following subsystems are only tracked
1825          * for demand attach fileservers */
1826     case FSYNC_VOL_STATS_VICEP:
1827         code = FSYNC_com_StatsOpViceP(&scom, res);
1828         break;
1829     case FSYNC_VOL_STATS_HASH:
1830         code = FSYNC_com_StatsOpHash(&scom, res);
1831         break;
1832     case FSYNC_VOL_STATS_HDR:
1833         code = FSYNC_com_StatsOpHdr(&scom, res);
1834         break;
1835     case FSYNC_VOL_STATS_VLRU:
1836         code = FSYNC_com_StatsOpVLRU(&scom, res);
1837         break;
1838 #endif /* AFS_DEMAND_ATTACH_FS */
1839     default:
1840         code = SYNC_BAD_COMMAND;
1841     }
1842
1843     return code;
1844 }
1845
1846 static afs_int32
1847 FSYNC_com_StatsOpGeneral(FSSYNC_StatsOp_command * scom, SYNC_response * res)
1848 {
1849     afs_int32 code = SYNC_OK;
1850
1851     memcpy(res->payload.buf, &VStats, sizeof(VStats));
1852     res->hdr.response_len += sizeof(VStats);
1853
1854     return code;
1855 }
1856
1857 #ifdef AFS_DEMAND_ATTACH_FS
1858 static afs_int32
1859 FSYNC_com_StatsOpViceP(FSSYNC_StatsOp_command * scom, SYNC_response * res)
1860 {
1861     afs_int32 code = SYNC_OK;
1862     struct DiskPartition64 * dp;
1863     struct DiskPartitionStats64 * stats;
1864
1865     if (SYNC_verifyProtocolString(scom->sop->args.partName, sizeof(scom->sop->args.partName))) {
1866         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1867         code = SYNC_FAILED;
1868         goto done;
1869     }
1870
1871     dp = VGetPartition_r(scom->sop->args.partName, 0);
1872     if (!dp) {
1873         code = SYNC_FAILED;
1874     } else {
1875         stats = (struct DiskPartitionStats64 *) res->payload.buf;
1876         stats->free = dp->free;
1877         stats->totalUsable = dp->totalUsable;
1878         stats->minFree = dp->minFree;
1879         stats->f_files = dp->f_files;
1880         stats->vol_list_len = dp->vol_list.len;
1881
1882         res->hdr.response_len += sizeof(struct DiskPartitionStats64);
1883     }
1884
1885  done:
1886     return code;
1887 }
1888
1889 static afs_int32
1890 FSYNC_com_StatsOpHash(FSSYNC_StatsOp_command * scom, SYNC_response * res)
1891 {
1892     afs_int32 code = SYNC_OK;
1893     struct VolumeHashChainStats * stats;
1894     struct VolumeHashChainHead * head;
1895
1896     if (scom->sop->args.hash_bucket >= VolumeHashTable.Size) {
1897         return SYNC_FAILED;
1898     }
1899
1900     head = &VolumeHashTable.Table[scom->sop->args.hash_bucket];
1901     stats = (struct VolumeHashChainStats *) res->payload.buf;
1902     stats->table_size = VolumeHashTable.Size;
1903     stats->chain_len = head->len;
1904     stats->chain_cacheCheck = head->cacheCheck;
1905     stats->chain_busy = head->busy;
1906     AssignInt64(head->looks, &stats->chain_looks);
1907     AssignInt64(head->gets, &stats->chain_gets);
1908     AssignInt64(head->reorders, &stats->chain_reorders);
1909
1910     res->hdr.response_len += sizeof(struct VolumeHashChainStats);
1911
1912     return code;
1913 }
1914
1915 static afs_int32
1916 FSYNC_com_StatsOpHdr(FSSYNC_StatsOp_command * scom, SYNC_response * res)
1917 {
1918     afs_int32 code = SYNC_OK;
1919
1920     memcpy(res->payload.buf, &volume_hdr_LRU.stats, sizeof(volume_hdr_LRU.stats));
1921     res->hdr.response_len += sizeof(volume_hdr_LRU.stats);
1922
1923     return code;
1924 }
1925
1926 static afs_int32
1927 FSYNC_com_StatsOpVLRU(FSSYNC_StatsOp_command * scom, SYNC_response * res)
1928 {
1929     afs_int32 code = SYNC_OK;
1930
1931     code = SYNC_BAD_COMMAND;
1932
1933     return code;
1934 }
1935 #endif /* AFS_DEMAND_ATTACH_FS */
1936
1937 /**
1938  * populate an FSSYNC_VolOp_info object from a command packet object.
1939  *
1940  * @param[in]   vcom  pointer to command packet
1941  * @param[out]  info  pointer to info object which will be populated
1942  *
1943  * @note FSSYNC_VolOp_info objects are attached to Volume objects when
1944  *       a volume operation is commenced.
1945  *
1946  * @internal
1947  */
1948 static void
1949 FSYNC_com_to_info(FSSYNC_VolOp_command * vcom, FSSYNC_VolOp_info * info)
1950 {
1951     memcpy(&info->com, vcom->hdr, sizeof(SYNC_command_hdr));
1952     memcpy(&info->vop, vcom->vop, sizeof(FSSYNC_VolOp_hdr));
1953     info->vol_op_state = FSSYNC_VolOpPending;
1954 }
1955
1956 /**
1957  * check whether command packet partition name matches volume
1958  * object's partition name.
1959  *
1960  * @param[in] vcom        pointer to command packet
1961  * @param[in] vp          pointer to volume object
1962  * @param[in] match_anon  anon matching control flag (see note below)
1963  *
1964  * @return whether partitions match
1965  *   @retval 0  partitions do NOT match
1966  *   @retval 1  partitions match
1967  *
1968  * @note if match_anon is non-zero, then this function will return a
1969  *       positive match for a zero-length partition string in the
1970  *       command packet.
1971  *
1972  * @internal
1973  */
1974 static int
1975 FSYNC_partMatch(FSSYNC_VolOp_command * vcom, Volume * vp, int match_anon)
1976 {
1977     return ((match_anon && vcom->vop->partName[0] == 0) ||
1978             (strncmp(vcom->vop->partName, V_partition(vp)->name,
1979                      sizeof(vcom->vop->partName)) == 0));
1980 }
1981
1982
1983 static void
1984 FSYNC_Drop(osi_socket fd)
1985 {
1986     struct offlineInfo *p;
1987     int i;
1988     Error error;
1989     char tvolName[VMAXPATHLEN];
1990
1991     VOL_LOCK;
1992     p = OfflineVolumes[FindHandler(fd)];
1993     for (i = 0; i < MAXOFFLINEVOLUMES; i++) {
1994         if (p[i].volumeID) {
1995
1996             Volume *vp;
1997
1998             tvolName[0] = OS_DIRSEPC;
1999             sprintf(&tvolName[1], VFORMAT, afs_printable_uint32_lu(p[i].volumeID));
2000             vp = VAttachVolumeByName_r(&error, p[i].partName, tvolName,
2001                                        V_VOLUPD);
2002             if (vp)
2003                 VPutVolume_r(vp);
2004             p[i].volumeID = 0;
2005         }
2006     }
2007     VOL_UNLOCK;
2008     RemoveHandler(fd);
2009     rk_closesocket(fd);
2010     AcceptOn();
2011 }
2012
2013 static int AcceptHandler = -1;  /* handler id for accept, if turned on */
2014
2015 static void
2016 AcceptOn(void)
2017 {
2018     if (AcceptHandler == -1) {
2019         osi_Assert(AddHandler(fssync_server_state.fd, FSYNC_newconnection));
2020         AcceptHandler = FindHandler(fssync_server_state.fd);
2021     }
2022 }
2023
2024 static void
2025 AcceptOff(void)
2026 {
2027     if (AcceptHandler != -1) {
2028         osi_Assert(RemoveHandler(fssync_server_state.fd));
2029         AcceptHandler = -1;
2030     }
2031 }
2032
2033 /* The multiple FD handling code. */
2034
2035 static osi_socket HandlerFD[MAXHANDLERS];
2036 static void (*HandlerProc[MAXHANDLERS]) (osi_socket);
2037
2038 static void
2039 InitHandler(void)
2040 {
2041     int i;
2042     ObtainWriteLock(&FSYNC_handler_lock);
2043     for (i = 0; i < MAXHANDLERS; i++) {
2044         HandlerFD[i] = OSI_NULLSOCKET;
2045         HandlerProc[i] = 0;
2046     }
2047     ReleaseWriteLock(&FSYNC_handler_lock);
2048 }
2049
2050 #if defined(HAVE_POLL) && defined(AFS_PTHREAD_ENV)
2051 static void
2052 CallHandler(struct pollfd *fds, int nfds, int mask)
2053 {
2054     int i;
2055     int handler;
2056     ObtainReadLock(&FSYNC_handler_lock);
2057     for (i = 0; i < nfds; i++) {
2058         if (fds[i].revents & mask) {
2059             handler = FindHandler_r(fds[i].fd);
2060             ReleaseReadLock(&FSYNC_handler_lock);
2061             (*HandlerProc[handler]) (fds[i].fd);
2062             ObtainReadLock(&FSYNC_handler_lock);
2063         }
2064     }
2065     ReleaseReadLock(&FSYNC_handler_lock);
2066 }
2067 #else
2068 static void
2069 CallHandler(fd_set * fdsetp)
2070 {
2071     int i;
2072     ObtainReadLock(&FSYNC_handler_lock);
2073     for (i = 0; i < MAXHANDLERS; i++) {
2074         if (HandlerFD[i] >= 0 && FD_ISSET(HandlerFD[i], fdsetp)) {
2075             ReleaseReadLock(&FSYNC_handler_lock);
2076             (*HandlerProc[i]) (HandlerFD[i]);
2077             ObtainReadLock(&FSYNC_handler_lock);
2078         }
2079     }
2080     ReleaseReadLock(&FSYNC_handler_lock);
2081 }
2082 #endif
2083
2084 static int
2085 AddHandler(osi_socket afd, void (*aproc) (osi_socket))
2086 {
2087     int i;
2088     ObtainWriteLock(&FSYNC_handler_lock);
2089     for (i = 0; i < MAXHANDLERS; i++)
2090         if (HandlerFD[i] == OSI_NULLSOCKET)
2091             break;
2092     if (i >= MAXHANDLERS) {
2093         ReleaseWriteLock(&FSYNC_handler_lock);
2094         return 0;
2095     }
2096     HandlerFD[i] = afd;
2097     HandlerProc[i] = aproc;
2098     ReleaseWriteLock(&FSYNC_handler_lock);
2099     return 1;
2100 }
2101
2102 static int
2103 FindHandler(osi_socket afd)
2104 {
2105     int i;
2106     ObtainReadLock(&FSYNC_handler_lock);
2107     for (i = 0; i < MAXHANDLERS; i++)
2108         if (HandlerFD[i] == afd) {
2109             ReleaseReadLock(&FSYNC_handler_lock);
2110             return i;
2111         }
2112     ReleaseReadLock(&FSYNC_handler_lock);       /* just in case */
2113     osi_Assert(1 == 2);
2114     return -1;                  /* satisfy compiler */
2115 }
2116
2117 static int
2118 FindHandler_r(osi_socket afd)
2119 {
2120     int i;
2121     for (i = 0; i < MAXHANDLERS; i++)
2122         if (HandlerFD[i] == afd) {
2123             return i;
2124         }
2125     osi_Assert(1 == 2);
2126     return -1;                  /* satisfy compiler */
2127 }
2128
2129 static int
2130 RemoveHandler(osi_socket afd)
2131 {
2132     ObtainWriteLock(&FSYNC_handler_lock);
2133     HandlerFD[FindHandler_r(afd)] = OSI_NULLSOCKET;
2134     ReleaseWriteLock(&FSYNC_handler_lock);
2135     return 1;
2136 }
2137
2138 #if defined(HAVE_POLL) && defined(AFS_PTHREAD_ENV)
2139 static void
2140 GetHandler(struct pollfd *fds, int maxfds, int events, int *nfds)
2141 {
2142     int i;
2143     int fdi = 0;
2144     ObtainReadLock(&FSYNC_handler_lock);
2145     for (i = 0; i < MAXHANDLERS; i++)
2146         if (HandlerFD[i] != OSI_NULLSOCKET) {
2147             osi_Assert(fdi<maxfds);
2148             fds[fdi].fd = HandlerFD[i];
2149             fds[fdi].events = events;
2150             fds[fdi].revents = 0;
2151             fdi++;
2152         }
2153     *nfds = fdi;
2154     ReleaseReadLock(&FSYNC_handler_lock);
2155 }
2156 #else
2157 static void
2158 GetHandler(fd_set * fdsetp, int *maxfdp)
2159 {
2160     int i;
2161     int maxfd = -1;
2162     FD_ZERO(fdsetp);
2163     ObtainReadLock(&FSYNC_handler_lock);        /* just in case */
2164     for (i = 0; i < MAXHANDLERS; i++)
2165         if (HandlerFD[i] != OSI_NULLSOCKET) {
2166             FD_SET(HandlerFD[i], fdsetp);
2167 #ifndef AFS_NT40_ENV
2168             /* On Windows the nfds parameter to select() is ignored */
2169             if (maxfd < HandlerFD[i] || maxfd == (int)-1)
2170                 maxfd = HandlerFD[i];
2171 #endif /* AFS_NT40_ENV */
2172         }
2173     *maxfdp = maxfd;
2174     ReleaseReadLock(&FSYNC_handler_lock);       /* just in case */
2175 }
2176 #endif /* HAVE_POLL && AFS_PTHREAD_ENV */
2177
2178 #endif /* FSSYNC_BUILD_SERVER */