9b60700c49e43734f76ab42a535b5b8f9fd44caa
[openafs.git] / src / afs / afs_pioctl.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
10 #include <afsconfig.h>
11 #include "afs/param.h"
12
13
14 #include "afs/sysincludes.h"    /* Standard vendor system headers */
15 #ifdef AFS_OBSD_ENV
16 #include "h/syscallargs.h"
17 #endif
18 #ifdef AFS_FBSD50_ENV
19 #include "h/sysproto.h"
20 #endif
21 #include "afsincludes.h"        /* Afs-based standard headers */
22 #include "afs/afs_stats.h"      /* afs statistics */
23 #include "afs/vice.h"
24 #include "afs/afs_bypasscache.h"
25 #include "rx/rx_globals.h"
26
27 struct VenusFid afs_rootFid;
28 afs_int32 afs_waitForever = 0;
29 short afs_waitForeverCount = 0;
30 afs_int32 afs_showflags = GAGUSER | GAGCONSOLE; /* show all messages */
31
32 #ifdef AFS_DISCON_ENV
33 afs_int32 afs_is_disconnected;
34 afs_int32 afs_is_discon_rw;
35 /* On reconnection, turn this knob on until it finishes,
36  * then turn it off.
37  */
38 afs_int32 afs_in_sync = 0;
39 #endif
40
41 struct afs_pdata {
42     char *ptr;
43     size_t remaining;
44 };
45
46 /*
47  * A set of handy little functions for encoding and decoding
48  * pioctls without losing your marbles, or memory integrity
49  */
50
51 static_inline int
52 afs_pd_alloc(struct afs_pdata *apd, size_t size) {
53
54     if (size > AFS_LRALLOCSIZ)
55         apd->ptr = osi_Alloc(size + 1);
56     else
57         apd->ptr = osi_AllocLargeSpace(AFS_LRALLOCSIZ);
58
59     if (apd->ptr == NULL)
60         return ENOMEM;
61
62     apd->remaining = size;
63
64     return 0;
65 }
66
67 static_inline void
68 afs_pd_free(struct afs_pdata *apd) {
69     if (apd->ptr == NULL)
70         return;
71
72     if (apd->remaining > AFS_LRALLOCSIZ)
73         osi_Free(apd->ptr, apd->remaining + 1);
74     else
75         osi_FreeLargeSpace(apd->ptr);
76
77     apd->ptr = NULL;
78     apd->remaining = 0;
79 }
80
81 static_inline char *
82 afs_pd_where(struct afs_pdata *apd) {
83     return apd ? apd->ptr : NULL;
84 }
85
86 static_inline size_t
87 afs_pd_remaining(struct afs_pdata *apd) {
88     return apd ? apd->remaining : 0;
89 }
90
91 static_inline int
92 afs_pd_skip(struct afs_pdata *apd, size_t skip) {
93     if (apd == NULL || apd->remaining < skip)
94         return EINVAL;
95     apd->remaining -= skip;
96     apd->ptr += skip;
97
98     return 0;
99 }
100
101 static_inline int
102 afs_pd_getInt(struct afs_pdata *apd, afs_int32 *val) {
103     if (apd == NULL || apd->remaining < sizeof(afs_int32))
104         return EINVAL;
105     apd->remaining -= sizeof(afs_int32);
106     *val = *(afs_int32 *)apd->ptr;
107     apd->ptr += sizeof(afs_int32);
108     return 0;
109 }
110
111 static_inline int
112 afs_pd_getUint(struct afs_pdata *apd, afs_uint32 *val) {
113     return afs_pd_getInt(apd, (afs_int32 *)val);
114 }
115
116 static_inline int
117 afs_pd_getBytes(struct afs_pdata *apd, void *dest, size_t bytes) {
118     if (apd == NULL || apd->remaining < bytes)
119         return EINVAL;
120     apd->remaining -= bytes;
121     memcpy(dest, apd->ptr, bytes);
122     apd->ptr += bytes;
123     return 0;
124 }
125
126 static_inline void *
127 afs_pd_inline(struct afs_pdata *apd, size_t bytes) {
128     void *ret;
129
130     if (apd == NULL || apd->remaining < bytes)
131         return NULL;
132
133     ret = apd->ptr;
134
135     apd->remaining -= bytes;
136     apd->ptr += bytes;
137
138     return ret;
139 }
140
141 static_inline int
142 afs_pd_getString(struct afs_pdata *apd, char *str, size_t maxLen) {
143     size_t len;
144
145     if (apd == NULL || apd->remaining <= 0)
146         return EINVAL;
147     len = strlen(apd->ptr) + 1;
148     if (len > maxLen)
149         return E2BIG;
150     memcpy(str, apd->ptr, len);
151     apd->ptr += len;
152     apd->remaining -= len;
153     return 0;
154 }
155
156 static_inline int
157 afs_pd_getStringPtr(struct afs_pdata *apd, char **str) {
158     size_t len;
159
160     if (apd == NULL || apd->remaining <= 0)
161         return EINVAL;
162     len = strlen(apd->ptr) + 1;
163     *str = apd->ptr;
164     apd->ptr += len;
165     apd->remaining -= len;
166     return 0;
167 }
168
169 static_inline int
170 afs_pd_putInt(struct afs_pdata *apd, afs_int32 val) {
171     if (apd == NULL || apd->remaining < sizeof(afs_int32))
172         return E2BIG;
173     *(afs_int32 *)apd->ptr = val;
174     apd->ptr += sizeof(afs_int32);
175     apd->remaining -= sizeof(afs_int32);
176
177     return 0;
178 }
179
180 static_inline int
181 afs_pd_putBytes(struct afs_pdata *apd, const void *bytes, size_t len) {
182     if (apd == NULL || apd->remaining < len)
183         return E2BIG;
184     memcpy(apd->ptr, bytes, len);
185     apd->ptr += len;
186     apd->remaining -= len;
187     return 0;
188 }
189
190 static_inline int
191 afs_pd_putString(struct afs_pdata *apd, char *str) {
192
193     /* Add 1 so we copy the NULL too */
194     return afs_pd_putBytes(apd, str, strlen(str) +1);
195 }
196
197 /*!
198  * \defgroup pioctl Path IOCTL functions
199  *
200  * DECL_PIOCTL is a macro defined to contain the following parameters for functions:
201  *
202  * \param[in] avc
203  *      the AFS vcache structure in use by pioctl
204  * \param[in] afun
205  *      not in use
206  * \param[in] areq
207  *      the AFS vrequest structure
208  * \param[in] ain
209  *      an afs_pdata block describing the data received from the caller
210  * \param[in] aout
211  *      an afs_pdata block describing a pre-allocated block for output
212  * \param[in] acred
213  *      UNIX credentials structure underlying the operation
214  */
215
216 #define DECL_PIOCTL(x) \
217         static int x(struct vcache *avc, int afun, struct vrequest *areq, \
218                      struct afs_pdata *ain, struct afs_pdata *aout, \
219                      afs_ucred_t **acred)
220
221 /* Prototypes for pioctl routines */
222 DECL_PIOCTL(PGetFID);
223 DECL_PIOCTL(PSetAcl);
224 DECL_PIOCTL(PStoreBehind);
225 DECL_PIOCTL(PGCPAGs);
226 DECL_PIOCTL(PGetAcl);
227 DECL_PIOCTL(PNoop);
228 DECL_PIOCTL(PBogus);
229 DECL_PIOCTL(PGetFileCell);
230 DECL_PIOCTL(PGetWSCell);
231 DECL_PIOCTL(PGetUserCell);
232 DECL_PIOCTL(PSetTokens);
233 DECL_PIOCTL(PGetVolumeStatus);
234 DECL_PIOCTL(PSetVolumeStatus);
235 DECL_PIOCTL(PFlush);
236 DECL_PIOCTL(PNewStatMount);
237 DECL_PIOCTL(PGetTokens);
238 DECL_PIOCTL(PUnlog);
239 DECL_PIOCTL(PMariner);
240 DECL_PIOCTL(PCheckServers);
241 DECL_PIOCTL(PCheckVolNames);
242 DECL_PIOCTL(PCheckAuth);
243 DECL_PIOCTL(PFindVolume);
244 DECL_PIOCTL(PViceAccess);
245 DECL_PIOCTL(PSetCacheSize);
246 DECL_PIOCTL(PGetCacheSize);
247 DECL_PIOCTL(PRemoveCallBack);
248 DECL_PIOCTL(PNewCell);
249 DECL_PIOCTL(PNewAlias);
250 DECL_PIOCTL(PListCells);
251 DECL_PIOCTL(PListAliases);
252 DECL_PIOCTL(PRemoveMount);
253 DECL_PIOCTL(PGetCellStatus);
254 DECL_PIOCTL(PSetCellStatus);
255 DECL_PIOCTL(PFlushVolumeData);
256 DECL_PIOCTL(PGetVnodeXStatus);
257 DECL_PIOCTL(PGetVnodeXStatus2);
258 DECL_PIOCTL(PSetSysName);
259 DECL_PIOCTL(PSetSPrefs);
260 DECL_PIOCTL(PSetSPrefs33);
261 DECL_PIOCTL(PGetSPrefs);
262 DECL_PIOCTL(PExportAfs);
263 DECL_PIOCTL(PGag);
264 DECL_PIOCTL(PTwiddleRx);
265 DECL_PIOCTL(PGetInitParams);
266 DECL_PIOCTL(PGetRxkcrypt);
267 DECL_PIOCTL(PSetRxkcrypt);
268 DECL_PIOCTL(PGetCPrefs);
269 DECL_PIOCTL(PSetCPrefs);
270 DECL_PIOCTL(PFlushMount);
271 DECL_PIOCTL(PRxStatProc);
272 DECL_PIOCTL(PRxStatPeer);
273 DECL_PIOCTL(PPrefetchFromTape);
274 DECL_PIOCTL(PFsCmd);
275 DECL_PIOCTL(PCallBackAddr);
276 DECL_PIOCTL(PDiscon);
277 DECL_PIOCTL(PNFSNukeCreds);
278 DECL_PIOCTL(PNewUuid);
279 DECL_PIOCTL(PPrecache); 
280 DECL_PIOCTL(PGetPAG);
281 #if defined(AFS_CACHE_BYPASS)
282 DECL_PIOCTL(PSetCachingThreshold);
283 DECL_PIOCTL(PSetCachingBlkSize);
284 #endif
285
286 /*
287  * A macro that says whether we're going to need HandleClientContext().
288  * This is currently used only by the nfs translator.
289  */
290 #if !defined(AFS_NONFSTRANS) || defined(AFS_AIX_IAUTH_ENV)
291 #define AFS_NEED_CLIENTCONTEXT
292 #endif
293
294 /* Prototypes for private routines */
295 #ifdef AFS_NEED_CLIENTCONTEXT
296 static int HandleClientContext(struct afs_ioctl *ablob, int *com,
297                                afs_ucred_t **acred,
298                                afs_ucred_t *credp);
299 #endif
300 int HandleIoctl(register struct vcache *avc, register afs_int32 acom,
301                 struct afs_ioctl *adata);
302 int afs_HandlePioctl(struct vnode *avp, afs_int32 acom,
303                      register struct afs_ioctl *ablob, int afollow,
304                      afs_ucred_t **acred);
305 static int Prefetch(uparmtype apath, struct afs_ioctl *adata, int afollow,
306                     afs_ucred_t *acred);
307
308 typedef int (*pioctlFunction) (struct vcache *, int, struct vrequest *,
309                                struct afs_pdata *, struct afs_pdata *,
310                                afs_ucred_t **);
311
312 static pioctlFunction VpioctlSw[] = {
313     PBogus,                     /* 0 */
314     PSetAcl,                    /* 1 */
315     PGetAcl,                    /* 2 */
316     PSetTokens,                 /* 3 */
317     PGetVolumeStatus,           /* 4 */
318     PSetVolumeStatus,           /* 5 */
319     PFlush,                     /* 6 */
320     PBogus,                     /* 7 */
321     PGetTokens,                 /* 8 */
322     PUnlog,                     /* 9 */
323     PCheckServers,              /* 10 */
324     PCheckVolNames,             /* 11 */
325     PCheckAuth,                 /* 12 */
326     PBogus,                     /* 13 -- used to be quick check time */
327     PFindVolume,                /* 14 */
328     PBogus,                     /* 15 -- prefetch is now special-cased; see pioctl code! */
329     PBogus,                     /* 16 -- used to be testing code */
330     PNoop,                      /* 17 -- used to be enable group */
331     PNoop,                      /* 18 -- used to be disable group */
332     PBogus,                     /* 19 -- used to be list group */
333     PViceAccess,                /* 20 */
334     PUnlog,                     /* 21 -- unlog *is* unpag in this system */
335     PGetFID,                    /* 22 -- get file ID */
336     PBogus,                     /* 23 -- used to be waitforever */
337     PSetCacheSize,              /* 24 */
338     PRemoveCallBack,            /* 25 -- flush only the callback */
339     PNewCell,                   /* 26 */
340     PListCells,                 /* 27 */
341     PRemoveMount,               /* 28 -- delete mount point */
342     PNewStatMount,              /* 29 -- new style mount point stat */
343     PGetFileCell,               /* 30 -- get cell name for input file */
344     PGetWSCell,                 /* 31 -- get cell name for workstation */
345     PMariner,                   /* 32 - set/get mariner host */
346     PGetUserCell,               /* 33 -- get cell name for user */
347     PBogus,                     /* 34 -- Enable/Disable logging */
348     PGetCellStatus,             /* 35 */
349     PSetCellStatus,             /* 36 */
350     PFlushVolumeData,           /* 37 -- flush all data from a volume */
351     PSetSysName,                /* 38 - Set system name */
352     PExportAfs,                 /* 39 - Export Afs to remote nfs clients */
353     PGetCacheSize,              /* 40 - get cache size and usage */
354     PGetVnodeXStatus,           /* 41 - get vcache's special status */
355     PSetSPrefs33,               /* 42 - Set CM Server preferences... */
356     PGetSPrefs,                 /* 43 - Get CM Server preferences... */
357     PGag,                       /* 44 - turn off/on all CM messages */
358     PTwiddleRx,                 /* 45 - adjust some RX params       */
359     PSetSPrefs,                 /* 46 - Set CM Server preferences... */
360     PStoreBehind,               /* 47 - set degree of store behind to be done */
361     PGCPAGs,                    /* 48 - disable automatic pag gc-ing */
362     PGetInitParams,             /* 49 - get initial cm params */
363     PGetCPrefs,                 /* 50 - get client interface addresses */
364     PSetCPrefs,                 /* 51 - set client interface addresses */
365     PFlushMount,                /* 52 - flush mount symlink data */
366     PRxStatProc,                /* 53 - control process RX statistics */
367     PRxStatPeer,                /* 54 - control peer RX statistics */
368     PGetRxkcrypt,               /* 55 -- Get rxkad encryption flag */
369     PSetRxkcrypt,               /* 56 -- Set rxkad encryption flag */
370     PBogus,                     /* 57 -- arla: set file prio */
371     PBogus,                     /* 58 -- arla: fallback getfh */
372     PBogus,                     /* 59 -- arla: fallback fhopen */
373     PBogus,                     /* 60 -- arla: controls xfsdebug */
374     PBogus,                     /* 61 -- arla: controls arla debug */
375     PBogus,                     /* 62 -- arla: debug interface */
376     PBogus,                     /* 63 -- arla: print xfs status */
377     PBogus,                     /* 64 -- arla: force cache check */
378     PBogus,                     /* 65 -- arla: break callback */
379     PPrefetchFromTape,          /* 66 -- MR-AFS: prefetch file from tape */
380     PFsCmd,                     /* 67 -- RXOSD: generic commnd interface */
381     PBogus,                     /* 68 -- arla: fetch stats */
382     PGetVnodeXStatus2,          /* 69 - get caller access and some vcache status */
383 };
384
385 static pioctlFunction CpioctlSw[] = {
386     PBogus,                     /* 0 */
387     PNewAlias,                  /* 1 -- create new cell alias */
388     PListAliases,               /* 2 -- list cell aliases */
389     PCallBackAddr,              /* 3 -- request addr for callback rxcon */
390     PBogus,                     /* 4 */
391     PDiscon,                    /* 5 -- get/set discon mode */
392     PBogus,                     /* 6 */
393     PBogus,                     /* 7 */
394     PBogus,                     /* 8 */
395     PNewUuid,                   /* 9 */
396     PBogus,                     /* 10 */
397     PBogus,                     /* 11 */
398     PPrecache,                  /* 12 */
399     PGetPAG,                    /* 13 */
400 };
401
402 static pioctlFunction OpioctlSw[]  = {
403     PBogus,                     /* 0 */
404     PNFSNukeCreds,              /* 1 -- nuke all creds for NFS client */
405 #if defined(AFS_CACHE_BYPASS)
406     PSetCachingThreshold        /* 2 -- get/set cache-bypass size threshold */
407 #else
408     PNoop                       /* 2 -- get/set cache-bypass size threshold */
409 #endif
410 };
411
412 #define PSetClientContext 99    /*  Special pioctl to setup caller's creds  */
413 int afs_nobody = NFS_NOBODY;
414
415 int
416 HandleIoctl(register struct vcache *avc, register afs_int32 acom,
417             struct afs_ioctl *adata)
418 {
419     register afs_int32 code;
420
421     code = 0;
422     AFS_STATCNT(HandleIoctl);
423
424     switch (acom & 0xff) {
425     case 1:
426         avc->f.states |= CSafeStore;
427         avc->asynchrony = 0;
428         /* SXW - Should we force a MetaData flush for this flag setting */
429         break;
430
431         /* case 2 used to be abort store, but this is no longer provided,
432          * since it is impossible to implement under normal Unix.
433          */
434
435     case 3:{
436             /* return the name of the cell this file is open on */
437             register struct cell *tcell;
438             register afs_int32 i;
439
440             tcell = afs_GetCell(avc->f.fid.Cell, READ_LOCK);
441             if (tcell) {
442                 i = strlen(tcell->cellName) + 1;        /* bytes to copy out */
443
444                 if (i > adata->out_size) {
445                     /* 0 means we're not interested in the output */
446                     if (adata->out_size != 0)
447                         code = EFAULT;
448                 } else {
449                     /* do the copy */
450                     AFS_COPYOUT(tcell->cellName, adata->out, i, code);
451                 }
452                 afs_PutCell(tcell, READ_LOCK);
453             } else
454                 code = ENOTTY;
455         }
456         break;
457
458     case 49:                    /* VIOC_GETINITPARAMS */
459         if (adata->out_size < sizeof(struct cm_initparams)) {
460             code = EFAULT;
461         } else {
462             AFS_COPYOUT(&cm_initParams, adata->out,
463                         sizeof(struct cm_initparams), code);
464         }
465         break;
466
467     default:
468
469         code = EINVAL;
470 #ifdef AFS_AIX51_ENV
471         code = ENOSYS;
472 #endif
473         break;
474     }
475     return code;                /* so far, none implemented */
476 }
477
478 #ifdef AFS_AIX_ENV
479 /* For aix we don't temporarily bypass ioctl(2) but rather do our
480  * thing directly in the vnode layer call, VNOP_IOCTL; thus afs_ioctl
481  * is now called from afs_gn_ioctl.
482  */
483 int
484 afs_ioctl(struct vcache *tvc, int cmd, int arg)
485 {
486     struct afs_ioctl data;
487     int error = 0;
488
489     AFS_STATCNT(afs_ioctl);
490     if (((cmd >> 8) & 0xff) == 'V') {
491         /* This is a VICEIOCTL call */
492         AFS_COPYIN(arg, (caddr_t) & data, sizeof(data), error);
493         if (error)
494             return (error);
495         error = HandleIoctl(tvc, cmd, &data);
496         return (error);
497     } else {
498         /* No-op call; just return. */
499         return (ENOTTY);
500     }
501 }
502 # if defined(AFS_AIX32_ENV)
503 #  if defined(AFS_AIX51_ENV)
504 #   ifdef __64BIT__
505 int
506 kioctl(int fdes, int com, caddr_t arg, caddr_t ext, caddr_t arg2,
507            caddr_t arg3)
508 #   else /* __64BIT__ */
509 int
510 kioctl32(int fdes, int com, caddr_t arg, caddr_t ext, caddr_t arg2,
511              caddr_t arg3)
512 #   endif /* __64BIT__ */
513 #  else
514 int
515 kioctl(int fdes, int com, caddr_t arg, caddr_t ext)
516 #  endif /* AFS_AIX51_ENV */
517 {
518     struct a {
519         int fd, com;
520         caddr_t arg, ext;
521 #  ifdef AFS_AIX51_ENV
522         caddr_t arg2, arg3;
523 #  endif
524     } u_uap, *uap = &u_uap;
525     struct file *fd;
526     register struct vcache *tvc;
527     register int ioctlDone = 0, code = 0;
528
529     AFS_STATCNT(afs_xioctl);
530     uap->fd = fdes;
531     uap->com = com;
532     uap->arg = arg;
533 #  ifdef AFS_AIX51_ENV
534     uap->arg2 = arg2;
535     uap->arg3 = arg3;
536 #  endif
537     if (setuerror(getf(uap->fd, &fd))) {
538         return -1;
539     }
540     if (fd->f_type == DTYPE_VNODE) {
541         /* good, this is a vnode; next see if it is an AFS vnode */
542         tvc = VTOAFS(fd->f_vnode);      /* valid, given a vnode */
543         if (tvc && IsAfsVnode(AFSTOV(tvc))) {
544             /* This is an AFS vnode */
545             if (((uap->com >> 8) & 0xff) == 'V') {
546                 register struct afs_ioctl *datap;
547                 AFS_GLOCK();
548                 datap =
549                     (struct afs_ioctl *)osi_AllocSmallSpace(AFS_SMALLOCSIZ);
550                 code=copyin_afs_ioctl((char *)uap->arg, datap);
551                 if (code) {
552                     osi_FreeSmallSpace(datap);
553                     AFS_GUNLOCK();
554 #  if defined(AFS_AIX41_ENV)
555                     ufdrele(uap->fd);
556 #  endif
557                     return (setuerror(code), code);
558                 }
559                 code = HandleIoctl(tvc, uap->com, datap);
560                 osi_FreeSmallSpace(datap);
561                 AFS_GUNLOCK();
562                 ioctlDone = 1;
563 #  if defined(AFS_AIX41_ENV)
564                 ufdrele(uap->fd);
565 #  endif
566              }
567         }
568     }
569     if (!ioctlDone) {
570 #  if defined(AFS_AIX41_ENV)
571         ufdrele(uap->fd);
572 #   if defined(AFS_AIX51_ENV)
573 #    ifdef __64BIT__
574         code = okioctl(fdes, com, arg, ext, arg2, arg3);
575 #    else /* __64BIT__ */
576         code = okioctl32(fdes, com, arg, ext, arg2, arg3);
577 #    endif /* __64BIT__ */
578 #   else /* !AFS_AIX51_ENV */
579         code = okioctl(fdes, com, arg, ext);
580 #   endif /* AFS_AIX51_ENV */
581         return code;
582 #  elif defined(AFS_AIX32_ENV)
583         okioctl(fdes, com, arg, ext);
584 #  endif
585     }
586 #  if defined(KERNEL_HAVE_UERROR)
587     if (!getuerror())
588         setuerror(code);
589 #   if !defined(AFS_AIX41_ENV)
590     return (getuerror()? -1 : u.u_ioctlrv);
591 #   else
592     return getuerror()? -1 : 0;
593 #   endif
594 #  endif
595     return 0;
596 }
597 # endif
598
599 #elif defined(AFS_SGI_ENV)
600 # if defined(AFS_SGI65_ENV)
601 afs_ioctl(OSI_VN_DECL(tvc), int cmd, void *arg, int flag, cred_t * cr,
602           rval_t * rvalp, struct vopbd * vbds)
603 # else
604 afs_ioctl(OSI_VN_DECL(tvc), int cmd, void *arg, int flag, cred_t * cr,
605           rval_t * rvalp, struct vopbd * vbds)
606 # endif
607 {
608     struct afs_ioctl data;
609     int error = 0;
610     int locked;
611
612     OSI_VN_CONVERT(tvc);
613
614     AFS_STATCNT(afs_ioctl);
615     if (((cmd >> 8) & 0xff) == 'V') {
616         /* This is a VICEIOCTL call */
617         error = copyin_afs_ioctl(arg, &data);
618         if (error)
619             return (error);
620         locked = ISAFS_GLOCK();
621         if (!locked)
622             AFS_GLOCK();
623         error = HandleIoctl(tvc, cmd, &data);
624         if (!locked)
625             AFS_GUNLOCK();
626         return (error);
627     } else {
628         /* No-op call; just return. */
629         return (ENOTTY);
630     }
631 }
632 #elif defined(AFS_SUN5_ENV)
633 struct afs_ioctl_sys {
634     int fd;
635     int com;
636     int arg;
637 };
638
639 int 
640 afs_xioctl(struct afs_ioctl_sys *uap, rval_t *rvp)
641 {
642     struct file *fd;
643     register struct vcache *tvc;
644     register int ioctlDone = 0, code = 0;
645
646     AFS_STATCNT(afs_xioctl);
647 # if defined(AFS_SUN57_ENV)
648     fd = getf(uap->fd);
649     if (!fd)
650         return (EBADF);
651 # elif defined(AFS_SUN54_ENV)
652     fd = GETF(uap->fd);
653     if (!fd)
654         return (EBADF);
655 # else
656     if (code = getf(uap->fd, &fd)) {
657         return (code);
658     }
659 # endif
660     if (fd->f_vnode->v_type == VREG || fd->f_vnode->v_type == VDIR) {
661         tvc = VTOAFS(fd->f_vnode);      /* valid, given a vnode */
662         if (tvc && IsAfsVnode(AFSTOV(tvc))) {
663             /* This is an AFS vnode */
664             if (((uap->com >> 8) & 0xff) == 'V') {
665                 register struct afs_ioctl *datap;
666                 AFS_GLOCK();
667                 datap =
668                     (struct afs_ioctl *)osi_AllocSmallSpace(AFS_SMALLOCSIZ);
669                 code=copyin_afs_ioctl((char *)uap->arg, datap);
670                 if (code) {
671                     osi_FreeSmallSpace(datap);
672                     AFS_GUNLOCK();
673 # if defined(AFS_SUN54_ENV)
674                     releasef(uap->fd);
675 # else
676                     releasef(fd);
677 # endif
678                     return (EFAULT);
679                 }
680                 code = HandleIoctl(tvc, uap->com, datap);
681                 osi_FreeSmallSpace(datap);
682                 AFS_GUNLOCK();
683                 ioctlDone = 1;
684             }
685         }
686     }
687 # if defined(AFS_SUN57_ENV)
688     releasef(uap->fd);
689 # elif defined(AFS_SUN54_ENV)
690     RELEASEF(uap->fd);
691 # else
692     releasef(fd);
693 # endif
694     if (!ioctlDone)
695         code = ioctl(uap, rvp);
696
697     return (code);
698 }
699 #elif defined(AFS_LINUX22_ENV)
700 struct afs_ioctl_sys {
701     unsigned int com;
702     unsigned long arg;
703 };
704 int
705 afs_xioctl(struct inode *ip, struct file *fp, unsigned int com,
706            unsigned long arg)
707 {
708     struct afs_ioctl_sys ua, *uap = &ua;
709     register struct vcache *tvc;
710     register int ioctlDone = 0, code = 0;
711
712     AFS_STATCNT(afs_xioctl);
713     ua.com = com;
714     ua.arg = arg;
715
716     tvc = VTOAFS(ip);
717     if (tvc && IsAfsVnode(AFSTOV(tvc))) {
718         /* This is an AFS vnode */
719         if (((uap->com >> 8) & 0xff) == 'V') {
720             register struct afs_ioctl *datap;
721             AFS_GLOCK();
722             datap = osi_AllocSmallSpace(AFS_SMALLOCSIZ);
723             code = copyin_afs_ioctl((char *)uap->arg, datap);
724             if (code) {
725                 osi_FreeSmallSpace(datap);
726                 AFS_GUNLOCK();
727                 return -code;
728             }
729             code = HandleIoctl(tvc, uap->com, datap);
730             osi_FreeSmallSpace(datap);
731             AFS_GUNLOCK();
732             ioctlDone = 1;
733         }
734         else
735             code = EINVAL;
736     }
737     return -code;
738 }
739 #elif defined(AFS_DARWIN_ENV) && !defined(AFS_DARWIN80_ENV)
740 struct ioctl_args {
741     int fd;
742     u_long com;
743     caddr_t arg;
744 };
745
746 int
747 afs_xioctl(afs_proc_t *p, register struct ioctl_args *uap, register_t *retval)
748 {
749     struct file *fd;
750     register struct vcache *tvc;
751     register int ioctlDone = 0, code = 0;
752
753     AFS_STATCNT(afs_xioctl);
754     if ((code = fdgetf(p, uap->fd, &fd)))
755         return code;
756     if (fd->f_type == DTYPE_VNODE) {
757         tvc = VTOAFS((struct vnode *)fd->f_data);       /* valid, given a vnode */
758         if (tvc && IsAfsVnode(AFSTOV(tvc))) {
759             /* This is an AFS vnode */
760             if (((uap->com >> 8) & 0xff) == 'V') {
761                 register struct afs_ioctl *datap;
762                 AFS_GLOCK();
763                 datap = osi_AllocSmallSpace(AFS_SMALLOCSIZ);
764                 code = copyin_afs_ioctl((char *)uap->arg, datap);
765                 if (code) {
766                     osi_FreeSmallSpace(datap);
767                     AFS_GUNLOCK();
768                     return code;
769                 }
770                 code = HandleIoctl(tvc, uap->com, datap);
771                 osi_FreeSmallSpace(datap);
772                 AFS_GUNLOCK();
773                 ioctlDone = 1;
774             }
775         }
776     }
777
778     if (!ioctlDone)
779         return ioctl(p, uap, retval);
780
781     return (code);
782 }
783 #elif defined(AFS_XBSD_ENV)
784 # if !defined(AFS_FBSD50_ENV)
785 #  define arg data
786 int
787 afs_xioctl(struct thread *td, register struct ioctl_args *uap,
788            register_t *retval)
789 {
790     afs_proc_t *p = td->td_proc;
791 # else
792 struct ioctl_args {
793     int fd;
794     u_long com;
795     caddr_t arg;
796 };
797
798 int
799 afs_xioctl(afs_proc_t *p, register struct ioctl_args *uap, register_t *retval)
800 {
801 # endif
802     register struct filedesc *fdp;
803     register struct vcache *tvc;
804     register int ioctlDone = 0, code = 0;
805
806     AFS_STATCNT(afs_xioctl);
807     fdp = p->p_fd;
808     if ((u_int) uap->fd >= fdp->fd_nfiles
809         || (fd = fdp->fd_ofiles[uap->fd]) == NULL)
810         return EBADF;
811     if ((fd->f_flag & (FREAD | FWRITE)) == 0)
812         return EBADF;
813     /* first determine whether this is any sort of vnode */
814     if (fd->f_type == DTYPE_VNODE) {
815         /* good, this is a vnode; next see if it is an AFS vnode */
816 # if defined(AFS_OBSD_ENV)
817         tvc =
818             IsAfsVnode((struct vnode *)fd->
819                        f_data) ? VTOAFS((struct vnode *)fd->f_data) : NULL;
820 # else
821         tvc = VTOAFS((struct vnode *)fd->f_data);       /* valid, given a vnode */
822 # endif
823         if (tvc && IsAfsVnode(AFSTOV(tvc))) {
824             /* This is an AFS vnode */
825             if (((uap->com >> 8) & 0xff) == 'V') {
826                 register struct afs_ioctl *datap;
827                 AFS_GLOCK();
828                 datap = osi_AllocSmallSpace(AFS_SMALLOCSIZ);
829                 code = copyin_afs_ioctl((char *)uap->arg, datap);
830                 if (code) {
831                     osi_FreeSmallSpace(datap);
832                     AFS_GUNLOCK();
833                     return code;
834                 }
835                 code = HandleIoctl(tvc, uap->com, datap);
836                 osi_FreeSmallSpace(datap);
837                 AFS_GUNLOCK();
838                 ioctlDone = 1;
839             }
840         }
841     }
842
843     if (!ioctlDone) {
844 # if defined(AFS_FBSD50_ENV)
845         return ioctl(td, uap);
846 # elif defined(AFS_FBSD_ENV)
847         return ioctl(p, uap);
848 # elif defined(AFS_OBSD_ENV)
849         code = sys_ioctl(p, uap, retval);
850 # endif
851     }
852
853     return (code);
854 }
855 #elif defined(UKERNEL)
856 int
857 afs_xioctl(void)
858 {
859     register struct a {
860         int fd;
861         int com;
862         caddr_t arg;
863     } *uap = (struct a *)get_user_struct()->u_ap;
864     register struct file *fd;
865     register struct vcache *tvc;
866     register int ioctlDone = 0, code = 0;
867
868     AFS_STATCNT(afs_xioctl);
869
870     fd = getf(uap->fd);
871     if (!fd)
872         return (EBADF);
873     /* first determine whether this is any sort of vnode */
874     if (fd->f_type == DTYPE_VNODE) {
875         /* good, this is a vnode; next see if it is an AFS vnode */
876         tvc = VTOAFS((struct vnode *)fd->f_data);       /* valid, given a vnode */
877         if (tvc && IsAfsVnode(AFSTOV(tvc))) {
878             /* This is an AFS vnode */
879             if (((uap->com >> 8) & 0xff) == 'V') {
880                 register struct afs_ioctl *datap;
881                 AFS_GLOCK();
882                 datap = osi_AllocSmallSpace(AFS_SMALLOCSIZ);
883                 code=copyin_afs_ioctl((char *)uap->arg, datap);
884                 if (code) {
885                     osi_FreeSmallSpace(datap);
886                     AFS_GUNLOCK();
887
888                     return (setuerror(code), code);
889                 }
890                 code = HandleIoctl(tvc, uap->com, datap);
891                 osi_FreeSmallSpace(datap);
892                 AFS_GUNLOCK();
893                 ioctlDone = 1;
894             }
895         }
896     }
897
898     if (!ioctlDone) {
899         ioctl();
900     }
901
902     return 0;
903 }
904 #endif /* AFS_HPUX102_ENV */
905
906 #if defined(AFS_SGI_ENV)
907   /* "pioctl" system call entry point; just pass argument to the parameterized
908    * call below */
909 struct pioctlargs {
910     char *path;
911     sysarg_t cmd;
912     caddr_t cmarg;
913     sysarg_t follow;
914 };
915 int
916 afs_pioctl(struct pioctlargs *uap, rval_t * rvp)
917 {
918     int code;
919
920     AFS_STATCNT(afs_pioctl);
921     AFS_GLOCK();
922     code = afs_syscall_pioctl(uap->path, uap->cmd, uap->cmarg, uap->follow);
923     AFS_GUNLOCK();
924 # ifdef AFS_SGI64_ENV
925     return code;
926 # else
927     return u.u_error;
928 # endif
929 }
930
931 #elif defined(AFS_FBSD50_ENV)
932 int
933 afs_pioctl(struct thread *td, void *args, int *retval)
934 {
935     struct a {
936         char *path;
937         int cmd;
938         caddr_t cmarg;
939         int follow;
940     } *uap = (struct a *)args;
941
942     AFS_STATCNT(afs_pioctl);
943     return (afs_syscall_pioctl
944             (uap->path, uap->cmd, uap->cmarg, uap->follow, td->td_ucred));
945 }
946
947 #elif defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
948 int
949 afs_pioctl(afs_proc_t *p, void *args, int *retval)
950 {
951     struct a {
952         char *path;
953         int cmd;
954         caddr_t cmarg;
955         int follow;
956     } *uap = (struct a *)args;
957
958     AFS_STATCNT(afs_pioctl);
959 # ifdef AFS_DARWIN80_ENV
960     return (afs_syscall_pioctl
961             (uap->path, uap->cmd, uap->cmarg, uap->follow,
962              kauth_cred_get()));
963 # else
964     return (afs_syscall_pioctl
965             (uap->path, uap->cmd, uap->cmarg, uap->follow,
966              p->p_cred->pc_ucred));
967 # endif
968 }
969
970 #endif
971
972 /* macro to avoid adding any more #ifdef's to pioctl code. */
973 #if defined(AFS_LINUX22_ENV) || defined(AFS_AIX41_ENV)
974 #define PIOCTL_FREE_CRED() crfree(credp)
975 #else
976 #define PIOCTL_FREE_CRED()
977 #endif
978
979 int
980 #ifdef  AFS_SUN5_ENV
981 afs_syscall_pioctl(char *path, unsigned int com, caddr_t cmarg, int follow, 
982                    rval_t *vvp, afs_ucred_t *credp)
983 #else
984 #ifdef AFS_DARWIN100_ENV
985 afs_syscall64_pioctl(user_addr_t path, unsigned int com, user_addr_t cmarg,
986                    int follow, afs_ucred_t *credp)
987 #elif defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
988 afs_syscall_pioctl(char *path, unsigned int com, caddr_t cmarg, int follow, 
989                    afs_ucred_t *credp)
990 #else
991 afs_syscall_pioctl(char *path, unsigned int com, caddr_t cmarg, int follow)
992 #endif
993 #endif
994 {
995     struct afs_ioctl data;
996 #ifdef AFS_NEED_CLIENTCONTEXT
997     afs_ucred_t *tmpcred = NULL;
998 #endif
999 #if defined(AFS_NEED_CLIENTCONTEXT) || defined(AFS_SUN5_ENV) || defined(AFS_AIX41_ENV) || defined(AFS_LINUX22_ENV) || defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
1000     afs_ucred_t *foreigncreds = NULL;
1001 #endif
1002     register afs_int32 code = 0;
1003     struct vnode *vp = NULL;
1004 #ifdef  AFS_AIX41_ENV
1005     struct ucred *credp = crref();      /* don't free until done! */
1006 #endif
1007 #ifdef AFS_LINUX22_ENV
1008     cred_t *credp = crref();    /* don't free until done! */
1009     struct dentry *dp;
1010 #endif
1011
1012     AFS_STATCNT(afs_syscall_pioctl);
1013     if (follow)
1014         follow = 1;             /* compat. with old venus */
1015     code = copyin_afs_ioctl(cmarg, &data);
1016     if (code) {
1017         PIOCTL_FREE_CRED();
1018 #if defined(KERNEL_HAVE_UERROR)
1019         setuerror(code);
1020 #endif
1021         return (code);
1022     }
1023     if ((com & 0xff) == PSetClientContext) {
1024 #ifdef AFS_NEED_CLIENTCONTEXT
1025 #if defined(AFS_SUN5_ENV) || defined(AFS_AIX41_ENV) || defined(AFS_LINUX22_ENV)
1026         code = HandleClientContext(&data, &com, &foreigncreds, credp);
1027 #else
1028         code = HandleClientContext(&data, &com, &foreigncreds, osi_curcred());
1029 #endif
1030         if (code) {
1031             if (foreigncreds) {
1032                 crfree(foreigncreds);
1033             }
1034             PIOCTL_FREE_CRED();
1035 #if defined(KERNEL_HAVE_UERROR)
1036             return (setuerror(code), code);
1037 #else
1038             return (code);
1039 #endif
1040         }
1041 #else /* AFS_NEED_CLIENTCONTEXT */
1042         return EINVAL;
1043 #endif /* AFS_NEED_CLIENTCONTEXT */
1044     }
1045 #ifdef AFS_NEED_CLIENTCONTEXT
1046     if (foreigncreds) {
1047         /*
1048          * We could have done without temporary setting the u.u_cred below
1049          * (foreigncreds could be passed as param the pioctl modules)
1050          * but calls such as afs_osi_suser() doesn't allow that since it
1051          * references u.u_cred directly.  We could, of course, do something
1052          * like afs_osi_suser(cred) which, I think, is better since it
1053          * generalizes and supports multi cred environments...
1054          */
1055 #if defined(AFS_SUN5_ENV) || defined(AFS_LINUX22_ENV)
1056         tmpcred = credp;
1057         credp = foreigncreds;
1058 #elif defined(AFS_AIX41_ENV)
1059         tmpcred = crref();      /* XXX */
1060         crset(foreigncreds);
1061 #elif defined(AFS_HPUX101_ENV)
1062         tmpcred = p_cred(u.u_procp);
1063         set_p_cred(u.u_procp, foreigncreds);
1064 #elif defined(AFS_SGI_ENV)
1065         tmpcred = OSI_GET_CURRENT_CRED();
1066         OSI_SET_CURRENT_CRED(foreigncreds);
1067 #else
1068         tmpcred = u.u_cred;
1069         u.u_cred = foreigncreds;
1070 #endif
1071     }
1072 #endif /* AFS_NEED_CLIENTCONTEXT */
1073     if ((com & 0xff) == 15) {
1074         /* special case prefetch so entire pathname eval occurs in helper process.
1075          * otherwise, the pioctl call is essentially useless */
1076 #if     defined(AFS_SUN5_ENV) || defined(AFS_AIX41_ENV) || defined(AFS_LINUX22_ENV) || defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
1077         code =
1078             Prefetch(path, &data, follow,
1079                      foreigncreds ? foreigncreds : credp);
1080 #else
1081         code = Prefetch(path, &data, follow, osi_curcred());
1082 #endif
1083         vp = NULL;
1084 #if defined(KERNEL_HAVE_UERROR)
1085         setuerror(code);
1086 #endif
1087         goto rescred;
1088     }
1089     if (path) {
1090         AFS_GUNLOCK();
1091 #ifdef  AFS_AIX41_ENV
1092         code =
1093             lookupname(path, USR, follow, NULL, &vp,
1094                        foreigncreds ? foreigncreds : credp);
1095 #else
1096 #ifdef AFS_LINUX22_ENV
1097         code = gop_lookupname_user(path, AFS_UIOUSER, follow, &dp);
1098         if (!code)
1099             vp = (struct vnode *)dp->d_inode;
1100 #else
1101         code = gop_lookupname_user(path, AFS_UIOUSER, follow, &vp);
1102 #if defined(AFS_FBSD80_ENV) /* XXX check on 7x */
1103         VN_HOLD(vp);
1104 #endif /* AFS_FBSD80_ENV */
1105 #endif /* AFS_LINUX22_ENV */
1106 #endif /* AFS_AIX41_ENV */
1107         AFS_GLOCK();
1108         if (code) {
1109             vp = NULL;
1110 #if defined(KERNEL_HAVE_UERROR)
1111             setuerror(code);
1112 #endif
1113             goto rescred;
1114         }
1115     } else
1116         vp = NULL;
1117
1118 #if defined(AFS_SUN510_ENV)
1119     if (vp && !IsAfsVnode(vp)) {
1120         struct vnode *realvp;
1121         if
1122 #ifdef AFS_SUN511_ENV
1123           (VOP_REALVP(vp, &realvp, NULL) == 0) 
1124 #else
1125           (VOP_REALVP(vp, &realvp) == 0) 
1126 #endif
1127 {
1128             struct vnode *oldvp = vp;
1129             
1130             VN_HOLD(realvp);
1131             vp = realvp;
1132             AFS_RELE(oldvp);
1133         }
1134     }
1135 #endif
1136     /* now make the call if we were passed no file, or were passed an AFS file */
1137     if (!vp || IsAfsVnode(vp)) {
1138 #if defined(AFS_SUN5_ENV)
1139         code = afs_HandlePioctl(vp, com, &data, follow, &credp);
1140 #elif defined(AFS_AIX41_ENV)
1141         {
1142             struct ucred *cred1, *cred2;
1143
1144             if (foreigncreds) {
1145                 cred1 = cred2 = foreigncreds;
1146             } else {
1147                 cred1 = cred2 = credp;
1148             }
1149             code = afs_HandlePioctl(vp, com, &data, follow, &cred1);
1150             if (cred1 != cred2) {
1151                 /* something changed the creds */
1152                 crset(cred1);
1153             }
1154         }
1155 #elif defined(AFS_HPUX101_ENV)
1156         {
1157             struct ucred *cred = p_cred(u.u_procp);
1158             code = afs_HandlePioctl(vp, com, &data, follow, &cred);
1159         }
1160 #elif defined(AFS_SGI_ENV)
1161         {
1162             struct cred *credp;
1163             credp = OSI_GET_CURRENT_CRED();
1164             code = afs_HandlePioctl(vp, com, &data, follow, &credp);
1165         }
1166 #elif defined(AFS_LINUX22_ENV) || defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
1167         code = afs_HandlePioctl(vp, com, &data, follow, &credp);
1168 #elif defined(UKERNEL)
1169         code = afs_HandlePioctl(vp, com, &data, follow,
1170                                 &(get_user_struct()->u_cred));
1171 #else
1172         code = afs_HandlePioctl(vp, com, &data, follow, &u.u_cred);
1173 #endif
1174     } else {
1175 #if defined(KERNEL_HAVE_UERROR)
1176         setuerror(EINVAL);
1177 #else
1178         code = EINVAL;          /* not in /afs */
1179 #endif
1180     }
1181
1182   rescred:
1183 #if defined(AFS_NEED_CLIENTCONTEXT)
1184     if (foreigncreds) {
1185 #ifdef  AFS_AIX41_ENV
1186         crset(tmpcred);         /* restore original credentials */
1187 #else
1188 #if     defined(AFS_HPUX101_ENV)
1189         set_p_cred(u.u_procp, tmpcred); /* restore original credentials */
1190 #elif   defined(AFS_SGI_ENV)
1191         OSI_SET_CURRENT_CRED(tmpcred);  /* restore original credentials */
1192 #elif   defined(AFS_SUN5_ENV) || defined(AFS_LINUX22_ENV)
1193         credp = tmpcred;                /* restore original credentials */
1194 #else
1195         osi_curcred() = tmpcred;        /* restore original credentials */
1196 #endif /* AFS_HPUX101_ENV */
1197         crfree(foreigncreds);
1198 #endif /* AIX41 */
1199     }
1200 #endif /* AFS_NEED_CLIENTCONTEXT */
1201     if (vp) {
1202 #ifdef AFS_LINUX22_ENV
1203         dput(dp);
1204 #else
1205 #if defined(AFS_FBSD80_ENV)
1206     if (VOP_ISLOCKED(vp))
1207         VOP_UNLOCK(vp, 0);
1208 #endif /* AFS_FBSD80_ENV */
1209         AFS_RELE(vp);           /* put vnode back */
1210 #endif
1211     }
1212     PIOCTL_FREE_CRED();
1213 #if defined(KERNEL_HAVE_UERROR)
1214     if (!getuerror())
1215         setuerror(code);
1216     return (getuerror());
1217 #else
1218     return (code);
1219 #endif
1220 }
1221
1222 #ifdef AFS_DARWIN100_ENV
1223 int
1224 afs_syscall_pioctl(char * path, unsigned int com, caddr_t cmarg,
1225                    int follow, afs_ucred_t *credp)
1226 {
1227     return afs_syscall64_pioctl(CAST_USER_ADDR_T(path), com,
1228                                 CAST_USER_ADDR_T((unsigned int)cmarg), follow,
1229                                 credp);
1230 }
1231 #endif
1232
1233 #define MAXPIOCTLTOKENLEN \
1234 (3*sizeof(afs_int32)+MAXKTCTICKETLEN+sizeof(struct ClearToken)+MAXKTCREALMLEN)
1235
1236 int
1237 afs_HandlePioctl(struct vnode *avp, afs_int32 acom,
1238                  register struct afs_ioctl *ablob, int afollow,
1239                  afs_ucred_t **acred)
1240 {
1241     struct vcache *avc;
1242     struct vrequest treq;
1243     register afs_int32 code;
1244     register afs_int32 function, device;
1245     struct afs_pdata input, output;
1246     struct afs_pdata copyInput, copyOutput;
1247     size_t outSize;
1248     pioctlFunction *pioctlSw;
1249     int pioctlSwSize;
1250     struct afs_fakestat_state fakestate;
1251
1252     memset(&input, 0, sizeof(input));
1253     memset(&output, 0, sizeof(output));
1254
1255     avc = avp ? VTOAFS(avp) : NULL;
1256     afs_Trace3(afs_iclSetp, CM_TRACE_PIOCTL, ICL_TYPE_INT32, acom & 0xff,
1257                ICL_TYPE_POINTER, avc, ICL_TYPE_INT32, afollow);
1258     AFS_STATCNT(HandlePioctl);
1259
1260     code = afs_InitReq(&treq, *acred);
1261     if (code)
1262         return code;
1263
1264     afs_InitFakeStat(&fakestate);
1265     if (avc) {
1266         code = afs_EvalFakeStat(&avc, &fakestate, &treq);
1267         if (code)
1268             goto out;
1269     }
1270     device = (acom & 0xff00) >> 8;
1271     switch (device) {
1272     case 'V':                   /* Original pioctls */
1273         pioctlSw = VpioctlSw;
1274         pioctlSwSize = sizeof(VpioctlSw);
1275         break;
1276     case 'C':                   /* Coordinated/common pioctls */
1277         pioctlSw = CpioctlSw;
1278         pioctlSwSize = sizeof(CpioctlSw);
1279         break;
1280     case 'O':                   /* Coordinated/common pioctls */
1281         pioctlSw = OpioctlSw;
1282         pioctlSwSize = sizeof(OpioctlSw);
1283         break;
1284     default:
1285         code = EINVAL;
1286         goto out;
1287     }
1288     function = acom & 0xff;
1289     if (function >= (pioctlSwSize / sizeof(char *))) {
1290         code = EINVAL;
1291         goto out;
1292     }
1293
1294     /* Do all range checking before continuing */
1295     if (ablob->in_size > MAXPIOCTLTOKENLEN ||
1296         ablob->in_size < 0 || ablob->out_size < 0) {
1297         code = EINVAL;
1298         goto out;
1299     }
1300
1301     code = afs_pd_alloc(&input, ablob->in_size);
1302     if (code)
1303         goto out;
1304
1305     if (ablob->in_size > 0) {
1306         AFS_COPYIN(ablob->in, input.ptr, ablob->in_size, code);
1307         input.ptr[input.remaining] = '\0';
1308     }
1309     if (code)
1310         goto out;
1311
1312     if (function == 8 && device == 'V') {       /* PGetTokens */
1313         code = afs_pd_alloc(&output, MAXPIOCTLTOKENLEN);
1314     } else {
1315         code = afs_pd_alloc(&output, AFS_LRALLOCSIZ);
1316     }
1317     if (code)
1318         goto out;
1319
1320     copyInput = input;
1321     copyOutput = output;
1322
1323     code =
1324         (*pioctlSw[function]) (avc, function, &treq, &copyInput,
1325                                &copyOutput, acred);
1326
1327     outSize = copyOutput.ptr - output.ptr;
1328
1329     if (code == 0 && ablob->out_size > 0) {
1330         if (outSize > ablob->out_size) {
1331             code = E2BIG;       /* data wont fit in user buffer */
1332         } else if (outSize) {
1333             AFS_COPYOUT(output.ptr, ablob->out, outSize, code);
1334         }
1335     }
1336
1337 out:
1338     afs_pd_free(&input);
1339     afs_pd_free(&output);
1340
1341     afs_PutFakeStat(&fakestate);
1342     return afs_CheckCode(code, &treq, 41);
1343 }
1344
1345 /*!
1346  * VIOCGETFID (22) - Get file ID quickly
1347  *
1348  * \ingroup pioctl
1349  *
1350  * \param[in] ain       not in use
1351  * \param[out] aout     fid of requested file
1352  *
1353  * \retval EINVAL       Error if some of the initial arguments aren't set
1354  *
1355  * \post get the file id of some file
1356  */
1357 DECL_PIOCTL(PGetFID)
1358 {
1359     AFS_STATCNT(PGetFID);
1360     if (!avc)
1361         return EINVAL;
1362     if (afs_pd_putBytes(aout, &avc->f.fid, sizeof(struct VenusFid)) != 0)
1363         return EINVAL;
1364     return 0;
1365 }
1366
1367 /*!
1368  * VIOCSETAL (1) - Set access control list
1369  *
1370  * \ingroup pioctl
1371  *
1372  * \param[in] ain       the ACL being set
1373  * \param[out] aout     the ACL being set returned
1374  *
1375  * \retval EINVAL       Error if some of the standard args aren't set
1376  *
1377  * \post Changed ACL, via direct writing to the wire
1378  */
1379 int dummy_PSetAcl(char *ain, char *aout)
1380 {
1381     return 0;
1382 }
1383
1384 DECL_PIOCTL(PSetAcl)
1385 {
1386     register afs_int32 code;
1387     struct afs_conn *tconn;
1388     struct AFSOpaque acl;
1389     struct AFSVolSync tsync;
1390     struct AFSFetchStatus OutStatus;
1391     XSTATS_DECLS;
1392
1393     AFS_STATCNT(PSetAcl);
1394     if (!avc)
1395         return EINVAL;
1396
1397     if (afs_pd_getStringPtr(ain, &acl.AFSOpaque_val) != 0)
1398         return EINVAL;
1399     acl.AFSOpaque_len = strlen(acl.AFSOpaque_val) + 1;
1400     if (acl.AFSOpaque_len > 1024)
1401         return EINVAL;
1402
1403     do {
1404         tconn = afs_Conn(&avc->f.fid, areq, SHARED_LOCK);
1405         if (tconn) {
1406             XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_STOREACL);
1407             RX_AFS_GUNLOCK();
1408             code =
1409                 RXAFS_StoreACL(tconn->id, (struct AFSFid *)&avc->f.fid.Fid,
1410                                &acl, &OutStatus, &tsync);
1411             RX_AFS_GLOCK();
1412             XSTATS_END_TIME;
1413         } else
1414             code = -1;
1415     } while (afs_Analyze
1416              (tconn, code, &avc->f.fid, areq, AFS_STATS_FS_RPCIDX_STOREACL,
1417               SHARED_LOCK, NULL));
1418
1419     /* now we've forgotten all of the access info */
1420     ObtainWriteLock(&afs_xcbhash, 455);
1421     avc->callback = 0;
1422     afs_DequeueCallback(avc);
1423     avc->f.states &= ~(CStatd | CUnique);
1424     ReleaseWriteLock(&afs_xcbhash);
1425     if (avc->f.fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
1426         osi_dnlc_purgedp(avc);
1427
1428     /* SXW - Should we flush metadata here? */
1429     return code;
1430 }
1431
1432 int afs_defaultAsynchrony = 0;
1433
1434 /*!
1435  * VIOC_STOREBEHIND (47) Adjust store asynchrony
1436  *
1437  * \ingroup pioctl
1438  *
1439  * \param[in] ain       sbstruct (store behind structure) input
1440  * \param[out] aout     resulting sbstruct
1441  *
1442  * \retval EPERM
1443  *      Error if the user doesn't have super-user credentials
1444  * \retval EACCES
1445  *      Error if there isn't enough access to not check the mode bits
1446  *
1447  * \post
1448  *      Changes either the default asynchrony (the amount of data that
1449  *      can remain to be written when the cache manager returns control
1450  *      to the user), or the asyncrony for the specified file.
1451  */
1452 DECL_PIOCTL(PStoreBehind)
1453 {
1454     struct sbstruct sbr;
1455
1456     if (afs_pd_getBytes(ain, &sbr, sizeof(struct sbstruct)) != 0)
1457         return EINVAL;
1458
1459     if (sbr.sb_default != -1) {
1460         if (afs_osi_suser(*acred))
1461             afs_defaultAsynchrony = sbr.sb_default;
1462         else
1463             return EPERM;
1464     }
1465
1466     if (avc && (sbr.sb_thisfile != -1)) {
1467         if (afs_AccessOK
1468             (avc, PRSFS_WRITE | PRSFS_ADMINISTER, areq, DONT_CHECK_MODE_BITS))
1469             avc->asynchrony = sbr.sb_thisfile;
1470         else
1471             return EACCES;
1472     }
1473
1474     memset(&sbr, 0, sizeof(sbr));
1475     sbr.sb_default = afs_defaultAsynchrony;
1476     if (avc) {
1477         sbr.sb_thisfile = avc->asynchrony;
1478     }
1479
1480     return afs_pd_putBytes(aout, &sbr, sizeof(sbr));
1481 }
1482
1483 /*!
1484  * VIOC_GCPAGS (48) - Disable automatic PAG gc'ing
1485  *
1486  * \ingroup pioctl
1487  *
1488  * \param[in] ain       not in use
1489  * \param[out] aout     not in use
1490  *
1491  * \retval EACCES       Error if the user doesn't have super-user credentials
1492  *
1493  * \post set the gcpags to GCPAGS_USERDISABLED
1494  */
1495 DECL_PIOCTL(PGCPAGs)
1496 {
1497     if (!afs_osi_suser(*acred)) {
1498         return EACCES;
1499     }
1500     afs_gcpags = AFS_GCPAGS_USERDISABLED;
1501     return 0;
1502 }
1503
1504 /*!
1505  * VIOCGETAL (2) - Get access control list
1506  *
1507  * \ingroup pioctl
1508  *
1509  * \param[in] ain       not in use
1510  * \param[out] aout     the ACL
1511  *
1512  * \retval EINVAL       Error if some of the standard args aren't set
1513  * \retval ERANGE       Error if the vnode of the file id is too large
1514  * \retval -1           Error if getting the ACL failed
1515  *
1516  * \post Obtain the ACL, based on file ID
1517  *
1518  * \notes
1519  *      There is a hack to tell which type of ACL is being returned, checks
1520  *      the top 2-bytes of the input size to judge what type of ACL it is,
1521  *      only for dfs xlator ACLs
1522  */
1523 DECL_PIOCTL(PGetAcl)
1524 {
1525     struct AFSOpaque acl;
1526     struct AFSVolSync tsync;
1527     struct AFSFetchStatus OutStatus;
1528     afs_int32 code;
1529     struct afs_conn *tconn;
1530     struct AFSFid Fid;
1531     XSTATS_DECLS;
1532
1533     AFS_STATCNT(PGetAcl);
1534     if (!avc)
1535         return EINVAL;
1536     Fid.Volume = avc->f.fid.Fid.Volume;
1537     Fid.Vnode = avc->f.fid.Fid.Vnode;
1538     Fid.Unique = avc->f.fid.Fid.Unique;
1539     if (avc->f.states & CForeign) {
1540         /*
1541          * For a dfs xlator acl we have a special hack so that the
1542          * xlator will distinguish which type of acl will return. So
1543          * we currently use the top 2-bytes (vals 0-4) to tell which
1544          * type of acl to bring back. Horrible hack but this will
1545          * cause the least number of changes to code size and interfaces.
1546          */
1547         if (Fid.Vnode & 0xc0000000)
1548             return ERANGE;
1549         Fid.Vnode |= (ain->remaining << 30);
1550     }
1551     acl.AFSOpaque_val = aout->ptr;
1552     do {
1553         tconn = afs_Conn(&avc->f.fid, areq, SHARED_LOCK);
1554         if (tconn) {
1555             acl.AFSOpaque_val[0] = '\0';
1556             XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_FETCHACL);
1557             RX_AFS_GUNLOCK();
1558             code = RXAFS_FetchACL(tconn->id, &Fid, &acl, &OutStatus, &tsync);
1559             RX_AFS_GLOCK();
1560             XSTATS_END_TIME;
1561         } else
1562             code = -1;
1563     } while (afs_Analyze
1564              (tconn, code, &avc->f.fid, areq, AFS_STATS_FS_RPCIDX_FETCHACL,
1565               SHARED_LOCK, NULL));
1566
1567     if (code == 0) {
1568         if (acl.AFSOpaque_len == 0)
1569             afs_pd_skip(aout, 1); /* leave the NULL */
1570         else
1571             afs_pd_skip(aout, acl.AFSOpaque_len); /* Length of the ACL */
1572     }
1573     return code;
1574 }
1575
1576 /*!
1577  * PNoop returns success.  Used for functions which are not implemented
1578  * or are no longer in use.
1579  *
1580  * \ingroup pioctl
1581  *
1582  * \retval Always returns success
1583  *
1584  * \notes
1585  *      Functions involved in this:
1586  *      17 (VIOCENGROUP) -- used to be enable group;
1587  *      18 (VIOCDISGROUP) -- used to be disable group;
1588  *      2 (?) -- get/set cache-bypass size threshold
1589  */
1590 DECL_PIOCTL(PNoop)
1591 {
1592     AFS_STATCNT(PNoop);
1593     return 0;
1594 }
1595
1596 /*!
1597  * PBogus returns fail.  Used for functions which are not implemented or
1598  * are no longer in use.
1599  *
1600  * \ingroup pioctl
1601  *
1602  * \retval EINVAL       Always returns this value
1603  *
1604  * \notes
1605  *      Functions involved in this:
1606  *      0 (?);
1607  *      4 (?);
1608  *      6 (?);
1609  *      7 (VIOCSTAT);
1610  *      8 (?);
1611  *      13 (VIOCGETTIME) -- used to be quick check time;
1612  *      15 (VIOCPREFETCH) -- prefetch is now special-cased; see pioctl code!;
1613  *      16 (VIOCNOP) -- used to be testing code;
1614  *      19 (VIOCLISTGROUPS) -- used to be list group;
1615  *      23 (VIOCWAITFOREVER) -- used to be waitforever;
1616  *      57 (VIOC_FPRIOSTATUS) -- arla: set file prio;
1617  *      58 (VIOC_FHGET) -- arla: fallback getfh;
1618  *      59 (VIOC_FHOPEN) -- arla: fallback fhopen;
1619  *      60 (VIOC_XFSDEBUG) -- arla: controls xfsdebug;
1620  *      61 (VIOC_ARLADEBUG) -- arla: controls arla debug;
1621  *      62 (VIOC_AVIATOR) -- arla: debug interface;
1622  *      63 (VIOC_XFSDEBUG_PRINT) -- arla: print xfs status;
1623  *      64 (VIOC_CALCULATE_CACHE) -- arla: force cache check;
1624  *      65 (VIOC_BREAKCELLBACK) -- arla: break callback;
1625  *      68 (?) -- arla: fetch stats;
1626  */
1627 DECL_PIOCTL(PBogus)
1628 {
1629     AFS_STATCNT(PBogus);
1630     return EINVAL;
1631 }
1632
1633 /*!
1634  * VIOC_FILE_CELL_NAME (30) - Get cell in which file lives
1635  *
1636  * \ingroup pioctl
1637  *
1638  * \param[in] ain       not in use (avc used to pass in file id)
1639  * \param[out] aout     cell name
1640  *
1641  * \retval EINVAL       Error if some of the standard args aren't set
1642  * \retval ESRCH        Error if the file isn't part of a cell
1643  *
1644  * \post Get a cell based on a passed in file id
1645  */
1646 DECL_PIOCTL(PGetFileCell)
1647 {
1648     register struct cell *tcell;
1649
1650     AFS_STATCNT(PGetFileCell);
1651     if (!avc)
1652         return EINVAL;
1653     tcell = afs_GetCell(avc->f.fid.Cell, READ_LOCK);
1654     if (!tcell)
1655         return ESRCH;
1656
1657     if (afs_pd_putString(aout, tcell->cellName) != 0)
1658         return EINVAL;
1659
1660     afs_PutCell(tcell, READ_LOCK);
1661     return 0;
1662 }
1663
1664 /*!
1665  * VIOC_GET_WS_CELL (31) - Get cell in which workstation lives
1666  *
1667  * \ingroup pioctl
1668  *
1669  * \param[in] ain       not in use
1670  * \param[out] aout     cell name
1671  *
1672  * \retval EIO
1673  *      Error if the afs daemon hasn't started yet
1674  * \retval ESRCH
1675  *      Error if the machine isn't part of a cell, for whatever reason
1676  *
1677  * \post Get the primary cell that the machine is a part of.
1678  */
1679 DECL_PIOCTL(PGetWSCell)
1680 {
1681     struct cell *tcell = NULL;
1682
1683     AFS_STATCNT(PGetWSCell);
1684     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
1685         return EIO;             /* Inappropriate ioctl for device */
1686
1687     tcell = afs_GetPrimaryCell(READ_LOCK);
1688     if (!tcell)                 /* no primary cell? */
1689         return ESRCH;
1690
1691     if (afs_pd_putString(aout, tcell->cellName) != 0)
1692         return EINVAL;
1693     afs_PutCell(tcell, READ_LOCK);
1694     return 0;
1695 }
1696
1697 /*!
1698  * VIOC_GET_PRIMARY_CELL (33) - Get primary cell for caller
1699  *
1700  * \ingroup pioctl
1701  *
1702  * \param[in] ain       not in use (user id found via areq)
1703  * \param[out] aout     cell name
1704  *
1705  * \retval ESRCH
1706  *      Error if the user id doesn't have a primary cell specified
1707  *
1708  * \post Get the primary cell for a certain user, based on the user's uid
1709  */
1710 DECL_PIOCTL(PGetUserCell)
1711 {
1712     register afs_int32 i;
1713     register struct unixuser *tu;
1714     register struct cell *tcell;
1715
1716     AFS_STATCNT(PGetUserCell);
1717     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
1718         return EIO;             /* Inappropriate ioctl for device */
1719
1720     /* return the cell name of the primary cell for this user */
1721     i = UHash(areq->uid);
1722     ObtainWriteLock(&afs_xuser, 224);
1723     for (tu = afs_users[i]; tu; tu = tu->next) {
1724         if (tu->uid == areq->uid && (tu->states & UPrimary)) {
1725             tu->refCount++;
1726             ReleaseWriteLock(&afs_xuser);
1727             break;
1728         }
1729     }
1730     if (tu) {
1731         tcell = afs_GetCell(tu->cell, READ_LOCK);
1732         afs_PutUser(tu, WRITE_LOCK);
1733         if (!tcell)
1734             return ESRCH;
1735         else {
1736             if (afs_pd_putString(aout, tcell->cellName) != 0)
1737                 return E2BIG;
1738             afs_PutCell(tcell, READ_LOCK);
1739         }
1740     } else {
1741         ReleaseWriteLock(&afs_xuser);
1742     }
1743     return 0;
1744 }
1745
1746 /*!
1747  * VIOCSETTOK (3) - Set authentication tokens
1748  *
1749  * \ingroup pioctl
1750  *
1751  * \param[in] ain       the krb tickets from which to set the afs tokens
1752  * \param[out] aout     not in use
1753  *
1754  * \retval EINVAL
1755  *      Error if the ticket is either too long or too short
1756  * \retval EIO
1757  *      Error if the AFS initState is below 101
1758  * \retval ESRCH
1759  *      Error if the cell for which the Token is being set can't be found
1760  *
1761  * \post
1762  *      Set the Tokens for a specific cell name, unless there is none set,
1763  *      then default to primary
1764  *
1765  */
1766 DECL_PIOCTL(PSetTokens)
1767 {
1768     afs_int32 i;
1769     register struct unixuser *tu;
1770     struct ClearToken clear;
1771     register struct cell *tcell;
1772     char *stp;
1773     char *cellName;
1774     int stLen;
1775     struct vrequest treq;
1776     afs_int32 flag, set_parent_pag = 0;
1777
1778     AFS_STATCNT(PSetTokens);
1779     if (!afs_resourceinit_flag) {
1780         return EIO;
1781     }
1782
1783     if (afs_pd_getInt(ain, &stLen) != 0)
1784         return EINVAL;
1785
1786     stp = afs_pd_where(ain);    /* remember where the ticket is */
1787     if (stLen < 0 || stLen > MAXKTCTICKETLEN)
1788         return EINVAL;          /* malloc may fail */
1789     if (afs_pd_skip(ain, stLen) != 0)
1790         return EINVAL;
1791
1792     if (afs_pd_getInt(ain, &i) != 0)
1793         return EINVAL;
1794     if (i != sizeof(struct ClearToken))
1795         return EINVAL;
1796
1797     if (afs_pd_getBytes(ain, &clear, sizeof(struct ClearToken)) !=0)
1798         return EINVAL;
1799
1800     if (clear.AuthHandle == -1)
1801         clear.AuthHandle = 999; /* more rxvab compat stuff */
1802
1803     if (afs_pd_remaining(ain) != 0) {
1804         /* still stuff left?  we've got primary flag and cell name.
1805          * Set these */
1806
1807         if (afs_pd_getInt(ain, &flag) != 0)
1808             return EINVAL;
1809
1810         /* some versions of gcc appear to need != 0 in order to get this
1811          * right */
1812         if ((flag & 0x8000) != 0) {     /* XXX Use Constant XXX */
1813             flag &= ~0x8000;
1814             set_parent_pag = 1;
1815         }
1816
1817         if (afs_pd_getStringPtr(ain, &cellName) != 0)
1818             return EINVAL;
1819
1820         /* rest is cell name, look it up */
1821         tcell = afs_GetCellByName(cellName, READ_LOCK);
1822         if (!tcell)
1823             goto nocell;
1824     } else {
1825         /* default to primary cell, primary id */
1826         flag = 1;               /* primary id */
1827         tcell = afs_GetPrimaryCell(READ_LOCK);
1828         if (!tcell)
1829             goto nocell;
1830     }
1831     i = tcell->cellNum;
1832     afs_PutCell(tcell, READ_LOCK);
1833     if (set_parent_pag) {
1834         afs_uint32 pag;
1835 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
1836 # if defined(AFS_DARWIN_ENV)
1837         afs_proc_t *p = current_proc(); /* XXX */
1838 # else
1839         afs_proc_t *p = curproc;        /* XXX */
1840 # endif
1841 # ifndef AFS_DARWIN80_ENV
1842         uprintf("Process %d (%s) tried to change pags in PSetTokens\n",
1843                 p->p_pid, p->p_comm);
1844 # endif
1845         if (!setpag(p, acred, -1, &pag, 1)) {
1846 #else
1847         if (!setpag(acred, -1, &pag, 1)) {
1848 #endif
1849             afs_InitReq(&treq, *acred);
1850             areq = &treq;
1851         }
1852     }
1853     /* now we just set the tokens */
1854     tu = afs_GetUser(areq->uid, i, WRITE_LOCK); /* i has the cell # */
1855     tu->vid = clear.ViceId;
1856     if (tu->stp != NULL) {
1857         afs_osi_Free(tu->stp, tu->stLen);
1858     }
1859     tu->stp = (char *)afs_osi_Alloc(stLen);
1860     if (tu->stp == NULL) {
1861         return ENOMEM;
1862     }
1863     tu->stLen = stLen;
1864     memcpy(tu->stp, stp, stLen);
1865     tu->ct = clear;
1866 #ifndef AFS_NOSTATS
1867     afs_stats_cmfullperf.authent.TicketUpdates++;
1868     afs_ComputePAGStats();
1869 #endif /* AFS_NOSTATS */
1870     tu->states |= UHasTokens;
1871     tu->states &= ~UTokensBad;
1872     afs_SetPrimary(tu, flag);
1873     tu->tokenTime = osi_Time();
1874     afs_ResetUserConns(tu);
1875     afs_PutUser(tu, WRITE_LOCK);
1876
1877     return 0;
1878
1879   nocell:
1880     {
1881         int t1;
1882         t1 = afs_initState;
1883         if (t1 < 101)
1884             return EIO;
1885         else
1886             return ESRCH;
1887     }
1888 }
1889
1890 /*!
1891  * VIOCGETVOLSTAT (4) - Get volume status
1892  *
1893  * \ingroup pioctl
1894  *
1895  * \param[in] ain       not in use
1896  * \param[out] aout     status of the volume
1897  *
1898  * \retval EINVAL       Error if some of the standard args aren't set
1899  *
1900  * \post
1901  *      The status of a volume (based on the FID of the volume), or an
1902  *      offline message /motd
1903  */
1904 DECL_PIOCTL(PGetVolumeStatus)
1905 {
1906     char volName[32];
1907     char *offLineMsg = afs_osi_Alloc(256);
1908     char *motd = afs_osi_Alloc(256);
1909     register struct afs_conn *tc;
1910     register afs_int32 code = 0;
1911     struct AFSFetchVolumeStatus volstat;
1912     char *Name;
1913     XSTATS_DECLS;
1914
1915     AFS_STATCNT(PGetVolumeStatus);
1916     if (!avc) {
1917         code = EINVAL;
1918         goto out;
1919     }
1920     Name = volName;
1921     do {
1922         tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK);
1923         if (tc) {
1924             XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_GETVOLUMESTATUS);
1925             RX_AFS_GUNLOCK();
1926             code =
1927                 RXAFS_GetVolumeStatus(tc->id, avc->f.fid.Fid.Volume, &volstat,
1928                                       &Name, &offLineMsg, &motd);
1929             RX_AFS_GLOCK();
1930             XSTATS_END_TIME;
1931         } else
1932             code = -1;
1933     } while (afs_Analyze
1934              (tc, code, &avc->f.fid, areq, AFS_STATS_FS_RPCIDX_GETVOLUMESTATUS,
1935               SHARED_LOCK, NULL));
1936
1937     if (code)
1938         goto out;
1939     /* Copy all this junk into msg->im_data, keeping track of the lengths. */
1940     if (afs_pd_putBytes(aout, &volstat, sizeof(VolumeStatus)) != 0)
1941         return E2BIG;
1942     if (afs_pd_putString(aout, volName) != 0)
1943         return E2BIG;
1944     if (afs_pd_putString(aout, offLineMsg) != 0)
1945         return E2BIG;
1946     if (afs_pd_putString(aout, motd) != 0)
1947         return E2BIG;
1948   out:
1949     afs_osi_Free(offLineMsg, 256);
1950     afs_osi_Free(motd, 256);
1951     return code;
1952 }
1953
1954 /*!
1955  * VIOCSETVOLSTAT (5) - Set volume status
1956  *
1957  * \ingroup pioctl
1958  *
1959  * \param[in] ain
1960  *      values to set the status at, offline message, message of the day,
1961  *      volume name, minimum quota, maximum quota
1962  * \param[out] aout
1963  *      status of a volume, offlines messages, minimum quota, maximumm quota
1964  *
1965  * \retval EINVAL
1966  *      Error if some of the standard args aren't set
1967  * \retval EROFS
1968  *      Error if the volume is read only, or a backup volume
1969  * \retval ENODEV
1970  *      Error if the volume can't be accessed
1971  * \retval E2BIG
1972  *      Error if the volume name, offline message, and motd are too big
1973  *
1974  * \post
1975  *      Set the status of a volume, including any offline messages,
1976  *      a minimum quota, and a maximum quota
1977  */
1978 DECL_PIOCTL(PSetVolumeStatus)
1979 {
1980     char *volName;
1981     char *offLineMsg;
1982     char *motd;
1983     register struct afs_conn *tc;
1984     register afs_int32 code = 0;
1985     struct AFSFetchVolumeStatus volstat;
1986     struct AFSStoreVolumeStatus storeStat;
1987     register struct volume *tvp;
1988     XSTATS_DECLS;
1989
1990     AFS_STATCNT(PSetVolumeStatus);
1991     if (!avc)
1992         return EINVAL;
1993
1994     tvp = afs_GetVolume(&avc->f.fid, areq, READ_LOCK);
1995     if (tvp) {
1996         if (tvp->states & (VRO | VBackup)) {
1997             afs_PutVolume(tvp, READ_LOCK);
1998             return EROFS;
1999         }
2000         afs_PutVolume(tvp, READ_LOCK);
2001     } else
2002         return ENODEV;
2003
2004
2005     if (afs_pd_getBytes(ain, &volstat, sizeof(AFSFetchVolumeStatus)) != 0)
2006         return EINVAL;
2007
2008     if (afs_pd_getStringPtr(ain, &volName) != 0)
2009         return EINVAL;
2010     if (strlen(volName) > 32)
2011         return E2BIG;
2012
2013     if (afs_pd_getStringPtr(ain, &offLineMsg) != 0)
2014         return EINVAL;
2015     if (strlen(offLineMsg) > 256)
2016         return E2BIG;
2017
2018     if (afs_pd_getStringPtr(ain, &motd) != 0)
2019         return EINVAL;
2020     if (strlen(motd) > 256)
2021         return E2BIG;
2022
2023     /* Done reading ... */
2024
2025     storeStat.Mask = 0;
2026     if (volstat.MinQuota != -1) {
2027         storeStat.MinQuota = volstat.MinQuota;
2028         storeStat.Mask |= AFS_SETMINQUOTA;
2029     }
2030     if (volstat.MaxQuota != -1) {
2031         storeStat.MaxQuota = volstat.MaxQuota;
2032         storeStat.Mask |= AFS_SETMAXQUOTA;
2033     }
2034     do {
2035         tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK);
2036         if (tc) {
2037             XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_SETVOLUMESTATUS);
2038             RX_AFS_GUNLOCK();
2039             code =
2040                 RXAFS_SetVolumeStatus(tc->id, avc->f.fid.Fid.Volume, &storeStat,
2041                                       volName, offLineMsg, motd);
2042             RX_AFS_GLOCK();
2043             XSTATS_END_TIME;
2044         } else
2045             code = -1;
2046     } while (afs_Analyze
2047              (tc, code, &avc->f.fid, areq, AFS_STATS_FS_RPCIDX_SETVOLUMESTATUS,
2048               SHARED_LOCK, NULL));
2049
2050     if (code)
2051         return code;
2052     /* we are sending parms back to make compat. with prev system.  should
2053      * change interface later to not ask for current status, just set new
2054      * status */
2055
2056     if (afs_pd_putBytes(aout, &volstat, sizeof(VolumeStatus)) != 0)
2057         return EINVAL;
2058     if (afs_pd_putString(aout, volName) != 0)
2059         return EINVAL;
2060     if (afs_pd_putString(aout, offLineMsg) != 0)
2061         return EINVAL;
2062     if (afs_pd_putString(aout, motd) != 0)
2063         return EINVAL;
2064
2065     return code;
2066 }
2067
2068 /*!
2069  * VIOCFLUSH (6) - Invalidate cache entry
2070  *
2071  * \ingroup pioctl
2072  *
2073  * \param[in] ain       not in use
2074  * \param[out] aout     not in use
2075  *
2076  * \retval EINVAL       Error if some of the standard args aren't set
2077  *
2078  * \post Flush any information the cache manager has on an entry
2079  */
2080 DECL_PIOCTL(PFlush)
2081 {
2082     AFS_STATCNT(PFlush);
2083     if (!avc)
2084         return EINVAL;
2085 #ifdef AFS_BOZONLOCK_ENV
2086     afs_BozonLock(&avc->pvnLock, avc);  /* Since afs_TryToSmush will do a pvn_vptrunc */
2087 #endif
2088     ObtainWriteLock(&avc->lock, 225);
2089     afs_ResetVCache(avc, *acred);
2090     ReleaseWriteLock(&avc->lock);
2091 #ifdef AFS_BOZONLOCK_ENV
2092     afs_BozonUnlock(&avc->pvnLock, avc);
2093 #endif
2094     return 0;
2095 }
2096
2097 /*!
2098  * VIOC_AFS_STAT_MT_PT (29) - Stat mount point
2099  *
2100  * \ingroup pioctl
2101  *
2102  * \param[in] ain
2103  *      the last component in a path, related to mountpoint that we're
2104  *      looking for information about
2105  * \param[out] aout
2106  *      volume, cell, link data
2107  *
2108  * \retval EINVAL       Error if some of the standard args aren't set
2109  * \retval ENOTDIR      Error if the 'mount point' argument isn't a directory
2110  * \retval EIO          Error if the link data can't be accessed
2111  *
2112  * \post Get the volume, and cell, as well as the link data for a mount point
2113  */
2114 DECL_PIOCTL(PNewStatMount)
2115 {
2116     register afs_int32 code;
2117     register struct vcache *tvc;
2118     register struct dcache *tdc;
2119     struct VenusFid tfid;
2120     char *bufp;
2121     char *name;
2122     struct sysname_info sysState;
2123     afs_size_t offset, len;
2124
2125     AFS_STATCNT(PNewStatMount);
2126     if (!avc)
2127         return EINVAL;
2128
2129     if (afs_pd_getStringPtr(ain, &name) != 0)
2130         return EINVAL;
2131
2132     code = afs_VerifyVCache(avc, areq);
2133     if (code)
2134         return code;
2135     if (vType(avc) != VDIR) {
2136         return ENOTDIR;
2137     }
2138     tdc = afs_GetDCache(avc, (afs_size_t) 0, areq, &offset, &len, 1);
2139     if (!tdc)
2140         return ENOENT;
2141     Check_AtSys(avc, name, &sysState, areq);
2142     ObtainReadLock(&tdc->lock);
2143     do {
2144         code = afs_dir_Lookup(tdc, sysState.name, &tfid.Fid);
2145     } while (code == ENOENT && Next_AtSys(avc, areq, &sysState));
2146     ReleaseReadLock(&tdc->lock);
2147     afs_PutDCache(tdc);         /* we're done with the data */
2148     bufp = sysState.name;
2149     if (code) {
2150         goto out;
2151     }
2152     tfid.Cell = avc->f.fid.Cell;
2153     tfid.Fid.Volume = avc->f.fid.Fid.Volume;
2154     if (!tfid.Fid.Unique && (avc->f.states & CForeign)) {
2155         tvc = afs_LookupVCache(&tfid, areq, NULL, avc, bufp);
2156     } else {
2157         tvc = afs_GetVCache(&tfid, areq, NULL, NULL);
2158     }
2159     if (!tvc) {
2160         code = ENOENT;
2161         goto out;
2162     }
2163     if (tvc->mvstat != 1) {
2164         afs_PutVCache(tvc);
2165         code = EINVAL;
2166         goto out;
2167     }
2168     ObtainWriteLock(&tvc->lock, 226);
2169     code = afs_HandleLink(tvc, areq);
2170     if (code == 0) {
2171         if (tvc->linkData) {
2172             if ((tvc->linkData[0] != '#') && (tvc->linkData[0] != '%'))
2173                 code = EINVAL;
2174             else {
2175                 /* we have the data */
2176                 if (afs_pd_putString(aout, tvc->linkData) != 0)
2177                     code = EINVAL;
2178             }
2179         } else
2180             code = EIO;
2181     }
2182     ReleaseWriteLock(&tvc->lock);
2183     afs_PutVCache(tvc);
2184   out:
2185     if (sysState.allocked)
2186         osi_FreeLargeSpace(bufp);
2187     return code;
2188 }
2189
2190 /*!
2191  * VIOCGETTOK (8) - Get authentication tokens
2192  *  
2193  * \ingroup pioctl
2194  *      
2195  * \param[in] ain       cellid to return tokens for
2196  * \param[out] aout     token
2197  * 
2198  * \retval EIO
2199  *      Error if the afs daemon hasn't started yet
2200  * \retval EDOM
2201  *      Error if the input parameter is out of the bounds of the available
2202  *      tokens
2203  * \retval ENOTCONN
2204  *      Error if there aren't tokens for this cell
2205  *  
2206  * \post
2207  *      If the input paramater exists, get the token that corresponds to
2208  *      the parameter value, if there is no token at this value, get the
2209  *      token for the first cell
2210  *
2211  * \notes "it's a weird interface (from comments in the code)"
2212  */
2213
2214 DECL_PIOCTL(PGetTokens)
2215 {
2216     register struct cell *tcell;
2217     register afs_int32 i;
2218     register struct unixuser *tu;
2219     afs_int32 iterator = 0;
2220     int newStyle;
2221     int code = E2BIG;
2222
2223     AFS_STATCNT(PGetTokens);
2224     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
2225         return EIO;             /* Inappropriate ioctl for device */
2226
2227     /* weird interface.  If input parameter is present, it is an integer and
2228      * we're supposed to return the parm'th tokens for this unix uid.
2229      * If not present, we just return tokens for cell 1.
2230      * If counter out of bounds, return EDOM.
2231      * If no tokens for the particular cell, return ENOTCONN.
2232      * Also, if this mysterious parm is present, we return, along with the
2233      * tokens, the primary cell indicator (an afs_int32 0) and the cell name
2234      * at the end, in that order.
2235      */
2236     newStyle = (afs_pd_remaining(ain) > 0);
2237     if (newStyle) {
2238         if (afs_pd_getInt(ain, &iterator) != 0)
2239             return EINVAL;
2240     }
2241     i = UHash(areq->uid);
2242     ObtainReadLock(&afs_xuser);
2243     for (tu = afs_users[i]; tu; tu = tu->next) {
2244         if (newStyle) {
2245             if (tu->uid == areq->uid && (tu->states & UHasTokens)) {
2246                 if (iterator-- == 0)
2247                     break;      /* are we done yet? */
2248             }
2249         } else {
2250             if (tu->uid == areq->uid && afs_IsPrimaryCellNum(tu->cell))
2251                 break;
2252         }
2253     }
2254     if (tu) {
2255         /*
2256          * No need to hold a read lock on each user entry
2257          */
2258         tu->refCount++;
2259     }
2260     ReleaseReadLock(&afs_xuser);
2261
2262     if (!tu) {
2263         return EDOM;
2264     }
2265     if (((tu->states & UHasTokens) == 0)
2266         || (tu->ct.EndTimestamp < osi_Time())) {
2267         tu->states |= (UTokensBad | UNeedsReset);
2268         afs_PutUser(tu, READ_LOCK);
2269         return ENOTCONN;
2270     }
2271     iterator = tu->stLen;       /* for compat, we try to return 56 byte tix if they fit */
2272     if (iterator < 56)
2273         iterator = 56;          /* # of bytes we're returning */
2274
2275     if (afs_pd_putInt(aout, iterator) != 0)
2276         goto out;
2277     if (afs_pd_putBytes(aout, tu->stp, tu->stLen) != 0)
2278         goto out;
2279     if (tu->stLen < 56) {
2280         /* Tokens are always 56 bytes or larger */
2281         if (afs_pd_skip(aout, iterator - tu->stLen) != 0) {
2282             goto out;
2283         }
2284     }
2285
2286     if (afs_pd_putInt(aout, sizeof(struct ClearToken)) != 0)
2287         goto out;
2288     if (afs_pd_putBytes(aout, &tu->ct, sizeof(struct ClearToken)) != 0)
2289         goto out;
2290
2291     if (newStyle) {
2292         /* put out primary id and cell name, too */
2293         iterator = (tu->states & UPrimary ? 1 : 0);
2294         if (afs_pd_putInt(aout, iterator) != 0)
2295             goto out;
2296         tcell = afs_GetCell(tu->cell, READ_LOCK);
2297         if (tcell) {
2298             if (afs_pd_putString(aout, tcell->cellName) != 0)
2299                 goto out;
2300             afs_PutCell(tcell, READ_LOCK);
2301         } else
2302             if (afs_pd_putString(aout, "") != 0)
2303                 goto out;
2304     }
2305     /* Got here, all is good */
2306     code = 0;
2307 out:
2308     afs_PutUser(tu, READ_LOCK);
2309     return code;
2310 }
2311
2312 /*!
2313  * VIOCUNLOG (9) - Invalidate tokens
2314  *
2315  * \ingroup pioctl
2316  *
2317  * \param[in] ain       not in use
2318  * \param[out] aout     not in use
2319  *
2320  * \retval EIO  Error if the afs daemon hasn't been started yet
2321  *
2322  * \post remove tokens from a user, specified by the user id
2323  *
2324  * \notes sets the token's time to 0, which then causes it to be removed
2325  * \notes Unlog is the same as un-pag in OpenAFS
2326  */
2327 DECL_PIOCTL(PUnlog)
2328 {
2329     register afs_int32 i;
2330     register struct unixuser *tu;
2331
2332     AFS_STATCNT(PUnlog);
2333     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
2334         return EIO;             /* Inappropriate ioctl for device */
2335
2336     i = UHash(areq->uid);
2337     ObtainWriteLock(&afs_xuser, 227);
2338     for (tu = afs_users[i]; tu; tu = tu->next) {
2339         if (tu->uid == areq->uid) {
2340             tu->vid = UNDEFVID;
2341             tu->states &= ~UHasTokens;
2342             /* security is not having to say you're sorry */
2343             memset(&tu->ct, 0, sizeof(struct ClearToken));
2344             tu->refCount++;
2345             ReleaseWriteLock(&afs_xuser);
2346             /* We have to drop the lock over the call to afs_ResetUserConns,
2347              * since it obtains the afs_xvcache lock.  We could also keep
2348              * the lock, and modify ResetUserConns to take parm saying we
2349              * obtained the lock already, but that is overkill.  By keeping
2350              * the "tu" pointer held over the released lock, we guarantee
2351              * that we won't lose our place, and that we'll pass over
2352              * every user conn that existed when we began this call.
2353              */
2354             afs_ResetUserConns(tu);
2355             tu->refCount--;
2356             ObtainWriteLock(&afs_xuser, 228);
2357 #ifdef UKERNEL
2358             /* set the expire times to 0, causes
2359              * afs_GCUserData to remove this entry
2360              */
2361             tu->ct.EndTimestamp = 0;
2362             tu->tokenTime = 0;
2363 #endif /* UKERNEL */
2364         }
2365     }
2366     ReleaseWriteLock(&afs_xuser);
2367     return 0;
2368 }
2369
2370 /*!
2371  * VIOC_AFS_MARINER_HOST (32) - Get/set mariner (cache manager monitor) host
2372  *
2373  * \ingroup pioctl
2374  *
2375  * \param[in] ain       host address to be set
2376  * \param[out] aout     old host address
2377  *
2378  * \post
2379  *      depending on whether or not a variable is set, either get the host
2380  *      for the cache manager monitor, or set the old address and give it
2381  *      a new address
2382  *
2383  * \notes Errors turn off mariner
2384  */
2385 DECL_PIOCTL(PMariner)
2386 {
2387     afs_int32 newHostAddr;
2388     afs_int32 oldHostAddr;
2389
2390     AFS_STATCNT(PMariner);
2391     if (afs_mariner)
2392         memcpy((char *)&oldHostAddr, (char *)&afs_marinerHost,
2393                sizeof(afs_int32));
2394     else
2395         oldHostAddr = 0xffffffff;       /* disabled */
2396
2397     if (afs_pd_getInt(ain, &newHostAddr) != 0)
2398         return EINVAL;
2399
2400     if (newHostAddr == 0xffffffff) {
2401         /* disable mariner operations */
2402         afs_mariner = 0;
2403     } else if (newHostAddr) {
2404         afs_mariner = 1;
2405         afs_marinerHost = newHostAddr;
2406     }
2407
2408     if (afs_pd_putInt(aout, oldHostAddr) != 0)
2409         return E2BIG;
2410
2411     return 0;
2412 }
2413
2414 /*!
2415  * VIOCCKSERV (10) - Check that servers are up
2416  *
2417  * \ingroup pioctl
2418  *
2419  * \param[in] ain       name of the cell
2420  * \param[out] aout     current down server list
2421  *
2422  * \retval EIO          Error if the afs daemon hasn't started yet
2423  * \retval EACCES       Error if the user doesn't have super-user credentials
2424  * \retval ENOENT       Error if we are unable to obtain the cell
2425  *
2426  * \post
2427  *      Either a fast check (where it doesn't contact servers) or a
2428  *      local check (checks local cell only)
2429  */
2430 DECL_PIOCTL(PCheckServers)
2431 {
2432     register int i;
2433     register struct server *ts;
2434     afs_int32 temp;
2435     char *cellName = NULL;
2436     struct cell *cellp;
2437     struct chservinfo *pcheck;
2438
2439     AFS_STATCNT(PCheckServers);
2440
2441     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
2442         return EIO;             /* Inappropriate ioctl for device */
2443
2444     /* This is tricky, because we need to peak at the datastream to see
2445      * what we're getting. For now, let's cheat. */
2446
2447     /* ain contains either an int32 or a string */
2448     if (ain->remaining == 0)
2449         return EINVAL;
2450
2451     if (*(afs_int32 *)ain->ptr == 0x12345678) { /* For afs3.3 version */
2452         pcheck = afs_pd_inline(ain, sizeof(*pcheck));
2453         if (pcheck == NULL)
2454             return EINVAL;
2455
2456         if (pcheck->tinterval >= 0) {
2457             if (afs_pd_putInt(aout, afs_probe_interval) != 0)
2458                 return E2BIG;
2459             if (pcheck->tinterval > 0) {
2460                 if (!afs_osi_suser(*acred))
2461                     return EACCES;
2462                 afs_probe_interval = pcheck->tinterval;
2463             }
2464             return 0;
2465         }
2466         temp = pcheck->tflags;
2467         if (pcheck->tsize)
2468             cellName = pcheck->tbuffer;
2469     } else {                    /* For pre afs3.3 versions */
2470         if (afs_pd_getInt(ain, &temp) != 0)
2471             return EINVAL;
2472         if (afs_pd_remaining(ain) > 0) {
2473             if (afs_pd_getStringPtr(ain, &cellName) != 0)
2474                 return EINVAL;
2475         }
2476     }
2477
2478     /*
2479      * 1: fast check, don't contact servers.
2480      * 2: local cell only.
2481      */
2482     if (cellName) {
2483         /* have cell name, too */
2484         cellp = afs_GetCellByName(cellName, READ_LOCK);
2485         if (!cellp)
2486             return ENOENT;
2487     } else
2488         cellp = NULL;
2489     if (!cellp && (temp & 2)) {
2490         /* use local cell */
2491         cellp = afs_GetPrimaryCell(READ_LOCK);
2492     }
2493     if (!(temp & 1)) {          /* if not fast, call server checker routine */
2494         afs_CheckServers(1, cellp);     /* check down servers */
2495         afs_CheckServers(0, cellp);     /* check up servers */
2496     }
2497     /* now return the current down server list */
2498     ObtainReadLock(&afs_xserver);
2499     for (i = 0; i < NSERVERS; i++) {
2500         for (ts = afs_servers[i]; ts; ts = ts->next) {
2501             if (cellp && ts->cell != cellp)
2502                 continue;       /* cell spec'd and wrong */
2503             if ((ts->flags & SRVR_ISDOWN)
2504                 && ts->addr->sa_portal != ts->cell->vlport) {
2505                 afs_pd_putInt(aout, ts->addr->sa_ip);
2506             }
2507         }
2508     }
2509     ReleaseReadLock(&afs_xserver);
2510     if (cellp)
2511         afs_PutCell(cellp, READ_LOCK);
2512     return 0;
2513 }
2514
2515 /*!
2516  * VIOCCKBACK (11) - Check backup volume mappings
2517  *
2518  * \ingroup pioctl
2519  *
2520  * \param[in] ain       not in use
2521  * \param[out] aout     not in use
2522  *
2523  * \retval EIO          Error if the afs daemon hasn't started yet
2524  *
2525  * \post
2526  *      Check the root volume, and then check the names if the volume
2527  *      check variable is set to force, has expired, is busy, or if
2528  *      the mount points variable is set
2529  */
2530 DECL_PIOCTL(PCheckVolNames)
2531 {
2532     AFS_STATCNT(PCheckVolNames);
2533     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
2534         return EIO;             /* Inappropriate ioctl for device */
2535
2536     afs_CheckRootVolume();
2537     afs_CheckVolumeNames(AFS_VOLCHECK_FORCE | AFS_VOLCHECK_EXPIRED |
2538                          AFS_VOLCHECK_BUSY | AFS_VOLCHECK_MTPTS);
2539     return 0;
2540 }
2541
2542 /*!
2543  * VIOCCKCONN (12) - Check connections for a user
2544  *
2545  * \ingroup pioctl
2546  *
2547  * \param[in] ain       not in use
2548  * \param[out] aout     not in use
2549  *
2550  * \retval EACCESS
2551  *      Error if no user is specififed, the user has no tokens set,
2552  *      or if the user's tokens are bad
2553  *
2554  * \post
2555  *      check to see if a user has the correct authentication.
2556  *      If so, allow access.
2557  *
2558  * \notes Check the connections to all the servers specified
2559  */
2560 DECL_PIOCTL(PCheckAuth)
2561 {
2562     int i;
2563     struct srvAddr *sa;
2564     struct afs_conn *tc;
2565     struct unixuser *tu;
2566     afs_int32 retValue;
2567
2568     AFS_STATCNT(PCheckAuth);
2569     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
2570         return EIO;             /* Inappropriate ioctl for device */
2571
2572     retValue = 0;
2573     tu = afs_GetUser(areq->uid, 1, READ_LOCK);  /* check local cell authentication */
2574     if (!tu)
2575         retValue = EACCES;
2576     else {
2577         /* we have a user */
2578         ObtainReadLock(&afs_xsrvAddr);
2579         ObtainReadLock(&afs_xconn);
2580
2581         /* any tokens set? */
2582         if ((tu->states & UHasTokens) == 0)
2583             retValue = EACCES;
2584         /* all connections in cell 1 working? */
2585         for (i = 0; i < NSERVERS; i++) {
2586             for (sa = afs_srvAddrs[i]; sa; sa = sa->next_bkt) {
2587                 for (tc = sa->conns; tc; tc = tc->next) {
2588                     if (tc->user == tu && (tu->states & UTokensBad))
2589                         retValue = EACCES;
2590                 }
2591             }
2592         }
2593         ReleaseReadLock(&afs_xsrvAddr);
2594         ReleaseReadLock(&afs_xconn);
2595         afs_PutUser(tu, READ_LOCK);
2596     }
2597     if (afs_pd_putInt(aout, retValue) != 0)
2598         return E2BIG;
2599     return 0;
2600 }
2601
2602 static int
2603 Prefetch(uparmtype apath, struct afs_ioctl *adata, int afollow,
2604          afs_ucred_t *acred)
2605 {
2606     register char *tp;
2607     register afs_int32 code;
2608 #if defined(AFS_SGI61_ENV) || defined(AFS_SUN57_ENV) || defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
2609     size_t bufferSize;
2610 #else
2611     u_int bufferSize;
2612 #endif
2613
2614     AFS_STATCNT(Prefetch);
2615     if (!apath)
2616         return EINVAL;
2617     tp = osi_AllocLargeSpace(1024);
2618     AFS_COPYINSTR(apath, tp, 1024, &bufferSize, code);
2619     if (code) {
2620         osi_FreeLargeSpace(tp);
2621         return code;
2622     }
2623     if (afs_BBusy()) {          /* do this as late as possible */
2624         osi_FreeLargeSpace(tp);
2625         return EWOULDBLOCK;     /* pretty close */
2626     }
2627     afs_BQueue(BOP_PATH, (struct vcache *)0, 0, 0, acred, (afs_size_t) 0,
2628                (afs_size_t) 0, tp);
2629     return 0;
2630 }
2631
2632 /*!
2633  * VIOCWHEREIS (14) - Find out where a volume is located
2634  *
2635  * \ingroup pioctl
2636  *
2637  * \param[in] ain       not in use
2638  * \param[out] aout     volume location
2639  *
2640  * \retval EINVAL       Error if some of the default arguments don't exist
2641  * \retval ENODEV       Error if there is no such volume
2642  *
2643  * \post fine a volume, based on a volume file id
2644  *
2645  * \notes check each of the servers specified
2646  */
2647 DECL_PIOCTL(PFindVolume)
2648 {
2649     register struct volume *tvp;
2650     register struct server *ts;
2651     register afs_int32 i;
2652     int code = 0;
2653
2654     AFS_STATCNT(PFindVolume);
2655     if (!avc)
2656         return EINVAL;
2657     tvp = afs_GetVolume(&avc->f.fid, areq, READ_LOCK);
2658     if (!tvp)
2659         return ENODEV;
2660
2661     for (i = 0; i < AFS_MAXHOSTS; i++) {
2662         ts = tvp->serverHost[i];
2663         if (!ts)
2664             break;
2665         if (afs_pd_putInt(aout, ts->addr->sa_ip) != 0) {
2666             code = E2BIG;
2667             goto out;
2668         }
2669     }
2670     if (i < AFS_MAXHOSTS) {
2671         /* still room for terminating NULL, add it on */
2672         if (afs_pd_putInt(aout, 0) != 0) {
2673             code = E2BIG;
2674             goto out;
2675         }
2676     }
2677 out:
2678     afs_PutVolume(tvp, READ_LOCK);
2679     return code;
2680 }
2681
2682 /*!
2683  * VIOCACCESS (20) - Access using PRS_FS bits
2684  *
2685  * \ingroup pioctl
2686  *
2687  * \param[in] ain       PRS_FS bits
2688  * \param[out] aout     not in use
2689  *
2690  * \retval EINVAL       Error if some of the initial arguments aren't set
2691  * \retval EACCES       Error if access is denied
2692  *
2693  * \post check to make sure access is allowed
2694  */
2695 DECL_PIOCTL(PViceAccess)
2696 {
2697     register afs_int32 code;
2698     afs_int32 temp;
2699
2700     AFS_STATCNT(PViceAccess);
2701     if (!avc)
2702         return EINVAL;
2703
2704     code = afs_VerifyVCache(avc, areq);
2705     if (code)
2706         return code;
2707
2708     if (afs_pd_getInt(ain, &temp) != 0)
2709         return EINVAL;
2710
2711     code = afs_AccessOK(avc, temp, areq, CHECK_MODE_BITS);
2712     if (code)
2713         return 0;
2714     else
2715         return EACCES;
2716 }
2717
2718 /*!
2719  * VIOC_GETPAG (13) - Get PAG value
2720  *
2721  * \ingroup pioctl
2722  *
2723  * \param[in] ain       not in use
2724  * \param[out] aout     PAG value or NOPAG
2725  *
2726  * \post get PAG value for the caller's cred
2727  */
2728 DECL_PIOCTL(PGetPAG)
2729 {
2730     afs_int32 pag;
2731
2732     pag = PagInCred(*acred);
2733
2734     return afs_pd_putInt(aout, pag);
2735 }
2736
2737 DECL_PIOCTL(PPrecache)
2738 {
2739     afs_int32 newValue;
2740
2741     /*AFS_STATCNT(PPrecache);*/
2742     if (!afs_osi_suser(*acred))
2743         return EACCES;
2744
2745     if (afs_pd_getInt(ain, &newValue) != 0)
2746         return EINVAL;
2747
2748     afs_preCache = newValue*1024;
2749     return 0;
2750 }
2751
2752 /*!
2753  * VIOCSETCACHESIZE (24) - Set venus cache size in 1000 units
2754  *
2755  * \ingroup pioctl
2756  *
2757  * \param[in] ain       the size the venus cache should be set to
2758  * \param[out] aout     not in use
2759  *
2760  * \retval EACCES       Error if the user doesn't have super-user credentials
2761  * \retval EROFS        Error if the cache is set to be in memory
2762  *
2763  * \post
2764  *      Set the cache size based on user input.  If no size is given,
2765  *      set it to the default OpenAFS cache size.
2766  *
2767  * \notes
2768  *      recompute the general cache parameters for every single block allocated
2769  */
2770 DECL_PIOCTL(PSetCacheSize)
2771 {
2772     afs_int32 newValue;
2773     int waitcnt = 0;
2774
2775     AFS_STATCNT(PSetCacheSize);
2776
2777     if (!afs_osi_suser(*acred))
2778         return EACCES;
2779     /* too many things are setup initially in mem cache version */
2780     if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
2781         return EROFS;
2782     if (afs_pd_getInt(ain, &newValue) != 0)
2783         return EINVAL;
2784     if (newValue == 0)
2785         afs_cacheBlocks = afs_stats_cmperf.cacheBlocksOrig;
2786     else {
2787         if (newValue < afs_min_cache)
2788             afs_cacheBlocks = afs_min_cache;
2789         else
2790             afs_cacheBlocks = newValue;
2791     }
2792     afs_stats_cmperf.cacheBlocksTotal = afs_cacheBlocks;
2793     afs_ComputeCacheParms();    /* recompute basic cache parameters */
2794     afs_MaybeWakeupTruncateDaemon();
2795     while (waitcnt++ < 100 && afs_cacheBlocks < afs_blocksUsed) {
2796         afs_osi_Wait(1000, 0, 0);
2797         afs_MaybeWakeupTruncateDaemon();
2798     }
2799     return 0;
2800 }
2801
2802 #define MAXGCSTATS      16
2803 /*!
2804  * VIOCGETCACHEPARMS (40) - Get cache stats
2805  *
2806  * \ingroup pioctl
2807  *
2808  * \param[in] ain       afs index flags
2809  * \param[out] aout     cache blocks, blocks used, blocks files (in an array)
2810  *
2811  * \post Get the cache blocks, and how many of the cache blocks there are
2812  */
2813 DECL_PIOCTL(PGetCacheSize)
2814 {
2815     afs_int32 results[MAXGCSTATS];
2816     afs_int32 flags;
2817     register struct dcache * tdc;
2818     int i, size;
2819     
2820     AFS_STATCNT(PGetCacheSize);
2821
2822     if (afs_pd_remaining(ain) == sizeof(afs_int32)) {
2823         afs_pd_getInt(ain, &flags); /* can't error, we just checked size */
2824     } else if (afs_pd_remaining(ain) == 0) {
2825         flags = 0;
2826     } else {
2827         return EINVAL;
2828     }
2829     
2830     memset(results, 0, sizeof(results));
2831     results[0] = afs_cacheBlocks;
2832     results[1] = afs_blocksUsed;
2833     results[2] = afs_cacheFiles;
2834     
2835     if (1 == flags){
2836         for (i = 0; i < afs_cacheFiles; i++) {
2837             if (afs_indexFlags[i] & IFFree) results[3]++;
2838         }
2839     } else if (2 == flags){
2840         for (i = 0; i < afs_cacheFiles; i++) {
2841             if (afs_indexFlags[i] & IFFree) results[3]++;
2842             if (afs_indexFlags[i] & IFEverUsed) results[4]++;
2843             if (afs_indexFlags[i] & IFDataMod) results[5]++;
2844             if (afs_indexFlags[i] & IFDirtyPages) results[6]++;
2845             if (afs_indexFlags[i] & IFAnyPages) results[7]++;
2846             if (afs_indexFlags[i] & IFDiscarded) results[8]++;
2847
2848             tdc = afs_indexTable[i];
2849             if (tdc){
2850                 results[9]++;
2851                 size = tdc->validPos;
2852                 if ( 0 < size && size < (1<<12) ) results[10]++;
2853                 else if (size < (1<<14) ) results[11]++;
2854                 else if (size < (1<<16) ) results[12]++;
2855                 else if (size < (1<<18) ) results[13]++;
2856                 else if (size < (1<<20) ) results[14]++;
2857                 else if (size >= (1<<20) ) results[15]++;
2858             }
2859         }
2860     }
2861     return afs_pd_putBytes(aout, results, sizeof(results));
2862 }
2863
2864 /*!
2865  * VIOCFLUSHCB (25) - Flush callback only
2866  *
2867  * \ingroup pioctl
2868  *
2869  * \param[in] ain       not in use
2870  * \param[out] aout     not in use
2871  *
2872  * \retval EINVAL       Error if some of the standard args aren't set
2873  * \retval 0            0 returned if the volume is set to read-only
2874  *
2875  * \post
2876  *      Flushes callbacks, by setting the length of callbacks to one,
2877  *      setting the next callback to be sent to the CB_DROPPED value,
2878  *      and then dequeues everything else.
2879  */
2880 DECL_PIOCTL(PRemoveCallBack)
2881 {
2882     register struct afs_conn *tc;
2883     register afs_int32 code = 0;
2884     struct AFSCallBack CallBacks_Array[1];
2885     struct AFSCBFids theFids;
2886     struct AFSCBs theCBs;
2887     XSTATS_DECLS;
2888
2889     AFS_STATCNT(PRemoveCallBack);
2890     if (!avc)
2891         return EINVAL;
2892     if (avc->f.states & CRO)
2893         return 0;               /* read-only-ness can't change */
2894     ObtainWriteLock(&avc->lock, 229);
2895     theFids.AFSCBFids_len = 1;
2896     theCBs.AFSCBs_len = 1;
2897     theFids.AFSCBFids_val = (struct AFSFid *)&avc->f.fid.Fid;
2898     theCBs.AFSCBs_val = CallBacks_Array;
2899     CallBacks_Array[0].CallBackType = CB_DROPPED;
2900     if (avc->callback) {
2901         do {
2902             tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK);
2903             if (tc) {
2904                 XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_GIVEUPCALLBACKS);
2905                 RX_AFS_GUNLOCK();
2906                 code = RXAFS_GiveUpCallBacks(tc->id, &theFids, &theCBs);
2907                 RX_AFS_GLOCK();
2908                 XSTATS_END_TIME;
2909             }
2910             /* don't set code on failure since we wouldn't use it */
2911         } while (afs_Analyze
2912                  (tc, code, &avc->f.fid, areq,
2913                   AFS_STATS_FS_RPCIDX_GIVEUPCALLBACKS, SHARED_LOCK, NULL));
2914
2915         ObtainWriteLock(&afs_xcbhash, 457);
2916         afs_DequeueCallback(avc);
2917         avc->callback = 0;
2918         avc->f.states &= ~(CStatd | CUnique);
2919         ReleaseWriteLock(&afs_xcbhash);
2920         if (avc->f.fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2921             osi_dnlc_purgedp(avc);
2922     }
2923     ReleaseWriteLock(&avc->lock);
2924     return 0;
2925 }
2926
2927 /*!
2928  * VIOCNEWCELL (26) - Configure new cell
2929  *
2930  * \ingroup pioctl
2931  *
2932  * \param[in] ain
2933  *      the name of the cell, the hosts that will be a part of the cell,
2934  *      whether or not it's linked with another cell, the other cell it's
2935  *      linked with, the file server port, and the volume server port
2936  * \param[out] aout
2937  *      not in use
2938  *
2939  * \retval EIO          Error if the afs daemon hasn't started yet
2940  * \retval EACCES       Error if the user doesn't have super-user cedentials
2941  * \retval EINVAL       Error if some 'magic' var doesn't have a certain bit set
2942  *
2943  * \post creates a new cell
2944  */
2945 DECL_PIOCTL(PNewCell)
2946 {
2947     afs_int32 cellHosts[AFS_MAXCELLHOSTS], magic = 0;
2948     char *newcell = NULL;
2949     char *linkedcell = NULL;
2950     afs_int32 code, ls;
2951     afs_int32 linkedstate = 0;
2952     afs_int32 fsport = 0, vlport = 0;
2953     int skip;
2954
2955     AFS_STATCNT(PNewCell);
2956     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
2957         return EIO;             /* Inappropriate ioctl for device */
2958
2959     if (!afs_osi_suser(*acred))
2960         return EACCES;
2961
2962     if (afs_pd_getInt(ain, &magic) != 0)
2963         return EINVAL;
2964     if (magic != 0x12345678)
2965         return EINVAL;
2966
2967     /* A 3.4 fs newcell command will pass an array of AFS_MAXCELLHOSTS
2968      * server addresses while the 3.5 fs newcell command passes
2969      * AFS_MAXHOSTS. To figure out which is which, check if the cellname
2970      * is good.
2971      *
2972      * This whole logic is bogus, because it relies on the newer command
2973      * sending its 12th address as 0.
2974      */
2975     if ((afs_pd_remaining(ain) < AFS_MAXCELLHOSTS +3) * sizeof(afs_int32))
2976         return EINVAL;
2977
2978     newcell = afs_pd_where(ain) + (AFS_MAXCELLHOSTS + 3) * sizeof(afs_int32);
2979     if (newcell[0] != '\0') {
2980         skip = 0;
2981     } else {
2982         skip = AFS_MAXHOSTS - AFS_MAXCELLHOSTS;
2983     }
2984
2985     /* AFS_MAXCELLHOSTS (=8) is less than AFS_MAXHOSTS (=13) */
2986     if (afs_pd_getBytes(ain, &cellHosts,
2987                         AFS_MAXCELLHOSTS * sizeof(afs_int32)) != 0)
2988         return EINVAL;
2989     if (afs_pd_skip(ain, skip * sizeof(afs_int32)) !=0)
2990         return EINVAL;
2991
2992     if (afs_pd_getInt(ain, &fsport) != 0)
2993         return EINVAL;
2994     if (fsport < 1024)
2995         fsport = 0;             /* Privileged ports not allowed */
2996
2997     if (afs_pd_getInt(ain, &vlport) != 0)
2998         return EINVAL;
2999     if (vlport < 1024)
3000         vlport = 0;             /* Privileged ports not allowed */
3001
3002     if (afs_pd_getInt(ain, &ls) != 0)
3003         return EINVAL;
3004
3005     if (afs_pd_getStringPtr(ain, &newcell) != 0)
3006         return EINVAL;
3007
3008     if (ls & 1) {
3009         if (afs_pd_getStringPtr(ain, &linkedcell) != 0)
3010             return EINVAL;
3011         linkedstate |= CLinkedCell;
3012     }
3013
3014     linkedstate |= CNoSUID;     /* setuid is disabled by default for fs newcell */
3015     code =
3016         afs_NewCell(newcell, cellHosts, linkedstate, linkedcell, fsport,
3017                     vlport, (int)0);
3018     return code;
3019 }
3020
3021 DECL_PIOCTL(PNewAlias)
3022 {
3023     /* create a new cell alias */
3024     char *realName, *aliasName;
3025
3026     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
3027         return EIO;             /* Inappropriate ioctl for device */
3028
3029     if (!afs_osi_suser(*acred))
3030         return EACCES;
3031
3032     if (afs_pd_getStringPtr(ain, &aliasName) != 0)
3033         return EINVAL;
3034     if (afs_pd_getStringPtr(ain, &realName) != 0)
3035         return EINVAL;
3036
3037     return afs_NewCellAlias(aliasName, realName);
3038 }
3039
3040 /*!
3041  * VIOCGETCELL (27) - Get cell info
3042  *
3043  * \ingroup pioctl
3044  *
3045  * \param[in] ain       The cell index of a specific cell
3046  * \param[out] aout     list of servers in the cell
3047  *
3048  * \retval EIO          Error if the afs daemon hasn't started yet
3049  * \retval EDOM         Error if there is no cell asked about
3050  *
3051  * \post Lists the cell's server names and and addresses
3052  */
3053 DECL_PIOCTL(PListCells)
3054 {
3055     afs_int32 whichCell;
3056     register struct cell *tcell = 0;
3057     register afs_int32 i;
3058     int code;
3059
3060     AFS_STATCNT(PListCells);
3061     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
3062         return EIO;             /* Inappropriate ioctl for device */
3063
3064     if (afs_pd_getInt(ain, &whichCell) != 0)
3065         return EINVAL;
3066
3067     tcell = afs_GetCellByIndex(whichCell, READ_LOCK);
3068     if (!tcell)
3069         return EDOM;
3070
3071     code = E2BIG;
3072
3073     for (i = 0; i < AFS_MAXCELLHOSTS; i++) {
3074         if (tcell->cellHosts[i] == 0)
3075             break;
3076         if (afs_pd_putInt(aout, tcell->cellHosts[i]->addr->sa_ip) != 0)
3077             goto out;
3078     }
3079     for (;i < AFS_MAXCELLHOSTS; i++) {
3080         if (afs_pd_putInt(aout, 0) != 0)
3081             goto out;
3082     }
3083     if (afs_pd_putString(aout, tcell->cellName) != 0)
3084         goto out;
3085     code = 0;
3086
3087 out:
3088     afs_PutCell(tcell, READ_LOCK);
3089     return code;
3090 }
3091
3092 DECL_PIOCTL(PListAliases)
3093 {
3094     afs_int32 whichAlias;
3095     register struct cell_alias *tcalias = 0;
3096     int code;
3097
3098     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
3099         return EIO;             /* Inappropriate ioctl for device */
3100
3101     if (afs_pd_getInt(ain, &whichAlias) != 0)
3102         return EINVAL;
3103
3104     tcalias = afs_GetCellAlias(whichAlias);
3105     if (tcalias == NULL)
3106         return EDOM;
3107
3108     code = E2BIG;
3109     if (afs_pd_putString(aout, tcalias->alias) != 0)
3110         goto out;
3111     if (afs_pd_putString(aout, tcalias->cell) != 0)
3112         goto out;
3113
3114     code = 0;
3115 out:
3116     afs_PutCellAlias(tcalias);
3117     return code;
3118 }
3119
3120 /*!
3121  * VIOC_AFS_DELETE_MT_PT (28) - Delete mount point
3122  *
3123  * \ingroup pioctl
3124  *
3125  * \param[in] ain       the name of the file in this dir to remove
3126  * \param[out] aout     not in use
3127  *
3128  * \retval EINVAL
3129  *      Error if some of the standard args aren't set
3130  * \retval ENOTDIR
3131  *      Error if the argument to remove is not a directory
3132  * \retval ENOENT
3133  *      Error if there is no cache to remove the mount point from or
3134  *      if a vcache doesn't exist
3135  *
3136  * \post
3137  *      Ensure that everything is OK before deleting the mountpoint.
3138  *      If not, don't delete.  Delete a mount point based on a file id.
3139  */
3140 DECL_PIOCTL(PRemoveMount)
3141 {
3142     register afs_int32 code;
3143     char *bufp;
3144     char *name;
3145     struct sysname_info sysState;
3146     afs_size_t offset, len;
3147     register struct afs_conn *tc;
3148     register struct dcache *tdc;
3149     register struct vcache *tvc;
3150     struct AFSFetchStatus OutDirStatus;
3151     struct VenusFid tfid;
3152     struct AFSVolSync tsync;
3153     XSTATS_DECLS;
3154
3155     /* "ain" is the name of the file in this dir to remove */
3156
3157     AFS_STATCNT(PRemoveMount);
3158     if (!avc)
3159         return EINVAL;
3160     if (afs_pd_getStringPtr(ain, &name) != 0)
3161         return EINVAL;
3162
3163     code = afs_VerifyVCache(avc, areq);
3164     if (code)
3165         return code;
3166     if (vType(avc) != VDIR)
3167         return ENOTDIR;
3168
3169     tdc = afs_GetDCache(avc, (afs_size_t) 0, areq, &offset, &len, 1);   /* test for error below */
3170     if (!tdc)
3171         return ENOENT;
3172     Check_AtSys(avc, name, &sysState, areq);
3173     ObtainReadLock(&tdc->lock);
3174     do {
3175         code = afs_dir_Lookup(tdc, sysState.name, &tfid.Fid);
3176     } while (code == ENOENT && Next_AtSys(avc, areq, &sysState));
3177     ReleaseReadLock(&tdc->lock);
3178     bufp = sysState.name;
3179     if (code) {
3180         afs_PutDCache(tdc);
3181         goto out;
3182     }
3183     tfid.Cell = avc->f.fid.Cell;
3184     tfid.Fid.Volume = avc->f.fid.Fid.Volume;
3185     if (!tfid.Fid.Unique && (avc->f.states & CForeign)) {
3186         tvc = afs_LookupVCache(&tfid, areq, NULL, avc, bufp);
3187     } else {
3188         tvc = afs_GetVCache(&tfid, areq, NULL, NULL);
3189     }
3190     if (!tvc) {
3191         code = ENOENT;
3192         afs_PutDCache(tdc);
3193         goto out;
3194     }
3195     if (tvc->mvstat != 1) {
3196         afs_PutDCache(tdc);
3197         afs_PutVCache(tvc);
3198         code = EINVAL;
3199         goto out;
3200     }
3201     ObtainWriteLock(&tvc->lock, 230);
3202     code = afs_HandleLink(tvc, areq);
3203     if (!code) {
3204         if (tvc->linkData) {
3205             if ((tvc->linkData[0] != '#') && (tvc->linkData[0] != '%'))
3206                 code = EINVAL;
3207         } else
3208             code = EIO;
3209     }
3210     ReleaseWriteLock(&tvc->lock);
3211     osi_dnlc_purgedp(tvc);
3212     afs_PutVCache(tvc);
3213     if (code) {
3214         afs_PutDCache(tdc);
3215         goto out;
3216     }
3217     ObtainWriteLock(&avc->lock, 231);
3218     osi_dnlc_remove(avc, bufp, tvc);
3219     do {
3220         tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK);
3221         if (tc) {
3222             XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_REMOVEFILE);
3223             RX_AFS_GUNLOCK();
3224             code =
3225                 RXAFS_RemoveFile(tc->id, (struct AFSFid *)&avc->f.fid.Fid, bufp,
3226                                  &OutDirStatus, &tsync);
3227             RX_AFS_GLOCK();
3228             XSTATS_END_TIME;
3229         } else
3230             code = -1;
3231     } while (afs_Analyze
3232              (tc, code, &avc->f.fid, areq, AFS_STATS_FS_RPCIDX_REMOVEFILE,
3233               SHARED_LOCK, NULL));
3234
3235     if (code) {
3236         if (tdc)
3237             afs_PutDCache(tdc);
3238         ReleaseWriteLock(&avc->lock);
3239         goto out;
3240     }
3241     if (tdc) {
3242         /* we have the thing in the cache */
3243         ObtainWriteLock(&tdc->lock, 661);
3244         if (afs_LocalHero(avc, tdc, &OutDirStatus, 1)) {
3245             /* we can do it locally */
3246             code = afs_dir_Delete(tdc, bufp);
3247             if (code) {
3248                 ZapDCE(tdc);    /* surprise error -- invalid value */
3249                 DZap(tdc);
3250             }
3251         }
3252         ReleaseWriteLock(&tdc->lock);
3253         afs_PutDCache(tdc);     /* drop ref count */
3254     }
3255     avc->f.states &= ~CUnique;  /* For the dfs xlator */
3256     ReleaseWriteLock(&avc->lock);
3257     code = 0;
3258   out:
3259     if (sysState.allocked)
3260         osi_FreeLargeSpace(bufp);
3261     return code;
3262 }
3263
3264 /*!
3265  * VIOC_GETCELLSTATUS (35) - Get cell status info
3266  *
3267  * \ingroup pioctl
3268  *
3269  * \param[in] ain       The cell you want status information on
3270  * \param[out] aout     cell state (as a struct)
3271  *
3272  * \retval EIO          Error if the afs daemon hasn't started yet
3273  * \retval ENOENT       Error if the cell doesn't exist
3274  *
3275  * \post Returns the state of the cell as defined in a struct cell
3276  */
3277 DECL_PIOCTL(PGetCellStatus)
3278 {
3279     register struct cell *tcell;
3280     char *cellName;
3281     afs_int32 temp;
3282
3283     AFS_STATCNT(PGetCellStatus);
3284     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
3285         return EIO;             /* Inappropriate ioctl for device */
3286
3287     if (afs_pd_getStringPtr(ain, &cellName) != 0)
3288         return EINVAL;
3289
3290     tcell = afs_GetCellByName(cellName, READ_LOCK);
3291     if (!tcell)
3292         return ENOENT;
3293     temp = tcell->states;
3294     afs_PutCell(tcell, READ_LOCK);
3295
3296     return afs_pd_putInt(aout, temp);
3297 }
3298
3299 /*!
3300  * VIOC_SETCELLSTATUS (36) - Set corresponding info
3301  *
3302  * \ingroup pioctl
3303  *
3304  * \param[in] ain
3305  *      The cell you want to set information about, and the values you
3306  *      want to set
3307  * \param[out] aout
3308  *      not in use
3309  *
3310  * \retval EIO          Error if the afs daemon hasn't started yet
3311  * \retval EACCES       Error if the user doesn't have super-user credentials
3312  *
3313  * \post
3314  *      Set the state of the cell in a defined struct cell, based on
3315  *      whether or not SetUID is allowed
3316  */
3317 DECL_PIOCTL(PSetCellStatus)
3318 {
3319     register struct cell *tcell;
3320     char *cellName;
3321     afs_int32 flags0, flags1;
3322
3323     if (!afs_osi_suser(*acred))
3324         return EACCES;
3325     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
3326         return EIO;             /* Inappropriate ioctl for device */
3327
3328     if (afs_pd_getInt(ain, &flags0) != 0)
3329         return EINVAL;
3330     if (afs_pd_getInt(ain, &flags1) != 0)
3331         return EINVAL;
3332     if (afs_pd_getStringPtr(ain, &cellName) != 0)
3333         return EINVAL;
3334
3335     tcell = afs_GetCellByName(cellName, WRITE_LOCK);
3336     if (!tcell)
3337         return ENOENT;
3338     if (flags0 & CNoSUID)
3339         tcell->states |= CNoSUID;
3340     else
3341         tcell->states &= ~CNoSUID;
3342     afs_PutCell(tcell, WRITE_LOCK);
3343     return 0;
3344 }
3345
3346 /*!
3347  * VIOC_FLUSHVOLUME (37) - Flush whole volume's data
3348  *
3349  * \ingroup pioctl
3350  *
3351  * \param[in] ain       not in use (args in avc)
3352  * \param[out] aout     not in use
3353  *
3354  * \retval EINVAL       Error if some of the standard args aren't set
3355  * \retval EIO          Error if the afs daemon hasn't started yet
3356  *
3357  * \post
3358  *      Flush all cached contents of a volume.  Exactly what stays and what
3359  *      goes depends on the platform.
3360  *
3361  * \notes
3362  *      Does not flush a file that a user has open and is using, because
3363  *      it will be re-created on next write.  Also purges the dnlc,
3364  *      because things are screwed up.
3365  */
3366 DECL_PIOCTL(PFlushVolumeData)
3367 {
3368     register afs_int32 i;
3369     register struct dcache *tdc;
3370     register struct vcache *tvc;
3371     register struct volume *tv;
3372     afs_int32 cell, volume;
3373     struct afs_q *tq, *uq;
3374 #ifdef AFS_DARWIN80_ENV
3375     vnode_t vp;
3376 #endif
3377
3378     AFS_STATCNT(PFlushVolumeData);
3379     if (!avc)
3380         return EINVAL;
3381     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
3382         return EIO;             /* Inappropriate ioctl for device */
3383
3384     volume = avc->f.fid.Fid.Volume;     /* who to zap */
3385     cell = avc->f.fid.Cell;
3386
3387     /*
3388      * Clear stat'd flag from all vnodes from this volume; this will
3389      * invalidate all the vcaches associated with the volume.
3390      */
3391  loop:
3392     ObtainReadLock(&afs_xvcache);
3393     i = VCHashV(&avc->f.fid);
3394     for (tq = afs_vhashTV[i].prev; tq != &afs_vhashTV[i]; tq = uq) {
3395             uq = QPrev(tq);
3396             tvc = QTOVH(tq);
3397             if (tvc->f.fid.Fid.Volume == volume && tvc->f.fid.Cell == cell) {
3398                 if (tvc->f.states & CVInit) {
3399                     ReleaseReadLock(&afs_xvcache);
3400                     afs_osi_Sleep(&tvc->f.states);
3401                     goto loop;
3402                 }
3403 #ifdef AFS_DARWIN80_ENV
3404                 if (tvc->f.states & CDeadVnode) {
3405                     ReleaseReadLock(&afs_xvcache);
3406                     afs_osi_Sleep(&tvc->f.states);
3407                     goto loop;
3408                 }
3409 #endif
3410 #if     defined(AFS_SGI_ENV) || defined(AFS_SUN5_ENV)  || defined(AFS_HPUX_ENV) || defined(AFS_LINUX20_ENV)
3411                 VN_HOLD(AFSTOV(tvc));
3412 #elif defined(AFS_DARWIN80_ENV)
3413                 vp = AFSTOV(tvc);
3414                 if (vnode_get(vp))
3415                     continue;
3416                 if (vnode_ref(vp)) {
3417                     AFS_GUNLOCK();
3418                     vnode_put(vp);
3419                     AFS_GLOCK();
3420                     continue;
3421                 }
3422 #elif defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
3423                 osi_vnhold(tvc, 0);
3424 #else
3425                 VREFCOUNT_INC(tvc); /* AIX, apparently */
3426 #endif
3427                 ReleaseReadLock(&afs_xvcache);
3428 #ifdef AFS_BOZONLOCK_ENV
3429                 afs_BozonLock(&tvc->pvnLock, tvc);      /* Since afs_TryToSmush will do a pvn_vptrunc */
3430 #endif
3431                 ObtainWriteLock(&tvc->lock, 232);
3432
3433                 ObtainWriteLock(&afs_xcbhash, 458);
3434                 afs_DequeueCallback(tvc);
3435                 tvc->f.states &= ~(CStatd | CDirty);
3436                 ReleaseWriteLock(&afs_xcbhash);
3437                 if (tvc->f.fid.Fid.Vnode & 1 || (vType(tvc) == VDIR))
3438                     osi_dnlc_purgedp(tvc);
3439                 afs_TryToSmush(tvc, *acred, 1);
3440                 ReleaseWriteLock(&tvc->lock);
3441 #ifdef AFS_BOZONLOCK_ENV
3442                 afs_BozonUnlock(&tvc->pvnLock, tvc);
3443 #endif
3444 #ifdef AFS_DARWIN80_ENV
3445                 vnode_put(AFSTOV(tvc));
3446 #endif
3447                 ObtainReadLock(&afs_xvcache);
3448                 uq = QPrev(tq);
3449                 /* our tvc ptr is still good until now */
3450                 AFS_FAST_RELE(tvc);
3451             }
3452         }
3453     ReleaseReadLock(&afs_xvcache);
3454
3455
3456     ObtainWriteLock(&afs_xdcache, 328); /* needed to flush any stuff */
3457     for (i = 0; i < afs_cacheFiles; i++) {
3458         if (!(afs_indexFlags[i] & IFEverUsed))
3459             continue;           /* never had any data */
3460         tdc = afs_GetDSlot(i, NULL);
3461         if (tdc->refCount <= 1) {    /* too high, in use by running sys call */
3462             ReleaseReadLock(&tdc->tlock);
3463             if (tdc->f.fid.Fid.Volume == volume && tdc->f.fid.Cell == cell) {
3464                 if (!(afs_indexFlags[i] & IFDataMod)) {
3465                     /* if the file is modified, but has a ref cnt of only 1,
3466                      * then someone probably has the file open and is writing
3467                      * into it. Better to skip flushing such a file, it will be
3468                      * brought back immediately on the next write anyway.
3469                      * 
3470                      * If we *must* flush, then this code has to be rearranged
3471                      * to call afs_storeAllSegments() first */
3472                     afs_FlushDCache(tdc);
3473                 }
3474             }
3475         } else {
3476             ReleaseReadLock(&tdc->tlock);
3477         }
3478         afs_PutDCache(tdc);     /* bumped by getdslot */
3479     }
3480     ReleaseWriteLock(&afs_xdcache);
3481
3482     ObtainReadLock(&afs_xvolume);
3483     for (i = 0; i < NVOLS; i++) {
3484         for (tv = afs_volumes[i]; tv; tv = tv->next) {
3485             if (tv->volume == volume) {
3486                 afs_ResetVolumeInfo(tv);
3487                 break;
3488             }
3489         }
3490     }
3491     ReleaseReadLock(&afs_xvolume);
3492
3493     /* probably, a user is doing this, probably, because things are screwed up.
3494      * maybe it's the dnlc's fault? */
3495     osi_dnlc_purge();
3496     return 0;
3497 }
3498
3499
3500 /*!
3501  * VIOCGETVCXSTATUS (41) - gets vnode x status
3502  *
3503  * \ingroup pioctl
3504  *
3505  * \param[in] ain
3506  *      not in use (avc used)
3507  * \param[out] aout
3508  *      vcxstat: the file id, the data version, any lock, the parent vnode,
3509  *      the parent unique id, the trunc position, the callback, cbExpires,
3510  *      what access is being made, what files are open,
3511  *      any users executing/writing, the flock count, the states,
3512  *      the move stat
3513  *
3514  * \retval EINVAL
3515  *      Error if some of the initial default arguments aren't set
3516  * \retval EACCES
3517  *      Error if access to check the mode bits is denied
3518  *
3519  * \post
3520  *      gets stats for the vnode, a struct listed in vcxstat
3521  */
3522 DECL_PIOCTL(PGetVnodeXStatus)
3523 {
3524     register afs_int32 code;
3525     struct vcxstat stat;
3526     afs_int32 mode, i;
3527
3528 /*  AFS_STATCNT(PGetVnodeXStatus); */
3529     if (!avc)
3530         return EINVAL;
3531     code = afs_VerifyVCache(avc, areq);
3532     if (code)
3533         return code;
3534     if (vType(avc) == VDIR)
3535         mode = PRSFS_LOOKUP;
3536     else
3537         mode = PRSFS_READ;
3538     if (!afs_AccessOK(avc, mode, areq, CHECK_MODE_BITS))
3539         return EACCES;
3540
3541     memset(&stat, 0, sizeof(struct vcxstat));
3542     stat.fid = avc->f.fid;
3543     hset32(stat.DataVersion, hgetlo(avc->f.m.DataVersion));
3544     stat.lock = avc->lock;
3545     stat.parentVnode = avc->f.parent.vnode;
3546     stat.parentUnique = avc->f.parent.unique;
3547     hset(stat.flushDV, avc->flushDV);
3548     hset(stat.mapDV, avc->mapDV);
3549     stat.truncPos = avc->f.truncPos;
3550     {                   /* just grab the first two - won't break anything... */
3551         struct axscache *ac;
3552
3553         for (i = 0, ac = avc->Access; ac && i < CPSIZE; i++, ac = ac->next) {
3554             stat.randomUid[i] = ac->uid;
3555             stat.randomAccess[i] = ac->axess;
3556         }
3557     }
3558     stat.callback = afs_data_pointer_to_int32(avc->callback);
3559     stat.cbExpires = avc->cbExpires;
3560     stat.anyAccess = avc->f.anyAccess;
3561     stat.opens = avc->opens;
3562     stat.execsOrWriters = avc->execsOrWriters;
3563     stat.flockCount = avc->flockCount;
3564     stat.mvstat = avc->mvstat;
3565     stat.states = avc->f.states;
3566     return afs_pd_putBytes(aout, &stat, sizeof(struct vcxstat));
3567 }
3568
3569
3570 DECL_PIOCTL(PGetVnodeXStatus2)
3571 {
3572     register afs_int32 code;
3573     struct vcxstat2 stat;
3574     afs_int32 mode;
3575
3576     if (!avc)
3577         return EINVAL;
3578     code = afs_VerifyVCache(avc, areq);
3579     if (code)
3580         return code;
3581     if (vType(avc) == VDIR)
3582         mode = PRSFS_LOOKUP;
3583     else
3584         mode = PRSFS_READ;
3585     if (!afs_AccessOK(avc, mode, areq, CHECK_MODE_BITS))
3586         return EACCES;
3587
3588     memset(&stat, 0, sizeof(struct vcxstat2));
3589
3590     stat.cbExpires = avc->cbExpires;
3591     stat.anyAccess = avc->f.anyAccess;
3592     stat.mvstat = avc->mvstat;
3593     stat.callerAccess = afs_GetAccessBits(avc, ~0, areq);
3594
3595     return afs_pd_putBytes(aout, &stat, sizeof(struct vcxstat2));
3596 }
3597
3598
3599 /*!
3600  * VIOC_AFS_SYSNAME (38) - Change @sys value
3601  *
3602  * \ingroup pioctl
3603  *
3604  * \param[in] ain       new value for @sys
3605  * \param[out] aout     count, entry, list (debug values?)
3606  *
3607  * \retval EINVAL
3608  *      Error if afsd isn't running, the new sysname is too large,
3609  *      the new sysname causes issues (starts with a . or ..),
3610  *      there is no PAG set in the credentials, or the user of a PAG
3611  *      can't be found
3612  * \retval EACCES
3613  *      Error if the user doesn't have super-user credentials
3614  *
3615  * \post
3616  *      Set the value of @sys if these things work: if the input isn't
3617  *      too long or if input doesn't start with . or ..
3618  *
3619  * \notes
3620  *      We require root for local sysname changes, but not for remote
3621  *      (since we don't really believe remote uids anyway)
3622  *      outname[] shouldn't really be needed- this is left as an
3623  *      exercise for the reader.
3624  */
3625 DECL_PIOCTL(PSetSysName)
3626 {
3627     char *inname = NULL;
3628     char outname[MAXSYSNAME];
3629     afs_int32 setsysname;
3630     int foundname = 0;
3631     register struct afs_exporter *exporter;
3632     register struct unixuser *au;
3633     register afs_int32 pag, error;
3634     int t, count, num = 0, allpags = 0;
3635     char **sysnamelist;
3636     struct afs_pdata validate;
3637
3638     AFS_STATCNT(PSetSysName);
3639     if (!afs_globalVFS) {
3640         /* Afsd is NOT running; disable it */
3641 #if defined(KERNEL_HAVE_UERROR)
3642         return (setuerror(EINVAL), EINVAL);
3643 #else
3644         return (EINVAL);
3645 #endif
3646     }
3647     if (afs_pd_getInt(ain, &setsysname) != 0)
3648         return EINVAL;
3649     if (setsysname & 0x8000) {
3650         allpags = 1;
3651         setsysname &= ~0x8000;
3652     }
3653     if (setsysname) {
3654
3655         /* Check my args */
3656         if (setsysname < 0 || setsysname > MAXNUMSYSNAMES)
3657             return EINVAL;
3658         validate = *ain;
3659         for (count = 0; count < setsysname; count++) {
3660             if (afs_pd_getStringPtr(&validate, &inname) != 0)
3661                 return EINVAL;
3662             t = strlen(inname);
3663             if (t >= MAXSYSNAME || t <= 0)
3664                 return EINVAL;
3665             /* check for names that can shoot us in the foot */
3666             if (inname[0] == '.' && (inname[1] == 0
3667                 || (inname[1] == '.' && inname[2] == 0)))
3668                 return EINVAL;
3669         }
3670         /* args ok, so go back to the beginning of that section */
3671
3672         if (afs_pd_getStringPtr(ain, &inname) != 0)
3673             return EINVAL;
3674         num = count;
3675     }
3676     if (afs_cr_gid(*acred) == RMTUSER_REQ ||
3677         afs_cr_gid(*acred) == RMTUSER_REQ_PRIV) {   /* Handles all exporters */
3678         if (allpags && afs_cr_gid(*acred) != RMTUSER_REQ_PRIV) {
3679             return EPERM;
3680         }
3681         pag = PagInCred(*acred);
3682         if (pag == NOPAG) {
3683             return EINVAL;      /* Better than panicing */
3684         }
3685         if (!(au = afs_FindUser(pag, -1, READ_LOCK))) {
3686             return EINVAL;      /* Better than panicing */
3687         }
3688         if (!(exporter = au->exporter)) {
3689             afs_PutUser(au, READ_LOCK);
3690             return EINVAL;      /* Better than panicing */
3691         }
3692         error = EXP_SYSNAME(exporter, inname, &sysnamelist,
3693                             &num, allpags);
3694         if (error) {
3695             if (error == ENODEV)
3696                 foundname = 0;  /* sysname not set yet! */
3697             else {
3698                 afs_PutUser(au, READ_LOCK);
3699                 return error;
3700             }
3701         } else {
3702             foundname = num;
3703             strcpy(outname, sysnamelist[0]);
3704         }
3705         afs_PutUser(au, READ_LOCK);
3706         if (setsysname)
3707             afs_sysnamegen++;
3708     } else {
3709         /* Not xlating, so local case */
3710         if (!afs_sysname)
3711             osi_Panic("PSetSysName: !afs_sysname\n");
3712         if (!setsysname) {      /* user just wants the info */
3713             strcpy(outname, afs_sysname);
3714             foundname = afs_sysnamecount;
3715             sysnamelist = afs_sysnamelist;
3716         } else {                /* Local guy; only root can change sysname */
3717             if (!afs_osi_suser(*acred))
3718                 return EACCES;
3719
3720             /* allpags makes no sense for local use */
3721             if (allpags)
3722                 return EINVAL;
3723
3724             /* clear @sys entries from the dnlc, once afs_lookup can
3725              * do lookups of @sys entries and thinks it can trust them */
3726             /* privs ok, store the entry, ... */
3727
3728             if (strlen(inname) >= MAXSYSNAME-1)
3729                 return EINVAL;
3730             strcpy(afs_sysname, inname);
3731
3732             if (setsysname > 1) {       /* ... or list */
3733                 for (count = 1; count < setsysname; ++count) {
3734                     if (!afs_sysnamelist[count])
3735                         osi_Panic
3736                            ("PSetSysName: no afs_sysnamelist entry to write\n");
3737                     if (afs_pd_getString(ain, afs_sysnamelist[count],
3738                                          MAXSYSNAME) != 0)
3739                         return EINVAL;
3740                 }
3741             }
3742             afs_sysnamecount = setsysname;
3743             afs_sysnamegen++;
3744         }
3745     }
3746     if (!setsysname) {
3747         if (afs_pd_putInt(aout, foundname) != 0)
3748             return E2BIG;
3749         if (foundname) {
3750             if (afs_pd_putString(aout, outname) != 0)
3751                 return E2BIG;
3752             for (count = 1; count < foundname; ++count) {    /* ... or list. */
3753                 if (!sysnamelist[count])
3754                     osi_Panic
3755                         ("PSetSysName: no afs_sysnamelist entry to read\n");
3756                 t = strlen(sysnamelist[count]);
3757                 if (t >= MAXSYSNAME)
3758                     osi_Panic("PSetSysName: sysname entry garbled\n");
3759                 if (afs_pd_putString(aout, sysnamelist[count]) != 0)
3760                     return E2BIG;
3761             }
3762         }
3763     }
3764     return 0;
3765 }
3766
3767 /* sequential search through the list of touched cells is not a good
3768  * long-term solution here. For small n, though, it should be just
3769  * fine.  Should consider special-casing the local cell for large n.
3770  * Likewise for PSetSPrefs.
3771  *
3772  * s - number of ids in array l[] -- NOT index of last id
3773  * l - array of cell ids which have volumes that need to be sorted
3774  * vlonly - sort vl servers or file servers?
3775  */
3776 static void *
3777 ReSortCells_cb(struct cell *cell, void *arg)
3778 {
3779     afs_int32 *p = (afs_int32 *) arg;
3780     afs_int32 *l = p + 1;
3781     int i, s = p[0];
3782
3783     for (i = 0; i < s; i++) {
3784         if (l[i] == cell->cellNum) {
3785             ObtainWriteLock(&cell->lock, 690);
3786             afs_SortServers(cell->cellHosts, AFS_MAXCELLHOSTS);
3787             ReleaseWriteLock(&cell->lock);
3788         }
3789     }
3790
3791     return NULL;
3792 }
3793
3794 static void
3795 ReSortCells(int s, afs_int32 * l, int vlonly)
3796 {
3797     int i;
3798     struct volume *j;
3799     register int k;
3800
3801     if (vlonly) {
3802         afs_int32 *p;
3803         p = (afs_int32 *) afs_osi_Alloc(sizeof(afs_int32) * (s + 1));
3804         p[0] = s;
3805         memcpy(p + 1, l, s * sizeof(afs_int32));
3806         afs_TraverseCells(&ReSortCells_cb, p);
3807         afs_osi_Free(p, sizeof(afs_int32) * (s + 1));
3808         return;
3809     }
3810
3811     ObtainReadLock(&afs_xvolume);
3812     for (i = 0; i < NVOLS; i++) {
3813         for (j = afs_volumes[i]; j; j = j->next) {
3814             for (k = 0; k < s; k++)
3815                 if (j->cell == l[k]) {
3816                     ObtainWriteLock(&j->lock, 233);
3817                     afs_SortServers(j->serverHost, AFS_MAXHOSTS);
3818                     ReleaseWriteLock(&j->lock);
3819                     break;
3820                 }
3821         }
3822     }
3823     ReleaseReadLock(&afs_xvolume);
3824 }
3825
3826
3827 static int debugsetsp = 0;
3828 static int
3829 afs_setsprefs(struct spref *sp, unsigned int num, unsigned int vlonly)
3830 {
3831     struct srvAddr *sa;
3832     int i, j, k, matches, touchedSize;
3833     struct server *srvr = NULL;
3834     afs_int32 touched[34];
3835     int isfs;
3836
3837     touchedSize = 0;
3838     for (k = 0; k < num; sp++, k++) {
3839         if (debugsetsp) {
3840             printf("sp host=%x, rank=%d\n", sp->host.s_addr, sp->rank);
3841         }
3842         matches = 0;
3843         ObtainReadLock(&afs_xserver);
3844
3845         i = SHash(sp->host.s_addr);
3846         for (sa = afs_srvAddrs[i]; sa; sa = sa->next_bkt) {
3847             if (sa->sa_ip == sp->host.s_addr) {
3848                 srvr = sa->server;
3849                 isfs = (srvr->cell && (sa->sa_portal == srvr->cell->fsport))
3850                     || (sa->sa_portal == AFS_FSPORT);
3851                 if ((!vlonly && isfs) || (vlonly && !isfs)) {
3852                     matches++;
3853                     break;
3854                 }
3855             }
3856         }
3857
3858         if (sa && matches) {    /* found one! */
3859             if (debugsetsp) {
3860                 printf("sa ip=%x, ip_rank=%d\n", sa->sa_ip, sa->sa_iprank);
3861             }
3862             sa->sa_iprank = sp->rank + afs_randomMod15();
3863             afs_SortOneServer(sa->server);
3864
3865             if (srvr->cell) {
3866                 /* if we don't know yet what cell it's in, this is moot */
3867                 for (j = touchedSize - 1;
3868                      j >= 0 && touched[j] != srvr->cell->cellNum; j--)
3869                     /* is it in our list of touched cells ?  */ ;
3870                 if (j < 0) {    /* no, it's not */
3871                     touched[touchedSize++] = srvr->cell->cellNum;
3872                     if (touchedSize >= 32) {    /* watch for ovrflow */
3873                         ReleaseReadLock(&afs_xserver);
3874                         ReSortCells(touchedSize, touched, vlonly);
3875                         touchedSize = 0;
3876                         ObtainReadLock(&afs_xserver);
3877                     }
3878                 }
3879             }
3880         }
3881
3882         ReleaseReadLock(&afs_xserver);
3883         /* if we didn't find one, start to create one. */
3884         /* Note that it doesn't have a cell yet...     */
3885         if (!matches) {
3886             afs_uint32 temp = sp->host.s_addr;
3887             srvr =
3888                 afs_GetServer(&temp, 1, 0, (vlonly ? AFS_VLPORT : AFS_FSPORT),
3889                               WRITE_LOCK, (afsUUID *) 0, 0);
3890             srvr->addr->sa_iprank = sp->rank + afs_randomMod15();
3891             afs_PutServer(srvr, WRITE_LOCK);
3892         }
3893     }                           /* for all cited preferences */
3894
3895     ReSortCells(touchedSize, touched, vlonly);
3896     return 0;
3897 }
3898
3899 /*!
3900  * VIOC_SETPREFS (46) - Set server ranks
3901  *
3902  * \param[in] ain       the sprefs value you want the sprefs to be set to
3903  * \param[out] aout     not in use
3904  *
3905  * \retval EIO
3906  *      Error if the afs daemon hasn't started yet
3907  * \retval EACCES
3908  *      Error if the user doesn't have super-user credentials
3909  * \retval EINVAL
3910  *      Error if the struct setsprefs is too large or if it multiplied
3911  *      by the number of servers is too large
3912  *
3913  * \post set the sprefs using the afs_setsprefs() function
3914  */
3915 DECL_PIOCTL(PSetSPrefs)
3916 {
3917     struct setspref *ssp;
3918     char *ainPtr;
3919     size_t ainSize;
3920
3921     AFS_STATCNT(PSetSPrefs);
3922
3923     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
3924         return EIO;             /* Inappropriate ioctl for device */
3925
3926     if (!afs_osi_suser(*acred))
3927         return EACCES;
3928
3929     /* The I/O handling here is ghastly, as it relies on overrunning the ends
3930      * of arrays. But, i'm not quite brave enough to change it yet. */
3931     ainPtr = ain->ptr;
3932     ainSize = ain->remaining;
3933
3934     if (ainSize < sizeof(struct setspref))
3935         return EINVAL;
3936
3937     ssp = (struct setspref *)ainPtr;
3938     if (ainSize < (sizeof(struct setspref)
3939                    + sizeof(struct spref) * ssp->num_servers-1))
3940         return EINVAL;
3941
3942     afs_setsprefs(&(ssp->servers[0]), ssp->num_servers,
3943                   (ssp->flags & DBservers));
3944     return 0;
3945 }
3946
3947 /* 
3948  * VIOC_SETPREFS33 (42) - Set server ranks (deprecated)
3949  *
3950  * \param[in] ain       the server preferences to be set
3951  * \param[out] aout     not in use
3952  *
3953  * \retval EIO          Error if the afs daemon hasn't started yet
3954  * \retval EACCES       Error if the user doesn't have super-user credentials
3955  *
3956  * \post set the server preferences, calling a function
3957  *
3958  * \notes this may only be performed by the local root user.
3959  */
3960 DECL_PIOCTL(PSetSPrefs33)
3961 {
3962     AFS_STATCNT(PSetSPrefs);
3963     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
3964         return EIO;             /* Inappropriate ioctl for device */
3965
3966
3967     if (!afs_osi_suser(*acred))
3968         return EACCES;
3969
3970     afs_setsprefs((struct spref *)afs_pd_where(ain),
3971                   afs_pd_remaining(ain) / sizeof(struct spref),
3972                   0 /*!vlonly */ );
3973     return 0;
3974 }
3975
3976 /* 
3977  * VIOC_GETSPREFS (43) - Get server ranks
3978  *
3979  * \ingroup pioctl
3980  *
3981  * \param[in] ain       the server preferences to get
3982  * \param[out] aout     the server preferences information
3983  *
3984  * \retval EIO          Error if the afs daemon hasn't started yet
3985  * \retval ENOENT       Error if the sprefrequest is too large
3986  *
3987  * \post Get the sprefs
3988  *
3989  * \notes
3990  *      in the hash table of server structs, all servers with the same
3991  *      IP address; will be on the same overflow chain; This could be
3992  *      sped slightly in some circumstances by having it cache the
3993  *      immediately previous slot in the hash table and some
3994  *      supporting information; Only reports file servers now.
3995  */
3996 DECL_PIOCTL(PGetSPrefs)
3997 {
3998     struct sprefrequest spin;   /* input */
3999     struct sprefinfo *spout;    /* output */
4000     struct spref *srvout;       /* one output component */
4001     int i, j;                   /* counters for hash table traversal */
4002     struct server *srvr;        /* one of CM's server structs */
4003     struct srvAddr *sa;
4004     int vlonly;                 /* just return vlservers ? */
4005     int isfs;
4006
4007     AFS_STATCNT(PGetSPrefs);
4008     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
4009         return EIO;             /* Inappropriate ioctl for device */
4010
4011     /* Work out from the size whether we've got a new, or old, style pioctl */
4012     if (afs_pd_remaining(ain) < sizeof(struct sprefrequest)) {
4013         if (afs_pd_getBytes(ain, &spin, sizeof(struct sprefrequest_33)) != 0)
4014            return ENOENT;
4015         vlonly = 0;
4016         spin.flags = 0;
4017     } else {
4018         if (afs_pd_getBytes(ain, &spin, sizeof(struct sprefrequest)) != 0)
4019            return EINVAL;
4020         vlonly = (spin.flags & DBservers);
4021     }
4022
4023     /* This code relies on overflowing arrays. It's ghastly, but I'm not
4024      * quite brave enough to tackle it yet ...
4025      */
4026
4027     /* struct sprefinfo includes 1 server struct...  that size gets added
4028      * in during the loop that follows.
4029      */
4030     spout = afs_pd_inline(aout,
4031                           sizeof(struct sprefinfo) - sizeof(struct spref));
4032     spout->next_offset = spin.offset;
4033     spout->num_servers = 0;
4034     srvout = spout->servers;
4035
4036     ObtainReadLock(&afs_xserver);
4037     for (i = 0, j = 0; j < NSERVERS; j++) {     /* sift through hash table */
4038         for (sa = afs_srvAddrs[j]; sa; sa = sa->next_bkt, i++) {
4039             if (spin.offset > (unsigned short)i) {
4040                 continue;       /* catch up to where we left off */
4041             }
4042             spout->next_offset++;
4043
4044             srvr = sa->server;
4045             isfs = (srvr->cell && (sa->sa_portal == srvr->cell->fsport))
4046                 || (sa->sa_portal == AFS_FSPORT);
4047
4048             if ((vlonly && isfs) || (!vlonly && !isfs)) {
4049                 /* only report ranks for vl servers */
4050                 continue;
4051             }
4052
4053             /* Check we've actually got the space we're about to use */
4054             if (afs_pd_inline(aout, sizeof(struct spref)) == NULL) {
4055                 ReleaseReadLock(&afs_xserver);  /* no more room! */
4056                 return 0;
4057             }
4058
4059             srvout->host.s_addr = sa->sa_ip;
4060             srvout->rank = sa->sa_iprank;
4061             spout->num_servers++;
4062             srvout++;
4063         }
4064     }
4065     ReleaseReadLock(&afs_xserver);
4066
4067     spout->next_offset = 0;     /* start over from the beginning next time */
4068
4069     return 0;
4070 }
4071
4072 /* Enable/Disable the specified exporter. Must be root to disable an exporter */
4073 int afs_NFSRootOnly = 1;
4074 /*!
4075  * VIOC_EXPORTAFS (39) - Export afs to nfs clients
4076  *
4077  * \ingroup pioctl
4078  *
4079  * \param[in] ain
4080  *      an integer containing the desired exportee flags
4081  * \param[out] aout
4082  *      an integer containing the current exporter flags
4083  *
4084  * \retval ENODEV       Error if the exporter doesn't exist
4085  * \retval EACCES       Error if the user doesn't have super-user credentials
4086  *
4087  * \post
4088  *      Changes the state of various values to reflect the change
4089  *      of the export values between nfs and afs.
4090  *
4091  * \notes Legacy code obtained from IBM.
4092  */
4093 DECL_PIOCTL(PExportAfs)
4094 {
4095     afs_int32 export, newint = 0;
4096     afs_int32 type, changestate, handleValue, convmode, pwsync, smounts;
4097     afs_int32 rempags = 0, pagcb = 0;
4098     register struct afs_exporter *exporter;
4099
4100     AFS_STATCNT(PExportAfs);
4101     if (afs_pd_getInt(ain, &handleValue) != 0)
4102         return EINVAL;
4103     type = handleValue >> 24;
4104     if (type == 0x71) {
4105         newint = 1;
4106         type = 1;               /* nfs */
4107     }
4108     exporter = exporter_find(type);
4109     if (newint) {
4110         export = handleValue & 3;
4111         changestate = handleValue & 0xfff;
4112         smounts = (handleValue >> 2) & 3;
4113         pwsync = (handleValue >> 4) & 3;
4114         convmode = (handleValue >> 6) & 3;
4115         rempags = (handleValue >> 8) & 3;
4116         pagcb = (handleValue >> 10) & 3;
4117     } else {
4118         changestate = (handleValue >> 16) & 0x1;
4119         convmode = (handleValue >> 16) & 0x2;
4120         pwsync = (handleValue >> 16) & 0x4;
4121         smounts = (handleValue >> 16) & 0x8;
4122         export = handleValue & 0xff;
4123     }
4124     if (!exporter) {
4125         /*  Failed finding desired exporter; */
4126         return ENODEV;
4127     }
4128     if (!changestate) {
4129         handleValue = exporter->exp_states;
4130         if (afs_pd_putInt(aout, handleValue) != 0)
4131             return E2BIG;
4132     } else {
4133         if (!afs_osi_suser(*acred))
4134             return EACCES;      /* Only superuser can do this */
4135         if (newint) {
4136             if (export & 2) {
4137                 if (export & 1)
4138                     exporter->exp_states |= EXP_EXPORTED;
4139                 else
4140                     exporter->exp_states &= ~EXP_EXPORTED;
4141             }
4142             if (convmode & 2) {
4143                 if (convmode & 1)
4144                     exporter->exp_states |= EXP_UNIXMODE;
4145                 else
4146                     exporter->exp_states &= ~EXP_UNIXMODE;
4147             }
4148             if (pwsync & 2) {
4149                 if (pwsync & 1)
4150                     exporter->exp_states |= EXP_PWSYNC;
4151                 else
4152                     exporter->exp_states &= ~EXP_PWSYNC;
4153             }
4154             if (smounts & 2) {
4155                 if (smounts & 1) {
4156                     afs_NFSRootOnly = 0;
4157                     exporter->exp_states |= EXP_SUBMOUNTS;
4158                 } else {
4159                     afs_NFSRootOnly = 1;
4160                     exporter->exp_states &= ~EXP_SUBMOUNTS;
4161                 }
4162             }
4163             if (rempags & 2) {
4164                 if (rempags & 1)
4165                     exporter->exp_states |= EXP_CLIPAGS;
4166                 else
4167                     exporter->exp_states &= ~EXP_CLIPAGS;
4168             }
4169             if (pagcb & 2) {
4170                 if (pagcb & 1)
4171                     exporter->exp_states |= EXP_CALLBACK;
4172                 else
4173                     exporter->exp_states &= ~EXP_CALLBACK;
4174             }
4175             handleValue = exporter->exp_states;
4176             if (afs_pd_putInt(aout, handleValue) != 0)
4177                 return E2BIG;
4178         } else {
4179             if (export)
4180                 exporter->exp_states |= EXP_EXPORTED;
4181             else
4182                 exporter->exp_states &= ~EXP_EXPORTED;
4183             if (convmode)
4184                 exporter->exp_states |= EXP_UNIXMODE;
4185             else
4186                 exporter->exp_states &= ~EXP_UNIXMODE;
4187             if (pwsync)
4188                 exporter->exp_states |= EXP_PWSYNC;
4189             else
4190                 exporter->exp_states &= ~EXP_PWSYNC;
4191             if (smounts) {
4192                 afs_NFSRootOnly = 0;
4193                 exporter->exp_states |= EXP_SUBMOUNTS;
4194             } else {
4195                 afs_NFSRootOnly = 1;
4196                 exporter->exp_states &= ~EXP_SUBMOUNTS;
4197             }
4198         }
4199     }
4200
4201     return 0;
4202 }
4203
4204 /*!
4205  * VIOC_GAG (44) - Silence Cache Manager
4206  *
4207  * \ingroup pioctl
4208  *
4209  * \param[in] ain       the flags to either gag or de-gag the cache manager
4210  * \param[out] aout     not in use
4211  *
4212  * \retval EACCES       Error if the user doesn't have super-user credentials
4213  *
4214  * \post set the gag flags, then show these flags
4215  */
4216 DECL_PIOCTL(PGag)
4217 {
4218     struct gaginfo *gagflags;
4219
4220     if (!afs_osi_suser(*acred))
4221         return EACCES;
4222
4223     gagflags = afs_pd_inline(ain, sizeof(*gagflags));
4224     if (gagflags == NULL)
4225         return EINVAL;
4226     afs_showflags = gagflags->showflags;
4227
4228     return 0;
4229 }
4230
4231 /*!
4232  * VIOC_TWIDDLE (45) - Adjust RX knobs
4233  *
4234  * \ingroup pioctl
4235  *
4236  * \param[in] ain       the previous settings of the 'knobs'
4237  * \param[out] aout     not in use
4238  *
4239  * \retval EACCES       Error if the user doesn't have super-user credentials
4240  *
4241  * \post build out the struct rxp, from a struct rx
4242  */
4243 DECL_PIOCTL(PTwiddleRx)
4244 {
4245     struct rxparams *rxp;
4246
4247     if (!afs_osi_suser(*acred))
4248         return EACCES;
4249
4250     rxp = afs_pd_inline(ain, sizeof(*rxp));
4251     if (rxp == NULL)
4252         return EINVAL;
4253
4254     if (rxp->rx_initReceiveWindow)
4255         rx_initReceiveWindow = rxp->rx_initReceiveWindow;
4256     if (rxp->rx_maxReceiveWindow)
4257         rx_maxReceiveWindow = rxp->rx_maxReceiveWindow;
4258     if (rxp->rx_initSendWindow)
4259         rx_initSendWindow = rxp->rx_initSendWindow;
4260     if (rxp->rx_maxSendWindow)
4261         rx_maxSendWindow = rxp->rx_maxSendWindow;
4262     if (rxp->rxi_nSendFrags)
4263         rxi_nSendFrags = rxp->rxi_nSendFrags;
4264     if (rxp->rxi_nRecvFrags)
4265         rxi_nRecvFrags = rxp->rxi_nRecvFrags;
4266     if (rxp->rxi_OrphanFragSize)
4267         rxi_OrphanFragSize = rxp->rxi_OrphanFragSize;
4268     if (rxp->rx_maxReceiveSize) {
4269         rx_maxReceiveSize = rxp->rx_maxReceiveSize;
4270         rx_maxReceiveSizeUser = rxp->rx_maxReceiveSize;
4271     }
4272     if (rxp->rx_MyMaxSendSize)
4273         rx_MyMaxSendSize = rxp->rx_MyMaxSendSize;
4274
4275     return 0;
4276 }
4277
4278 /*!
4279  * VIOC_GETINITPARAMS (49) - Get initial cache manager parameters
4280  *
4281  * \ingroup pioctl
4282  *
4283  * \param[in] ain       not in use
4284  * \param[out] aout     initial cache manager params
4285  *
4286  * \retval E2BIG
4287  *      Error if the initial parameters are bigger than some PIGGYSIZE
4288  *
4289  * \post return the initial cache manager parameters
4290  */
4291 DECL_PIOCTL(PGetInitParams)
4292 {
4293     if (sizeof(struct cm_initparams) > PIGGYSIZE)
4294         return E2BIG;
4295
4296     return afs_pd_putBytes(aout, &cm_initParams,
4297                            sizeof(struct cm_initparams));
4298     return 0;
4299 }
4300
4301 #ifdef AFS_SGI65_ENV
4302 /* They took crget() from us, so fake it. */
4303 static cred_t *
4304 crget(void)
4305 {
4306     cred_t *cr;
4307     cr = crdup(get_current_cred());
4308     memset(cr, 0, sizeof(cred_t));
4309 #if CELL || CELL_PREPARE
4310     cr->cr_id = -1;
4311 #endif
4312     return cr;
4313 }
4314 #endif
4315
4316 /*!
4317  * VIOC_GETRXKCRYPT (55) - Get rxkad encryption flag
4318  *
4319  * \ingroup pioctl
4320  *
4321  * \param[in] ain       not in use
4322  * \param[out] aout     value of cryptall
4323  *
4324  * \post Turns on, or disables, rxkad encryption by setting the cryptall global
4325  */
4326 DECL_PIOCTL(PGetRxkcrypt)
4327 {
4328     return afs_pd_putInt(aout, cryptall);
4329 }
4330
4331 /*!
4332  * VIOC_SETRXKCRYPT (56) - Set rxkad encryption flag
4333  *
4334  * \ingroup pioctl
4335  *
4336  * \param[in] ain       the argument whether or not things should be encrypted
4337  * \param[out] aout     not in use
4338  *
4339  * \retval EPERM
4340  *      Error if the user doesn't have super-user credentials
4341  * \retval EINVAL
4342  *      Error if the input is too big, or if the input is outside the
4343  *      bounds of what it can be set to
4344  *
4345  * \post set whether or not things should be encrypted
4346  *
4347  * \notes
4348  *      may need to be modified at a later date to take into account
4349  *      other values for cryptall (beyond true or false)
4350  */
4351 DECL_PIOCTL(PSetRxkcrypt)
4352 {
4353     afs_int32 tmpval;
4354
4355     if (!afs_osi_suser(*acred))
4356         return EPERM;
4357     if (afs_pd_getInt(ain, &tmpval) != 0)
4358         return EINVAL;
4359     /* if new mappings added later this will need to be changed */
4360     if (tmpval != 0 && tmpval != 1)
4361         return EINVAL;
4362     cryptall = tmpval;
4363     return 0;
4364 }
4365
4366 #ifdef AFS_NEED_CLIENTCONTEXT
4367 /*
4368  * Create new credentials to correspond to a remote user with given
4369  * <hostaddr, uid, g0, g1>.  This allows a server running as root to
4370  * provide pioctl (and other) services to foreign clients (i.e. nfs
4371  * clients) by using this call to `become' the client.
4372  */
4373 #define PSETPAG         110
4374 #define PIOCTL_HEADER   6
4375 static int
4376 HandleClientContext(struct afs_ioctl *ablob, int *com,
4377                     afs_ucred_t **acred, afs_ucred_t *credp)
4378 {
4379     char *ain, *inData;
4380     afs_uint32 hostaddr;
4381     afs_int32 uid, g0, g1, i, code, pag, exporter_type, isroot = 0;
4382     struct afs_exporter *exporter, *outexporter;
4383     afs_ucred_t *newcred;
4384     struct unixuser *au;
4385     afs_uint32 comp = *com & 0xff00;
4386     afs_uint32 h, l;
4387 #if defined(AFS_SUN510_ENV)
4388     gid_t gids[2];
4389 #endif
4390
4391 #if defined(AFS_SGIMP_ENV)
4392     osi_Assert(ISAFS_GLOCK());
4393 #endif
4394     AFS_STATCNT(HandleClientContext);
4395     if (ablob->in_size < PIOCTL_HEADER * sizeof(afs_int32)) {
4396         /* Must at least include the PIOCTL_HEADER header words
4397          * required by the protocol */
4398         return EINVAL;          /* Too small to be good  */
4399     }
4400     ain = inData = osi_AllocLargeSpace(AFS_LRALLOCSIZ);
4401     AFS_COPYIN(ablob->in, ain, PIOCTL_HEADER * sizeof(afs_int32), code);
4402     if (code) {
4403         osi_FreeLargeSpace(inData);
4404         return code;
4405     }
4406
4407     /* Extract information for remote user */
4408     hostaddr = *((afs_uint32 *) ain);
4409     ain += sizeof(hostaddr);
4410     uid = *((afs_uint32 *) ain);
4411     ain += sizeof(uid);
4412     g0 = *((afs_uint32 *) ain);
4413     ain += sizeof(g0);
4414     g1 = *((afs_uint32 *) ain);
4415     ain += sizeof(g1);
4416     *com = *((afs_uint32 *) ain);
4417     ain += sizeof(afs_int32);
4418     exporter_type = *((afs_uint32 *) ain);/* In case we support more than NFS */
4419
4420     /*
4421      * Of course, one must be root for most of these functions, but
4422      * we'll allow (for knfs) you to set things if the pag is 0 and
4423      * you're setting tokens or unlogging.
4424      */
4425     i = (*com) & 0xff;
4426     if (!afs_osi_suser(credp)) {
4427 #if defined(AFS_SGI_ENV) && !defined(AFS_SGI64_ENV)
4428         /* Since SGI's suser() returns explicit failure after the call.. */
4429         u.u_error = 0;
4430 #endif
4431         /* check for acceptable opcodes for normal folks, which are, so far,
4432          * get/set tokens, sysname, and unlog.
4433          */
4434         if (i != 9 && i != 3 && i != 38 && i != 8) {
4435             osi_FreeLargeSpace(inData);
4436             return EACCES;
4437         }
4438     }
4439
4440     ablob->in_size -= PIOCTL_HEADER * sizeof(afs_int32);
4441     ablob->in += PIOCTL_HEADER * sizeof(afs_int32);
4442     osi_FreeLargeSpace(inData);
4443     if (uid == 0) {
4444         /*
4445          * We map uid 0 to nobody to match the mapping that the nfs
4446          * server does and to ensure that the suser() calls in the afs
4447          * code fails for remote client roots.
4448          */
4449         uid = afs_nobody;       /* NFS_NOBODY == -2 */
4450         isroot = 1;
4451     }
4452     newcred = crget();
4453 #ifdef  AFS_AIX41_ENV
4454     setuerror(0);
4455 #endif
4456     afs_set_cr_gid(newcred, isroot ? RMTUSER_REQ_PRIV : RMTUSER_REQ);
4457 #ifdef AFS_AIX51_ENV
4458     newcred->cr_groupset.gs_union.un_groups[0] = g0;
4459     newcred->cr_groupset.gs_union.un_groups[1] = g1;
4460 #elif defined(AFS_LINUX26_ENV)
4461 # ifdef AFS_LINUX26_ONEGROUP_ENV
4462     set_cr_group_info(newcred, groups_alloc(1)); /* nothing sets this */
4463     l = (((g0-0x3f00) & 0x3fff) << 14) | ((g1-0x3f00) & 0x3fff);
4464     h = ((g0-0x3f00) >> 14);
4465     h = ((g1-0x3f00) >> 14) + h + h + h;
4466     GROUP_AT(cr_group_info(newcred), 0) = ((h << 28) | l);
4467 # else
4468     set_cr_group_info(newcred, groups_alloc(2));
4469     GROUP_AT(cr_group_info(newcred), 0) = g0;
4470     GROUP_AT(cr_group_info(newcred), 1) = g1;
4471 # endif
4472 #elif defined(AFS_SUN510_ENV)
4473     gids[0] = g0;
4474     gids[1] = g1;
4475     crsetgroups(newcred, 2, gids);
4476 #else
4477     newcred->cr_groups[0] = g0;
4478     newcred->cr_groups[1] = g1;
4479 #endif
4480 #ifdef AFS_AIX_ENV
4481     newcred->cr_ngrps = 2;
4482 #elif !defined(AFS_LINUX26_ENV) && !defined(AFS_SUN510_ENV)
4483 # if defined(AFS_SGI_ENV) || defined(AFS_SUN5_ENV) || defined(AFS_LINUX22_ENV)
4484     newcred->cr_ngroups = 2;
4485 # else
4486     for (i = 2; i < NGROUPS; i++)
4487         newcred->cr_groups[i] = NOGROUP;
4488 # endif
4489 #endif
4490     if (!(exporter = exporter_find(exporter_type))) {
4491         /* Exporter wasn't initialized or an invalid exporter type */
4492         crfree(newcred);
4493         return EINVAL;
4494     }
4495     if (exporter->exp_states & EXP_PWSYNC) {
4496         if (uid != afs_cr_uid(credp)) {
4497             crfree(newcred);
4498             return ENOEXEC;     /* XXX Find a better errno XXX */
4499         }
4500     }
4501     afs_set_cr_uid(newcred, uid);       /* Only temporary  */
4502     code = EXP_REQHANDLER(exporter, &newcred, hostaddr, &pag, &outexporter);
4503     /* The client's pag is the only unique identifier for it */
4504     afs_set_cr_uid(newcred, pag);
4505     *acred = newcred;
4506     if (!code && *com == PSETPAG) {
4507         /* Special case for 'setpag' */
4508         afs_uint32 pagvalue = genpag();
4509
4510         au = afs_GetUser(pagvalue, -1, WRITE_LOCK); /* a new unixuser struct */
4511         /*
4512          * Note that we leave the 'outexporter' struct held so it won't
4513          * dissappear on us
4514          */
4515         au->exporter = outexporter;
4516         if (ablob->out_size >= 4) {
4517             AFS_COPYOUT((char *)&pagvalue, ablob->out, sizeof(afs_int32),
4518                         code);
4519         }
4520         afs_PutUser(au, WRITE_LOCK);
4521         if (code)
4522             return code;
4523         return PSETPAG;         /*  Special return for setpag  */
4524     } else if (!code) {
4525         EXP_RELE(outexporter);
4526     }
4527     if (!code) 
4528         *com = (*com) | comp;
4529     return code;
4530 }
4531 #endif /* AFS_NEED_CLIENTCONTEXT */
4532
4533
4534 /*! 
4535  * VIOC_GETCPREFS (50) - Get client interface
4536  *
4537  * \ingroup pioctl
4538  *
4539  * \param[in] ain       sprefrequest input
4540  * \param[out] aout     spref information
4541  *
4542  * \retval EIO          Error if the afs daemon hasn't started yet
4543  * \retval EINVAL       Error if some of the standard args aren't set
4544  *
4545  * \post
4546  *      get all interface addresses and other information of the client
4547  *      interface
4548  */
4549 DECL_PIOCTL(PGetCPrefs)
4550 {
4551     struct sprefrequest *spin;  /* input */
4552     struct sprefinfo *spout;    /* output */
4553     struct spref *srvout;       /* one output component */
4554     int maxNumber;
4555     int i, j;
4556
4557     AFS_STATCNT(PGetCPrefs);
4558     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
4559         return EIO;             /* Inappropriate ioctl for device */
4560
4561     spin = afs_pd_inline(ain, sizeof(*spin));
4562     if (spin == NULL)
4563         return EINVAL;
4564
4565     /* Output spout relies on writing past the end of arrays. It's horrible,
4566      * but I'm not quite brave enough to tackle it yet */
4567     spout = (struct sprefinfo *)aout->ptr;
4568
4569     maxNumber = spin->num_servers;      /* max addrs this time */
4570     srvout = spout->servers;
4571
4572     ObtainReadLock(&afs_xinterface);
4573
4574     /* copy out the client interface information from the
4575      * kernel data structure "interface" to the output buffer
4576      */
4577     for (i = spin->offset, j = 0; (i < afs_cb_interface.numberOfInterfaces)
4578          && (j < maxNumber); i++, j++, srvout++)
4579         srvout->host.s_addr = afs_cb_interface.addr_in[i];
4580
4581     spout->num_servers = j;
4582     aout->ptr += sizeof(struct sprefinfo) + (j - 1) * sizeof(struct spref);
4583
4584     if (i >= afs_cb_interface.numberOfInterfaces)
4585         spout->next_offset = 0; /* start from beginning again */
4586     else
4587         spout->next_offset = spin->offset + j;
4588
4589     ReleaseReadLock(&afs_xinterface);
4590     return 0;
4591 }
4592
4593 /*!
4594  * VIOC_SETCPREFS (51) - Set client interface
4595  *
4596  * \ingroup pioctl
4597  *
4598  * \param[in] ain       the interfaces you want set
4599  * \param[out] aout     not in use
4600  *
4601  * \retval EIO          Error if the afs daemon hasn't started yet
4602  * \retval EINVAL       Error if the input is too large for the struct
4603  * \retval ENOMEM       Error if there are too many servers
4604  *
4605  * \post set the callbak interfaces addresses to those of the hosts
4606  */
4607 DECL_PIOCTL(PSetCPrefs)
4608 {
4609     char *ainPtr;
4610     size_t ainSize;
4611     struct setspref *sin;
4612     int i;
4613
4614     AFS_STATCNT(PSetCPrefs);
4615     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
4616         return EIO;             /* Inappropriate ioctl for device */
4617
4618     /* Yuck. Input to this function relies on reading past the end of
4619      * structures. Bodge it for now.
4620      */
4621     ainPtr = ain->ptr;
4622     ainSize = ain->remaining;
4623
4624     sin = (struct setspref *)ainPtr;
4625
4626     if (ainSize < sizeof(struct setspref))
4627         return EINVAL;
4628 #if 0                           /* num_servers is unsigned */
4629     if (sin->num_servers < 0)
4630         return EINVAL;
4631 #endif
4632     if (sin->num_servers > AFS_MAX_INTERFACE_ADDR)
4633         return ENOMEM;
4634
4635     ObtainWriteLock(&afs_xinterface, 412);
4636     afs_cb_interface.numberOfInterfaces = sin->num_servers;
4637     for (i = 0; (unsigned short)i < sin->num_servers; i++)
4638         afs_cb_interface.addr_in[i] = sin->servers[i].host.s_addr;
4639
4640     ReleaseWriteLock(&afs_xinterface);
4641     return 0;
4642 }
4643
4644 /*!
4645  * VIOC_AFS_FLUSHMOUNT (52) - Flush mount symlink data
4646  *
4647  * \ingroup pioctl
4648  *
4649  * \param[in] ain
4650  *      the last part of a path to a mount point, which tells us what to flush
4651  * \param[out] aout
4652  *      not in use
4653  *
4654  * \retval EINVAL
4655  *      Error if some of the initial arguments aren't set
4656  * \retval ENOTDIR
4657  *      Error if the initial argument for the mount point isn't a directory
4658  * \retval ENOENT
4659  *      Error if the dcache entry isn't set
4660  *
4661  * \post
4662  *      remove all of the mount data from the dcache regarding a
4663  *      certain mount point
4664  */
4665 DECL_PIOCTL(PFlushMount)
4666 {
4667     register afs_int32 code;
4668     register struct vcache *tvc;
4669     register struct dcache *tdc;
4670     struct VenusFid tfid;
4671     char *bufp;
4672     char *mount;
4673     struct sysname_info sysState;
4674     afs_size_t offset, len;
4675
4676     AFS_STATCNT(PFlushMount);
4677     if (!avc)
4678         return EINVAL;
4679
4680     if (afs_pd_getStringPtr(ain, &mount) != 0)
4681         return EINVAL;
4682
4683     code = afs_VerifyVCache(avc, areq);
4684     if (code)
4685         return code;
4686     if (vType(avc) != VDIR) {
4687         return ENOTDIR;
4688     }
4689     tdc = afs_GetDCache(avc, (afs_size_t) 0, areq, &offset, &len, 1);
4690     if (!tdc)
4691         return ENOENT;
4692     Check_AtSys(avc, mount, &sysState, areq);
4693     ObtainReadLock(&tdc->lock);
4694     do {
4695         code = afs_dir_Lookup(tdc, sysState.name, &tfid.Fid);
4696     } while (code == ENOENT && Next_AtSys(avc, areq, &sysState));
4697     ReleaseReadLock(&tdc->lock);
4698     afs_PutDCache(tdc);         /* we're done with the data */
4699     bufp = sysState.name;
4700     if (code) {
4701         goto out;
4702     }
4703     tfid.Cell = avc->f.fid.Cell;
4704     tfid.Fid.Volume = avc->f.fid.Fid.Volume;
4705     if (!tfid.Fid.Unique && (avc->f.states & CForeign)) {
4706         tvc = afs_LookupVCache(&tfid, areq, NULL, avc, bufp);
4707     } else {
4708         tvc = afs_GetVCache(&tfid, areq, NULL, NULL);
4709     }
4710     if (!tvc) {
4711         code = ENOENT;
4712         goto out;
4713     }
4714     if (tvc->mvstat != 1) {
4715         afs_PutVCache(tvc);
4716         code = EINVAL;
4717         goto out;
4718     }
4719 #ifdef AFS_BOZONLOCK_ENV
4720     afs_BozonLock(&tvc->pvnLock, tvc);  /* Since afs_TryToSmush will do a pvn_vptrunc */
4721 #endif
4722     ObtainWriteLock(&tvc->lock, 649);
4723     ObtainWriteLock(&afs_xcbhash, 650);
4724     afs_DequeueCallback(tvc);
4725     tvc->f.states &= ~(CStatd | CDirty); /* next reference will re-stat cache entry */
4726     ReleaseWriteLock(&afs_xcbhash);
4727     /* now find the disk cache entries */
4728     afs_TryToSmush(tvc, *acred, 1);
4729     osi_dnlc_purgedp(tvc);
4730     if (tvc->linkData && !(tvc->f.states & CCore)) {
4731         afs_osi_Free(tvc->linkData, strlen(tvc->linkData) + 1);
4732         tvc->linkData = NULL;
4733     }
4734     ReleaseWriteLock(&tvc->lock);
4735 #ifdef AFS_BOZONLOCK_ENV
4736     afs_BozonUnlock(&tvc->pvnLock, tvc);
4737 #endif
4738     afs_PutVCache(tvc);
4739   out:
4740     if (sysState.allocked)
4741         osi_FreeLargeSpace(bufp);
4742     return code;
4743 }
4744
4745 /*!
4746  * VIOC_RXSTAT_PROC (53) - Control process RX statistics
4747  *
4748  * \ingroup pioctl
4749  *
4750  * \param[in] ain       the flags that control which stats to use
4751  * \param[out] aout     not in use
4752  *
4753  * \retval EACCES       Error if the user doesn't have super-user credentials
4754  * \retval EINVAL       Error if the flag input is too long
4755  *
4756  * \post
4757  *      either enable process RPCStats, disable process RPCStats,
4758  *      or clear the process RPCStats
4759  */
4760 DECL_PIOCTL(PRxStatProc)
4761 {
4762     afs_int32 flags;
4763
4764     if (!afs_osi_suser(*acred))
4765         return EACCES;
4766
4767     if (afs_pd_getInt(ain, &flags) != 0)
4768         return EINVAL;
4769
4770     if (!(flags & AFSCALL_RXSTATS_MASK) || (flags & ~AFSCALL_RXSTATS_MASK))
4771         return EINVAL;
4772
4773     if (flags & AFSCALL_RXSTATS_ENABLE) {
4774         rx_enableProcessRPCStats();
4775     }
4776     if (flags & AFSCALL_RXSTATS_DISABLE) {
4777         rx_disableProcessRPCStats();
4778     }
4779     if (flags & AFSCALL_RXSTATS_CLEAR) {
4780         rx_clearProcessRPCStats(AFS_RX_STATS_CLEAR_ALL);
4781     }
4782     return 0;
4783 }
4784
4785
4786 /*!
4787  * VIOC_RXSTAT_PEER (54) - Control peer RX statistics
4788  *
4789  * \ingroup pioctl
4790  *
4791  * \param[in] ain       the flags that control which statistics to use
4792  * \param[out] aout     not in use
4793  *
4794  * \retval EACCES       Error if the user doesn't have super-user credentials
4795  * \retval EINVAL       Error if the flag input is too long
4796  *
4797  * \post
4798  *      either enable peer RPCStatws, disable peer RPCStats,
4799  *      or clear the peer RPCStats
4800  */
4801 DECL_PIOCTL(PRxStatPeer)
4802 {
4803     afs_int32 flags;
4804
4805     if (!afs_osi_suser(*acred))
4806         return EACCES;
4807
4808     if (afs_pd_getInt(ain, &flags) != 0)
4809         return EINVAL;
4810
4811     if (!(flags & AFSCALL_RXSTATS_MASK) || (flags & ~AFSCALL_RXSTATS_MASK))
4812         return EINVAL;
4813
4814     if (flags & AFSCALL_RXSTATS_ENABLE) {
4815         rx_enablePeerRPCStats();
4816     }
4817     if (flags & AFSCALL_RXSTATS_DISABLE) {
4818         rx_disablePeerRPCStats();
4819     }
4820     if (flags & AFSCALL_RXSTATS_CLEAR) {
4821         rx_clearPeerRPCStats(AFS_RX_STATS_CLEAR_ALL);
4822     }
4823     return 0;
4824 }
4825
4826 DECL_PIOCTL(PPrefetchFromTape)
4827 {
4828     register afs_int32 code, code1;
4829     afs_int32 bytes, outval;
4830     struct afs_conn *tc;
4831     struct rx_call *tcall;
4832     struct AFSVolSync tsync;
4833     struct AFSFetchStatus OutStatus;
4834     struct AFSCallBack CallBack;
4835     struct VenusFid tfid;
4836     struct AFSFid *Fid;
4837     struct vcache *tvc;
4838
4839     AFS_STATCNT(PSetAcl);
4840     if (!avc)
4841         return EINVAL;
4842
4843     Fid = afs_pd_inline(ain, sizeof(struct AFSFid));
4844     if (Fid == NULL)
4845         Fid = &avc->f.fid.Fid;
4846
4847     tfid.Cell = avc->f.fid.Cell;
4848     tfid.Fid.Volume = Fid->Volume;
4849     tfid.Fid.Vnode = Fid->Vnode;
4850     tfid.Fid.Unique = Fid->Unique;
4851
4852     tvc = afs_GetVCache(&tfid, areq, NULL, NULL);
4853     if (!tvc) {
4854         afs_Trace3(afs_iclSetp, CM_TRACE_PREFETCHCMD, ICL_TYPE_POINTER, tvc,
4855                    ICL_TYPE_FID, &tfid, ICL_TYPE_FID, &avc->f.fid);
4856         return ENOENT;
4857     }
4858     afs_Trace3(afs_iclSetp, CM_TRACE_PREFETCHCMD, ICL_TYPE_POINTER, tvc,
4859                ICL_TYPE_FID, &tfid, ICL_TYPE_FID, &tvc->f.fid);
4860
4861     do {
4862         tc = afs_Conn(&tvc->f.fid, areq, SHARED_LOCK);
4863         if (tc) {
4864
4865             RX_AFS_GUNLOCK();
4866             tcall = rx_NewCall(tc->id);
4867             code =
4868                 StartRXAFS_FetchData(tcall, (struct AFSFid *)&tvc->f.fid.Fid, 0,
4869                                      0);
4870             if (!code) {
4871                 bytes = rx_Read(tcall, (char *)&outval, sizeof(afs_int32));
4872                 code =
4873                     EndRXAFS_FetchData(tcall, &OutStatus, &CallBack, &tsync);
4874             }
4875             code1 = rx_EndCall(tcall, code);
4876             RX_AFS_GLOCK();
4877         } else
4878             code = -1;
4879     } while (afs_Analyze
4880              (tc, code, &tvc->f.fid, areq, AFS_STATS_FS_RPCIDX_RESIDENCYRPCS,
4881               SHARED_LOCK, NULL));
4882     /* This call is done only to have the callback things handled correctly */
4883     afs_FetchStatus(tvc, &tfid, areq, &OutStatus);
4884     afs_PutVCache(tvc);
4885
4886     if (code)
4887         return code;
4888
4889     return afs_pd_putInt(aout, outval);
4890 }
4891
4892 DECL_PIOCTL(PFsCmd)
4893 {
4894     register afs_int32 code;
4895     struct afs_conn *tc;
4896     struct vcache *tvc;
4897     struct FsCmdInputs *Inputs;
4898     struct FsCmdOutputs *Outputs;
4899     struct VenusFid tfid;
4900     struct AFSFid *Fid;
4901
4902     if (!avc)
4903         return EINVAL;
4904
4905     Inputs = afs_pd_inline(ain, sizeof(*Inputs));
4906     if (Inputs == NULL)
4907         return EINVAL;
4908
4909     Outputs = afs_pd_inline(aout, sizeof(*Outputs));
4910     if (Outputs == NULL)
4911         return E2BIG;
4912
4913     Fid = &Inputs->fid;
4914     if (!Fid->Volume)
4915         Fid = &avc->f.fid.Fid;
4916
4917     tfid.Cell = avc->f.fid.Cell;
4918     tfid.Fid.Volume = Fid->Volume;
4919     tfid.Fid.Vnode = Fid->Vnode;
4920     tfid.Fid.Unique = Fid->Unique;
4921
4922     tvc = afs_GetVCache(&tfid, areq, NULL, NULL);
4923     afs_Trace3(afs_iclSetp, CM_TRACE_RESIDCMD, ICL_TYPE_POINTER, tvc,
4924                ICL_TYPE_INT32, Inputs->command, ICL_TYPE_FID, &tfid);
4925     if (!tvc)
4926         return ENOENT;
4927
4928     if (Inputs->command) {
4929         do {
4930             tc = afs_Conn(&tvc->f.fid, areq, SHARED_LOCK);
4931             if (tc) {
4932                 RX_AFS_GUNLOCK();
4933                 code =
4934                     RXAFS_FsCmd(tc->id, Fid, Inputs, 
4935                                         (struct FsCmdOutputs *)aout);
4936                 RX_AFS_GLOCK();
4937             } else
4938                 code = -1;
4939         } while (afs_Analyze
4940                  (tc, code, &tvc->f.fid, areq,
4941                   AFS_STATS_FS_RPCIDX_RESIDENCYRPCS, SHARED_LOCK, NULL));
4942         /* This call is done to have the callback things handled correctly */
4943         afs_FetchStatus(tvc, &tfid, areq, &Outputs->status);
4944     } else {            /* just a status request, return also link data */
4945         code = 0;
4946         Outputs->code = afs_FetchStatus(tvc, &tfid, areq, &Outputs->status);
4947         Outputs->chars[0] = 0;
4948         if (vType(tvc) == VLNK) {
4949             ObtainWriteLock(&tvc->lock, 555);
4950             if (afs_HandleLink(tvc, areq) == 0)
4951                 strncpy((char *)&Outputs->chars, tvc->linkData, MAXCMDCHARS);
4952             ReleaseWriteLock(&tvc->lock);
4953         }
4954     }
4955
4956     afs_PutVCache(tvc);
4957
4958     return code;
4959 }
4960
4961 DECL_PIOCTL(PNewUuid)
4962 {
4963     /*AFS_STATCNT(PNewUuid); */
4964     if (!afs_resourceinit_flag) /* afs deamons havn't started yet */
4965         return EIO;             /* Inappropriate ioctl for device */
4966
4967     if (!afs_osi_suser(*acred))
4968         return EACCES;
4969
4970     ObtainWriteLock(&afs_xinterface, 555);
4971     afs_uuid_create(&afs_cb_interface.uuid);
4972     ReleaseWriteLock(&afs_xinterface);
4973     ForceAllNewConnections();
4974     return 0;
4975 }
4976
4977 #if defined(AFS_CACHE_BYPASS)
4978
4979 DECL_PIOCTL(PSetCachingThreshold)
4980 {
4981     afs_int32 getting = 1;
4982     afs_int32 setting = 1;
4983     afs_int32 threshold;
4984
4985     if (afs_pd_getInt(ain, &threshold) != 0)
4986         setting = 0;
4987
4988     if (aout == NULL)
4989         getting = 0;
4990
4991     if (setting == 0 && getting == 0)
4992         return EINVAL;
4993         
4994     /* 
4995      * If setting, set first, and return the value now in effect
4996      */
4997     if (setting) {
4998         if (!afs_osi_suser(*acred))
4999             return EPERM;
5000         cache_bypass_threshold = threshold;
5001         afs_warn("Cache Bypass Threshold set to: %d\n", threshold);             
5002         /* TODO:  move to separate pioctl, or enhance pioctl */
5003         cache_bypass_strategy = LARGE_FILES_BYPASS_CACHE;
5004     }
5005         
5006     /* Return the current size threshold */
5007     if (getting) {
5008         return afs_pd_putInt32(aout, cache_bypass_threshold);
5009
5010     return(0);
5011 }
5012
5013 #endif /* defined(AFS_CACHE_BYPASS) */
5014
5015 DECL_PIOCTL(PCallBackAddr)
5016 {
5017 #ifndef UKERNEL
5018     afs_uint32 addr, code;
5019     int srvAddrCount;
5020     struct server *ts;
5021     struct srvAddr *sa;
5022     struct afs_conn *tc;
5023     afs_int32 i, j;
5024     struct unixuser *tu;
5025     struct srvAddr **addrs;
5026
5027     /*AFS_STATCNT(PCallBackAddr); */
5028     if (!afs_resourceinit_flag) /* afs deamons havn't started yet */
5029         return EIO;             /* Inappropriate ioctl for device */
5030
5031     if (!afs_osi_suser(acred))
5032         return EACCES;
5033
5034     if (afs_pd_getInt(ain, &addr) != 0)
5035         return EINVAL;
5036
5037     ObtainReadLock(&afs_xinterface);
5038     for (i = 0; (unsigned short)i < afs_cb_interface.numberOfInterfaces; i++) {
5039         if (afs_cb_interface.addr_in[i] == addr)
5040             break;
5041     }
5042
5043     ReleaseWriteLock(&afs_xinterface);
5044
5045     if (afs_cb_interface.addr_in[i] != addr)
5046         return EINVAL;
5047
5048     ObtainReadLock(&afs_xserver);       /* Necessary? */
5049     ObtainReadLock(&afs_xsrvAddr);
5050
5051     srvAddrCount = 0;
5052     for (i = 0; i < NSERVERS; i++) {
5053         for (sa = afs_srvAddrs[i]; sa; sa = sa->next_bkt) {
5054             srvAddrCount++;
5055         }
5056     }
5057
5058     addrs = afs_osi_Alloc(srvAddrCount * sizeof(*addrs));
5059     j = 0;
5060     for (i = 0; i < NSERVERS; i++) {
5061         for (sa = afs_srvAddrs[i]; sa; sa = sa->next_bkt) {
5062             if (j >= srvAddrCount)
5063                 break;
5064             addrs[j++] = sa;
5065         }
5066     }
5067
5068     ReleaseReadLock(&afs_xsrvAddr);
5069     ReleaseReadLock(&afs_xserver);
5070
5071     for (i = 0; i < j; i++) {
5072         sa = addrs[i];
5073         ts = sa->server;
5074         if (!ts)
5075             continue;
5076
5077         /* vlserver has no callback conn */
5078         if (sa->sa_portal == AFS_VLPORT) {
5079             continue;
5080         }
5081
5082         if (!ts->cell)          /* not really an active server, anyway, it must */
5083             continue;           /* have just been added by setsprefs */
5084
5085         /* get a connection, even if host is down; bumps conn ref count */
5086         tu = afs_GetUser(areq->uid, ts->cell->cellNum, SHARED_LOCK);
5087         tc = afs_ConnBySA(sa, ts->cell->fsport, ts->cell->cellNum, tu,
5088                           1 /*force */ , 1 /*create */ , SHARED_LOCK);
5089         afs_PutUser(tu, SHARED_LOCK);
5090         if (!tc)
5091             continue;
5092
5093         if ((sa->sa_flags & SRVADDR_ISDOWN) || afs_HaveCallBacksFrom(ts)) {
5094             if (sa->sa_flags & SRVADDR_ISDOWN) {
5095                 rx_SetConnDeadTime(tc->id, 3);
5096             }
5097 #ifdef RX_ENABLE_LOCKS
5098             AFS_GUNLOCK();
5099 #endif /* RX_ENABLE_LOCKS */
5100             code = RXAFS_CallBackRxConnAddr(tc->id, &addr);
5101 #ifdef RX_ENABLE_LOCKS
5102             AFS_GLOCK();
5103 #endif /* RX_ENABLE_LOCKS */
5104         }
5105         afs_PutConn(tc, SHARED_LOCK);   /* done with it now */
5106     }                           /* Outer loop over addrs */
5107 #endif /* UKERNEL */
5108     return 0;
5109 }
5110
5111 DECL_PIOCTL(PDiscon)
5112 {
5113 #ifdef AFS_DISCON_ENV
5114     static afs_int32 mode = 1; /* Start up in 'off' */
5115     afs_int32 force = 0;
5116     int code = 0;
5117     char flags[3];
5118
5119     if (afs_pd_getBytes(ain, &flags, 3) == 0) {
5120         if (!afs_osi_suser(*acred))
5121             return EPERM;
5122
5123         if (flags[0])
5124             mode = flags[0] - 1;
5125         if (flags[1])
5126             afs_ConflictPolicy = flags[1] - 1;
5127         if (flags[2])
5128             force = 1;
5129
5130         /*
5131          * All of these numbers are hard coded in fs.c. If they
5132          * change here, they should change there and vice versa
5133          */
5134         switch (mode) {
5135         case 0: /* Disconnect ("offline" mode), breaking all callbacks */
5136             if (!AFS_IS_DISCONNECTED) {
5137                 ObtainWriteLock(&afs_discon_lock, 999);
5138                 afs_DisconGiveUpCallbacks();
5139                 afs_RemoveAllConns();
5140                 afs_is_disconnected = 1;
5141                 afs_is_discon_rw = 1;
5142                 ReleaseWriteLock(&afs_discon_lock);
5143             }
5144             break;
5145         case 1: /* Fully connected, ("online" mode). */
5146             ObtainWriteLock(&afs_discon_lock, 998);
5147
5148             afs_in_sync = 1;
5149             afs_MarkAllServersUp();
5150             code = afs_ResyncDisconFiles(areq, *acred);
5151             afs_in_sync = 0;
5152
5153             if (code && !force) {
5154                 printf("Files not synchronized properly, still in discon state. \n"
5155                        "Please retry or use \"force\".\n");
5156                 mode = 0;
5157             } else {
5158                 if (force) {
5159                     afs_DisconDiscardAll(*acred);
5160                 }
5161                 afs_ClearAllStatdFlag();
5162                 afs_is_disconnected = 0;
5163                 afs_is_discon_rw = 0;
5164                 printf("\nSync succeeded. You are back online.\n");
5165             }
5166
5167             ReleaseWriteLock(&afs_discon_lock);
5168             break;
5169         default:
5170             return EINVAL;
5171         }
5172     } else {
5173         return EINVAL;
5174     }
5175
5176     if (code)
5177         return code;
5178
5179     return afs_pd_putInt(aout, mode);
5180 #else
5181     return EINVAL;
5182 #endif
5183 }
5184
5185 DECL_PIOCTL(PNFSNukeCreds)
5186 {
5187     afs_uint32 addr;
5188     register afs_int32 i;
5189     register struct unixuser *tu;
5190
5191     AFS_STATCNT(PUnlog);
5192     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
5193         return EIO;             /* Inappropriate ioctl for device */
5194
5195     if (afs_pd_getUint(ain, &addr) != 0)
5196         return EINVAL;
5197
5198     if (afs_cr_gid(*acred) == RMTUSER_REQ_PRIV && !addr) {
5199         tu = afs_GetUser(areq->uid, -1, SHARED_LOCK);
5200         if (!tu->exporter || !(addr = EXP_GETHOST(tu->exporter))) {
5201             afs_PutUser(tu, SHARED_LOCK);
5202             return EACCES;
5203         }
5204         afs_PutUser(tu, SHARED_LOCK);
5205     } else if (!afs_osi_suser(acred)) {
5206         return EACCES;
5207     }
5208
5209     ObtainWriteLock(&afs_xuser, 227);
5210     for (i = 0; i < NUSERS; i++) {
5211         for (tu = afs_users[i]; tu; tu = tu->next) {
5212             if (tu->exporter && EXP_CHECKHOST(tu->exporter, addr)) {
5213                 tu->vid = UNDEFVID;
5214                 tu->states &= ~UHasTokens;
5215                 /* security is not having to say you're sorry */
5216                 memset(&tu->ct, 0, sizeof(struct ClearToken));
5217                 tu->refCount++;
5218                 ReleaseWriteLock(&afs_xuser);
5219                 afs_ResetUserConns(tu);
5220                 tu->refCount--;
5221                 ObtainWriteLock(&afs_xuser, 228);
5222 #ifdef UKERNEL
5223                 /* set the expire times to 0, causes
5224                  * afs_GCUserData to remove this entry
5225                  */
5226                 tu->ct.EndTimestamp = 0;
5227                 tu->tokenTime = 0;
5228 #endif /* UKERNEL */
5229             }
5230         }
5231     }
5232     ReleaseWriteLock(&afs_xuser);
5233     return 0;
5234 }