Avoid duplicate definitions of globals
[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 <afs/opr.h>
49 #ifdef AFS_PTHREAD_ENV
50 # include <opr/lock.h>
51 #endif
52 #include <afs/afsint.h>
53 #include <rx/rx_queue.h>
54 #include "nfs.h"
55 #include <afs/errors.h>
56 #include "daemon_com.h"
57 #include "daemon_com_inline.h"
58 #include "fssync.h"
59 #include "fssync_inline.h"
60 #include "salvsync.h"
61 #include "lwp.h"
62 #include "lock.h"
63 #include <afs/afssyscalls.h>
64 #include "ihandle.h"
65 #include "vnode.h"
66 #include "volume.h"
67 #include "volume_inline.h"
68 #include "partition.h"
69 #include "vg_cache.h"
70 #include "common.h"
71
72 #ifdef HAVE_POLL
73 #include <sys/poll.h>
74 #endif /* HAVE_POLL */
75
76 #ifdef USE_UNIX_SOCKETS
77 #include <sys/un.h>
78 #include <afs/afsutil.h>
79 #endif /* USE_UNIX_SOCKETS */
80
81 #ifdef FSSYNC_BUILD_SERVER
82 #define MAXHANDLERS     4       /* Up to 4 clients; must be at least 2, so that
83                                  * move = dump+restore can run on single server */
84 #define MAXOFFLINEVOLUMES 128   /* This needs to be as big as the maximum
85                                  * number that would be offline for 1 operation.
86                                  * Current winner is salvage, which needs all
87                                  * cloned read-only copies offline when salvaging
88                                  * a single read-write volume */
89
90
91
92 static struct offlineInfo OfflineVolumes[MAXHANDLERS][MAXOFFLINEVOLUMES];
93
94 /**
95  * fssync server socket handle.
96  */
97 static SYNC_server_state_t fssync_server_state =
98     { OSI_NULLSOCKET,                       /* file descriptor */
99       FSSYNC_ENDPOINT_DECL,     /* server endpoint */
100       FSYNC_PROTO_VERSION,      /* protocol version */
101       5,                        /* bind() retry limit */
102       100,                      /* listen() queue depth */
103       "FSSYNC",                 /* protocol name string */
104     };
105
106 #ifdef AFS_DEMAND_ATTACH_FS
107 /**
108  * a queue of volume pointers to salvage in the background.
109  */
110 struct fsync_salv_node {
111     struct rx_queue q;
112     Volume *vp;                     /**< volume to salvage */
113     unsigned char update_salv_prio; /**< whether we should update the salvage priority or not */
114 };
115 static struct {
116     struct rx_queue head;
117     pthread_cond_t cv;
118 } fsync_salv;
119
120 static void * FSYNC_salvageThread(void *);
121 static void FSYNC_backgroundSalvage(Volume *vp);
122 #endif /* AFS_DEMAND_ATTACH_FS */
123
124 /* Forward declarations */
125 static void * FSYNC_sync(void *);
126 static void FSYNC_newconnection(osi_socket afd);
127 static void FSYNC_com(osi_socket fd);
128 static void FSYNC_Drop(osi_socket fd);
129 static void AcceptOn(void);
130 static void AcceptOff(void);
131 static void InitHandler(void);
132 static int AddHandler(osi_socket fd, void (*aproc)(osi_socket));
133 static int FindHandler(osi_socket afd);
134 static int FindHandler_r(osi_socket afd);
135 static int RemoveHandler(osi_socket afd);
136 #if defined(HAVE_POLL) && defined (AFS_PTHREAD_ENV)
137 static void CallHandler(struct pollfd *fds, int nfds, int mask);
138 static void GetHandler(struct pollfd *fds, int maxfds, int events, int *nfds);
139 #else
140 static void CallHandler(fd_set * fdsetp);
141 static void GetHandler(fd_set * fdsetp, int *maxfdp);
142 #endif
143
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     opr_Verify(pthread_attr_init(&tattr) == 0);
202     opr_Verify(pthread_attr_setdetachstate(&tattr,
203                                            PTHREAD_CREATE_DETACHED) == 0);
204     opr_Verify(pthread_create(&tid, &tattr, FSYNC_sync, NULL) == 0);
205 #else /* AFS_PTHREAD_ENV */
206     opr_Verify(LWP_CreateProcess(FSYNC_sync, USUAL_STACK_SIZE,
207                                  USUAL_PRIORITY, NULL,
208                                  "FSYNC_sync", &pid) == LWP_SUCCESS);
209 #endif /* AFS_PTHREAD_ENV */
210
211 #ifdef AFS_DEMAND_ATTACH_FS
212     queue_Init(&fsync_salv.head);
213     opr_cv_init(&fsync_salv.cv);
214     opr_Verify(pthread_create(&tid, &tattr, FSYNC_salvageThread, NULL) == 0);
215 #endif /* AFS_DEMAND_ATTACH_FS */
216 }
217
218 #if defined(HAVE_POLL) && defined(AFS_PTHREAD_ENV)
219 static struct pollfd FSYNC_readfds[MAXHANDLERS];
220 #else
221 static fd_set FSYNC_readfds;
222 #endif
223
224
225 static void *
226 FSYNC_sync(void * args)
227 {
228     extern int VInit;
229     int code;
230 #ifdef AFS_PTHREAD_ENV
231     int tid;
232 #endif
233     SYNC_server_state_t * state = &fssync_server_state;
234 #ifdef AFS_DEMAND_ATTACH_FS
235     VThreadOptions_t * thread_opts;
236     int min_vinit = 2;
237 #else
238     /*
239      * For non-DAFS, only wait until we begin attaching volumes (instead
240      * of waiting until all volumes are attached), since it can take
241      * awhile until VInit == 2.
242      */
243     int min_vinit = 1;
244 #endif /* AFS_DEMAND_ATTACH_FS */
245
246     /* we must not be called before vol package initialization, since we use
247      * vol package mutexes and conds etc */
248     opr_Assert(VInit);
249
250     SYNC_getAddr(&state->endpoint, &state->addr);
251     SYNC_cleanupSock(state);
252
253 #ifndef AFS_NT40_ENV
254     (void)signal(SIGPIPE, SIG_IGN);
255 #endif
256
257 #ifdef AFS_PTHREAD_ENV
258     /* set our 'thread-id' so that the host hold table works */
259     tid = rx_SetThreadNum();
260     Log("Set thread id %d for FSYNC_sync\n", tid);
261     opr_threadname_set("FSYNC_sync");
262 #endif /* AFS_PTHREAD_ENV */
263
264     VOL_LOCK;
265
266     while (VInit < min_vinit) {
267         /* Let somebody else run until all volumes have been preattached
268          * (DAFS), or we have started attaching volumes (non-DAFS). This
269          * doesn't mean that all volumes have been attached.
270          */
271 #ifdef AFS_PTHREAD_ENV
272         VOL_CV_WAIT(&vol_vinit_cond);
273 #else /* AFS_PTHREAD_ENV */
274         LWP_DispatchProcess();
275 #endif /* AFS_PTHREAD_ENV */
276     }
277
278     VOL_UNLOCK;
279
280     state->fd = SYNC_getSock(&state->endpoint);
281     code = SYNC_bindSock(state);
282     opr_Assert(!code);
283
284 #ifdef AFS_DEMAND_ATTACH_FS
285     /*
286      * make sure the volume package is incapable of recursively executing
287      * salvsync calls on this thread, since there is a possibility of
288      * deadlock.
289      */
290     thread_opts = malloc(sizeof(VThreadOptions_t));
291     if (thread_opts == NULL) {
292         Log("failed to allocate memory for thread-specific volume package options structure\n");
293         return NULL;
294     }
295     memcpy(thread_opts, &VThread_defaults, sizeof(VThread_defaults));
296     thread_opts->disallow_salvsync = 1;
297     opr_Verify(pthread_setspecific(VThread_key, thread_opts) == 0);
298
299     code = VVGCache_PkgInit();
300     opr_Assert(code == 0);
301 #endif
302
303     InitHandler();
304     AcceptOn();
305
306     for (;;) {
307 #if defined(HAVE_POLL) && defined(AFS_PTHREAD_ENV)
308         int nfds;
309         GetHandler(FSYNC_readfds, MAXHANDLERS, POLLIN|POLLPRI, &nfds);
310         if (poll(FSYNC_readfds, nfds, -1) >=1)
311             CallHandler(FSYNC_readfds, nfds, POLLIN|POLLPRI);
312 #else
313         int maxfd;
314 #ifdef AFS_PTHREAD_ENV
315         struct timeval s_timeout;
316 #endif
317         GetHandler(&FSYNC_readfds, &maxfd);
318         /* Note: check for >= 1 below is essential since IOMGR_select
319          * doesn't have exactly same semantics as select.
320          */
321 #ifdef AFS_PTHREAD_ENV
322         s_timeout.tv_sec = SYNC_SELECT_TIMEOUT;
323         s_timeout.tv_usec = 0;
324         if (select(maxfd + 1, &FSYNC_readfds, NULL, NULL, &s_timeout) >= 1)
325 #else /* AFS_PTHREAD_ENV */
326         if (IOMGR_Select(maxfd + 1, &FSYNC_readfds, NULL, NULL, NULL) >= 1)
327 #endif /* AFS_PTHREAD_ENV */
328             CallHandler(&FSYNC_readfds);
329 #endif
330     }
331     AFS_UNREACHED(return(NULL)); /* hush now, little gcc */
332 }
333
334 #ifdef AFS_DEMAND_ATTACH_FS
335 /**
336  * thread for salvaging volumes in the background.
337  *
338  * Since FSSYNC handlers cannot issue SALVSYNC requests in order to avoid
339  * deadlock issues, this thread exists so code in the FSSYNC handler thread
340  * can hand off volumes to be salvaged in the background.
341  *
342  * @param[in] args  unused
343  *
344  * @note DEMAND_ATTACH_FS only
345  */
346 static void *
347 FSYNC_salvageThread(void * args)
348 {
349     Volume *vp;
350     struct fsync_salv_node *node;
351
352     VOL_LOCK;
353
354     for (;;) {
355         while (queue_IsEmpty(&fsync_salv.head)) {
356             VOL_CV_WAIT(&fsync_salv.cv);
357         }
358
359         node = queue_First(&fsync_salv.head, fsync_salv_node);
360         queue_Remove(node);
361
362         vp = node->vp;
363         if (node->update_salv_prio) {
364             if (VUpdateSalvagePriority_r(vp)) {
365                 ViceLog(0, ("FSYNC_salvageThread: unable to raise salvage priority "
366                             "for volume %" AFS_VOLID_FMT "\n", afs_printable_VolumeId_lu(vp->hashid)));
367             }
368         }
369
370         free(node);
371         node = NULL;
372
373         VCancelReservation_r(vp);
374     }
375
376     AFS_UNREACHED(VOL_UNLOCK);
377     AFS_UNREACHED(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 %" AFS_VOLID_FMT "\n",
410                     afs_printable_VolumeId_lu(vp->hashid)));
411     }
412
413     queue_Append(&fsync_salv.head, node);
414     opr_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         opr_abort();
433     } else if (!AddHandler(fd, FSYNC_com)) {
434         AcceptOff();
435         opr_Verify(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 %" AFS_VOLID_FMT " 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             afs_printable_VolumeId_lu(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_VolumeId_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 %" AFS_VOLID_FMT "; volume is salvaging\n",
892                         afs_printable_VolumeId_lu(vp->hashid));
893
894                     res->hdr.reason = FSYNC_SALVAGE;
895                     goto deny;
896                 }
897                 Log("volume %" AFS_VOLID_FMT " already checked out\n",
898                     afs_printable_VolumeId_lu(vp->hashid));
899                 /* XXX debug */
900                 Log("vp->vop = { com = { ver=%u, prog=%d, com=%d, reason=%d, len=%u, flags=0x%x }, vop = { vol=%" AFS_VOLID_FMT ", part='%s' } }\n",
901                     vp->pending_vol_op->com.proto_version,
902                     vp->pending_vol_op->com.programType,
903                     vp->pending_vol_op->com.command,
904                     vp->pending_vol_op->com.reason,
905                     vp->pending_vol_op->com.command_len,
906                     vp->pending_vol_op->com.flags,
907                     afs_printable_VolumeId_lu(vp->pending_vol_op->vop.volume),
908                     vp->pending_vol_op->vop.partName );
909                 Log("vcom = { com = { ver=%u, prog=%d, com=%d, reason=%d, len=%u, flags=0x%x } , vop = { vol=%" AFS_VOLID_FMT ", part='%s' } }\n",
910                     vcom->hdr->proto_version,
911                     vcom->hdr->programType,
912                     vcom->hdr->command,
913                     vcom->hdr->reason,
914                     vcom->hdr->command_len,
915                     vcom->hdr->flags,
916                     afs_printable_VolumeId_lu(vcom->vop->volume),
917                     vcom->vop->partName);
918                 res->hdr.reason = FSYNC_EXCLUSIVE;
919                 goto deny;
920             } else {
921                 Log("warning: volume %" AFS_VOLID_FMT " recursively checked out by programType id %d\n",
922                     afs_printable_VolumeId_lu(vp->hashid), vcom->hdr->programType);
923             }
924         }
925
926         /* wait for exclusive ops, so we have an accurate picture of the
927          * vol attach state */
928         VCreateReservation_r(vp);
929         VWaitExclusiveState_r(vp);
930         rvp = vp;
931
932         /* filter based upon requestor
933          *
934          * volume utilities / volserver are not allowed to check out
935          * volumes which are in an error state
936          *
937          * unknown utility programs will be denied on principal
938          */
939         switch (type) {
940         case salvageServer:
941         case volumeSalvager:
942             /* it is possible for the salvageserver to checkout a
943              * volume for salvage before its scheduling request
944              * has been sent to the salvageserver */
945             if (vp->salvage.requested && !vp->salvage.scheduled) {
946                 vp->salvage.scheduled = 1;
947             }
948
949             /* If the volume is in VOL_STATE_SALVAGE_REQ, we need to wait
950              * for the vol to go offline before we can give it away. Also
951              * make sure we don't come out with vp in an excl state. */
952             while (V_attachState(vp) == VOL_STATE_SALVAGE_REQ ||
953                    VIsExclusiveState(V_attachState(vp))) {
954
955                 VOL_CV_WAIT(&V_attachCV(vp));
956             }
957
958         case debugUtility:
959             break;
960
961         case volumeUtility:
962         case volumeServer:
963             if (VIsSalvaging(vp)) {
964                 Log("denying offline request for volume %" AFS_VOLID_FMT "; volume is in salvaging state\n",
965                     afs_printable_VolumeId_lu(vp->hashid));
966                 res->hdr.reason = FSYNC_SALVAGE;
967
968                 /* the volume hasn't been checked out yet by the salvager,
969                  * but we think the volume is salvaging; schedule a
970                  * a salvage to update the salvage priority */
971                 FSYNC_backgroundSalvage(vp);
972
973                 goto deny;
974             }
975             if (VIsErrorState(V_attachState(vp))) {
976                 goto deny;
977             }
978             break;
979
980         default:
981             Log("bad program type passed to FSSYNC\n");
982             goto deny;
983         }
984
985         /* short circuit for offline volume states
986          * so we can avoid I/O penalty of attachment */
987         switch (V_attachState(vp)) {
988         case VOL_STATE_UNATTACHED:
989         case VOL_STATE_PREATTACHED:
990         case VOL_STATE_SALVAGING:
991         case VOL_STATE_ERROR:
992             /* register the volume operation metadata with the volume
993              *
994              * if the volume is currently pre-attached, attach2()
995              * will evaluate the vol op metadata to determine whether
996              * attaching the volume would be safe */
997             VRegisterVolOp_r(vp, &info);
998             vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningUnknown;
999             /* fall through */
1000
1001         case VOL_STATE_DELETED:
1002             goto done;
1003         default:
1004             break;
1005         }
1006
1007         /* convert to heavyweight ref */
1008         nvp = VGetVolumeByVp_r(&error, vp);
1009         if (!nvp) {
1010             /*
1011              * It's possible for VGetVolumeByVp_r to have dropped and
1012              * re-acquired VOL_LOCK, so volume state may have changed
1013              * back to one of the states we tested for above. Since
1014              * GetVolume can return NULL in some of those states, just
1015              * test for the states again here.
1016              */
1017             switch (V_attachState(vp)) {
1018             case VOL_STATE_UNATTACHED:
1019             case VOL_STATE_PREATTACHED:
1020             case VOL_STATE_SALVAGING:
1021             case VOL_STATE_ERROR:
1022                 /* register the volume operation metadata with the volume
1023                  *
1024                  * if the volume is currently pre-attached, attach2()
1025                  * will evaluate the vol op metadata to determine whether
1026                  * attaching the volume would be safe */
1027                 VRegisterVolOp_r(vp, &info);
1028                 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningUnknown;
1029                 /* fall through */
1030
1031             case VOL_STATE_DELETED:
1032                 goto done;
1033             default:
1034                 break;
1035             }
1036
1037             Log("FSYNC_com_VolOff: failed to get heavyweight reference to volume %" AFS_VOLID_FMT " (state=%u, flags=0x%x)\n",
1038                 afs_printable_VolumeId_lu(vcom->vop->volume),
1039                 V_attachState(vp), V_attachFlags(vp));
1040             res->hdr.reason = FSYNC_VOL_PKG_ERROR;
1041             goto deny;
1042         } else if (nvp != vp) {
1043             /* i don't think this should ever happen, but just in case... */
1044             Log("FSYNC_com_VolOff: warning: potentially dangerous race detected\n");
1045             vp = nvp;
1046         }
1047
1048         /* kill off lightweight ref to ensure we can't deadlock against ourselves later... */
1049         VCancelReservation_r(rvp);
1050         rvp = NULL;
1051
1052         /* register the volume operation metadata with the volume */
1053         VRegisterVolOp_r(vp, &info);
1054
1055     }
1056 #endif /* AFS_DEMAND_ATTACH_FS */
1057
1058     if (vp) {
1059         if (VVolOpLeaveOnline_r(vp, &info)) {
1060             VUpdateVolume_r(&error, vp, VOL_UPDATE_WAIT);       /* At least get volume stats right */
1061             if (GetLogLevel() > 0) {
1062                 Log("FSYNC: Volume %" AFS_VOLID_FMT " (%s) was left on line for an external %s request\n",
1063                     afs_printable_VolumeId_lu(V_id(vp)), V_name(vp),
1064                     vcom->hdr->reason == V_CLONE ? "clone" :
1065                     vcom->hdr->reason == V_READONLY ? "readonly" :
1066                     vcom->hdr->reason == V_DUMP ? "dump" :
1067                     vcom->hdr->reason == FSYNC_SALVAGE ? "salvage" :
1068                     "UNKNOWN");
1069             }
1070 #ifdef AFS_DEMAND_ATTACH_FS
1071             vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOnline;
1072 #endif
1073             VPutVolume_r(vp);
1074         } else {
1075             if (VVolOpSetVBusy_r(vp, &info)) {
1076                 vp->specialStatus = VBUSY;
1077             }
1078
1079             /* remember what volume we got, so we can keep track of how
1080              * many volumes the volserver or whatever is using.  Note that
1081              * vp is valid since leaveonline is only set when vp is valid.
1082              */
1083             if (vcom->v) {
1084                 vcom->v->volumeID = vcom->vop->volume;
1085                 strlcpy(vcom->v->partName, vp->partition->name, sizeof(vcom->v->partName));
1086             }
1087
1088 #ifdef AFS_DEMAND_ATTACH_FS
1089             VCreateReservation_r(vp);
1090             VOfflineForVolOp_r(&error, vp, "A volume utility is running.");
1091             if (error==0) {
1092                 opr_Assert(vp->nUsers==0);
1093                 vp->pending_vol_op->vol_op_state = FSSYNC_VolOpRunningOffline;
1094             }
1095             else {
1096                 VWaitExclusiveState_r(vp);
1097                 VDeregisterVolOp_r(vp);
1098                 code = SYNC_DENIED;
1099             }
1100             VCancelReservation_r(vp);
1101 #else
1102             VOffline_r(vp, "A volume utility is running.");
1103 #endif
1104             vp = NULL;
1105         }
1106     }
1107     goto done;
1108
1109  deny:
1110     code = SYNC_DENIED;
1111
1112  done:
1113 #ifdef AFS_DEMAND_ATTACH_FS
1114     if (rvp) {
1115         VCancelReservation_r(rvp);
1116     }
1117 #endif
1118     return code;
1119 }
1120
1121 /**
1122  * service an FSYNC request to mark a volume as moved.
1123  *
1124  * @param[in]   vcom  pointer command object
1125  * @param[out]  res   object in which to store response packet
1126  *
1127  * @return operation status
1128  *   @retval SYNC_OK volume marked as moved to a remote server
1129  *   @retval SYNC_FAILED invalid command protocol message
1130  *   @retval SYNC_DENIED current volume state does not permit this operation
1131  *
1132  * @note this is an FSYNC RPC server stub
1133  *
1134  * @note this operation also breaks all callbacks for the given volume
1135  *
1136  * @note this procedure handles the following FSSYNC command codes:
1137  *       - FSYNC_VOL_MOVE
1138  *
1139  * @note the supplementary reason code contains additional details.  For
1140  *       instance, SYNC_OK is still returned when the partition specified
1141  *       does not match the one registered in the volume object -- reason
1142  *       will be FSYNC_WRONG_PART in this case.
1143  *
1144  * @internal
1145  */
1146 static afs_int32
1147 FSYNC_com_VolMove(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1148 {
1149     afs_int32 code = SYNC_DENIED;
1150     Error error;
1151     Volume * vp;
1152
1153     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
1154         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1155         code = SYNC_FAILED;
1156         goto done;
1157     }
1158
1159     /* Yuch:  the "reason" for the move is the site it got moved to... */
1160     /* still set specialStatus so we stop sending back VBUSY.
1161      * also should still break callbacks.  Note that I don't know
1162      * how to tell if we should break all or not, so we just do it
1163      * since it doesn't matter much if we do an extra break
1164      * volume callbacks on a volume move within the same server */
1165 #ifdef AFS_DEMAND_ATTACH_FS
1166     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
1167 #else
1168     vp = VGetVolume_r(&error, vcom->vop->volume);
1169 #endif
1170     if (vp) {
1171         if (FSYNC_partMatch(vcom, vp, 1)) {
1172 #ifdef AFS_DEMAND_ATTACH_FS
1173             if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
1174                 (V_attachState(vp) == VOL_STATE_PREATTACHED)) {
1175 #endif
1176                 code = SYNC_OK;
1177                 vp->specialStatus = VMOVED;
1178 #ifdef AFS_DEMAND_ATTACH_FS
1179             } else {
1180                 res->hdr.reason = FSYNC_BAD_STATE;
1181             }
1182 #endif
1183         } else {
1184             res->hdr.reason = FSYNC_WRONG_PART;
1185         }
1186 #ifndef AFS_DEMAND_ATTACH_FS
1187         VPutVolume_r(vp);
1188 #endif /* !AFS_DEMAND_ATTACH_FS */
1189     } else {
1190         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1191     }
1192
1193     if ((code == SYNC_OK) && (V_BreakVolumeCallbacks != NULL)) {
1194         Log("fssync: volume %" AFS_VOLID_FMT " moved to %x; breaking all call backs\n",
1195             afs_printable_VolumeId_lu(vcom->vop->volume), vcom->hdr->reason);
1196         VOL_UNLOCK;
1197         (*V_BreakVolumeCallbacks) (vcom->vop->volume);
1198         VOL_LOCK;
1199     }
1200
1201
1202  done:
1203     return code;
1204 }
1205
1206 /**
1207  * service an FSYNC request to mark a volume as destroyed.
1208  *
1209  * @param[in]   vcom  pointer command object
1210  * @param[out]  res   object in which to store response packet
1211  *
1212  * @return operation status
1213  *   @retval SYNC_OK volume marked as destroyed
1214  *   @retval SYNC_FAILED invalid command protocol message
1215  *   @retval SYNC_DENIED current volume state does not permit this operation
1216  *
1217  * @note this is an FSYNC RPC server stub
1218  *
1219  * @note this procedure handles the following FSSYNC command codes:
1220  *       - FSYNC_VOL_DONE
1221  *
1222  * @note the supplementary reason code contains additional details.  For
1223  *       instance, SYNC_OK is still returned when the partition specified
1224  *       does not match the one registered in the volume object -- reason
1225  *       will be FSYNC_WRONG_PART in this case.
1226  *
1227  * @internal
1228  */
1229 static afs_int32
1230 FSYNC_com_VolDone(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1231 {
1232     afs_int32 code = SYNC_FAILED;
1233     Error error;
1234     Volume * vp;
1235
1236     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
1237         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1238         goto done;
1239     }
1240
1241     /* don't try to put online, this call is made only after deleting
1242      * a volume, in which case we want to remove the vol # from the
1243      * OfflineVolumes array only */
1244     if (vcom->v)
1245         vcom->v->volumeID = 0;
1246
1247     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
1248     if (vp) {
1249         if (FSYNC_partMatch(vcom, vp, 1)) {
1250 #ifdef AFS_DEMAND_ATTACH_FS
1251             VCreateReservation_r(vp);
1252             VWaitExclusiveState_r(vp);
1253
1254             if ((V_attachState(vp) == VOL_STATE_UNATTACHED) ||
1255                 (V_attachState(vp) == VOL_STATE_PREATTACHED) ||
1256                 VIsErrorState(V_attachState(vp))) {
1257
1258                 /* Change state to DELETED, not UNATTACHED, so clients get
1259                  * a VNOVOL error when they try to access from now on. */
1260
1261                 VChangeState_r(vp, VOL_STATE_DELETED);
1262                 VDeregisterVolOp_r(vp);
1263
1264                 /* Volume is gone; clear out old salvage stats */
1265                 memset(&vp->salvage, 0, sizeof(vp->salvage));
1266
1267                 /* Someday we should free the vp, too, after about 2 hours,
1268                  * possibly by putting the vp back on the VLRU. */
1269
1270                 code = SYNC_OK;
1271             } else if (V_attachState(vp) == VOL_STATE_DELETED) {
1272                 VDeregisterVolOp_r(vp);
1273                 res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1274
1275             } else {
1276                 code = SYNC_DENIED;
1277                 res->hdr.reason = FSYNC_BAD_STATE;
1278             }
1279
1280             VCancelReservation_r(vp);
1281             vp = NULL;
1282 #else /* AFS_DEMAND_ATTACH_FS */
1283             if (!vp->specialStatus) {
1284                 vp->specialStatus = VNOVOL;
1285             }
1286             code = SYNC_OK;
1287 #endif /* !AFS_DEMAND_ATTACH_FS */
1288         } else {
1289             code = SYNC_OK; /* XXX is this really a good idea? */
1290             res->hdr.reason = FSYNC_WRONG_PART;
1291         }
1292     } else {
1293         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1294     }
1295
1296  done:
1297     return code;
1298 }
1299
1300 #ifdef AFS_DEMAND_ATTACH_FS
1301 /**
1302  * service an FSYNC request to transition a volume to the hard error state.
1303  *
1304  * @param[in]   vcom  pointer command object
1305  * @param[out]  res   object in which to store response packet
1306  *
1307  * @return operation status
1308  *   @retval SYNC_OK volume transitioned to hard error state
1309  *   @retval SYNC_FAILED invalid command protocol message
1310  *   @retval SYNC_DENIED (see note)
1311  *
1312  * @note this is an FSYNC RPC server stub
1313  *
1314  * @note this procedure handles the following FSSYNC command codes:
1315  *       - FSYNC_VOL_FORCE_ERROR
1316  *
1317  * @note SYNC_DENIED is returned in the following cases:
1318  *        - no partition name is specified (reason field set to
1319  *          FSYNC_WRONG_PART).
1320  *        - volume id not known to fileserver (reason field set
1321  *          to FSYNC_UNKNOWN_VOLID).
1322  *
1323  * @note demand attach fileserver only
1324  *
1325  * @internal
1326  */
1327 static afs_int32
1328 FSYNC_com_VolError(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1329 {
1330     Error error;
1331     Volume * vp;
1332     afs_int32 code = SYNC_FAILED;
1333
1334     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
1335         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1336         goto done;
1337     }
1338
1339     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
1340
1341     if (!vp && vcom->hdr->reason == FSYNC_SALVAGE) {
1342         /* The requested volume doesn't seem to exist. However, it is possible
1343          * that this is triggered by trying to create or clone a volume that
1344          * was prevented from succeeding by a half-created volume in the way.
1345          * (e.g. we tried to create volume X, but volume X exists except that
1346          * its .vol header was deleted for some reason) So, still try to
1347          * a salvage for that volume ID. */
1348
1349         Log("FSYNC_com_VolError: attempting to schedule salvage for unknown "
1350             "volume %lu part %s\n", afs_printable_uint32_lu(vcom->vop->volume),
1351             vcom->vop->partName);
1352         vp = VPreAttachVolumeById_r(&error, vcom->vop->partName,
1353                                     vcom->vop->volume);
1354     }
1355
1356     if (vp) {
1357         if (FSYNC_partMatch(vcom, vp, 0)) {
1358             VCreateReservation_r(vp);
1359             VWaitExclusiveState_r(vp);
1360             VDeregisterVolOp_r(vp);
1361
1362             if (vcom->hdr->reason == FSYNC_SALVAGE) {
1363                 FSYNC_backgroundSalvage(vp);
1364             } else {
1365                 /* null out salvsync control state, as it's no longer relevant */
1366                 memset(&vp->salvage, 0, sizeof(vp->salvage));
1367                 VChangeState_r(vp, VOL_STATE_ERROR);
1368             }
1369
1370             VCancelReservation_r(vp);
1371             vp = NULL;
1372
1373             code = SYNC_OK;
1374         } else {
1375             res->hdr.reason = FSYNC_WRONG_PART;
1376         }
1377     } else {
1378         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1379     }
1380
1381  done:
1382     return code;
1383 }
1384 #endif /* AFS_DEMAND_ATTACH_FS */
1385
1386 /**
1387  * service an FSYNC request to break all callbacks for this volume.
1388  *
1389  * @param[in]   vcom  pointer command object
1390  * @param[out]  res   object in which to store response packet
1391  *
1392  * @return operation status
1393  *   @retval SYNC_OK callback breaks scheduled for volume
1394  *
1395  * @note this is an FSYNC RPC server stub
1396  *
1397  * @note this procedure handles the following FSSYNC command codes:
1398  *       - FSYNC_VOL_BREAKCBKS
1399  *
1400  * @note demand attach fileserver only
1401  *
1402  * @todo should do partition matching
1403  *
1404  * @internal
1405  */
1406 static afs_int32
1407 FSYNC_com_VolBreakCBKs(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1408 {
1409     /* if the volume is being restored, break all callbacks on it */
1410     if (V_BreakVolumeCallbacks) {
1411         Log("fssync: breaking all call backs for volume %" AFS_VOLID_FMT "\n",
1412             afs_printable_VolumeId_lu(vcom->vop->volume));
1413         VOL_UNLOCK;
1414         (*V_BreakVolumeCallbacks) (vcom->vop->volume);
1415         VOL_LOCK;
1416     }
1417     return SYNC_OK;
1418 }
1419
1420 /**
1421  * service an FSYNC request to return the Volume object.
1422  *
1423  * @param[in]   vcom  pointer command object
1424  * @param[out]  res   object in which to store response packet
1425  *
1426  * @return operation status
1427  *   @retval SYNC_OK      volume object returned to caller
1428  *   @retval SYNC_FAILED  bad command packet, or failed to locate volume object
1429  *
1430  * @note this is an FSYNC RPC server stub
1431  *
1432  * @note this procedure handles the following FSSYNC command codes:
1433  *       - FSYNC_VOL_QUERY
1434  *
1435  * @internal
1436  */
1437 static afs_int32
1438 FSYNC_com_VolQuery(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1439 {
1440     afs_int32 code = SYNC_FAILED;
1441     Error error;
1442     Volume * vp;
1443
1444     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
1445         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1446         goto done;
1447     }
1448
1449 #ifdef AFS_DEMAND_ATTACH_FS
1450     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
1451 #else /* !AFS_DEMAND_ATTACH_FS */
1452     vp = VGetVolume_r(&error, vcom->vop->volume);
1453 #endif /* !AFS_DEMAND_ATTACH_FS */
1454
1455     if (vp) {
1456         if (FSYNC_partMatch(vcom, vp, 1)) {
1457             if (res->payload.len >= sizeof(Volume)) {
1458                 memcpy(res->payload.buf, vp, sizeof(Volume));
1459                 res->hdr.response_len += sizeof(Volume);
1460                 code = SYNC_OK;
1461             } else {
1462                 res->hdr.reason = SYNC_REASON_PAYLOAD_TOO_BIG;
1463             }
1464         } else {
1465             res->hdr.reason = FSYNC_WRONG_PART;
1466         }
1467 #ifndef AFS_DEMAND_ATTACH_FS
1468         VPutVolume_r(vp);
1469 #endif
1470     } else {
1471         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1472     }
1473
1474  done:
1475     return code;
1476 }
1477
1478 /**
1479  * service an FSYNC request to return the Volume header.
1480  *
1481  * @param[in]   vcom  pointer command object
1482  * @param[out]  res   object in which to store response packet
1483  *
1484  * @return operation status
1485  *   @retval SYNC_OK volume header returned to caller
1486  *   @retval SYNC_FAILED  bad command packet, or failed to locate volume header
1487  *
1488  * @note this is an FSYNC RPC server stub
1489  *
1490  * @note this procedure handles the following FSSYNC command codes:
1491  *       - FSYNC_VOL_QUERY_HDR
1492  *
1493  * @internal
1494  */
1495 static afs_int32
1496 FSYNC_com_VolHdrQuery(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1497 {
1498     afs_int32 code = SYNC_FAILED;
1499     Error error;
1500     Volume * vp;
1501
1502     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
1503         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1504         goto done;
1505     }
1506     if (res->payload.len < sizeof(VolumeDiskData)) {
1507         res->hdr.reason = SYNC_REASON_PAYLOAD_TOO_BIG;
1508         goto done;
1509     }
1510
1511 #ifdef AFS_DEMAND_ATTACH_FS
1512     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
1513 #else /* !AFS_DEMAND_ATTACH_FS */
1514     vp = VGetVolume_r(&error, vcom->vop->volume);
1515 #endif
1516
1517     if (vp) {
1518         if (FSYNC_partMatch(vcom, vp, 1)) {
1519 #ifdef AFS_DEMAND_ATTACH_FS
1520             if ((vp->header == NULL) ||
1521                 !(V_attachFlags(vp) & VOL_HDR_ATTACHED) ||
1522                 !(V_attachFlags(vp) & VOL_HDR_LOADED)) {
1523                 res->hdr.reason = FSYNC_HDR_NOT_ATTACHED;
1524                 goto cleanup;
1525             }
1526 #else /* !AFS_DEMAND_ATTACH_FS */
1527             if (!vp || !vp->header) {
1528                 res->hdr.reason = FSYNC_HDR_NOT_ATTACHED;
1529                 goto cleanup;
1530             }
1531 #endif /* !AFS_DEMAND_ATTACH_FS */
1532         } else {
1533             res->hdr.reason = FSYNC_WRONG_PART;
1534             goto cleanup;
1535         }
1536     } else {
1537         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1538         goto done;
1539     }
1540
1541     memcpy(res->payload.buf, &V_disk(vp), sizeof(VolumeDiskData));
1542     res->hdr.response_len += sizeof(VolumeDiskData);
1543     code = SYNC_OK;
1544
1545  cleanup:
1546 #ifndef AFS_DEMAND_ATTACH_FS
1547     VPutVolume_r(vp);
1548 #endif
1549
1550  done:
1551     return code;
1552 }
1553
1554 #ifdef AFS_DEMAND_ATTACH_FS
1555 static afs_int32
1556 FSYNC_com_VolOpQuery(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1557 {
1558     afs_int32 code = SYNC_OK;
1559     Error error;
1560     Volume * vp;
1561
1562     vp = VLookupVolume_r(&error, vcom->vop->volume, NULL);
1563
1564     if (vp) {
1565         VCreateReservation_r(vp);
1566         VWaitExclusiveState_r(vp);
1567     }
1568
1569     if (vp && vp->pending_vol_op) {
1570         if (!FSYNC_partMatch(vcom, vp, 1)) {
1571             res->hdr.reason = FSYNC_WRONG_PART;
1572             code = SYNC_FAILED;
1573         } else {
1574             opr_Assert(sizeof(FSSYNC_VolOp_info) <= res->payload.len);
1575             memcpy(res->payload.buf, vp->pending_vol_op, sizeof(FSSYNC_VolOp_info));
1576             res->hdr.response_len += sizeof(FSSYNC_VolOp_info);
1577         }
1578     } else {
1579         if (!vp || V_attachState(vp) == VOL_STATE_DELETED) {
1580             res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1581         } else if (!FSYNC_partMatch(vcom, vp, 1)) {
1582             res->hdr.reason = FSYNC_WRONG_PART;
1583         } else {
1584             res->hdr.reason = FSYNC_NO_PENDING_VOL_OP;
1585         }
1586         code = SYNC_FAILED;
1587     }
1588
1589     if (vp) {
1590         VCancelReservation_r(vp);
1591     }
1592     return code;
1593 }
1594
1595 static afs_int32
1596 FSYNC_com_VGQuery(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1597 {
1598     afs_int32 code = SYNC_FAILED;
1599     int rc;
1600     struct DiskPartition64 * dp;
1601
1602     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
1603         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1604         goto done;
1605     }
1606
1607     dp = VGetPartition_r(vcom->vop->partName, 0);
1608     if (dp == NULL) {
1609         res->hdr.reason = FSYNC_BAD_PART;
1610         goto done;
1611     }
1612
1613     opr_Assert(sizeof(FSSYNC_VGQry_response_t) <= res->payload.len);
1614
1615     rc = VVGCache_query_r(dp, vcom->vop->volume, res->payload.buf);
1616     switch (rc) {
1617     case 0:
1618         res->hdr.response_len += sizeof(FSSYNC_VGQry_response_t);
1619         code = SYNC_OK;
1620         break;
1621     case EAGAIN:
1622         res->hdr.reason = FSYNC_PART_SCANNING;
1623         break;
1624     case ENOENT:
1625         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1626         break;
1627     default:
1628         break;
1629     }
1630
1631  done:
1632     return code;
1633 }
1634
1635 static afs_int32
1636 FSYNC_com_VGUpdate(osi_socket fd, SYNC_command * com, SYNC_response * res)
1637 {
1638     afs_int32 code = SYNC_FAILED;
1639     struct DiskPartition64 * dp;
1640     FSSYNC_VGUpdate_command_t * vgucom;
1641     int rc;
1642
1643     if (com->recv_len != (sizeof(com->hdr) + sizeof(*vgucom))) {
1644         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1645         res->hdr.flags |= SYNC_FLAG_CHANNEL_SHUTDOWN;
1646         code = SYNC_COM_ERROR;
1647         goto done;
1648     }
1649
1650     vgucom = com->payload.buf;
1651
1652     ViceLog(125, ("FSYNC_com_VGUpdate: fd %d got command for parent %lu child "
1653                   "%lu partName %.16s\n", (int)fd,
1654                   afs_printable_uint32_lu(vgucom->parent),
1655                   afs_printable_uint32_lu(vgucom->child),
1656                   vgucom->partName));
1657
1658     if (SYNC_verifyProtocolString(vgucom->partName, sizeof(vgucom->partName))) {
1659         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1660         goto done;
1661     }
1662
1663     dp = VGetPartition_r(vgucom->partName, 0);
1664     if (dp == NULL) {
1665         res->hdr.reason = FSYNC_BAD_PART;
1666         goto done;
1667     }
1668
1669     switch(com->hdr.command) {
1670     case FSYNC_VG_ADD:
1671         rc = VVGCache_entry_add_r(dp, vgucom->parent, vgucom->child, NULL);
1672         break;
1673
1674     case FSYNC_VG_DEL:
1675         rc = VVGCache_entry_del_r(dp, vgucom->parent, vgucom->child);
1676         break;
1677
1678     default:
1679         Log("FSYNC_com_VGUpdate called improperly\n");
1680         rc = -1;
1681         break;
1682     }
1683
1684     /* EINVAL means the partition VGC doesn't exist at all; not really
1685      * an error */
1686     if (rc == 0 || rc == EINVAL) {
1687         code = SYNC_OK;
1688     }
1689
1690     if (rc == ENOENT) {
1691         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1692     } else {
1693         res->hdr.reason = FSYNC_WHATEVER;
1694     }
1695
1696  done:
1697     return code;
1698 }
1699
1700 static afs_int32
1701 FSYNC_com_VGScan(FSSYNC_VolOp_command * vcom, SYNC_response * res)
1702 {
1703     afs_int32 code = SYNC_FAILED;
1704     struct DiskPartition64 * dp;
1705
1706     if (SYNC_verifyProtocolString(vcom->vop->partName, sizeof(vcom->vop->partName))) {
1707         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1708         goto done;
1709     }
1710
1711     dp = VGetPartition_r(vcom->vop->partName, 0);
1712     if (dp == NULL) {
1713         res->hdr.reason = FSYNC_BAD_PART;
1714         goto done;
1715     }
1716
1717     if (VVGCache_scanStart_r(dp) == 0) {
1718         code = SYNC_OK;
1719     }
1720
1721  done:
1722     return code;
1723 }
1724
1725 static afs_int32
1726 FSYNC_com_VGScanAll(FSSYNC_VolOp_command * com, SYNC_response * res)
1727 {
1728     afs_int32 code = SYNC_FAILED;
1729
1730     if (VVGCache_scanStart_r(NULL) == 0) {
1731         code = SYNC_OK;
1732     }
1733
1734     return code;
1735 }
1736 #endif /* AFS_DEMAND_ATTACH_FS */
1737
1738 static afs_int32
1739 FSYNC_com_VnQry(osi_socket fd, SYNC_command * com, SYNC_response * res)
1740 {
1741     afs_int32 code = SYNC_OK;
1742     FSSYNC_VnQry_hdr * qry = com->payload.buf;
1743     Volume * vp;
1744     Vnode * vnp;
1745     Error error;
1746
1747     if (com->recv_len != (sizeof(com->hdr) + sizeof(FSSYNC_VnQry_hdr))) {
1748         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1749         res->hdr.flags |= SYNC_FLAG_CHANNEL_SHUTDOWN;
1750         return SYNC_COM_ERROR;
1751     }
1752
1753     ViceLog(125, ("FSYNC_com_VnQry: fd %d got command for vol %lu vnode %lu "
1754                   "uniq %lu spare %lu partName %.16s\n", (int)fd,
1755                   afs_printable_uint32_lu(qry->volume),
1756                   afs_printable_uint32_lu(qry->vnode),
1757                   afs_printable_uint32_lu(qry->unique),
1758                   afs_printable_uint32_lu(qry->spare),
1759                   qry->partName));
1760
1761 #ifdef AFS_DEMAND_ATTACH_FS
1762     vp = VLookupVolume_r(&error, qry->volume, NULL);
1763 #else /* !AFS_DEMAND_ATTACH_FS */
1764     vp = VGetVolume_r(&error, qry->volume);
1765 #endif /* !AFS_DEMAND_ATTACH_FS */
1766
1767     if (!vp) {
1768         res->hdr.reason = FSYNC_UNKNOWN_VOLID;
1769         code = SYNC_FAILED;
1770         goto done;
1771     }
1772
1773     vnp = VLookupVnode(vp, qry->vnode);
1774     if (!vnp) {
1775         res->hdr.reason = FSYNC_UNKNOWN_VNID;
1776         code = SYNC_FAILED;
1777         goto cleanup;
1778     }
1779
1780     if (Vn_class(vnp)->residentSize > res->payload.len) {
1781         res->hdr.reason = SYNC_REASON_ENCODING_ERROR;
1782         code = SYNC_FAILED;
1783         goto cleanup;
1784     }
1785
1786     memcpy(res->payload.buf, vnp, Vn_class(vnp)->residentSize);
1787     res->hdr.response_len += Vn_class(vnp)->residentSize;
1788
1789  cleanup:
1790 #ifndef AFS_DEMAND_ATTACH_FS
1791     VPutVolume_r(vp);
1792 #endif
1793
1794  done:
1795     return code;
1796 }
1797
1798 static afs_int32
1799 FSYNC_com_StatsOp(osi_socket fd, SYNC_command * com, SYNC_response * res)
1800 {
1801     afs_int32 code = SYNC_OK;
1802     FSSYNC_StatsOp_command scom;
1803
1804     if (com->recv_len != (sizeof(com->hdr) + sizeof(FSSYNC_StatsOp_hdr))) {
1805         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1806         res->hdr.flags |= SYNC_FLAG_CHANNEL_SHUTDOWN;
1807         return SYNC_COM_ERROR;
1808     }
1809
1810     scom.hdr = &com->hdr;
1811     scom.sop = (FSSYNC_StatsOp_hdr *) com->payload.buf;
1812     scom.com = com;
1813
1814     ViceLog(125, ("FSYNC_com_StatsOp: fd %d got command for stats: "
1815                   "{vlru_generation = %lu, hash_bucket = %lu, partName = "
1816                   "%.16s}\n", (int)fd,
1817                   afs_printable_uint32_lu(scom.sop->args.vlru_generation),
1818                   afs_printable_uint32_lu(scom.sop->args.hash_bucket),
1819                   scom.sop->args.partName));
1820
1821     switch (com->hdr.command) {
1822     case FSYNC_VOL_STATS_GENERAL:
1823         code = FSYNC_com_StatsOpGeneral(&scom, res);
1824         break;
1825 #ifdef AFS_DEMAND_ATTACH_FS
1826         /* statistics for the following subsystems are only tracked
1827          * for demand attach fileservers */
1828     case FSYNC_VOL_STATS_VICEP:
1829         code = FSYNC_com_StatsOpViceP(&scom, res);
1830         break;
1831     case FSYNC_VOL_STATS_HASH:
1832         code = FSYNC_com_StatsOpHash(&scom, res);
1833         break;
1834     case FSYNC_VOL_STATS_HDR:
1835         code = FSYNC_com_StatsOpHdr(&scom, res);
1836         break;
1837     case FSYNC_VOL_STATS_VLRU:
1838         code = FSYNC_com_StatsOpVLRU(&scom, res);
1839         break;
1840 #endif /* AFS_DEMAND_ATTACH_FS */
1841     default:
1842         code = SYNC_BAD_COMMAND;
1843     }
1844
1845     return code;
1846 }
1847
1848 static afs_int32
1849 FSYNC_com_StatsOpGeneral(FSSYNC_StatsOp_command * scom, SYNC_response * res)
1850 {
1851     afs_int32 code = SYNC_OK;
1852
1853     memcpy(res->payload.buf, &VStats, sizeof(VStats));
1854     res->hdr.response_len += sizeof(VStats);
1855
1856     return code;
1857 }
1858
1859 #ifdef AFS_DEMAND_ATTACH_FS
1860 static afs_int32
1861 FSYNC_com_StatsOpViceP(FSSYNC_StatsOp_command * scom, SYNC_response * res)
1862 {
1863     afs_int32 code = SYNC_OK;
1864     struct DiskPartition64 * dp;
1865     struct DiskPartitionStats64 * stats;
1866
1867     if (SYNC_verifyProtocolString(scom->sop->args.partName, sizeof(scom->sop->args.partName))) {
1868         res->hdr.reason = SYNC_REASON_MALFORMED_PACKET;
1869         code = SYNC_FAILED;
1870         goto done;
1871     }
1872
1873     dp = VGetPartition_r(scom->sop->args.partName, 0);
1874     if (!dp) {
1875         code = SYNC_FAILED;
1876     } else {
1877         stats = (struct DiskPartitionStats64 *) res->payload.buf;
1878         stats->free = dp->free;
1879         stats->totalUsable = dp->totalUsable;
1880         stats->minFree = dp->minFree;
1881         stats->f_files = dp->f_files;
1882         stats->vol_list_len = dp->vol_list.len;
1883
1884         res->hdr.response_len += sizeof(struct DiskPartitionStats64);
1885     }
1886
1887  done:
1888     return code;
1889 }
1890
1891 static afs_int32
1892 FSYNC_com_StatsOpHash(FSSYNC_StatsOp_command * scom, SYNC_response * res)
1893 {
1894     afs_int32 code = SYNC_OK;
1895     struct VolumeHashChainStats * stats;
1896     struct VolumeHashChainHead * head;
1897
1898     if (scom->sop->args.hash_bucket >= VolumeHashTable.Size) {
1899         return SYNC_FAILED;
1900     }
1901
1902     head = &VolumeHashTable.Table[scom->sop->args.hash_bucket];
1903     stats = (struct VolumeHashChainStats *) res->payload.buf;
1904     stats->table_size = VolumeHashTable.Size;
1905     stats->chain_len = head->len;
1906     stats->chain_cacheCheck = head->cacheCheck;
1907     stats->chain_busy = head->busy;
1908     AssignInt64(head->looks, &stats->chain_looks);
1909     AssignInt64(head->gets, &stats->chain_gets);
1910     AssignInt64(head->reorders, &stats->chain_reorders);
1911
1912     res->hdr.response_len += sizeof(struct VolumeHashChainStats);
1913
1914     return code;
1915 }
1916
1917 static afs_int32
1918 FSYNC_com_StatsOpHdr(FSSYNC_StatsOp_command * scom, SYNC_response * res)
1919 {
1920     afs_int32 code = SYNC_OK;
1921
1922     memcpy(res->payload.buf, &volume_hdr_LRU.stats, sizeof(volume_hdr_LRU.stats));
1923     res->hdr.response_len += sizeof(volume_hdr_LRU.stats);
1924
1925     return code;
1926 }
1927
1928 static afs_int32
1929 FSYNC_com_StatsOpVLRU(FSSYNC_StatsOp_command * scom, SYNC_response * res)
1930 {
1931     afs_int32 code = SYNC_OK;
1932
1933     code = SYNC_BAD_COMMAND;
1934
1935     return code;
1936 }
1937 #endif /* AFS_DEMAND_ATTACH_FS */
1938
1939 /**
1940  * populate an FSSYNC_VolOp_info object from a command packet object.
1941  *
1942  * @param[in]   vcom  pointer to command packet
1943  * @param[out]  info  pointer to info object which will be populated
1944  *
1945  * @note FSSYNC_VolOp_info objects are attached to Volume objects when
1946  *       a volume operation is commenced.
1947  *
1948  * @internal
1949  */
1950 static void
1951 FSYNC_com_to_info(FSSYNC_VolOp_command * vcom, FSSYNC_VolOp_info * info)
1952 {
1953     memcpy(&info->com, vcom->hdr, sizeof(SYNC_command_hdr));
1954     memcpy(&info->vop, vcom->vop, sizeof(FSSYNC_VolOp_hdr));
1955     info->vol_op_state = FSSYNC_VolOpPending;
1956 }
1957
1958 /**
1959  * check whether command packet partition name matches volume
1960  * object's partition name.
1961  *
1962  * @param[in] vcom        pointer to command packet
1963  * @param[in] vp          pointer to volume object
1964  * @param[in] match_anon  anon matching control flag (see note below)
1965  *
1966  * @return whether partitions match
1967  *   @retval 0  partitions do NOT match
1968  *   @retval 1  partitions match
1969  *
1970  * @note if match_anon is non-zero, then this function will return a
1971  *       positive match for a zero-length partition string in the
1972  *       command packet.
1973  *
1974  * @internal
1975  */
1976 static int
1977 FSYNC_partMatch(FSSYNC_VolOp_command * vcom, Volume * vp, int match_anon)
1978 {
1979     return ((match_anon && vcom->vop->partName[0] == 0) ||
1980             (strncmp(vcom->vop->partName, V_partition(vp)->name,
1981                      sizeof(vcom->vop->partName)) == 0));
1982 }
1983
1984
1985 static void
1986 FSYNC_Drop(osi_socket fd)
1987 {
1988     struct offlineInfo *p;
1989     int i;
1990     Error error;
1991 #ifndef AFS_DEMAND_ATTACH_FS
1992     char tvolName[VMAXPATHLEN];
1993 #endif
1994
1995     VOL_LOCK;
1996     p = OfflineVolumes[FindHandler(fd)];
1997     for (i = 0; i < MAXOFFLINEVOLUMES; i++) {
1998         if (p[i].volumeID) {
1999             Volume *vp;
2000
2001 #ifdef AFS_DEMAND_ATTACH_FS
2002             vp = VPreAttachVolumeById_r(&error, p[i].partName, p[i].volumeID);
2003             if (vp) {
2004                 VCreateReservation_r(vp);
2005                 VWaitExclusiveState_r(vp);
2006                 VDeregisterVolOp_r(vp);
2007                 VCancelReservation_r(vp);
2008             }
2009 #else
2010             tvolName[0] = OS_DIRSEPC;
2011             sprintf(&tvolName[1], VFORMAT, afs_printable_VolumeId_lu(p[i].volumeID));
2012             vp = VAttachVolumeByName_r(&error, p[i].partName, tvolName,
2013                                        V_VOLUPD);
2014             if (vp)
2015                 VPutVolume_r(vp);
2016 #endif /* !AFS_DEMAND_ATTACH_FS */
2017             p[i].volumeID = 0;
2018         }
2019     }
2020     VOL_UNLOCK;
2021     RemoveHandler(fd);
2022     rk_closesocket(fd);
2023     AcceptOn();
2024 }
2025
2026 static int AcceptHandler = -1;  /* handler id for accept, if turned on */
2027
2028 static void
2029 AcceptOn(void)
2030 {
2031     if (AcceptHandler == -1) {
2032         opr_Verify(AddHandler(fssync_server_state.fd, FSYNC_newconnection));
2033         AcceptHandler = FindHandler(fssync_server_state.fd);
2034     }
2035 }
2036
2037 static void
2038 AcceptOff(void)
2039 {
2040     if (AcceptHandler != -1) {
2041         opr_Verify(RemoveHandler(fssync_server_state.fd));
2042         AcceptHandler = -1;
2043     }
2044 }
2045
2046 /* The multiple FD handling code. */
2047
2048 static osi_socket HandlerFD[MAXHANDLERS];
2049 static void (*HandlerProc[MAXHANDLERS]) (osi_socket);
2050
2051 static void
2052 InitHandler(void)
2053 {
2054     int i;
2055     ObtainWriteLock(&FSYNC_handler_lock);
2056     for (i = 0; i < MAXHANDLERS; i++) {
2057         HandlerFD[i] = OSI_NULLSOCKET;
2058         HandlerProc[i] = 0;
2059     }
2060     ReleaseWriteLock(&FSYNC_handler_lock);
2061 }
2062
2063 #if defined(HAVE_POLL) && defined(AFS_PTHREAD_ENV)
2064 static void
2065 CallHandler(struct pollfd *fds, int nfds, int mask)
2066 {
2067     int i;
2068     int handler;
2069     ObtainReadLock(&FSYNC_handler_lock);
2070     for (i = 0; i < nfds; i++) {
2071         if (fds[i].revents & mask) {
2072             handler = FindHandler_r(fds[i].fd);
2073             ReleaseReadLock(&FSYNC_handler_lock);
2074             (*HandlerProc[handler]) (fds[i].fd);
2075             ObtainReadLock(&FSYNC_handler_lock);
2076         }
2077     }
2078     ReleaseReadLock(&FSYNC_handler_lock);
2079 }
2080 #else
2081 static void
2082 CallHandler(fd_set * fdsetp)
2083 {
2084     int i;
2085     ObtainReadLock(&FSYNC_handler_lock);
2086     for (i = 0; i < MAXHANDLERS; i++) {
2087         if (HandlerFD[i] >= 0 && FD_ISSET(HandlerFD[i], fdsetp)) {
2088             ReleaseReadLock(&FSYNC_handler_lock);
2089             (*HandlerProc[i]) (HandlerFD[i]);
2090             ObtainReadLock(&FSYNC_handler_lock);
2091         }
2092     }
2093     ReleaseReadLock(&FSYNC_handler_lock);
2094 }
2095 #endif
2096
2097 static int
2098 AddHandler(osi_socket afd, void (*aproc) (osi_socket))
2099 {
2100     int i;
2101     ObtainWriteLock(&FSYNC_handler_lock);
2102     for (i = 0; i < MAXHANDLERS; i++)
2103         if (HandlerFD[i] == OSI_NULLSOCKET)
2104             break;
2105     if (i >= MAXHANDLERS) {
2106         ReleaseWriteLock(&FSYNC_handler_lock);
2107         return 0;
2108     }
2109     HandlerFD[i] = afd;
2110     HandlerProc[i] = aproc;
2111     ReleaseWriteLock(&FSYNC_handler_lock);
2112     return 1;
2113 }
2114
2115 static int
2116 FindHandler(osi_socket afd)
2117 {
2118     int i;
2119     ObtainReadLock(&FSYNC_handler_lock);
2120     for (i = 0; i < MAXHANDLERS; i++)
2121         if (HandlerFD[i] == afd) {
2122             ReleaseReadLock(&FSYNC_handler_lock);
2123             return i;
2124         }
2125     ReleaseReadLock(&FSYNC_handler_lock);       /* just in case */
2126     opr_abort();
2127     AFS_UNREACHED(return(-1));                  /* satisfy compiler */
2128 }
2129
2130 static int
2131 FindHandler_r(osi_socket afd)
2132 {
2133     int i;
2134     for (i = 0; i < MAXHANDLERS; i++)
2135         if (HandlerFD[i] == afd) {
2136             return i;
2137         }
2138     opr_abort();
2139     AFS_UNREACHED(return(-1));                  /* satisfy compiler */
2140 }
2141
2142 static int
2143 RemoveHandler(osi_socket afd)
2144 {
2145     ObtainWriteLock(&FSYNC_handler_lock);
2146     HandlerFD[FindHandler_r(afd)] = OSI_NULLSOCKET;
2147     ReleaseWriteLock(&FSYNC_handler_lock);
2148     return 1;
2149 }
2150
2151 #if defined(HAVE_POLL) && defined(AFS_PTHREAD_ENV)
2152 static void
2153 GetHandler(struct pollfd *fds, int maxfds, int events, int *nfds)
2154 {
2155     int i;
2156     int fdi = 0;
2157     ObtainReadLock(&FSYNC_handler_lock);
2158     for (i = 0; i < MAXHANDLERS; i++)
2159         if (HandlerFD[i] != OSI_NULLSOCKET) {
2160             opr_Assert(fdi<maxfds);
2161             fds[fdi].fd = HandlerFD[i];
2162             fds[fdi].events = events;
2163             fds[fdi].revents = 0;
2164             fdi++;
2165         }
2166     *nfds = fdi;
2167     ReleaseReadLock(&FSYNC_handler_lock);
2168 }
2169 #else
2170 static void
2171 GetHandler(fd_set * fdsetp, int *maxfdp)
2172 {
2173     int i;
2174     int maxfd = -1;
2175     FD_ZERO(fdsetp);
2176     ObtainReadLock(&FSYNC_handler_lock);        /* just in case */
2177     for (i = 0; i < MAXHANDLERS; i++)
2178         if (HandlerFD[i] != OSI_NULLSOCKET) {
2179             FD_SET(HandlerFD[i], fdsetp);
2180 #ifndef AFS_NT40_ENV
2181             /* On Windows the nfds parameter to select() is ignored */
2182             if (maxfd < HandlerFD[i] || maxfd == (int)-1)
2183                 maxfd = HandlerFD[i];
2184 #endif /* AFS_NT40_ENV */
2185         }
2186     *maxfdp = maxfd;
2187     ReleaseReadLock(&FSYNC_handler_lock);       /* just in case */
2188 }
2189 #endif /* HAVE_POLL && AFS_PTHREAD_ENV */
2190
2191 #endif /* FSSYNC_BUILD_SERVER */