libafs: Get rx conn ref with afs conn ref
[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_FBSD_ENV
19 #include "h/sysproto.h"
20 #endif
21 #ifdef AFS_NBSD40_ENV
22 #include <sys/ioctl.h>
23 #include <sys/ioccom.h>
24 #endif
25 #include "afsincludes.h"        /* Afs-based standard headers */
26 #include "afs/afs_stats.h"      /* afs statistics */
27 #include "afs/vice.h"
28 #include "afs/afs_bypasscache.h"
29 #include "rx/rx_globals.h"
30 #include "token.h"
31
32 struct VenusFid afs_rootFid;
33 afs_int32 afs_waitForever = 0;
34 short afs_waitForeverCount = 0;
35 afs_int32 afs_showflags = GAGUSER | GAGCONSOLE; /* show all messages */
36
37 afs_int32 afs_is_disconnected;
38 afs_int32 afs_is_discon_rw;
39 /* On reconnection, turn this knob on until it finishes,
40  * then turn it off.
41  */
42 afs_int32 afs_in_sync = 0;
43
44 struct afs_pdata {
45     char *ptr;
46     size_t remaining;
47 };
48
49 /*
50  * A set of handy little functions for encoding and decoding
51  * pioctls without losing your marbles, or memory integrity
52  */
53
54 static_inline int
55 afs_pd_alloc(struct afs_pdata *apd, size_t size)
56 {
57
58     if (size > AFS_LRALLOCSIZ)
59         apd->ptr = osi_Alloc(size + 1);
60     else
61         apd->ptr = osi_AllocLargeSpace(AFS_LRALLOCSIZ);
62
63     if (apd->ptr == NULL)
64         return ENOMEM;
65
66     apd->remaining = size;
67
68     return 0;
69 }
70
71 static_inline void
72 afs_pd_free(struct afs_pdata *apd)
73 {
74     if (apd->ptr == NULL)
75         return;
76
77     if (apd->remaining > AFS_LRALLOCSIZ)
78         osi_Free(apd->ptr, apd->remaining + 1);
79     else
80         osi_FreeLargeSpace(apd->ptr);
81
82     apd->ptr = NULL;
83     apd->remaining = 0;
84 }
85
86 static_inline char *
87 afs_pd_where(struct afs_pdata *apd)
88 {
89     return apd ? apd->ptr : NULL;
90 }
91
92 static_inline size_t
93 afs_pd_remaining(struct afs_pdata *apd)
94 {
95     return apd ? apd->remaining : 0;
96 }
97
98 static_inline int
99 afs_pd_skip(struct afs_pdata *apd, size_t skip)
100 {
101     if (apd == NULL || apd->remaining < skip)
102         return EINVAL;
103     apd->remaining -= skip;
104     apd->ptr += skip;
105
106     return 0;
107 }
108
109 static_inline int
110 afs_pd_getBytes(struct afs_pdata *apd, void *dest, size_t bytes)
111 {
112     if (apd == NULL || apd->remaining < bytes)
113         return EINVAL;
114     apd->remaining -= bytes;
115     memcpy(dest, apd->ptr, bytes);
116     apd->ptr += bytes;
117     return 0;
118 }
119
120 static_inline int
121 afs_pd_getInt(struct afs_pdata *apd, afs_int32 *val)
122 {
123     return afs_pd_getBytes(apd, val, sizeof(*val));
124 }
125
126 static_inline int
127 afs_pd_getUint(struct afs_pdata *apd, afs_uint32 *val)
128 {
129     return afs_pd_getBytes(apd, val, sizeof(*val));
130 }
131
132 static_inline void *
133 afs_pd_inline(struct afs_pdata *apd, size_t bytes)
134 {
135     void *ret;
136
137     if (apd == NULL || apd->remaining < bytes)
138         return NULL;
139
140     ret = apd->ptr;
141
142     apd->remaining -= bytes;
143     apd->ptr += bytes;
144
145     return ret;
146 }
147
148 static_inline void
149 afs_pd_xdrStart(struct afs_pdata *apd, XDR *xdrs, enum xdr_op op) {
150     xdrmem_create(xdrs, apd->ptr, apd->remaining, op);
151 }
152
153 static_inline void
154 afs_pd_xdrEnd(struct afs_pdata *apd, XDR *xdrs) {
155     size_t pos;
156
157     pos = xdr_getpos(xdrs);
158     apd->ptr += pos;
159     apd->remaining -= pos;
160     xdr_destroy(xdrs);
161 }
162
163
164
165 static_inline int
166 afs_pd_getString(struct afs_pdata *apd, char *str, size_t maxLen)
167 {
168     size_t len;
169
170     if (apd == NULL || apd->remaining <= 0)
171         return EINVAL;
172     len = strlen(apd->ptr) + 1;
173     if (len > maxLen)
174         return E2BIG;
175     memcpy(str, apd->ptr, len);
176     apd->ptr += len;
177     apd->remaining -= len;
178     return 0;
179 }
180
181 static_inline int
182 afs_pd_getStringPtr(struct afs_pdata *apd, char **str)
183 {
184     size_t len;
185
186     if (apd == NULL || apd->remaining <= 0)
187         return EINVAL;
188     len = strlen(apd->ptr) + 1;
189     *str = apd->ptr;
190     apd->ptr += len;
191     apd->remaining -= len;
192     return 0;
193 }
194
195 static_inline int
196 afs_pd_putBytes(struct afs_pdata *apd, const void *bytes, size_t len)
197 {
198     if (apd == NULL || apd->remaining < len)
199         return E2BIG;
200     memcpy(apd->ptr, bytes, len);
201     apd->ptr += len;
202     apd->remaining -= len;
203     return 0;
204 }
205
206 static_inline int
207 afs_pd_putInt(struct afs_pdata *apd, afs_int32 val)
208 {
209     return afs_pd_putBytes(apd, &val, sizeof(val));
210 }
211
212 static_inline int
213 afs_pd_putString(struct afs_pdata *apd, char *str) {
214
215     /* Add 1 so we copy the NULL too */
216     return afs_pd_putBytes(apd, str, strlen(str) +1);
217 }
218
219 /*!
220  * \defgroup pioctl Path IOCTL functions
221  *
222  * DECL_PIOCTL is a macro defined to contain the following parameters for functions:
223  *
224  * \param[in] avc
225  *      the AFS vcache structure in use by pioctl
226  * \param[in] afun
227  *      not in use
228  * \param[in] areq
229  *      the AFS vrequest structure
230  * \param[in] ain
231  *      an afs_pdata block describing the data received from the caller
232  * \param[in] aout
233  *      an afs_pdata block describing a pre-allocated block for output
234  * \param[in] acred
235  *      UNIX credentials structure underlying the operation
236  */
237
238 #define DECL_PIOCTL(x) \
239         static int x(struct vcache *avc, int afun, struct vrequest *areq, \
240                      struct afs_pdata *ain, struct afs_pdata *aout, \
241                      afs_ucred_t **acred)
242
243 /* Prototypes for pioctl routines */
244 DECL_PIOCTL(PGetFID);
245 DECL_PIOCTL(PSetAcl);
246 DECL_PIOCTL(PStoreBehind);
247 DECL_PIOCTL(PGCPAGs);
248 DECL_PIOCTL(PGetAcl);
249 DECL_PIOCTL(PNoop);
250 DECL_PIOCTL(PBogus);
251 DECL_PIOCTL(PGetFileCell);
252 DECL_PIOCTL(PGetWSCell);
253 DECL_PIOCTL(PGetUserCell);
254 DECL_PIOCTL(PSetTokens);
255 DECL_PIOCTL(PSetTokens2);
256 DECL_PIOCTL(PGetVolumeStatus);
257 DECL_PIOCTL(PSetVolumeStatus);
258 DECL_PIOCTL(PFlush);
259 DECL_PIOCTL(PNewStatMount);
260 DECL_PIOCTL(PGetTokens);
261 DECL_PIOCTL(PGetTokens2);
262 DECL_PIOCTL(PUnlog);
263 DECL_PIOCTL(PMariner);
264 DECL_PIOCTL(PCheckServers);
265 DECL_PIOCTL(PCheckVolNames);
266 DECL_PIOCTL(PCheckAuth);
267 DECL_PIOCTL(PFindVolume);
268 DECL_PIOCTL(PViceAccess);
269 DECL_PIOCTL(PSetCacheSize);
270 DECL_PIOCTL(PGetCacheSize);
271 DECL_PIOCTL(PRemoveCallBack);
272 DECL_PIOCTL(PNewCell);
273 DECL_PIOCTL(PNewAlias);
274 DECL_PIOCTL(PListCells);
275 DECL_PIOCTL(PListAliases);
276 DECL_PIOCTL(PRemoveMount);
277 DECL_PIOCTL(PGetCellStatus);
278 DECL_PIOCTL(PSetCellStatus);
279 DECL_PIOCTL(PFlushVolumeData);
280 DECL_PIOCTL(PGetVnodeXStatus);
281 DECL_PIOCTL(PGetVnodeXStatus2);
282 DECL_PIOCTL(PSetSysName);
283 DECL_PIOCTL(PSetSPrefs);
284 DECL_PIOCTL(PSetSPrefs33);
285 DECL_PIOCTL(PGetSPrefs);
286 DECL_PIOCTL(PExportAfs);
287 DECL_PIOCTL(PGag);
288 DECL_PIOCTL(PTwiddleRx);
289 DECL_PIOCTL(PGetInitParams);
290 DECL_PIOCTL(PGetRxkcrypt);
291 DECL_PIOCTL(PSetRxkcrypt);
292 DECL_PIOCTL(PGetCPrefs);
293 DECL_PIOCTL(PSetCPrefs);
294 DECL_PIOCTL(PFlushMount);
295 DECL_PIOCTL(PRxStatProc);
296 DECL_PIOCTL(PRxStatPeer);
297 DECL_PIOCTL(PPrefetchFromTape);
298 DECL_PIOCTL(PFsCmd);
299 DECL_PIOCTL(PCallBackAddr);
300 DECL_PIOCTL(PDiscon);
301 DECL_PIOCTL(PNFSNukeCreds);
302 DECL_PIOCTL(PNewUuid);
303 DECL_PIOCTL(PPrecache);
304 DECL_PIOCTL(PGetPAG);
305 #if defined(AFS_CACHE_BYPASS) && defined(AFS_LINUX24_ENV)
306 DECL_PIOCTL(PSetCachingThreshold);
307 #endif
308
309 /*
310  * A macro that says whether we're going to need HandleClientContext().
311  * This is currently used only by the nfs translator.
312  */
313 #if !defined(AFS_NONFSTRANS) || defined(AFS_AIX_IAUTH_ENV)
314 #define AFS_NEED_CLIENTCONTEXT
315 #endif
316
317 /* Prototypes for private routines */
318 #ifdef AFS_NEED_CLIENTCONTEXT
319 static int HandleClientContext(struct afs_ioctl *ablob, int *com,
320                                afs_ucred_t **acred,
321                                afs_ucred_t *credp);
322 #endif
323 int HandleIoctl(struct vcache *avc, afs_int32 acom,
324                 struct afs_ioctl *adata);
325 int afs_HandlePioctl(struct vnode *avp, afs_int32 acom,
326                      struct afs_ioctl *ablob, int afollow,
327                      afs_ucred_t **acred);
328 static int Prefetch(uparmtype apath, struct afs_ioctl *adata, int afollow,
329                     afs_ucred_t *acred);
330
331 typedef int (*pioctlFunction) (struct vcache *, int, struct vrequest *,
332                                struct afs_pdata *, struct afs_pdata *,
333                                afs_ucred_t **);
334
335 static pioctlFunction VpioctlSw[] = {
336     PBogus,                     /* 0 */
337     PSetAcl,                    /* 1 */
338     PGetAcl,                    /* 2 */
339     PSetTokens,                 /* 3 */
340     PGetVolumeStatus,           /* 4 */
341     PSetVolumeStatus,           /* 5 */
342     PFlush,                     /* 6 */
343     PBogus,                     /* 7 */
344     PGetTokens,                 /* 8 */
345     PUnlog,                     /* 9 */
346     PCheckServers,              /* 10 */
347     PCheckVolNames,             /* 11 */
348     PCheckAuth,                 /* 12 */
349     PBogus,                     /* 13 -- used to be quick check time */
350     PFindVolume,                /* 14 */
351     PBogus,                     /* 15 -- prefetch is now special-cased; see pioctl code! */
352     PBogus,                     /* 16 -- used to be testing code */
353     PNoop,                      /* 17 -- used to be enable group */
354     PNoop,                      /* 18 -- used to be disable group */
355     PBogus,                     /* 19 -- used to be list group */
356     PViceAccess,                /* 20 */
357     PUnlog,                     /* 21 -- unlog *is* unpag in this system */
358     PGetFID,                    /* 22 -- get file ID */
359     PBogus,                     /* 23 -- used to be waitforever */
360     PSetCacheSize,              /* 24 */
361     PRemoveCallBack,            /* 25 -- flush only the callback */
362     PNewCell,                   /* 26 */
363     PListCells,                 /* 27 */
364     PRemoveMount,               /* 28 -- delete mount point */
365     PNewStatMount,              /* 29 -- new style mount point stat */
366     PGetFileCell,               /* 30 -- get cell name for input file */
367     PGetWSCell,                 /* 31 -- get cell name for workstation */
368     PMariner,                   /* 32 - set/get mariner host */
369     PGetUserCell,               /* 33 -- get cell name for user */
370     PBogus,                     /* 34 -- Enable/Disable logging */
371     PGetCellStatus,             /* 35 */
372     PSetCellStatus,             /* 36 */
373     PFlushVolumeData,           /* 37 -- flush all data from a volume */
374     PSetSysName,                /* 38 - Set system name */
375     PExportAfs,                 /* 39 - Export Afs to remote nfs clients */
376     PGetCacheSize,              /* 40 - get cache size and usage */
377     PGetVnodeXStatus,           /* 41 - get vcache's special status */
378     PSetSPrefs33,               /* 42 - Set CM Server preferences... */
379     PGetSPrefs,                 /* 43 - Get CM Server preferences... */
380     PGag,                       /* 44 - turn off/on all CM messages */
381     PTwiddleRx,                 /* 45 - adjust some RX params       */
382     PSetSPrefs,                 /* 46 - Set CM Server preferences... */
383     PStoreBehind,               /* 47 - set degree of store behind to be done */
384     PGCPAGs,                    /* 48 - disable automatic pag gc-ing */
385     PGetInitParams,             /* 49 - get initial cm params */
386     PGetCPrefs,                 /* 50 - get client interface addresses */
387     PSetCPrefs,                 /* 51 - set client interface addresses */
388     PFlushMount,                /* 52 - flush mount symlink data */
389     PRxStatProc,                /* 53 - control process RX statistics */
390     PRxStatPeer,                /* 54 - control peer RX statistics */
391     PGetRxkcrypt,               /* 55 -- Get rxkad encryption flag */
392     PSetRxkcrypt,               /* 56 -- Set rxkad encryption flag */
393     PBogus,                     /* 57 -- arla: set file prio */
394     PBogus,                     /* 58 -- arla: fallback getfh */
395     PBogus,                     /* 59 -- arla: fallback fhopen */
396     PBogus,                     /* 60 -- arla: controls xfsdebug */
397     PBogus,                     /* 61 -- arla: controls arla debug */
398     PBogus,                     /* 62 -- arla: debug interface */
399     PBogus,                     /* 63 -- arla: print xfs status */
400     PBogus,                     /* 64 -- arla: force cache check */
401     PBogus,                     /* 65 -- arla: break callback */
402     PPrefetchFromTape,          /* 66 -- MR-AFS: prefetch file from tape */
403     PFsCmd,                     /* 67 -- RXOSD: generic commnd interface */
404     PBogus,                     /* 68 -- arla: fetch stats */
405     PGetVnodeXStatus2,          /* 69 - get caller access and some vcache status */
406 };
407
408 static pioctlFunction CpioctlSw[] = {
409     PBogus,                     /* 0 */
410     PNewAlias,                  /* 1 -- create new cell alias */
411     PListAliases,               /* 2 -- list cell aliases */
412     PCallBackAddr,              /* 3 -- request addr for callback rxcon */
413     PBogus,                     /* 4 */
414     PDiscon,                    /* 5 -- get/set discon mode */
415     PBogus,                     /* 6 */
416     PGetTokens2,                /* 7 */
417     PSetTokens2,                /* 8 */
418     PNewUuid,                   /* 9 */
419     PBogus,                     /* 10 */
420     PBogus,                     /* 11 */
421     PPrecache,                  /* 12 */
422     PGetPAG,                    /* 13 */
423 };
424
425 static pioctlFunction OpioctlSw[]  = {
426     PBogus,                     /* 0 */
427     PNFSNukeCreds,              /* 1 -- nuke all creds for NFS client */
428 #if defined(AFS_CACHE_BYPASS) && defined(AFS_LINUX24_ENV)
429     PSetCachingThreshold        /* 2 -- get/set cache-bypass size threshold */
430 #else
431     PNoop                       /* 2 -- get/set cache-bypass size threshold */
432 #endif
433 };
434
435 #define PSetClientContext 99    /*  Special pioctl to setup caller's creds  */
436 int afs_nobody = NFS_NOBODY;
437
438 int
439 HandleIoctl(struct vcache *avc, afs_int32 acom,
440             struct afs_ioctl *adata)
441 {
442     afs_int32 code;
443
444     code = 0;
445     AFS_STATCNT(HandleIoctl);
446
447     switch (acom & 0xff) {
448     case 1:
449         avc->f.states |= CSafeStore;
450         avc->asynchrony = 0;
451         /* SXW - Should we force a MetaData flush for this flag setting */
452         break;
453
454         /* case 2 used to be abort store, but this is no longer provided,
455          * since it is impossible to implement under normal Unix.
456          */
457
458     case 3:{
459             /* return the name of the cell this file is open on */
460             struct cell *tcell;
461             afs_int32 i;
462
463             tcell = afs_GetCell(avc->f.fid.Cell, READ_LOCK);
464             if (tcell) {
465                 i = strlen(tcell->cellName) + 1;        /* bytes to copy out */
466
467                 if (i > adata->out_size) {
468                     /* 0 means we're not interested in the output */
469                     if (adata->out_size != 0)
470                         code = EFAULT;
471                 } else {
472                     /* do the copy */
473                     AFS_COPYOUT(tcell->cellName, adata->out, i, code);
474                 }
475                 afs_PutCell(tcell, READ_LOCK);
476             } else
477                 code = ENOTTY;
478         }
479         break;
480
481     case 49:                    /* VIOC_GETINITPARAMS */
482         if (adata->out_size < sizeof(struct cm_initparams)) {
483             code = EFAULT;
484         } else {
485             AFS_COPYOUT(&cm_initParams, adata->out,
486                         sizeof(struct cm_initparams), code);
487         }
488         break;
489
490     default:
491
492         code = EINVAL;
493 #ifdef AFS_AIX51_ENV
494         code = ENOSYS;
495 #endif
496         break;
497     }
498     return code;                /* so far, none implemented */
499 }
500
501 #ifdef AFS_AIX_ENV
502 /* For aix we don't temporarily bypass ioctl(2) but rather do our
503  * thing directly in the vnode layer call, VNOP_IOCTL; thus afs_ioctl
504  * is now called from afs_gn_ioctl.
505  */
506 int
507 afs_ioctl(struct vcache *tvc, int cmd, int arg)
508 {
509     struct afs_ioctl data;
510     int error = 0;
511
512     AFS_STATCNT(afs_ioctl);
513     if (((cmd >> 8) & 0xff) == 'V') {
514         /* This is a VICEIOCTL call */
515         AFS_COPYIN(arg, (caddr_t) & data, sizeof(data), error);
516         if (error)
517             return (error);
518         error = HandleIoctl(tvc, cmd, &data);
519         return (error);
520     } else {
521         /* No-op call; just return. */
522         return (ENOTTY);
523     }
524 }
525 # if defined(AFS_AIX32_ENV)
526 #  if defined(AFS_AIX51_ENV)
527 #   ifdef __64BIT__
528 int
529 kioctl(int fdes, int com, caddr_t arg, caddr_t ext, caddr_t arg2,
530            caddr_t arg3)
531 #   else /* __64BIT__ */
532 int
533 kioctl32(int fdes, int com, caddr_t arg, caddr_t ext, caddr_t arg2,
534              caddr_t arg3)
535 #   endif /* __64BIT__ */
536 #  else
537 int
538 kioctl(int fdes, int com, caddr_t arg, caddr_t ext)
539 #  endif /* AFS_AIX51_ENV */
540 {
541     struct a {
542         int fd, com;
543         caddr_t arg, ext;
544 #  ifdef AFS_AIX51_ENV
545         caddr_t arg2, arg3;
546 #  endif
547     } u_uap, *uap = &u_uap;
548     struct file *fd;
549     struct vcache *tvc;
550     int ioctlDone = 0, code = 0;
551
552     AFS_STATCNT(afs_xioctl);
553     uap->fd = fdes;
554     uap->com = com;
555     uap->arg = arg;
556 #  ifdef AFS_AIX51_ENV
557     uap->arg2 = arg2;
558     uap->arg3 = arg3;
559 #  endif
560     if (setuerror(getf(uap->fd, &fd))) {
561         return -1;
562     }
563     if (fd->f_type == DTYPE_VNODE) {
564         /* good, this is a vnode; next see if it is an AFS vnode */
565         tvc = VTOAFS(fd->f_vnode);      /* valid, given a vnode */
566         if (tvc && IsAfsVnode(AFSTOV(tvc))) {
567             /* This is an AFS vnode */
568             if (((uap->com >> 8) & 0xff) == 'V') {
569                 struct afs_ioctl *datap;
570                 AFS_GLOCK();
571                 datap =
572                     (struct afs_ioctl *)osi_AllocSmallSpace(AFS_SMALLOCSIZ);
573                 code=copyin_afs_ioctl((char *)uap->arg, datap);
574                 if (code) {
575                     osi_FreeSmallSpace(datap);
576                     AFS_GUNLOCK();
577 #  if defined(AFS_AIX41_ENV)
578                     ufdrele(uap->fd);
579 #  endif
580                     return (setuerror(code), code);
581                 }
582                 code = HandleIoctl(tvc, uap->com, datap);
583                 osi_FreeSmallSpace(datap);
584                 AFS_GUNLOCK();
585                 ioctlDone = 1;
586 #  if defined(AFS_AIX41_ENV)
587                 ufdrele(uap->fd);
588 #  endif
589              }
590         }
591     }
592     if (!ioctlDone) {
593 #  if defined(AFS_AIX41_ENV)
594         ufdrele(uap->fd);
595 #   if defined(AFS_AIX51_ENV)
596 #    ifdef __64BIT__
597         code = okioctl(fdes, com, arg, ext, arg2, arg3);
598 #    else /* __64BIT__ */
599         code = okioctl32(fdes, com, arg, ext, arg2, arg3);
600 #    endif /* __64BIT__ */
601 #   else /* !AFS_AIX51_ENV */
602         code = okioctl(fdes, com, arg, ext);
603 #   endif /* AFS_AIX51_ENV */
604         return code;
605 #  elif defined(AFS_AIX32_ENV)
606         okioctl(fdes, com, arg, ext);
607 #  endif
608     }
609 #  if defined(KERNEL_HAVE_UERROR)
610     if (!getuerror())
611         setuerror(code);
612 #   if !defined(AFS_AIX41_ENV)
613     return (getuerror()? -1 : u.u_ioctlrv);
614 #   else
615     return getuerror()? -1 : 0;
616 #   endif
617 #  endif
618     return 0;
619 }
620 # endif
621
622 #elif defined(AFS_SGI_ENV)
623 # if defined(AFS_SGI65_ENV)
624 afs_ioctl(OSI_VN_DECL(tvc), int cmd, void *arg, int flag, cred_t * cr,
625           rval_t * rvalp, struct vopbd * vbds)
626 # else
627 afs_ioctl(OSI_VN_DECL(tvc), int cmd, void *arg, int flag, cred_t * cr,
628           rval_t * rvalp, struct vopbd * vbds)
629 # endif
630 {
631     struct afs_ioctl data;
632     int error = 0;
633     int locked;
634
635     OSI_VN_CONVERT(tvc);
636
637     AFS_STATCNT(afs_ioctl);
638     if (((cmd >> 8) & 0xff) == 'V') {
639         /* This is a VICEIOCTL call */
640         error = copyin_afs_ioctl(arg, &data);
641         if (error)
642             return (error);
643         locked = ISAFS_GLOCK();
644         if (!locked)
645             AFS_GLOCK();
646         error = HandleIoctl(tvc, cmd, &data);
647         if (!locked)
648             AFS_GUNLOCK();
649         return (error);
650     } else {
651         /* No-op call; just return. */
652         return (ENOTTY);
653     }
654 }
655 #elif defined(AFS_SUN5_ENV)
656 struct afs_ioctl_sys {
657     int fd;
658     int com;
659     int arg;
660 };
661
662 int
663 afs_xioctl(struct afs_ioctl_sys *uap, rval_t *rvp)
664 {
665     struct file *fd;
666     struct vcache *tvc;
667     int ioctlDone = 0, code = 0;
668
669     AFS_STATCNT(afs_xioctl);
670 # if defined(AFS_SUN57_ENV)
671     fd = getf(uap->fd);
672     if (!fd)
673         return (EBADF);
674 # elif defined(AFS_SUN54_ENV)
675     fd = GETF(uap->fd);
676     if (!fd)
677         return (EBADF);
678 # else
679     if (code = getf(uap->fd, &fd)) {
680         return (code);
681     }
682 # endif
683     if (fd->f_vnode->v_type == VREG || fd->f_vnode->v_type == VDIR) {
684         tvc = VTOAFS(fd->f_vnode);      /* valid, given a vnode */
685         if (tvc && IsAfsVnode(AFSTOV(tvc))) {
686             /* This is an AFS vnode */
687             if (((uap->com >> 8) & 0xff) == 'V') {
688                 struct afs_ioctl *datap;
689                 AFS_GLOCK();
690                 datap =
691                     (struct afs_ioctl *)osi_AllocSmallSpace(AFS_SMALLOCSIZ);
692                 code=copyin_afs_ioctl((char *)uap->arg, datap);
693                 if (code) {
694                     osi_FreeSmallSpace(datap);
695                     AFS_GUNLOCK();
696 # if defined(AFS_SUN54_ENV)
697                     releasef(uap->fd);
698 # else
699                     releasef(fd);
700 # endif
701                     return (EFAULT);
702                 }
703                 code = HandleIoctl(tvc, uap->com, datap);
704                 osi_FreeSmallSpace(datap);
705                 AFS_GUNLOCK();
706                 ioctlDone = 1;
707             }
708         }
709     }
710 # if defined(AFS_SUN57_ENV)
711     releasef(uap->fd);
712 # elif defined(AFS_SUN54_ENV)
713     RELEASEF(uap->fd);
714 # else
715     releasef(fd);
716 # endif
717     if (!ioctlDone)
718         code = ioctl(uap, rvp);
719
720     return (code);
721 }
722 #elif defined(AFS_LINUX22_ENV)
723 struct afs_ioctl_sys {
724     unsigned int com;
725     unsigned long arg;
726 };
727 int
728 afs_xioctl(struct inode *ip, struct file *fp, unsigned int com,
729            unsigned long arg)
730 {
731     struct afs_ioctl_sys ua, *uap = &ua;
732     struct vcache *tvc;
733     int code = 0;
734
735     AFS_STATCNT(afs_xioctl);
736     ua.com = com;
737     ua.arg = arg;
738
739     tvc = VTOAFS(ip);
740     if (tvc && IsAfsVnode(AFSTOV(tvc))) {
741         /* This is an AFS vnode */
742         if (((uap->com >> 8) & 0xff) == 'V') {
743             struct afs_ioctl *datap;
744             AFS_GLOCK();
745             datap = osi_AllocSmallSpace(AFS_SMALLOCSIZ);
746             code = copyin_afs_ioctl((char *)uap->arg, datap);
747             if (code) {
748                 osi_FreeSmallSpace(datap);
749                 AFS_GUNLOCK();
750                 return -code;
751             }
752             code = HandleIoctl(tvc, uap->com, datap);
753             osi_FreeSmallSpace(datap);
754             AFS_GUNLOCK();
755         }
756         else
757             code = EINVAL;
758     }
759     return -code;
760 }
761 #elif defined(AFS_DARWIN_ENV) && !defined(AFS_DARWIN80_ENV)
762 struct ioctl_args {
763     int fd;
764     u_long com;
765     caddr_t arg;
766 };
767
768 int
769 afs_xioctl(afs_proc_t *p, struct ioctl_args *uap, register_t *retval)
770 {
771     struct file *fd;
772     struct vcache *tvc;
773     int ioctlDone = 0, code = 0;
774
775     AFS_STATCNT(afs_xioctl);
776     if ((code = fdgetf(p, uap->fd, &fd)))
777         return code;
778     if (fd->f_type == DTYPE_VNODE) {
779         tvc = VTOAFS((struct vnode *)fd->f_data);       /* valid, given a vnode */
780         if (tvc && IsAfsVnode(AFSTOV(tvc))) {
781             /* This is an AFS vnode */
782             if (((uap->com >> 8) & 0xff) == 'V') {
783                 struct afs_ioctl *datap;
784                 AFS_GLOCK();
785                 datap = osi_AllocSmallSpace(AFS_SMALLOCSIZ);
786                 code = copyin_afs_ioctl((char *)uap->arg, datap);
787                 if (code) {
788                     osi_FreeSmallSpace(datap);
789                     AFS_GUNLOCK();
790                     return code;
791                 }
792                 code = HandleIoctl(tvc, uap->com, datap);
793                 osi_FreeSmallSpace(datap);
794                 AFS_GUNLOCK();
795                 ioctlDone = 1;
796             }
797         }
798     }
799
800     if (!ioctlDone)
801         return ioctl(p, uap, retval);
802
803     return (code);
804 }
805 #elif defined(AFS_XBSD_ENV)
806 # if defined(AFS_FBSD_ENV)
807 #  define arg data
808 int
809 afs_xioctl(struct thread *td, struct ioctl_args *uap,
810            register_t *retval)
811 {
812     afs_proc_t *p = td->td_proc;
813 # else
814 struct ioctl_args {
815     int fd;
816     u_long com;
817     caddr_t arg;
818 };
819
820 int
821 afs_xioctl(afs_proc_t *p, struct ioctl_args *uap, register_t *retval)
822 {
823 # endif
824     struct filedesc *fdp;
825     struct vcache *tvc;
826     int ioctlDone = 0, code = 0;
827     struct file *fd;
828
829     AFS_STATCNT(afs_xioctl);
830 #   if defined(AFS_NBSD40_ENV)
831      fdp = p->l_proc->p_fd;
832 #   else
833     fdp = p->p_fd;
834 #endif
835     if ((u_int) uap->fd >= fdp->fd_nfiles
836         || (fd = fdp->fd_ofiles[uap->fd]) == NULL)
837         return EBADF;
838     if ((fd->f_flag & (FREAD | FWRITE)) == 0)
839         return EBADF;
840     /* first determine whether this is any sort of vnode */
841     if (fd->f_type == DTYPE_VNODE) {
842         /* good, this is a vnode; next see if it is an AFS vnode */
843 # if defined(AFS_OBSD_ENV)
844         tvc =
845             IsAfsVnode((struct vnode *)fd->
846                        f_data) ? VTOAFS((struct vnode *)fd->f_data) : NULL;
847 # else
848         tvc = VTOAFS((struct vnode *)fd->f_data);       /* valid, given a vnode */
849 # endif
850         if (tvc && IsAfsVnode(AFSTOV(tvc))) {
851             /* This is an AFS vnode */
852             if (((uap->com >> 8) & 0xff) == 'V') {
853                 struct afs_ioctl *datap;
854                 AFS_GLOCK();
855                 datap = osi_AllocSmallSpace(AFS_SMALLOCSIZ);
856                 code = copyin_afs_ioctl((char *)uap->arg, datap);
857                 if (code) {
858                     osi_FreeSmallSpace(datap);
859                     AFS_GUNLOCK();
860                     return code;
861                 }
862                 code = HandleIoctl(tvc, uap->com, datap);
863                 osi_FreeSmallSpace(datap);
864                 AFS_GUNLOCK();
865                 ioctlDone = 1;
866             }
867         }
868     }
869
870     if (!ioctlDone) {
871 # if defined(AFS_FBSD_ENV)
872         return ioctl(td, uap);
873 # elif defined(AFS_OBSD_ENV)
874         code = sys_ioctl(p, uap, retval);
875 # elif defined(AFS_NBSD_ENV)
876            struct lwp *l = osi_curproc();
877            code = sys_ioctl(l, uap, retval);
878 # endif
879     }
880
881     return (code);
882 }
883 #elif defined(UKERNEL)
884 int
885 afs_xioctl(void)
886 {
887     struct a {
888         int fd;
889         int com;
890         caddr_t arg;
891     } *uap = (struct a *)get_user_struct()->u_ap;
892     struct file *fd;
893     struct vcache *tvc;
894     int ioctlDone = 0, code = 0;
895
896     AFS_STATCNT(afs_xioctl);
897
898     fd = getf(uap->fd);
899     if (!fd)
900         return (EBADF);
901     /* first determine whether this is any sort of vnode */
902     if (fd->f_type == DTYPE_VNODE) {
903         /* good, this is a vnode; next see if it is an AFS vnode */
904         tvc = VTOAFS((struct vnode *)fd->f_data);       /* valid, given a vnode */
905         if (tvc && IsAfsVnode(AFSTOV(tvc))) {
906             /* This is an AFS vnode */
907             if (((uap->com >> 8) & 0xff) == 'V') {
908                 struct afs_ioctl *datap;
909                 AFS_GLOCK();
910                 datap = osi_AllocSmallSpace(AFS_SMALLOCSIZ);
911                 code=copyin_afs_ioctl((char *)uap->arg, datap);
912                 if (code) {
913                     osi_FreeSmallSpace(datap);
914                     AFS_GUNLOCK();
915
916                     return (setuerror(code), code);
917                 }
918                 code = HandleIoctl(tvc, uap->com, datap);
919                 osi_FreeSmallSpace(datap);
920                 AFS_GUNLOCK();
921                 ioctlDone = 1;
922             }
923         }
924     }
925
926     if (!ioctlDone) {
927         ioctl();
928     }
929
930     return 0;
931 }
932 #endif /* AFS_HPUX102_ENV */
933
934 #if defined(AFS_SGI_ENV)
935   /* "pioctl" system call entry point; just pass argument to the parameterized
936    * call below */
937 struct pioctlargs {
938     char *path;
939     sysarg_t cmd;
940     caddr_t cmarg;
941     sysarg_t follow;
942 };
943 int
944 afs_pioctl(struct pioctlargs *uap, rval_t * rvp)
945 {
946     int code;
947
948     AFS_STATCNT(afs_pioctl);
949     AFS_GLOCK();
950     code = afs_syscall_pioctl(uap->path, uap->cmd, uap->cmarg, uap->follow);
951     AFS_GUNLOCK();
952 # ifdef AFS_SGI64_ENV
953     return code;
954 # else
955     return u.u_error;
956 # endif
957 }
958
959 #elif defined(AFS_FBSD_ENV)
960 int
961 afs_pioctl(struct thread *td, void *args, int *retval)
962 {
963     struct a {
964         char *path;
965         int cmd;
966         caddr_t cmarg;
967         int follow;
968     } *uap = (struct a *)args;
969
970     AFS_STATCNT(afs_pioctl);
971     return (afs_syscall_pioctl
972             (uap->path, uap->cmd, uap->cmarg, uap->follow, td->td_ucred));
973 }
974
975 #elif defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
976 int
977 afs_pioctl(afs_proc_t *p, void *args, int *retval)
978 {
979     struct a {
980         char *path;
981         int cmd;
982         caddr_t cmarg;
983         int follow;
984     } *uap = (struct a *)args;
985
986     AFS_STATCNT(afs_pioctl);
987 # if defined(AFS_DARWIN80_ENV) || defined(AFS_NBSD40_ENV)
988     return (afs_syscall_pioctl
989             (uap->path, uap->cmd, uap->cmarg, uap->follow,
990              kauth_cred_get()));
991 # else
992     return (afs_syscall_pioctl
993             (uap->path, uap->cmd, uap->cmarg, uap->follow,
994 #  if defined(AFS_FBSD_ENV)
995              td->td_ucred));
996 #  else
997              p->p_cred->pc_ucred));
998 #  endif
999 # endif
1000 }
1001
1002 #endif
1003
1004 /* macro to avoid adding any more #ifdef's to pioctl code. */
1005 #if defined(AFS_LINUX22_ENV) || defined(AFS_AIX41_ENV)
1006 #define PIOCTL_FREE_CRED() crfree(credp)
1007 #else
1008 #define PIOCTL_FREE_CRED()
1009 #endif
1010
1011 int
1012 #ifdef  AFS_SUN5_ENV
1013 afs_syscall_pioctl(char *path, unsigned int com, caddr_t cmarg, int follow,
1014                    rval_t *vvp, afs_ucred_t *credp)
1015 #else
1016 #ifdef AFS_DARWIN100_ENV
1017 afs_syscall64_pioctl(user_addr_t path, unsigned int com, user_addr_t cmarg,
1018                    int follow, afs_ucred_t *credp)
1019 #elif defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
1020 afs_syscall_pioctl(char *path, unsigned int com, caddr_t cmarg, int follow,
1021                    afs_ucred_t *credp)
1022 #else
1023 afs_syscall_pioctl(char *path, unsigned int com, caddr_t cmarg, int follow)
1024 #endif
1025 #endif
1026 {
1027     struct afs_ioctl data;
1028 #ifdef AFS_NEED_CLIENTCONTEXT
1029     afs_ucred_t *tmpcred = NULL;
1030 #endif
1031 #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)
1032     afs_ucred_t *foreigncreds = NULL;
1033 #endif
1034     afs_int32 code = 0;
1035     struct vnode *vp = NULL;
1036 #ifdef  AFS_AIX41_ENV
1037     struct ucred *credp = crref();      /* don't free until done! */
1038 #endif
1039 #ifdef AFS_LINUX22_ENV
1040     cred_t *credp = crref();    /* don't free until done! */
1041     struct dentry *dp;
1042 #endif
1043
1044     AFS_STATCNT(afs_syscall_pioctl);
1045     if (follow)
1046         follow = 1;             /* compat. with old venus */
1047     code = copyin_afs_ioctl(cmarg, &data);
1048     if (code) {
1049         PIOCTL_FREE_CRED();
1050 #if defined(KERNEL_HAVE_UERROR)
1051         setuerror(code);
1052 #endif
1053         return (code);
1054     }
1055     if ((com & 0xff) == PSetClientContext) {
1056 #ifdef AFS_NEED_CLIENTCONTEXT
1057 #if defined(AFS_SUN5_ENV) || defined(AFS_AIX41_ENV) || defined(AFS_LINUX22_ENV)
1058         code = HandleClientContext(&data, &com, &foreigncreds, credp);
1059 #else
1060         code = HandleClientContext(&data, &com, &foreigncreds, osi_curcred());
1061 #endif
1062         if (code) {
1063             if (foreigncreds) {
1064                 crfree(foreigncreds);
1065             }
1066             PIOCTL_FREE_CRED();
1067 #if defined(KERNEL_HAVE_UERROR)
1068             return (setuerror(code), code);
1069 #else
1070             return (code);
1071 #endif
1072         }
1073 #else /* AFS_NEED_CLIENTCONTEXT */
1074         return EINVAL;
1075 #endif /* AFS_NEED_CLIENTCONTEXT */
1076     }
1077 #ifdef AFS_NEED_CLIENTCONTEXT
1078     if (foreigncreds) {
1079         /*
1080          * We could have done without temporary setting the u.u_cred below
1081          * (foreigncreds could be passed as param the pioctl modules)
1082          * but calls such as afs_osi_suser() doesn't allow that since it
1083          * references u.u_cred directly.  We could, of course, do something
1084          * like afs_osi_suser(cred) which, I think, is better since it
1085          * generalizes and supports multi cred environments...
1086          */
1087 #if defined(AFS_SUN5_ENV) || defined(AFS_LINUX22_ENV)
1088         tmpcred = credp;
1089         credp = foreigncreds;
1090 #elif defined(AFS_AIX41_ENV)
1091         tmpcred = crref();      /* XXX */
1092         crset(foreigncreds);
1093 #elif defined(AFS_HPUX101_ENV)
1094         tmpcred = p_cred(u.u_procp);
1095         set_p_cred(u.u_procp, foreigncreds);
1096 #elif defined(AFS_SGI_ENV)
1097         tmpcred = OSI_GET_CURRENT_CRED();
1098         OSI_SET_CURRENT_CRED(foreigncreds);
1099 #else
1100         tmpcred = u.u_cred;
1101         u.u_cred = foreigncreds;
1102 #endif
1103     }
1104 #endif /* AFS_NEED_CLIENTCONTEXT */
1105     if ((com & 0xff) == 15) {
1106         /* special case prefetch so entire pathname eval occurs in helper process.
1107          * otherwise, the pioctl call is essentially useless */
1108 #if     defined(AFS_SUN5_ENV) || defined(AFS_AIX41_ENV) || defined(AFS_LINUX22_ENV) || defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
1109         code =
1110             Prefetch(path, &data, follow,
1111                      foreigncreds ? foreigncreds : credp);
1112 #else
1113         code = Prefetch(path, &data, follow, osi_curcred());
1114 #endif
1115         vp = NULL;
1116 #if defined(KERNEL_HAVE_UERROR)
1117         setuerror(code);
1118 #endif
1119         goto rescred;
1120     }
1121     if (path) {
1122         AFS_GUNLOCK();
1123 #ifdef  AFS_AIX41_ENV
1124         code =
1125             lookupname(path, USR, follow, NULL, &vp,
1126                        foreigncreds ? foreigncreds : credp);
1127 #else
1128 #ifdef AFS_LINUX22_ENV
1129         code = gop_lookupname_user(path, AFS_UIOUSER, follow, &dp);
1130         if (!code)
1131             vp = (struct vnode *)dp->d_inode;
1132 #else
1133         code = gop_lookupname_user(path, AFS_UIOUSER, follow, &vp);
1134 #if defined(AFS_FBSD80_ENV) /* XXX check on 7x */
1135         if (vp != NULL)
1136                 VN_HOLD(vp);
1137 #endif /* AFS_FBSD80_ENV */
1138 #endif /* AFS_LINUX22_ENV */
1139 #endif /* AFS_AIX41_ENV */
1140         AFS_GLOCK();
1141         if (code) {
1142             vp = NULL;
1143 #if defined(KERNEL_HAVE_UERROR)
1144             setuerror(code);
1145 #endif
1146             goto rescred;
1147         }
1148     } else
1149         vp = NULL;
1150
1151 #if defined(AFS_SUN510_ENV)
1152     if (vp && !IsAfsVnode(vp)) {
1153         struct vnode *realvp;
1154         if
1155 #ifdef AFS_SUN511_ENV
1156           (VOP_REALVP(vp, &realvp, NULL) == 0)
1157 #else
1158           (VOP_REALVP(vp, &realvp) == 0)
1159 #endif
1160 {
1161             struct vnode *oldvp = vp;
1162
1163             VN_HOLD(realvp);
1164             vp = realvp;
1165             AFS_RELE(oldvp);
1166         }
1167     }
1168 #endif
1169     /* now make the call if we were passed no file, or were passed an AFS file */
1170     if (!vp || IsAfsVnode(vp)) {
1171 #if defined(AFS_SUN5_ENV)
1172         code = afs_HandlePioctl(vp, com, &data, follow, &credp);
1173 #elif defined(AFS_AIX41_ENV)
1174         {
1175             struct ucred *cred1, *cred2;
1176
1177             if (foreigncreds) {
1178                 cred1 = cred2 = foreigncreds;
1179             } else {
1180                 cred1 = cred2 = credp;
1181             }
1182             code = afs_HandlePioctl(vp, com, &data, follow, &cred1);
1183             if (cred1 != cred2) {
1184                 /* something changed the creds */
1185                 crset(cred1);
1186             }
1187         }
1188 #elif defined(AFS_HPUX101_ENV)
1189         {
1190             struct ucred *cred = p_cred(u.u_procp);
1191             code = afs_HandlePioctl(vp, com, &data, follow, &cred);
1192         }
1193 #elif defined(AFS_SGI_ENV)
1194         {
1195             struct cred *credp;
1196             credp = OSI_GET_CURRENT_CRED();
1197             code = afs_HandlePioctl(vp, com, &data, follow, &credp);
1198         }
1199 #elif defined(AFS_LINUX22_ENV) || defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
1200         code = afs_HandlePioctl(vp, com, &data, follow, &credp);
1201 #elif defined(UKERNEL)
1202         code = afs_HandlePioctl(vp, com, &data, follow,
1203                                 &(get_user_struct()->u_cred));
1204 #else
1205         code = afs_HandlePioctl(vp, com, &data, follow, &u.u_cred);
1206 #endif
1207     } else {
1208 #if defined(KERNEL_HAVE_UERROR)
1209         setuerror(EINVAL);
1210 #else
1211         code = EINVAL;          /* not in /afs */
1212 #endif
1213     }
1214
1215   rescred:
1216 #if defined(AFS_NEED_CLIENTCONTEXT)
1217     if (foreigncreds) {
1218 #ifdef  AFS_AIX41_ENV
1219         crset(tmpcred);         /* restore original credentials */
1220 #else
1221 #if     defined(AFS_HPUX101_ENV)
1222         set_p_cred(u.u_procp, tmpcred); /* restore original credentials */
1223 #elif   defined(AFS_SGI_ENV)
1224         OSI_SET_CURRENT_CRED(tmpcred);  /* restore original credentials */
1225 #elif   defined(AFS_SUN5_ENV) || defined(AFS_LINUX22_ENV)
1226         credp = tmpcred;                /* restore original credentials */
1227 #else
1228         osi_curcred() = tmpcred;        /* restore original credentials */
1229 #endif /* AFS_HPUX101_ENV */
1230         crfree(foreigncreds);
1231 #endif /* AIX41 */
1232     }
1233 #endif /* AFS_NEED_CLIENTCONTEXT */
1234     if (vp) {
1235 #ifdef AFS_LINUX22_ENV
1236         dput(dp);
1237 #else
1238 #if defined(AFS_FBSD80_ENV)
1239     if (VOP_ISLOCKED(vp))
1240         VOP_UNLOCK(vp, 0);
1241 #endif /* AFS_FBSD80_ENV */
1242         AFS_RELE(vp);           /* put vnode back */
1243 #endif
1244     }
1245     PIOCTL_FREE_CRED();
1246 #if defined(KERNEL_HAVE_UERROR)
1247     if (!getuerror())
1248         setuerror(code);
1249     return (getuerror());
1250 #else
1251     return (code);
1252 #endif
1253 }
1254
1255 #ifdef AFS_DARWIN100_ENV
1256 int
1257 afs_syscall_pioctl(char * path, unsigned int com, caddr_t cmarg,
1258                    int follow, afs_ucred_t *credp)
1259 {
1260     return afs_syscall64_pioctl(CAST_USER_ADDR_T(path), com,
1261                                 CAST_USER_ADDR_T((unsigned int)cmarg), follow,
1262                                 credp);
1263 }
1264 #endif
1265
1266 #define MAXPIOCTLTOKENLEN \
1267 (3*sizeof(afs_int32)+MAXKTCTICKETLEN+sizeof(struct ClearToken)+MAXKTCREALMLEN)
1268
1269 int
1270 afs_HandlePioctl(struct vnode *avp, afs_int32 acom,
1271                  struct afs_ioctl *ablob, int afollow,
1272                  afs_ucred_t **acred)
1273 {
1274     struct vcache *avc;
1275     struct vrequest treq;
1276     afs_int32 code;
1277     afs_int32 function, device;
1278     struct afs_pdata input, output;
1279     struct afs_pdata copyInput, copyOutput;
1280     size_t outSize;
1281     pioctlFunction *pioctlSw;
1282     int pioctlSwSize;
1283     struct afs_fakestat_state fakestate;
1284
1285     memset(&input, 0, sizeof(input));
1286     memset(&output, 0, sizeof(output));
1287
1288     avc = avp ? VTOAFS(avp) : NULL;
1289     afs_Trace3(afs_iclSetp, CM_TRACE_PIOCTL, ICL_TYPE_INT32, acom & 0xff,
1290                ICL_TYPE_POINTER, avc, ICL_TYPE_INT32, afollow);
1291     AFS_STATCNT(HandlePioctl);
1292
1293     code = afs_InitReq(&treq, *acred);
1294     if (code)
1295         return code;
1296
1297     afs_InitFakeStat(&fakestate);
1298     if (avc) {
1299         code = afs_EvalFakeStat(&avc, &fakestate, &treq);
1300         if (code)
1301             goto out;
1302     }
1303     device = (acom & 0xff00) >> 8;
1304     switch (device) {
1305     case 'V':                   /* Original pioctls */
1306         pioctlSw = VpioctlSw;
1307         pioctlSwSize = sizeof(VpioctlSw);
1308         break;
1309     case 'C':                   /* Coordinated/common pioctls */
1310         pioctlSw = CpioctlSw;
1311         pioctlSwSize = sizeof(CpioctlSw);
1312         break;
1313     case 'O':                   /* Coordinated/common pioctls */
1314         pioctlSw = OpioctlSw;
1315         pioctlSwSize = sizeof(OpioctlSw);
1316         break;
1317     default:
1318         code = EINVAL;
1319         goto out;
1320     }
1321     function = acom & 0xff;
1322     if (function >= (pioctlSwSize / sizeof(char *))) {
1323         code = EINVAL;
1324         goto out;
1325     }
1326
1327     /* Do all range checking before continuing */
1328     if (ablob->in_size > MAXPIOCTLTOKENLEN ||
1329         ablob->in_size < 0 || ablob->out_size < 0) {
1330         code = EINVAL;
1331         goto out;
1332     }
1333
1334     code = afs_pd_alloc(&input, ablob->in_size);
1335     if (code)
1336         goto out;
1337
1338     if (ablob->in_size > 0) {
1339         AFS_COPYIN(ablob->in, input.ptr, ablob->in_size, code);
1340         input.ptr[input.remaining] = '\0';
1341     }
1342     if (code)
1343         goto out;
1344
1345     if ((function == 8 && device == 'V') ||
1346        (function == 7 && device == 'C')) {      /* PGetTokens */
1347         code = afs_pd_alloc(&output, MAXPIOCTLTOKENLEN);
1348     } else {
1349         code = afs_pd_alloc(&output, AFS_LRALLOCSIZ);
1350     }
1351     if (code)
1352         goto out;
1353
1354     copyInput = input;
1355     copyOutput = output;
1356
1357     code =
1358         (*pioctlSw[function]) (avc, function, &treq, &copyInput,
1359                                &copyOutput, acred);
1360
1361     outSize = copyOutput.ptr - output.ptr;
1362
1363     if (code == 0 && ablob->out_size > 0) {
1364         if (outSize > ablob->out_size) {
1365             code = E2BIG;       /* data wont fit in user buffer */
1366         } else if (outSize) {
1367             AFS_COPYOUT(output.ptr, ablob->out, outSize, code);
1368         }
1369     }
1370
1371 out:
1372     afs_pd_free(&input);
1373     afs_pd_free(&output);
1374
1375     afs_PutFakeStat(&fakestate);
1376     return afs_CheckCode(code, &treq, 41);
1377 }
1378
1379 /*!
1380  * VIOCGETFID (22) - Get file ID quickly
1381  *
1382  * \ingroup pioctl
1383  *
1384  * \param[in] ain       not in use
1385  * \param[out] aout     fid of requested file
1386  *
1387  * \retval EINVAL       Error if some of the initial arguments aren't set
1388  *
1389  * \post get the file id of some file
1390  */
1391 DECL_PIOCTL(PGetFID)
1392 {
1393     AFS_STATCNT(PGetFID);
1394     if (!avc)
1395         return EINVAL;
1396     if (afs_pd_putBytes(aout, &avc->f.fid, sizeof(struct VenusFid)) != 0)
1397         return EINVAL;
1398     return 0;
1399 }
1400
1401 /*!
1402  * VIOCSETAL (1) - Set access control list
1403  *
1404  * \ingroup pioctl
1405  *
1406  * \param[in] ain       the ACL being set
1407  * \param[out] aout     the ACL being set returned
1408  *
1409  * \retval EINVAL       Error if some of the standard args aren't set
1410  *
1411  * \post Changed ACL, via direct writing to the wire
1412  */
1413 int
1414 dummy_PSetAcl(char *ain, char *aout)
1415 {
1416     return 0;
1417 }
1418
1419 DECL_PIOCTL(PSetAcl)
1420 {
1421     afs_int32 code;
1422     struct afs_conn *tconn;
1423     struct AFSOpaque acl;
1424     struct AFSVolSync tsync;
1425     struct AFSFetchStatus OutStatus;
1426     struct rx_connection *rxconn;
1427     XSTATS_DECLS;
1428
1429     AFS_STATCNT(PSetAcl);
1430     if (!avc)
1431         return EINVAL;
1432
1433     if (afs_pd_getStringPtr(ain, &acl.AFSOpaque_val) != 0)
1434         return EINVAL;
1435     acl.AFSOpaque_len = strlen(acl.AFSOpaque_val) + 1;
1436     if (acl.AFSOpaque_len > 1024)
1437         return EINVAL;
1438
1439     do {
1440         tconn = afs_Conn(&avc->f.fid, areq, SHARED_LOCK, &rxconn);
1441         if (tconn) {
1442             XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_STOREACL);
1443             RX_AFS_GUNLOCK();
1444             code =
1445                 RXAFS_StoreACL(rxconn, (struct AFSFid *)&avc->f.fid.Fid,
1446                                &acl, &OutStatus, &tsync);
1447             RX_AFS_GLOCK();
1448             XSTATS_END_TIME;
1449         } else
1450             code = -1;
1451     } while (afs_Analyze
1452              (tconn, rxconn, code, &avc->f.fid, areq, AFS_STATS_FS_RPCIDX_STOREACL,
1453               SHARED_LOCK, NULL));
1454
1455     /* now we've forgotten all of the access info */
1456     ObtainWriteLock(&afs_xcbhash, 455);
1457     avc->callback = 0;
1458     afs_DequeueCallback(avc);
1459     avc->f.states &= ~(CStatd | CUnique);
1460     ReleaseWriteLock(&afs_xcbhash);
1461     if (avc->f.fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
1462         osi_dnlc_purgedp(avc);
1463
1464     /* SXW - Should we flush metadata here? */
1465     return code;
1466 }
1467
1468 int afs_defaultAsynchrony = 0;
1469
1470 /*!
1471  * VIOC_STOREBEHIND (47) Adjust store asynchrony
1472  *
1473  * \ingroup pioctl
1474  *
1475  * \param[in] ain       sbstruct (store behind structure) input
1476  * \param[out] aout     resulting sbstruct
1477  *
1478  * \retval EPERM
1479  *      Error if the user doesn't have super-user credentials
1480  * \retval EACCES
1481  *      Error if there isn't enough access to not check the mode bits
1482  *
1483  * \post
1484  *      Changes either the default asynchrony (the amount of data that
1485  *      can remain to be written when the cache manager returns control
1486  *      to the user), or the asyncrony for the specified file.
1487  */
1488 DECL_PIOCTL(PStoreBehind)
1489 {
1490     struct sbstruct sbr;
1491
1492     if (afs_pd_getBytes(ain, &sbr, sizeof(struct sbstruct)) != 0)
1493         return EINVAL;
1494
1495     if (sbr.sb_default != -1) {
1496         if (afs_osi_suser(*acred))
1497             afs_defaultAsynchrony = sbr.sb_default;
1498         else
1499             return EPERM;
1500     }
1501
1502     if (avc && (sbr.sb_thisfile != -1)) {
1503         if (afs_AccessOK
1504             (avc, PRSFS_WRITE | PRSFS_ADMINISTER, areq, DONT_CHECK_MODE_BITS))
1505             avc->asynchrony = sbr.sb_thisfile;
1506         else
1507             return EACCES;
1508     }
1509
1510     memset(&sbr, 0, sizeof(sbr));
1511     sbr.sb_default = afs_defaultAsynchrony;
1512     if (avc) {
1513         sbr.sb_thisfile = avc->asynchrony;
1514     }
1515
1516     return afs_pd_putBytes(aout, &sbr, sizeof(sbr));
1517 }
1518
1519 /*!
1520  * VIOC_GCPAGS (48) - Disable automatic PAG gc'ing
1521  *
1522  * \ingroup pioctl
1523  *
1524  * \param[in] ain       not in use
1525  * \param[out] aout     not in use
1526  *
1527  * \retval EACCES       Error if the user doesn't have super-user credentials
1528  *
1529  * \post set the gcpags to GCPAGS_USERDISABLED
1530  */
1531 DECL_PIOCTL(PGCPAGs)
1532 {
1533     if (!afs_osi_suser(*acred)) {
1534         return EACCES;
1535     }
1536     afs_gcpags = AFS_GCPAGS_USERDISABLED;
1537     return 0;
1538 }
1539
1540 /*!
1541  * VIOCGETAL (2) - Get access control list
1542  *
1543  * \ingroup pioctl
1544  *
1545  * \param[in] ain       not in use
1546  * \param[out] aout     the ACL
1547  *
1548  * \retval EINVAL       Error if some of the standard args aren't set
1549  * \retval ERANGE       Error if the vnode of the file id is too large
1550  * \retval -1           Error if getting the ACL failed
1551  *
1552  * \post Obtain the ACL, based on file ID
1553  *
1554  * \notes
1555  *      There is a hack to tell which type of ACL is being returned, checks
1556  *      the top 2-bytes of the input size to judge what type of ACL it is,
1557  *      only for dfs xlator ACLs
1558  */
1559 DECL_PIOCTL(PGetAcl)
1560 {
1561     struct AFSOpaque acl;
1562     struct AFSVolSync tsync;
1563     struct AFSFetchStatus OutStatus;
1564     afs_int32 code;
1565     struct afs_conn *tconn;
1566     struct AFSFid Fid;
1567     struct rx_connection *rxconn;
1568     XSTATS_DECLS;
1569
1570     AFS_STATCNT(PGetAcl);
1571     if (!avc)
1572         return EINVAL;
1573     Fid.Volume = avc->f.fid.Fid.Volume;
1574     Fid.Vnode = avc->f.fid.Fid.Vnode;
1575     Fid.Unique = avc->f.fid.Fid.Unique;
1576     if (avc->f.states & CForeign) {
1577         /*
1578          * For a dfs xlator acl we have a special hack so that the
1579          * xlator will distinguish which type of acl will return. So
1580          * we currently use the top 2-bytes (vals 0-4) to tell which
1581          * type of acl to bring back. Horrible hack but this will
1582          * cause the least number of changes to code size and interfaces.
1583          */
1584         if (Fid.Vnode & 0xc0000000)
1585             return ERANGE;
1586         Fid.Vnode |= (ain->remaining << 30);
1587     }
1588     acl.AFSOpaque_val = aout->ptr;
1589     do {
1590         tconn = afs_Conn(&avc->f.fid, areq, SHARED_LOCK, &rxconn);
1591         if (tconn) {
1592             acl.AFSOpaque_val[0] = '\0';
1593             XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_FETCHACL);
1594             RX_AFS_GUNLOCK();
1595             code = RXAFS_FetchACL(rxconn, &Fid, &acl, &OutStatus, &tsync);
1596             RX_AFS_GLOCK();
1597             XSTATS_END_TIME;
1598         } else
1599             code = -1;
1600     } while (afs_Analyze
1601              (tconn, rxconn, code, &avc->f.fid, areq, AFS_STATS_FS_RPCIDX_FETCHACL,
1602               SHARED_LOCK, NULL));
1603
1604     if (code == 0) {
1605         if (acl.AFSOpaque_len == 0)
1606             afs_pd_skip(aout, 1); /* leave the NULL */
1607         else
1608             afs_pd_skip(aout, acl.AFSOpaque_len); /* Length of the ACL */
1609     }
1610     return code;
1611 }
1612
1613 /*!
1614  * PNoop returns success.  Used for functions which are not implemented
1615  * or are no longer in use.
1616  *
1617  * \ingroup pioctl
1618  *
1619  * \retval Always returns success
1620  *
1621  * \notes
1622  *      Functions involved in this:
1623  *      17 (VIOCENGROUP) -- used to be enable group;
1624  *      18 (VIOCDISGROUP) -- used to be disable group;
1625  *      2 (?) -- get/set cache-bypass size threshold
1626  */
1627 DECL_PIOCTL(PNoop)
1628 {
1629     AFS_STATCNT(PNoop);
1630     return 0;
1631 }
1632
1633 /*!
1634  * PBogus returns fail.  Used for functions which are not implemented or
1635  * are no longer in use.
1636  *
1637  * \ingroup pioctl
1638  *
1639  * \retval EINVAL       Always returns this value
1640  *
1641  * \notes
1642  *      Functions involved in this:
1643  *      0 (?);
1644  *      4 (?);
1645  *      6 (?);
1646  *      7 (VIOCSTAT);
1647  *      8 (?);
1648  *      13 (VIOCGETTIME) -- used to be quick check time;
1649  *      15 (VIOCPREFETCH) -- prefetch is now special-cased; see pioctl code!;
1650  *      16 (VIOCNOP) -- used to be testing code;
1651  *      19 (VIOCLISTGROUPS) -- used to be list group;
1652  *      23 (VIOCWAITFOREVER) -- used to be waitforever;
1653  *      57 (VIOC_FPRIOSTATUS) -- arla: set file prio;
1654  *      58 (VIOC_FHGET) -- arla: fallback getfh;
1655  *      59 (VIOC_FHOPEN) -- arla: fallback fhopen;
1656  *      60 (VIOC_XFSDEBUG) -- arla: controls xfsdebug;
1657  *      61 (VIOC_ARLADEBUG) -- arla: controls arla debug;
1658  *      62 (VIOC_AVIATOR) -- arla: debug interface;
1659  *      63 (VIOC_XFSDEBUG_PRINT) -- arla: print xfs status;
1660  *      64 (VIOC_CALCULATE_CACHE) -- arla: force cache check;
1661  *      65 (VIOC_BREAKCELLBACK) -- arla: break callback;
1662  *      68 (?) -- arla: fetch stats;
1663  */
1664 DECL_PIOCTL(PBogus)
1665 {
1666     AFS_STATCNT(PBogus);
1667     return EINVAL;
1668 }
1669
1670 /*!
1671  * VIOC_FILE_CELL_NAME (30) - Get cell in which file lives
1672  *
1673  * \ingroup pioctl
1674  *
1675  * \param[in] ain       not in use (avc used to pass in file id)
1676  * \param[out] aout     cell name
1677  *
1678  * \retval EINVAL       Error if some of the standard args aren't set
1679  * \retval ESRCH        Error if the file isn't part of a cell
1680  *
1681  * \post Get a cell based on a passed in file id
1682  */
1683 DECL_PIOCTL(PGetFileCell)
1684 {
1685     struct cell *tcell;
1686
1687     AFS_STATCNT(PGetFileCell);
1688     if (!avc)
1689         return EINVAL;
1690     tcell = afs_GetCell(avc->f.fid.Cell, READ_LOCK);
1691     if (!tcell)
1692         return ESRCH;
1693
1694     if (afs_pd_putString(aout, tcell->cellName) != 0)
1695         return EINVAL;
1696
1697     afs_PutCell(tcell, READ_LOCK);
1698     return 0;
1699 }
1700
1701 /*!
1702  * VIOC_GET_WS_CELL (31) - Get cell in which workstation lives
1703  *
1704  * \ingroup pioctl
1705  *
1706  * \param[in] ain       not in use
1707  * \param[out] aout     cell name
1708  *
1709  * \retval EIO
1710  *      Error if the afs daemon hasn't started yet
1711  * \retval ESRCH
1712  *      Error if the machine isn't part of a cell, for whatever reason
1713  *
1714  * \post Get the primary cell that the machine is a part of.
1715  */
1716 DECL_PIOCTL(PGetWSCell)
1717 {
1718     struct cell *tcell = NULL;
1719
1720     AFS_STATCNT(PGetWSCell);
1721     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
1722         return EIO;             /* Inappropriate ioctl for device */
1723
1724     tcell = afs_GetPrimaryCell(READ_LOCK);
1725     if (!tcell)                 /* no primary cell? */
1726         return ESRCH;
1727
1728     if (afs_pd_putString(aout, tcell->cellName) != 0)
1729         return EINVAL;
1730     afs_PutCell(tcell, READ_LOCK);
1731     return 0;
1732 }
1733
1734 /*!
1735  * VIOC_GET_PRIMARY_CELL (33) - Get primary cell for caller
1736  *
1737  * \ingroup pioctl
1738  *
1739  * \param[in] ain       not in use (user id found via areq)
1740  * \param[out] aout     cell name
1741  *
1742  * \retval ESRCH
1743  *      Error if the user id doesn't have a primary cell specified
1744  *
1745  * \post Get the primary cell for a certain user, based on the user's uid
1746  */
1747 DECL_PIOCTL(PGetUserCell)
1748 {
1749     afs_int32 i;
1750     struct unixuser *tu;
1751     struct cell *tcell;
1752
1753     AFS_STATCNT(PGetUserCell);
1754     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
1755         return EIO;             /* Inappropriate ioctl for device */
1756
1757     /* return the cell name of the primary cell for this user */
1758     i = UHash(areq->uid);
1759     ObtainWriteLock(&afs_xuser, 224);
1760     for (tu = afs_users[i]; tu; tu = tu->next) {
1761         if (tu->uid == areq->uid && (tu->states & UPrimary)) {
1762             tu->refCount++;
1763             ReleaseWriteLock(&afs_xuser);
1764             break;
1765         }
1766     }
1767     if (tu) {
1768         tcell = afs_GetCell(tu->cell, READ_LOCK);
1769         afs_PutUser(tu, WRITE_LOCK);
1770         if (!tcell)
1771             return ESRCH;
1772         else {
1773             if (afs_pd_putString(aout, tcell->cellName) != 0)
1774                 return E2BIG;
1775             afs_PutCell(tcell, READ_LOCK);
1776         }
1777     } else {
1778         ReleaseWriteLock(&afs_xuser);
1779     }
1780     return 0;
1781 }
1782
1783 /* Work out which cell we're changing tokens for */
1784 static_inline int
1785 _settok_tokenCell(char *cellName, int *cellNum, int *primary) {
1786     int t1;
1787     struct cell *cell;
1788
1789     if (primary) {
1790         *primary = 0;
1791     }
1792
1793     if (cellName && strlen(cellName) > 0) {
1794         cell = afs_GetCellByName(cellName, READ_LOCK);
1795     } else {
1796         cell = afs_GetPrimaryCell(READ_LOCK);
1797         if (primary)
1798             *primary = 1;
1799     }
1800     if (!cell) {
1801         t1 = afs_initState;
1802         if (t1 < 101)
1803             return EIO;
1804         else
1805             return ESRCH;
1806     }
1807     *cellNum = cell->cellNum;
1808     afs_PutCell(cell, READ_LOCK);
1809
1810     return 0;
1811 }
1812
1813
1814 static_inline int
1815 _settok_setParentPag(afs_ucred_t **cred) {
1816     afs_uint32 pag;
1817 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
1818     char procname[256];
1819     osi_procname(procname, 256);
1820     afs_warnuser("Process %d (%s) tried to change pags in PSetTokens\n",
1821                  MyPidxx2Pid(MyPidxx), procname);
1822     return setpag(osi_curproc(), cred, -1, &pag, 1);
1823 #else
1824     return setpag(cred, -1, &pag, 1);
1825 #endif
1826 }
1827
1828 /*!
1829  * VIOCSETTOK (3) - Set authentication tokens
1830  *
1831  * \ingroup pioctl
1832  *
1833  * \param[in] ain       the krb tickets from which to set the afs tokens
1834  * \param[out] aout     not in use
1835  *
1836  * \retval EINVAL
1837  *      Error if the ticket is either too long or too short
1838  * \retval EIO
1839  *      Error if the AFS initState is below 101
1840  * \retval ESRCH
1841  *      Error if the cell for which the Token is being set can't be found
1842  *
1843  * \post
1844  *      Set the Tokens for a specific cell name, unless there is none set,
1845  *      then default to primary
1846  *
1847  */
1848 DECL_PIOCTL(PSetTokens)
1849 {
1850     afs_int32 cellNum;
1851     afs_int32 size;
1852     afs_int32 code;
1853     struct unixuser *tu;
1854     struct ClearToken clear;
1855     char *stp;
1856     char *cellName;
1857     int stLen;
1858     struct vrequest treq;
1859     afs_int32 flag, set_parent_pag = 0;
1860
1861     AFS_STATCNT(PSetTokens);
1862     if (!afs_resourceinit_flag) {
1863         return EIO;
1864     }
1865
1866     if (afs_pd_getInt(ain, &stLen) != 0)
1867         return EINVAL;
1868
1869     stp = afs_pd_where(ain);    /* remember where the ticket is */
1870     if (stLen < 0 || stLen > MAXKTCTICKETLEN)
1871         return EINVAL;          /* malloc may fail */
1872     if (afs_pd_skip(ain, stLen) != 0)
1873         return EINVAL;
1874
1875     if (afs_pd_getInt(ain, &size) != 0)
1876         return EINVAL;
1877     if (size != sizeof(struct ClearToken))
1878         return EINVAL;
1879
1880     if (afs_pd_getBytes(ain, &clear, sizeof(struct ClearToken)) !=0)
1881         return EINVAL;
1882
1883     if (clear.AuthHandle == -1)
1884         clear.AuthHandle = 999; /* more rxvab compat stuff */
1885
1886     if (afs_pd_remaining(ain) != 0) {
1887         /* still stuff left?  we've got primary flag and cell name.
1888          * Set these */
1889
1890         if (afs_pd_getInt(ain, &flag) != 0)
1891             return EINVAL;
1892
1893         /* some versions of gcc appear to need != 0 in order to get this
1894          * right */
1895         if ((flag & 0x8000) != 0) {     /* XXX Use Constant XXX */
1896             flag &= ~0x8000;
1897             set_parent_pag = 1;
1898         }
1899
1900         if (afs_pd_getStringPtr(ain, &cellName) != 0)
1901             return EINVAL;
1902
1903         code = _settok_tokenCell(cellName, &cellNum, NULL);
1904         if (code)
1905             return code;
1906     } else {
1907         /* default to primary cell, primary id */
1908         code = _settok_tokenCell(NULL, &cellNum, &flag);
1909         if (code)
1910             return code;
1911     }
1912
1913     if (set_parent_pag) {
1914         if (_settok_setParentPag(acred) == 0) {
1915             afs_InitReq(&treq, *acred);
1916             areq = &treq;
1917         }
1918     }
1919
1920     /* now we just set the tokens */
1921     tu = afs_GetUser(areq->uid, cellNum, WRITE_LOCK);
1922     /* Set tokens destroys any that are already there */
1923     afs_FreeTokens(&tu->tokens);
1924     afs_AddRxkadToken(&tu->tokens, stp, stLen, &clear);
1925 #ifndef AFS_NOSTATS
1926     afs_stats_cmfullperf.authent.TicketUpdates++;
1927     afs_ComputePAGStats();
1928 #endif /* AFS_NOSTATS */
1929     tu->states |= UHasTokens;
1930     tu->states &= ~UTokensBad;
1931     afs_SetPrimary(tu, flag);
1932     tu->tokenTime = osi_Time();
1933     afs_ResetUserConns(tu);
1934     afs_NotifyUser(tu, UTokensObtained);
1935     afs_PutUser(tu, WRITE_LOCK);
1936
1937     return 0;
1938 }
1939
1940 /*!
1941  * VIOCGETVOLSTAT (4) - Get volume status
1942  *
1943  * \ingroup pioctl
1944  *
1945  * \param[in] ain       not in use
1946  * \param[out] aout     status of the volume
1947  *
1948  * \retval EINVAL       Error if some of the standard args aren't set
1949  *
1950  * \post
1951  *      The status of a volume (based on the FID of the volume), or an
1952  *      offline message /motd
1953  */
1954 DECL_PIOCTL(PGetVolumeStatus)
1955 {
1956     char volName[32];
1957     char *offLineMsg = afs_osi_Alloc(256);
1958     char *motd = afs_osi_Alloc(256);
1959     struct afs_conn *tc;
1960     afs_int32 code = 0;
1961     struct AFSFetchVolumeStatus volstat;
1962     char *Name;
1963     struct rx_connection *rxconn;
1964     XSTATS_DECLS;
1965
1966     osi_Assert(offLineMsg != NULL);
1967     osi_Assert(motd != NULL);
1968     AFS_STATCNT(PGetVolumeStatus);
1969     if (!avc) {
1970         code = EINVAL;
1971         goto out;
1972     }
1973     Name = volName;
1974     do {
1975         tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK, &rxconn);
1976         if (tc) {
1977             XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_GETVOLUMESTATUS);
1978             RX_AFS_GUNLOCK();
1979             code =
1980                 RXAFS_GetVolumeStatus(rxconn, avc->f.fid.Fid.Volume, &volstat,
1981                                       &Name, &offLineMsg, &motd);
1982             RX_AFS_GLOCK();
1983             XSTATS_END_TIME;
1984         } else
1985             code = -1;
1986     } while (afs_Analyze
1987              (tc, rxconn, code, &avc->f.fid, areq, AFS_STATS_FS_RPCIDX_GETVOLUMESTATUS,
1988               SHARED_LOCK, NULL));
1989
1990     if (code)
1991         goto out;
1992     /* Copy all this junk into msg->im_data, keeping track of the lengths. */
1993     if (afs_pd_putBytes(aout, &volstat, sizeof(VolumeStatus)) != 0)
1994         return E2BIG;
1995     if (afs_pd_putString(aout, volName) != 0)
1996         return E2BIG;
1997     if (afs_pd_putString(aout, offLineMsg) != 0)
1998         return E2BIG;
1999     if (afs_pd_putString(aout, motd) != 0)
2000         return E2BIG;
2001   out:
2002     afs_osi_Free(offLineMsg, 256);
2003     afs_osi_Free(motd, 256);
2004     return code;
2005 }
2006
2007 /*!
2008  * VIOCSETVOLSTAT (5) - Set volume status
2009  *
2010  * \ingroup pioctl
2011  *
2012  * \param[in] ain
2013  *      values to set the status at, offline message, message of the day,
2014  *      volume name, minimum quota, maximum quota
2015  * \param[out] aout
2016  *      status of a volume, offlines messages, minimum quota, maximumm quota
2017  *
2018  * \retval EINVAL
2019  *      Error if some of the standard args aren't set
2020  * \retval EROFS
2021  *      Error if the volume is read only, or a backup volume
2022  * \retval ENODEV
2023  *      Error if the volume can't be accessed
2024  * \retval E2BIG
2025  *      Error if the volume name, offline message, and motd are too big
2026  *
2027  * \post
2028  *      Set the status of a volume, including any offline messages,
2029  *      a minimum quota, and a maximum quota
2030  */
2031 DECL_PIOCTL(PSetVolumeStatus)
2032 {
2033     char *volName;
2034     char *offLineMsg;
2035     char *motd;
2036     struct afs_conn *tc;
2037     afs_int32 code = 0;
2038     struct AFSFetchVolumeStatus volstat;
2039     struct AFSStoreVolumeStatus storeStat;
2040     struct volume *tvp;
2041     struct rx_connection *rxconn;
2042     XSTATS_DECLS;
2043
2044     AFS_STATCNT(PSetVolumeStatus);
2045     if (!avc)
2046         return EINVAL;
2047
2048     tvp = afs_GetVolume(&avc->f.fid, areq, READ_LOCK);
2049     if (tvp) {
2050         if (tvp->states & (VRO | VBackup)) {
2051             afs_PutVolume(tvp, READ_LOCK);
2052             return EROFS;
2053         }
2054         afs_PutVolume(tvp, READ_LOCK);
2055     } else
2056         return ENODEV;
2057
2058
2059     if (afs_pd_getBytes(ain, &volstat, sizeof(AFSFetchVolumeStatus)) != 0)
2060         return EINVAL;
2061
2062     if (afs_pd_getStringPtr(ain, &volName) != 0)
2063         return EINVAL;
2064     if (strlen(volName) > 32)
2065         return E2BIG;
2066
2067     if (afs_pd_getStringPtr(ain, &offLineMsg) != 0)
2068         return EINVAL;
2069     if (strlen(offLineMsg) > 256)
2070         return E2BIG;
2071
2072     if (afs_pd_getStringPtr(ain, &motd) != 0)
2073         return EINVAL;
2074     if (strlen(motd) > 256)
2075         return E2BIG;
2076
2077     /* Done reading ... */
2078
2079     storeStat.Mask = 0;
2080     if (volstat.MinQuota != -1) {
2081         storeStat.MinQuota = volstat.MinQuota;
2082         storeStat.Mask |= AFS_SETMINQUOTA;
2083     }
2084     if (volstat.MaxQuota != -1) {
2085         storeStat.MaxQuota = volstat.MaxQuota;
2086         storeStat.Mask |= AFS_SETMAXQUOTA;
2087     }
2088     do {
2089         tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK, &rxconn);
2090         if (tc) {
2091             XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_SETVOLUMESTATUS);
2092             RX_AFS_GUNLOCK();
2093             code =
2094                 RXAFS_SetVolumeStatus(rxconn, avc->f.fid.Fid.Volume, &storeStat,
2095                                       volName, offLineMsg, motd);
2096             RX_AFS_GLOCK();
2097             XSTATS_END_TIME;
2098         } else
2099             code = -1;
2100     } while (afs_Analyze
2101              (tc, rxconn, code, &avc->f.fid, areq, AFS_STATS_FS_RPCIDX_SETVOLUMESTATUS,
2102               SHARED_LOCK, NULL));
2103
2104     if (code)
2105         return code;
2106     /* we are sending parms back to make compat. with prev system.  should
2107      * change interface later to not ask for current status, just set new
2108      * status */
2109
2110     if (afs_pd_putBytes(aout, &volstat, sizeof(VolumeStatus)) != 0)
2111         return EINVAL;
2112     if (afs_pd_putString(aout, volName) != 0)
2113         return EINVAL;
2114     if (afs_pd_putString(aout, offLineMsg) != 0)
2115         return EINVAL;
2116     if (afs_pd_putString(aout, motd) != 0)
2117         return EINVAL;
2118
2119     return code;
2120 }
2121
2122 /*!
2123  * VIOCFLUSH (6) - Invalidate cache entry
2124  *
2125  * \ingroup pioctl
2126  *
2127  * \param[in] ain       not in use
2128  * \param[out] aout     not in use
2129  *
2130  * \retval EINVAL       Error if some of the standard args aren't set
2131  *
2132  * \post Flush any information the cache manager has on an entry
2133  */
2134 DECL_PIOCTL(PFlush)
2135 {
2136     AFS_STATCNT(PFlush);
2137     if (!avc)
2138         return EINVAL;
2139 #ifdef AFS_BOZONLOCK_ENV
2140     afs_BozonLock(&avc->pvnLock, avc);  /* Since afs_TryToSmush will do a pvn_vptrunc */
2141 #endif
2142     ObtainWriteLock(&avc->lock, 225);
2143     afs_ResetVCache(avc, *acred);
2144     ReleaseWriteLock(&avc->lock);
2145 #ifdef AFS_BOZONLOCK_ENV
2146     afs_BozonUnlock(&avc->pvnLock, avc);
2147 #endif
2148     return 0;
2149 }
2150
2151 /*!
2152  * VIOC_AFS_STAT_MT_PT (29) - Stat mount point
2153  *
2154  * \ingroup pioctl
2155  *
2156  * \param[in] ain
2157  *      the last component in a path, related to mountpoint that we're
2158  *      looking for information about
2159  * \param[out] aout
2160  *      volume, cell, link data
2161  *
2162  * \retval EINVAL       Error if some of the standard args aren't set
2163  * \retval ENOTDIR      Error if the 'mount point' argument isn't a directory
2164  * \retval EIO          Error if the link data can't be accessed
2165  *
2166  * \post Get the volume, and cell, as well as the link data for a mount point
2167  */
2168 DECL_PIOCTL(PNewStatMount)
2169 {
2170     afs_int32 code;
2171     struct vcache *tvc;
2172     struct dcache *tdc;
2173     struct VenusFid tfid;
2174     char *bufp;
2175     char *name;
2176     struct sysname_info sysState;
2177     afs_size_t offset, len;
2178
2179     AFS_STATCNT(PNewStatMount);
2180     if (!avc)
2181         return EINVAL;
2182
2183     if (afs_pd_getStringPtr(ain, &name) != 0)
2184         return EINVAL;
2185
2186     code = afs_VerifyVCache(avc, areq);
2187     if (code)
2188         return code;
2189     if (vType(avc) != VDIR) {
2190         return ENOTDIR;
2191     }
2192     tdc = afs_GetDCache(avc, (afs_size_t) 0, areq, &offset, &len, 1);
2193     if (!tdc)
2194         return ENOENT;
2195     Check_AtSys(avc, name, &sysState, areq);
2196     ObtainReadLock(&tdc->lock);
2197     do {
2198         code = afs_dir_Lookup(tdc, sysState.name, &tfid.Fid);
2199     } while (code == ENOENT && Next_AtSys(avc, areq, &sysState));
2200     ReleaseReadLock(&tdc->lock);
2201     afs_PutDCache(tdc);         /* we're done with the data */
2202     bufp = sysState.name;
2203     if (code) {
2204         goto out;
2205     }
2206     tfid.Cell = avc->f.fid.Cell;
2207     tfid.Fid.Volume = avc->f.fid.Fid.Volume;
2208     if (!tfid.Fid.Unique && (avc->f.states & CForeign)) {
2209         tvc = afs_LookupVCache(&tfid, areq, NULL, avc, bufp);
2210     } else {
2211         tvc = afs_GetVCache(&tfid, areq, NULL, NULL);
2212     }
2213     if (!tvc) {
2214         code = ENOENT;
2215         goto out;
2216     }
2217     if (tvc->mvstat != 1) {
2218         afs_PutVCache(tvc);
2219         code = EINVAL;
2220         goto out;
2221     }
2222     ObtainWriteLock(&tvc->lock, 226);
2223     code = afs_HandleLink(tvc, areq);
2224     if (code == 0) {
2225         if (tvc->linkData) {
2226             if ((tvc->linkData[0] != '#') && (tvc->linkData[0] != '%'))
2227                 code = EINVAL;
2228             else {
2229                 /* we have the data */
2230                 if (afs_pd_putString(aout, tvc->linkData) != 0)
2231                     code = EINVAL;
2232             }
2233         } else
2234             code = EIO;
2235     }
2236     ReleaseWriteLock(&tvc->lock);
2237     afs_PutVCache(tvc);
2238   out:
2239     if (sysState.allocked)
2240         osi_FreeLargeSpace(bufp);
2241     return code;
2242 }
2243
2244 /*!
2245  * A helper function to get the n'th cell which a particular user has tokens
2246  * for. This is racy. If new tokens are added whilst we're iterating, then
2247  * we may return some cells twice. If tokens expire mid run, then we'll
2248  * miss some cells from our output. So, could be better, but that would
2249  * require an interface change.
2250  */
2251
2252 static struct unixuser *
2253 getNthCell(afs_int32 uid, afs_int32 iterator) {
2254     int i;
2255     struct unixuser *tu = NULL;
2256
2257     i = UHash(uid);
2258     ObtainReadLock(&afs_xuser);
2259     for (tu = afs_users[i]; tu; tu = tu->next) {
2260         if (tu->uid == uid && (tu->states & UHasTokens)) {
2261             if (iterator-- == 0)
2262             break;      /* are we done yet? */
2263         }
2264     }
2265     if (tu) {
2266         tu->refCount++;
2267     }
2268     ReleaseReadLock(&afs_xuser);
2269
2270     return tu;
2271 }
2272 /*!
2273  * VIOCGETTOK (8) - Get authentication tokens
2274  *
2275  * \ingroup pioctl
2276  *
2277  * \param[in] ain       cellid to return tokens for
2278  * \param[out] aout     token
2279  *
2280  * \retval EIO
2281  *      Error if the afs daemon hasn't started yet
2282  * \retval EDOM
2283  *      Error if the input parameter is out of the bounds of the available
2284  *      tokens
2285  * \retval ENOTCONN
2286  *      Error if there aren't tokens for this cell
2287  *
2288  * \post
2289  *      If the input paramater exists, get the token that corresponds to
2290  *      the parameter value, if there is no token at this value, get the
2291  *      token for the first cell
2292  *
2293  * \notes "it's a weird interface (from comments in the code)"
2294  */
2295
2296 DECL_PIOCTL(PGetTokens)
2297 {
2298     struct cell *tcell;
2299     struct unixuser *tu = NULL;
2300     union tokenUnion *token;
2301     afs_int32 iterator = 0;
2302     int newStyle;
2303     int cellNum;
2304     int code = E2BIG;
2305
2306     AFS_STATCNT(PGetTokens);
2307     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
2308         return EIO;             /* Inappropriate ioctl for device */
2309
2310     /* weird interface.  If input parameter is present, it is an integer and
2311      * we're supposed to return the parm'th tokens for this unix uid.
2312      * If not present, we just return tokens for cell 1.
2313      * If counter out of bounds, return EDOM.
2314      * If no tokens for the particular cell, return ENOTCONN.
2315      * Also, if this mysterious parm is present, we return, along with the
2316      * tokens, the primary cell indicator (an afs_int32 0) and the cell name
2317      * at the end, in that order.
2318      */
2319     newStyle = (afs_pd_remaining(ain) > 0);
2320     if (newStyle) {
2321         if (afs_pd_getInt(ain, &iterator) != 0)
2322             return EINVAL;
2323     }
2324     if (newStyle) {
2325         tu = getNthCell(areq->uid, iterator);
2326     } else {
2327         cellNum = afs_GetPrimaryCellNum();
2328         if (cellNum)
2329             tu = afs_FindUser(areq->uid, cellNum, READ_LOCK);
2330     }
2331     if (!tu) {
2332         return EDOM;
2333     }
2334     if (!(tu->states & UHasTokens)
2335         || !afs_HasUsableTokens(tu->tokens, osi_Time())) {
2336         tu->states |= (UTokensBad | UNeedsReset);
2337         afs_NotifyUser(tu, UTokensDropped);
2338         afs_PutUser(tu, READ_LOCK);
2339         return ENOTCONN;
2340     }
2341     token = afs_FindToken(tu->tokens, RX_SECIDX_KAD);
2342
2343     /* If they don't have an RXKAD token, but do have other tokens,
2344      * then sadly there's nothing this interface can do to help them. */
2345     if (token == NULL)
2346         return ENOTCONN;
2347
2348     /* for compat, we try to return 56 byte tix if they fit */
2349     iterator = token->rxkad.ticketLen;
2350     if (iterator < 56)
2351         iterator = 56;          /* # of bytes we're returning */
2352
2353     if (afs_pd_putInt(aout, iterator) != 0)
2354         goto out;
2355     if (afs_pd_putBytes(aout, token->rxkad.ticket, token->rxkad.ticketLen) != 0)
2356         goto out;
2357     if (token->rxkad.ticketLen < 56) {
2358         /* Tokens are always 56 bytes or larger */
2359         if (afs_pd_skip(aout, iterator - token->rxkad.ticketLen) != 0) {
2360             goto out;
2361         }
2362     }
2363
2364     if (afs_pd_putInt(aout, sizeof(struct ClearToken)) != 0)
2365         goto out;
2366     if (afs_pd_putBytes(aout, &token->rxkad.clearToken,
2367                         sizeof(struct ClearToken)) != 0)
2368         goto out;
2369
2370     if (newStyle) {
2371         /* put out primary id and cell name, too */
2372         iterator = (tu->states & UPrimary ? 1 : 0);
2373         if (afs_pd_putInt(aout, iterator) != 0)
2374             goto out;
2375         tcell = afs_GetCell(tu->cell, READ_LOCK);
2376         if (tcell) {
2377             if (afs_pd_putString(aout, tcell->cellName) != 0)
2378                 goto out;
2379             afs_PutCell(tcell, READ_LOCK);
2380         } else
2381             if (afs_pd_putString(aout, "") != 0)
2382                 goto out;
2383     }
2384     /* Got here, all is good */
2385     code = 0;
2386 out:
2387     afs_PutUser(tu, READ_LOCK);
2388     return code;
2389 }
2390
2391 /*!
2392  * VIOCUNLOG (9) - Invalidate tokens
2393  *
2394  * \ingroup pioctl
2395  *
2396  * \param[in] ain       not in use
2397  * \param[out] aout     not in use
2398  *
2399  * \retval EIO  Error if the afs daemon hasn't been started yet
2400  *
2401  * \post remove tokens from a user, specified by the user id
2402  *
2403  * \notes sets the token's time to 0, which then causes it to be removed
2404  * \notes Unlog is the same as un-pag in OpenAFS
2405  */
2406 DECL_PIOCTL(PUnlog)
2407 {
2408     afs_int32 i;
2409     struct unixuser *tu;
2410
2411     AFS_STATCNT(PUnlog);
2412     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
2413         return EIO;             /* Inappropriate ioctl for device */
2414
2415     i = UHash(areq->uid);
2416     ObtainWriteLock(&afs_xuser, 227);
2417     for (tu = afs_users[i]; tu; tu = tu->next) {
2418         if (tu->uid == areq->uid) {
2419             tu->states &= ~UHasTokens;
2420             afs_FreeTokens(&tu->tokens);
2421             tu->refCount++;
2422             ReleaseWriteLock(&afs_xuser);
2423             afs_NotifyUser(tu, UTokensDropped);
2424             /* We have to drop the lock over the call to afs_ResetUserConns,
2425              * since it obtains the afs_xvcache lock.  We could also keep
2426              * the lock, and modify ResetUserConns to take parm saying we
2427              * obtained the lock already, but that is overkill.  By keeping
2428              * the "tu" pointer held over the released lock, we guarantee
2429              * that we won't lose our place, and that we'll pass over
2430              * every user conn that existed when we began this call.
2431              */
2432             afs_ResetUserConns(tu);
2433             tu->refCount--;
2434             ObtainWriteLock(&afs_xuser, 228);
2435 #ifdef UKERNEL
2436             /* set the expire times to 0, causes
2437              * afs_GCUserData to remove this entry
2438              */
2439             tu->tokenTime = 0;
2440 #endif /* UKERNEL */
2441         }
2442     }
2443     ReleaseWriteLock(&afs_xuser);
2444     return 0;
2445 }
2446
2447 /*!
2448  * VIOC_AFS_MARINER_HOST (32) - Get/set mariner (cache manager monitor) host
2449  *
2450  * \ingroup pioctl
2451  *
2452  * \param[in] ain       host address to be set
2453  * \param[out] aout     old host address
2454  *
2455  * \post
2456  *      depending on whether or not a variable is set, either get the host
2457  *      for the cache manager monitor, or set the old address and give it
2458  *      a new address
2459  *
2460  * \notes Errors turn off mariner
2461  */
2462 DECL_PIOCTL(PMariner)
2463 {
2464     afs_int32 newHostAddr;
2465     afs_int32 oldHostAddr;
2466
2467     AFS_STATCNT(PMariner);
2468     if (afs_mariner)
2469         memcpy((char *)&oldHostAddr, (char *)&afs_marinerHost,
2470                sizeof(afs_int32));
2471     else
2472         oldHostAddr = 0xffffffff;       /* disabled */
2473
2474     if (afs_pd_getInt(ain, &newHostAddr) != 0)
2475         return EINVAL;
2476
2477     if (newHostAddr == 0xffffffff) {
2478         /* disable mariner operations */
2479         afs_mariner = 0;
2480     } else if (newHostAddr) {
2481         afs_mariner = 1;
2482         afs_marinerHost = newHostAddr;
2483     }
2484
2485     if (afs_pd_putInt(aout, oldHostAddr) != 0)
2486         return E2BIG;
2487
2488     return 0;
2489 }
2490
2491 /*!
2492  * VIOCCKSERV (10) - Check that servers are up
2493  *
2494  * \ingroup pioctl
2495  *
2496  * \param[in] ain       name of the cell
2497  * \param[out] aout     current down server list
2498  *
2499  * \retval EIO          Error if the afs daemon hasn't started yet
2500  * \retval EACCES       Error if the user doesn't have super-user credentials
2501  * \retval ENOENT       Error if we are unable to obtain the cell
2502  *
2503  * \post
2504  *      Either a fast check (where it doesn't contact servers) or a
2505  *      local check (checks local cell only)
2506  */
2507 DECL_PIOCTL(PCheckServers)
2508 {
2509     int i;
2510     struct server *ts;
2511     afs_int32 temp;
2512     char *cellName = NULL;
2513     struct cell *cellp;
2514     struct chservinfo *pcheck;
2515
2516     AFS_STATCNT(PCheckServers);
2517
2518     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
2519         return EIO;             /* Inappropriate ioctl for device */
2520
2521     /* This is tricky, because we need to peak at the datastream to see
2522      * what we're getting. For now, let's cheat. */
2523
2524     /* ain contains either an int32 or a string */
2525     if (ain->remaining == 0)
2526         return EINVAL;
2527
2528     if (*(afs_int32 *)ain->ptr == 0x12345678) { /* For afs3.3 version */
2529         pcheck = afs_pd_inline(ain, sizeof(*pcheck));
2530         if (pcheck == NULL)
2531             return EINVAL;
2532
2533         if (pcheck->tinterval >= 0) {
2534             if (afs_pd_putInt(aout, afs_probe_interval) != 0)
2535                 return E2BIG;
2536             if (pcheck->tinterval > 0) {
2537                 if (!afs_osi_suser(*acred))
2538                     return EACCES;
2539                 afs_probe_interval = pcheck->tinterval;
2540             }
2541             return 0;
2542         }
2543         temp = pcheck->tflags;
2544         if (pcheck->tsize)
2545             cellName = pcheck->tbuffer;
2546     } else {                    /* For pre afs3.3 versions */
2547         if (afs_pd_getInt(ain, &temp) != 0)
2548             return EINVAL;
2549         if (afs_pd_remaining(ain) > 0) {
2550             if (afs_pd_getStringPtr(ain, &cellName) != 0)
2551                 return EINVAL;
2552         }
2553     }
2554
2555     /*
2556      * 1: fast check, don't contact servers.
2557      * 2: local cell only.
2558      */
2559     if (cellName) {
2560         /* have cell name, too */
2561         cellp = afs_GetCellByName(cellName, READ_LOCK);
2562         if (!cellp)
2563             return ENOENT;
2564     } else
2565         cellp = NULL;
2566     if (!cellp && (temp & 2)) {
2567         /* use local cell */
2568         cellp = afs_GetPrimaryCell(READ_LOCK);
2569     }
2570     if (!(temp & 1)) {          /* if not fast, call server checker routine */
2571         afs_CheckServers(1, cellp);     /* check down servers */
2572         afs_CheckServers(0, cellp);     /* check up servers */
2573     }
2574     /* now return the current down server list */
2575     ObtainReadLock(&afs_xserver);
2576     for (i = 0; i < NSERVERS; i++) {
2577         for (ts = afs_servers[i]; ts; ts = ts->next) {
2578             if (cellp && ts->cell != cellp)
2579                 continue;       /* cell spec'd and wrong */
2580             if ((ts->flags & SRVR_ISDOWN)
2581                 && ts->addr->sa_portal != ts->cell->vlport) {
2582                 afs_pd_putInt(aout, ts->addr->sa_ip);
2583             }
2584         }
2585     }
2586     ReleaseReadLock(&afs_xserver);
2587     if (cellp)
2588         afs_PutCell(cellp, READ_LOCK);
2589     return 0;
2590 }
2591
2592 /*!
2593  * VIOCCKBACK (11) - Check backup volume mappings
2594  *
2595  * \ingroup pioctl
2596  *
2597  * \param[in] ain       not in use
2598  * \param[out] aout     not in use
2599  *
2600  * \retval EIO          Error if the afs daemon hasn't started yet
2601  *
2602  * \post
2603  *      Check the root volume, and then check the names if the volume
2604  *      check variable is set to force, has expired, is busy, or if
2605  *      the mount points variable is set
2606  */
2607 DECL_PIOCTL(PCheckVolNames)
2608 {
2609     AFS_STATCNT(PCheckVolNames);
2610     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
2611         return EIO;             /* Inappropriate ioctl for device */
2612
2613     afs_CheckRootVolume();
2614     afs_CheckVolumeNames(AFS_VOLCHECK_FORCE | AFS_VOLCHECK_EXPIRED |
2615                          AFS_VOLCHECK_BUSY | AFS_VOLCHECK_MTPTS);
2616     return 0;
2617 }
2618
2619 /*!
2620  * VIOCCKCONN (12) - Check connections for a user
2621  *
2622  * \ingroup pioctl
2623  *
2624  * \param[in] ain       not in use
2625  * \param[out] aout     not in use
2626  *
2627  * \retval EACCESS
2628  *      Error if no user is specififed, the user has no tokens set,
2629  *      or if the user's tokens are bad
2630  *
2631  * \post
2632  *      check to see if a user has the correct authentication.
2633  *      If so, allow access.
2634  *
2635  * \notes Check the connections to all the servers specified
2636  */
2637 DECL_PIOCTL(PCheckAuth)
2638 {
2639     int i;
2640     struct srvAddr *sa;
2641     struct sa_conn_vector *tcv;
2642     struct unixuser *tu;
2643     afs_int32 retValue;
2644
2645     AFS_STATCNT(PCheckAuth);
2646     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
2647         return EIO;             /* Inappropriate ioctl for device */
2648
2649     retValue = 0;
2650     tu = afs_GetUser(areq->uid, 1, READ_LOCK);  /* check local cell authentication */
2651     if (!tu)
2652         retValue = EACCES;
2653     else {
2654         /* we have a user */
2655         ObtainReadLock(&afs_xsrvAddr);
2656         ObtainReadLock(&afs_xconn);
2657
2658         /* any tokens set? */
2659         if ((tu->states & UHasTokens) == 0)
2660             retValue = EACCES;
2661         /* all connections in cell 1 working? */
2662         for (i = 0; i < NSERVERS; i++) {
2663             for (sa = afs_srvAddrs[i]; sa; sa = sa->next_bkt) {
2664                 for (tcv = sa->conns; tcv; tcv = tcv->next) {
2665                     if (tcv->user == tu && (tu->states & UTokensBad))
2666                         retValue = EACCES;
2667                 }
2668             }
2669         }
2670         ReleaseReadLock(&afs_xsrvAddr);
2671         ReleaseReadLock(&afs_xconn);
2672         afs_PutUser(tu, READ_LOCK);
2673     }
2674     if (afs_pd_putInt(aout, retValue) != 0)
2675         return E2BIG;
2676     return 0;
2677 }
2678
2679 static int
2680 Prefetch(uparmtype apath, struct afs_ioctl *adata, int afollow,
2681          afs_ucred_t *acred)
2682 {
2683     char *tp;
2684     afs_int32 code;
2685 #if defined(AFS_SGI61_ENV) || defined(AFS_SUN57_ENV) || defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
2686     size_t bufferSize;
2687 #else
2688     u_int bufferSize;
2689 #endif
2690
2691     AFS_STATCNT(Prefetch);
2692     if (!apath)
2693         return EINVAL;
2694     tp = osi_AllocLargeSpace(1024);
2695     AFS_COPYINSTR(apath, tp, 1024, &bufferSize, code);
2696     if (code) {
2697         osi_FreeLargeSpace(tp);
2698         return code;
2699     }
2700     if (afs_BBusy()) {          /* do this as late as possible */
2701         osi_FreeLargeSpace(tp);
2702         return EWOULDBLOCK;     /* pretty close */
2703     }
2704     afs_BQueue(BOP_PATH, (struct vcache *)0, 0, 0, acred, (afs_size_t) 0,
2705                (afs_size_t) 0, tp, (void *)0, (void *)0);
2706     return 0;
2707 }
2708
2709 /*!
2710  * VIOCWHEREIS (14) - Find out where a volume is located
2711  *
2712  * \ingroup pioctl
2713  *
2714  * \param[in] ain       not in use
2715  * \param[out] aout     volume location
2716  *
2717  * \retval EINVAL       Error if some of the default arguments don't exist
2718  * \retval ENODEV       Error if there is no such volume
2719  *
2720  * \post fine a volume, based on a volume file id
2721  *
2722  * \notes check each of the servers specified
2723  */
2724 DECL_PIOCTL(PFindVolume)
2725 {
2726     struct volume *tvp;
2727     struct server *ts;
2728     afs_int32 i;
2729     int code = 0;
2730
2731     AFS_STATCNT(PFindVolume);
2732     if (!avc)
2733         return EINVAL;
2734     tvp = afs_GetVolume(&avc->f.fid, areq, READ_LOCK);
2735     if (!tvp)
2736         return ENODEV;
2737
2738     for (i = 0; i < AFS_MAXHOSTS; i++) {
2739         ts = tvp->serverHost[i];
2740         if (!ts)
2741             break;
2742         if (afs_pd_putInt(aout, ts->addr->sa_ip) != 0) {
2743             code = E2BIG;
2744             goto out;
2745         }
2746     }
2747     if (i < AFS_MAXHOSTS) {
2748         /* still room for terminating NULL, add it on */
2749         if (afs_pd_putInt(aout, 0) != 0) {
2750             code = E2BIG;
2751             goto out;
2752         }
2753     }
2754 out:
2755     afs_PutVolume(tvp, READ_LOCK);
2756     return code;
2757 }
2758
2759 /*!
2760  * VIOCACCESS (20) - Access using PRS_FS bits
2761  *
2762  * \ingroup pioctl
2763  *
2764  * \param[in] ain       PRS_FS bits
2765  * \param[out] aout     not in use
2766  *
2767  * \retval EINVAL       Error if some of the initial arguments aren't set
2768  * \retval EACCES       Error if access is denied
2769  *
2770  * \post check to make sure access is allowed
2771  */
2772 DECL_PIOCTL(PViceAccess)
2773 {
2774     afs_int32 code;
2775     afs_int32 temp;
2776
2777     AFS_STATCNT(PViceAccess);
2778     if (!avc)
2779         return EINVAL;
2780
2781     code = afs_VerifyVCache(avc, areq);
2782     if (code)
2783         return code;
2784
2785     if (afs_pd_getInt(ain, &temp) != 0)
2786         return EINVAL;
2787
2788     code = afs_AccessOK(avc, temp, areq, CHECK_MODE_BITS);
2789     if (code)
2790         return 0;
2791     else
2792         return EACCES;
2793 }
2794
2795 /*!
2796  * VIOC_GETPAG (13) - Get PAG value
2797  *
2798  * \ingroup pioctl
2799  *
2800  * \param[in] ain       not in use
2801  * \param[out] aout     PAG value or NOPAG
2802  *
2803  * \post get PAG value for the caller's cred
2804  */
2805 DECL_PIOCTL(PGetPAG)
2806 {
2807     afs_int32 pag;
2808
2809     pag = PagInCred(*acred);
2810
2811     return afs_pd_putInt(aout, pag);
2812 }
2813
2814 DECL_PIOCTL(PPrecache)
2815 {
2816     afs_int32 newValue;
2817
2818     /*AFS_STATCNT(PPrecache);*/
2819     if (!afs_osi_suser(*acred))
2820         return EACCES;
2821
2822     if (afs_pd_getInt(ain, &newValue) != 0)
2823         return EINVAL;
2824
2825     afs_preCache = newValue*1024;
2826     return 0;
2827 }
2828
2829 /*!
2830  * VIOCSETCACHESIZE (24) - Set venus cache size in 1000 units
2831  *
2832  * \ingroup pioctl
2833  *
2834  * \param[in] ain       the size the venus cache should be set to
2835  * \param[out] aout     not in use
2836  *
2837  * \retval EACCES       Error if the user doesn't have super-user credentials
2838  * \retval EROFS        Error if the cache is set to be in memory
2839  *
2840  * \post
2841  *      Set the cache size based on user input.  If no size is given,
2842  *      set it to the default OpenAFS cache size.
2843  *
2844  * \notes
2845  *      recompute the general cache parameters for every single block allocated
2846  */
2847 DECL_PIOCTL(PSetCacheSize)
2848 {
2849     afs_int32 newValue;
2850     int waitcnt = 0;
2851
2852     AFS_STATCNT(PSetCacheSize);
2853
2854     if (!afs_osi_suser(*acred))
2855         return EACCES;
2856     /* too many things are setup initially in mem cache version */
2857     if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
2858         return EROFS;
2859     if (afs_pd_getInt(ain, &newValue) != 0)
2860         return EINVAL;
2861     if (newValue == 0)
2862         afs_cacheBlocks = afs_stats_cmperf.cacheBlocksOrig;
2863     else {
2864         if (newValue < afs_min_cache)
2865             afs_cacheBlocks = afs_min_cache;
2866         else
2867             afs_cacheBlocks = newValue;
2868     }
2869     afs_stats_cmperf.cacheBlocksTotal = afs_cacheBlocks;
2870     afs_ComputeCacheParms();    /* recompute basic cache parameters */
2871     afs_MaybeWakeupTruncateDaemon();
2872     while (waitcnt++ < 100 && afs_cacheBlocks < afs_blocksUsed) {
2873         afs_osi_Wait(1000, 0, 0);
2874         afs_MaybeWakeupTruncateDaemon();
2875     }
2876     return 0;
2877 }
2878
2879 #define MAXGCSTATS      16
2880 /*!
2881  * VIOCGETCACHEPARMS (40) - Get cache stats
2882  *
2883  * \ingroup pioctl
2884  *
2885  * \param[in] ain       afs index flags
2886  * \param[out] aout     cache blocks, blocks used, blocks files (in an array)
2887  *
2888  * \post Get the cache blocks, and how many of the cache blocks there are
2889  */
2890 DECL_PIOCTL(PGetCacheSize)
2891 {
2892     afs_int32 results[MAXGCSTATS];
2893     afs_int32 flags;
2894     struct dcache * tdc;
2895     int i, size;
2896
2897     AFS_STATCNT(PGetCacheSize);
2898
2899     if (afs_pd_remaining(ain) == sizeof(afs_int32)) {
2900         afs_pd_getInt(ain, &flags); /* can't error, we just checked size */
2901     } else if (afs_pd_remaining(ain) == 0) {
2902         flags = 0;
2903     } else {
2904         return EINVAL;
2905     }
2906
2907     memset(results, 0, sizeof(results));
2908     results[0] = afs_cacheBlocks;
2909     results[1] = afs_blocksUsed;
2910     results[2] = afs_cacheFiles;
2911
2912     if (1 == flags){
2913         for (i = 0; i < afs_cacheFiles; i++) {
2914             if (afs_indexFlags[i] & IFFree) results[3]++;
2915         }
2916     } else if (2 == flags){
2917         for (i = 0; i < afs_cacheFiles; i++) {
2918             if (afs_indexFlags[i] & IFFree) results[3]++;
2919             if (afs_indexFlags[i] & IFEverUsed) results[4]++;
2920             if (afs_indexFlags[i] & IFDataMod) results[5]++;
2921             if (afs_indexFlags[i] & IFDirtyPages) results[6]++;
2922             if (afs_indexFlags[i] & IFAnyPages) results[7]++;
2923             if (afs_indexFlags[i] & IFDiscarded) results[8]++;
2924
2925             tdc = afs_indexTable[i];
2926             if (tdc){
2927                 results[9]++;
2928                 size = tdc->validPos;
2929                 if ( 0 < size && size < (1<<12) ) results[10]++;
2930                 else if (size < (1<<14) ) results[11]++;
2931                 else if (size < (1<<16) ) results[12]++;
2932                 else if (size < (1<<18) ) results[13]++;
2933                 else if (size < (1<<20) ) results[14]++;
2934                 else if (size >= (1<<20) ) results[15]++;
2935             }
2936         }
2937     }
2938     return afs_pd_putBytes(aout, results, sizeof(results));
2939 }
2940
2941 /*!
2942  * VIOCFLUSHCB (25) - Flush callback only
2943  *
2944  * \ingroup pioctl
2945  *
2946  * \param[in] ain       not in use
2947  * \param[out] aout     not in use
2948  *
2949  * \retval EINVAL       Error if some of the standard args aren't set
2950  * \retval 0            0 returned if the volume is set to read-only
2951  *
2952  * \post
2953  *      Flushes callbacks, by setting the length of callbacks to one,
2954  *      setting the next callback to be sent to the CB_DROPPED value,
2955  *      and then dequeues everything else.
2956  */
2957 DECL_PIOCTL(PRemoveCallBack)
2958 {
2959     struct afs_conn *tc;
2960     afs_int32 code = 0;
2961     struct AFSCallBack CallBacks_Array[1];
2962     struct AFSCBFids theFids;
2963     struct AFSCBs theCBs;
2964     struct rx_connection *rxconn;
2965     XSTATS_DECLS;
2966
2967     AFS_STATCNT(PRemoveCallBack);
2968     if (!avc)
2969         return EINVAL;
2970     if (avc->f.states & CRO)
2971         return 0;               /* read-only-ness can't change */
2972     ObtainWriteLock(&avc->lock, 229);
2973     theFids.AFSCBFids_len = 1;
2974     theCBs.AFSCBs_len = 1;
2975     theFids.AFSCBFids_val = (struct AFSFid *)&avc->f.fid.Fid;
2976     theCBs.AFSCBs_val = CallBacks_Array;
2977     CallBacks_Array[0].CallBackType = CB_DROPPED;
2978     if (avc->callback) {
2979         do {
2980             tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK, &rxconn);
2981             if (tc) {
2982                 XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_GIVEUPCALLBACKS);
2983                 RX_AFS_GUNLOCK();
2984                 code = RXAFS_GiveUpCallBacks(rxconn, &theFids, &theCBs);
2985                 RX_AFS_GLOCK();
2986                 XSTATS_END_TIME;
2987             }
2988             /* don't set code on failure since we wouldn't use it */
2989         } while (afs_Analyze
2990                  (tc, rxconn, code, &avc->f.fid, areq,
2991                   AFS_STATS_FS_RPCIDX_GIVEUPCALLBACKS, SHARED_LOCK, NULL));
2992
2993         ObtainWriteLock(&afs_xcbhash, 457);
2994         afs_DequeueCallback(avc);
2995         avc->callback = 0;
2996         avc->f.states &= ~(CStatd | CUnique);
2997         ReleaseWriteLock(&afs_xcbhash);
2998         if (avc->f.fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2999             osi_dnlc_purgedp(avc);
3000     }
3001     ReleaseWriteLock(&avc->lock);
3002     return 0;
3003 }
3004
3005 /*!
3006  * VIOCNEWCELL (26) - Configure new cell
3007  *
3008  * \ingroup pioctl
3009  *
3010  * \param[in] ain
3011  *      the name of the cell, the hosts that will be a part of the cell,
3012  *      whether or not it's linked with another cell, the other cell it's
3013  *      linked with, the file server port, and the volume server port
3014  * \param[out] aout
3015  *      not in use
3016  *
3017  * \retval EIO          Error if the afs daemon hasn't started yet
3018  * \retval EACCES       Error if the user doesn't have super-user cedentials
3019  * \retval EINVAL       Error if some 'magic' var doesn't have a certain bit set
3020  *
3021  * \post creates a new cell
3022  */
3023 DECL_PIOCTL(PNewCell)
3024 {
3025     afs_int32 cellHosts[AFS_MAXCELLHOSTS], magic = 0;
3026     char *newcell = NULL;
3027     char *linkedcell = NULL;
3028     afs_int32 code, ls;
3029     afs_int32 linkedstate = 0;
3030     afs_int32 fsport = 0, vlport = 0;
3031     int skip;
3032
3033     AFS_STATCNT(PNewCell);
3034     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
3035         return EIO;             /* Inappropriate ioctl for device */
3036
3037     if (!afs_osi_suser(*acred))
3038         return EACCES;
3039
3040     if (afs_pd_getInt(ain, &magic) != 0)
3041         return EINVAL;
3042     if (magic != 0x12345678)
3043         return EINVAL;
3044
3045     /* A 3.4 fs newcell command will pass an array of AFS_MAXCELLHOSTS
3046      * server addresses while the 3.5 fs newcell command passes
3047      * AFS_MAXHOSTS. To figure out which is which, check if the cellname
3048      * is good.
3049      *
3050      * This whole logic is bogus, because it relies on the newer command
3051      * sending its 12th address as 0.
3052      */
3053     if ((afs_pd_remaining(ain) < AFS_MAXCELLHOSTS +3) * sizeof(afs_int32))
3054         return EINVAL;
3055
3056     newcell = afs_pd_where(ain) + (AFS_MAXCELLHOSTS + 3) * sizeof(afs_int32);
3057     if (newcell[0] != '\0') {
3058         skip = 0;
3059     } else {
3060         skip = AFS_MAXHOSTS - AFS_MAXCELLHOSTS;
3061     }
3062
3063     /* AFS_MAXCELLHOSTS (=8) is less than AFS_MAXHOSTS (=13) */
3064     if (afs_pd_getBytes(ain, &cellHosts,
3065                         AFS_MAXCELLHOSTS * sizeof(afs_int32)) != 0)
3066         return EINVAL;
3067     if (afs_pd_skip(ain, skip * sizeof(afs_int32)) !=0)
3068         return EINVAL;
3069
3070     if (afs_pd_getInt(ain, &fsport) != 0)
3071         return EINVAL;
3072     if (fsport < 1024)
3073         fsport = 0;             /* Privileged ports not allowed */
3074
3075     if (afs_pd_getInt(ain, &vlport) != 0)
3076         return EINVAL;
3077     if (vlport < 1024)
3078         vlport = 0;             /* Privileged ports not allowed */
3079
3080     if (afs_pd_getInt(ain, &ls) != 0)
3081         return EINVAL;
3082
3083     if (afs_pd_getStringPtr(ain, &newcell) != 0)
3084         return EINVAL;
3085
3086     if (ls & 1) {
3087         if (afs_pd_getStringPtr(ain, &linkedcell) != 0)
3088             return EINVAL;
3089         linkedstate |= CLinkedCell;
3090     }
3091
3092     linkedstate |= CNoSUID;     /* setuid is disabled by default for fs newcell */
3093     code =
3094         afs_NewCell(newcell, cellHosts, linkedstate, linkedcell, fsport,
3095                     vlport, (int)0);
3096     return code;
3097 }
3098
3099 DECL_PIOCTL(PNewAlias)
3100 {
3101     /* create a new cell alias */
3102     char *realName, *aliasName;
3103
3104     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
3105         return EIO;             /* Inappropriate ioctl for device */
3106
3107     if (!afs_osi_suser(*acred))
3108         return EACCES;
3109
3110     if (afs_pd_getStringPtr(ain, &aliasName) != 0)
3111         return EINVAL;
3112     if (afs_pd_getStringPtr(ain, &realName) != 0)
3113         return EINVAL;
3114
3115     return afs_NewCellAlias(aliasName, realName);
3116 }
3117
3118 /*!
3119  * VIOCGETCELL (27) - Get cell info
3120  *
3121  * \ingroup pioctl
3122  *
3123  * \param[in] ain       The cell index of a specific cell
3124  * \param[out] aout     list of servers in the cell
3125  *
3126  * \retval EIO          Error if the afs daemon hasn't started yet
3127  * \retval EDOM         Error if there is no cell asked about
3128  *
3129  * \post Lists the cell's server names and and addresses
3130  */
3131 DECL_PIOCTL(PListCells)
3132 {
3133     afs_int32 whichCell;
3134     struct cell *tcell = 0;
3135     afs_int32 i;
3136     int code;
3137
3138     AFS_STATCNT(PListCells);
3139     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
3140         return EIO;             /* Inappropriate ioctl for device */
3141
3142     if (afs_pd_getInt(ain, &whichCell) != 0)
3143         return EINVAL;
3144
3145     tcell = afs_GetCellByIndex(whichCell, READ_LOCK);
3146     if (!tcell)
3147         return EDOM;
3148
3149     code = E2BIG;
3150
3151     for (i = 0; i < AFS_MAXCELLHOSTS; i++) {
3152         if (tcell->cellHosts[i] == 0)
3153             break;
3154         if (afs_pd_putInt(aout, tcell->cellHosts[i]->addr->sa_ip) != 0)
3155             goto out;
3156     }
3157     for (;i < AFS_MAXCELLHOSTS; i++) {
3158         if (afs_pd_putInt(aout, 0) != 0)
3159             goto out;
3160     }
3161     if (afs_pd_putString(aout, tcell->cellName) != 0)
3162         goto out;
3163     code = 0;
3164
3165 out:
3166     afs_PutCell(tcell, READ_LOCK);
3167     return code;
3168 }
3169
3170 DECL_PIOCTL(PListAliases)
3171 {
3172     afs_int32 whichAlias;
3173     struct cell_alias *tcalias = 0;
3174     int code;
3175
3176     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
3177         return EIO;             /* Inappropriate ioctl for device */
3178
3179     if (afs_pd_getInt(ain, &whichAlias) != 0)
3180         return EINVAL;
3181
3182     tcalias = afs_GetCellAlias(whichAlias);
3183     if (tcalias == NULL)
3184         return EDOM;
3185
3186     code = E2BIG;
3187     if (afs_pd_putString(aout, tcalias->alias) != 0)
3188         goto out;
3189     if (afs_pd_putString(aout, tcalias->cell) != 0)
3190         goto out;
3191
3192     code = 0;
3193 out:
3194     afs_PutCellAlias(tcalias);
3195     return code;
3196 }
3197
3198 /*!
3199  * VIOC_AFS_DELETE_MT_PT (28) - Delete mount point
3200  *
3201  * \ingroup pioctl
3202  *
3203  * \param[in] ain       the name of the file in this dir to remove
3204  * \param[out] aout     not in use
3205  *
3206  * \retval EINVAL
3207  *      Error if some of the standard args aren't set
3208  * \retval ENOTDIR
3209  *      Error if the argument to remove is not a directory
3210  * \retval ENOENT
3211  *      Error if there is no cache to remove the mount point from or
3212  *      if a vcache doesn't exist
3213  *
3214  * \post
3215  *      Ensure that everything is OK before deleting the mountpoint.
3216  *      If not, don't delete.  Delete a mount point based on a file id.
3217  */
3218 DECL_PIOCTL(PRemoveMount)
3219 {
3220     afs_int32 code;
3221     char *bufp;
3222     char *name;
3223     struct sysname_info sysState;
3224     afs_size_t offset, len;
3225     struct afs_conn *tc;
3226     struct dcache *tdc;
3227     struct vcache *tvc;
3228     struct AFSFetchStatus OutDirStatus;
3229     struct VenusFid tfid;
3230     struct AFSVolSync tsync;
3231     struct rx_connection *rxconn;
3232     XSTATS_DECLS;
3233
3234     /* "ain" is the name of the file in this dir to remove */
3235
3236     AFS_STATCNT(PRemoveMount);
3237     if (!avc)
3238         return EINVAL;
3239     if (afs_pd_getStringPtr(ain, &name) != 0)
3240         return EINVAL;
3241
3242     code = afs_VerifyVCache(avc, areq);
3243     if (code)
3244         return code;
3245     if (vType(avc) != VDIR)
3246         return ENOTDIR;
3247
3248     tdc = afs_GetDCache(avc, (afs_size_t) 0, areq, &offset, &len, 1);   /* test for error below */
3249     if (!tdc)
3250         return ENOENT;
3251     Check_AtSys(avc, name, &sysState, areq);
3252     ObtainReadLock(&tdc->lock);
3253     do {
3254         code = afs_dir_Lookup(tdc, sysState.name, &tfid.Fid);
3255     } while (code == ENOENT && Next_AtSys(avc, areq, &sysState));
3256     ReleaseReadLock(&tdc->lock);
3257     bufp = sysState.name;
3258     if (code) {
3259         afs_PutDCache(tdc);
3260         goto out;
3261     }
3262     tfid.Cell = avc->f.fid.Cell;
3263     tfid.Fid.Volume = avc->f.fid.Fid.Volume;
3264     if (!tfid.Fid.Unique && (avc->f.states & CForeign)) {
3265         tvc = afs_LookupVCache(&tfid, areq, NULL, avc, bufp);
3266     } else {
3267         tvc = afs_GetVCache(&tfid, areq, NULL, NULL);
3268     }
3269     if (!tvc) {
3270         code = ENOENT;
3271         afs_PutDCache(tdc);
3272         goto out;
3273     }
3274     if (tvc->mvstat != 1) {
3275         afs_PutDCache(tdc);
3276         afs_PutVCache(tvc);
3277         code = EINVAL;
3278         goto out;
3279     }
3280     ObtainWriteLock(&tvc->lock, 230);
3281     code = afs_HandleLink(tvc, areq);
3282     if (!code) {
3283         if (tvc->linkData) {
3284             if ((tvc->linkData[0] != '#') && (tvc->linkData[0] != '%'))
3285                 code = EINVAL;
3286         } else
3287             code = EIO;
3288     }
3289     ReleaseWriteLock(&tvc->lock);
3290     osi_dnlc_purgedp(tvc);
3291     afs_PutVCache(tvc);
3292     if (code) {
3293         afs_PutDCache(tdc);
3294         goto out;
3295     }
3296     ObtainWriteLock(&avc->lock, 231);
3297     osi_dnlc_remove(avc, bufp, tvc);
3298     do {
3299         tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK, &rxconn);
3300         if (tc) {
3301             XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_REMOVEFILE);
3302             RX_AFS_GUNLOCK();
3303             code =
3304                 RXAFS_RemoveFile(rxconn, (struct AFSFid *)&avc->f.fid.Fid, bufp,
3305                                  &OutDirStatus, &tsync);
3306             RX_AFS_GLOCK();
3307             XSTATS_END_TIME;
3308         } else
3309             code = -1;
3310     } while (afs_Analyze
3311              (tc, rxconn, code, &avc->f.fid, areq, AFS_STATS_FS_RPCIDX_REMOVEFILE,
3312               SHARED_LOCK, NULL));
3313
3314     if (code) {
3315         if (tdc)
3316             afs_PutDCache(tdc);
3317         ReleaseWriteLock(&avc->lock);
3318         goto out;
3319     }
3320     if (tdc) {
3321         /* we have the thing in the cache */
3322         ObtainWriteLock(&tdc->lock, 661);
3323         if (afs_LocalHero(avc, tdc, &OutDirStatus, 1)) {
3324             /* we can do it locally */
3325             code = afs_dir_Delete(tdc, bufp);
3326             if (code) {
3327                 ZapDCE(tdc);    /* surprise error -- invalid value */
3328                 DZap(tdc);
3329             }
3330         }
3331         ReleaseWriteLock(&tdc->lock);
3332         afs_PutDCache(tdc);     /* drop ref count */
3333     }
3334     avc->f.states &= ~CUnique;  /* For the dfs xlator */
3335     ReleaseWriteLock(&avc->lock);
3336     code = 0;
3337   out:
3338     if (sysState.allocked)
3339         osi_FreeLargeSpace(bufp);
3340     return code;
3341 }
3342
3343 /*!
3344  * VIOC_GETCELLSTATUS (35) - Get cell status info
3345  *
3346  * \ingroup pioctl
3347  *
3348  * \param[in] ain       The cell you want status information on
3349  * \param[out] aout     cell state (as a struct)
3350  *
3351  * \retval EIO          Error if the afs daemon hasn't started yet
3352  * \retval ENOENT       Error if the cell doesn't exist
3353  *
3354  * \post Returns the state of the cell as defined in a struct cell
3355  */
3356 DECL_PIOCTL(PGetCellStatus)
3357 {
3358     struct cell *tcell;
3359     char *cellName;
3360     afs_int32 temp;
3361
3362     AFS_STATCNT(PGetCellStatus);
3363     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
3364         return EIO;             /* Inappropriate ioctl for device */
3365
3366     if (afs_pd_getStringPtr(ain, &cellName) != 0)
3367         return EINVAL;
3368
3369     tcell = afs_GetCellByName(cellName, READ_LOCK);
3370     if (!tcell)
3371         return ENOENT;
3372     temp = tcell->states;
3373     afs_PutCell(tcell, READ_LOCK);
3374
3375     return afs_pd_putInt(aout, temp);
3376 }
3377
3378 /*!
3379  * VIOC_SETCELLSTATUS (36) - Set corresponding info
3380  *
3381  * \ingroup pioctl
3382  *
3383  * \param[in] ain
3384  *      The cell you want to set information about, and the values you
3385  *      want to set
3386  * \param[out] aout
3387  *      not in use
3388  *
3389  * \retval EIO          Error if the afs daemon hasn't started yet
3390  * \retval EACCES       Error if the user doesn't have super-user credentials
3391  *
3392  * \post
3393  *      Set the state of the cell in a defined struct cell, based on
3394  *      whether or not SetUID is allowed
3395  */
3396 DECL_PIOCTL(PSetCellStatus)
3397 {
3398     struct cell *tcell;
3399     char *cellName;
3400     afs_int32 flags0, flags1;
3401
3402     if (!afs_osi_suser(*acred))
3403         return EACCES;
3404     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
3405         return EIO;             /* Inappropriate ioctl for device */
3406
3407     if (afs_pd_getInt(ain, &flags0) != 0)
3408         return EINVAL;
3409     if (afs_pd_getInt(ain, &flags1) != 0)
3410         return EINVAL;
3411     if (afs_pd_getStringPtr(ain, &cellName) != 0)
3412         return EINVAL;
3413
3414     tcell = afs_GetCellByName(cellName, WRITE_LOCK);
3415     if (!tcell)
3416         return ENOENT;
3417     if (flags0 & CNoSUID)
3418         tcell->states |= CNoSUID;
3419     else
3420         tcell->states &= ~CNoSUID;
3421     afs_PutCell(tcell, WRITE_LOCK);
3422     return 0;
3423 }
3424
3425 /*!
3426  * VIOC_FLUSHVOLUME (37) - Flush whole volume's data
3427  *
3428  * \ingroup pioctl
3429  *
3430  * \param[in] ain       not in use (args in avc)
3431  * \param[out] aout     not in use
3432  *
3433  * \retval EINVAL       Error if some of the standard args aren't set
3434  * \retval EIO          Error if the afs daemon hasn't started yet
3435  *
3436  * \post
3437  *      Flush all cached contents of a volume.  Exactly what stays and what
3438  *      goes depends on the platform.
3439  *
3440  * \notes
3441  *      Does not flush a file that a user has open and is using, because
3442  *      it will be re-created on next write.  Also purges the dnlc,
3443  *      because things are screwed up.
3444  */
3445 DECL_PIOCTL(PFlushVolumeData)
3446 {
3447     afs_int32 i;
3448     struct dcache *tdc;
3449     struct vcache *tvc;
3450     struct volume *tv;
3451     afs_int32 cell, volume;
3452     struct afs_q *tq, *uq;
3453 #ifdef AFS_DARWIN80_ENV
3454     vnode_t vp;
3455 #endif
3456
3457     AFS_STATCNT(PFlushVolumeData);
3458     if (!avc)
3459         return EINVAL;
3460     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
3461         return EIO;             /* Inappropriate ioctl for device */
3462
3463     volume = avc->f.fid.Fid.Volume;     /* who to zap */
3464     cell = avc->f.fid.Cell;
3465
3466     /*
3467      * Clear stat'd flag from all vnodes from this volume; this will
3468      * invalidate all the vcaches associated with the volume.
3469      */
3470  loop:
3471     ObtainReadLock(&afs_xvcache);
3472     i = VCHashV(&avc->f.fid);
3473     for (tq = afs_vhashTV[i].prev; tq != &afs_vhashTV[i]; tq = uq) {
3474             uq = QPrev(tq);
3475             tvc = QTOVH(tq);
3476             if (tvc->f.fid.Fid.Volume == volume && tvc->f.fid.Cell == cell) {
3477                 if (tvc->f.states & CVInit) {
3478                     ReleaseReadLock(&afs_xvcache);
3479                     afs_osi_Sleep(&tvc->f.states);
3480                     goto loop;
3481                 }
3482 #ifdef AFS_DARWIN80_ENV
3483                 if (tvc->f.states & CDeadVnode) {
3484                     if (!(tvc->f.states & CBulkFetching)) {
3485                         ReleaseReadLock(&afs_xvcache);
3486                         afs_osi_Sleep(&tvc->f.states);
3487                         goto loop;
3488                     }
3489                 }
3490                 vp = AFSTOV(tvc);
3491                 if (vnode_get(vp))
3492                     continue;
3493                 if (vnode_ref(vp)) {
3494                     AFS_GUNLOCK();
3495                     vnode_put(vp);
3496                     AFS_GLOCK();
3497                     continue;
3498                 }
3499                 if (tvc->f.states & (CBulkFetching|CDeadVnode)) {
3500                     AFS_GUNLOCK();
3501                     vnode_recycle(AFSTOV(tvc));
3502                     AFS_GLOCK();
3503                 }
3504 #else
3505                 AFS_FAST_HOLD(tvc);
3506 #endif
3507                 ReleaseReadLock(&afs_xvcache);
3508 #ifdef AFS_BOZONLOCK_ENV
3509                 afs_BozonLock(&tvc->pvnLock, tvc);      /* Since afs_TryToSmush will do a pvn_vptrunc */
3510 #endif
3511                 ObtainWriteLock(&tvc->lock, 232);
3512
3513                 ObtainWriteLock(&afs_xcbhash, 458);
3514                 afs_DequeueCallback(tvc);
3515                 tvc->f.states &= ~(CStatd | CDirty);
3516                 ReleaseWriteLock(&afs_xcbhash);
3517                 if (tvc->f.fid.Fid.Vnode & 1 || (vType(tvc) == VDIR))
3518                     osi_dnlc_purgedp(tvc);
3519                 afs_TryToSmush(tvc, *acred, 1);
3520                 ReleaseWriteLock(&tvc->lock);
3521 #ifdef AFS_BOZONLOCK_ENV
3522                 afs_BozonUnlock(&tvc->pvnLock, tvc);
3523 #endif
3524 #ifdef AFS_DARWIN80_ENV
3525                 vnode_put(AFSTOV(tvc));
3526 #endif
3527                 ObtainReadLock(&afs_xvcache);
3528                 uq = QPrev(tq);
3529                 /* our tvc ptr is still good until now */
3530                 AFS_FAST_RELE(tvc);
3531             }
3532         }
3533     ReleaseReadLock(&afs_xvcache);
3534
3535
3536     ObtainWriteLock(&afs_xdcache, 328); /* needed to flush any stuff */
3537     for (i = 0; i < afs_cacheFiles; i++) {
3538         if (!(afs_indexFlags[i] & IFEverUsed))
3539             continue;           /* never had any data */
3540         tdc = afs_GetDSlot(i, NULL);
3541         if (tdc->refCount <= 1) {    /* too high, in use by running sys call */
3542             ReleaseReadLock(&tdc->tlock);
3543             if (tdc->f.fid.Fid.Volume == volume && tdc->f.fid.Cell == cell) {
3544                 if (!(afs_indexFlags[i] & IFDataMod)) {
3545                     /* if the file is modified, but has a ref cnt of only 1,
3546                      * then someone probably has the file open and is writing
3547                      * into it. Better to skip flushing such a file, it will be
3548                      * brought back immediately on the next write anyway.
3549                      *
3550                      * If we *must* flush, then this code has to be rearranged
3551                      * to call afs_storeAllSegments() first */
3552                     afs_FlushDCache(tdc);
3553                 }
3554             }
3555         } else {
3556             ReleaseReadLock(&tdc->tlock);
3557         }
3558         afs_PutDCache(tdc);     /* bumped by getdslot */
3559     }
3560     ReleaseWriteLock(&afs_xdcache);
3561
3562     ObtainReadLock(&afs_xvolume);
3563     for (i = 0; i < NVOLS; i++) {
3564         for (tv = afs_volumes[i]; tv; tv = tv->next) {
3565             if (tv->volume == volume) {
3566                 afs_ResetVolumeInfo(tv);
3567                 break;
3568             }
3569         }
3570     }
3571     ReleaseReadLock(&afs_xvolume);
3572
3573     /* probably, a user is doing this, probably, because things are screwed up.
3574      * maybe it's the dnlc's fault? */
3575     osi_dnlc_purge();
3576     return 0;
3577 }
3578
3579
3580 /*!
3581  * VIOCGETVCXSTATUS (41) - gets vnode x status
3582  *
3583  * \ingroup pioctl
3584  *
3585  * \param[in] ain
3586  *      not in use (avc used)
3587  * \param[out] aout
3588  *      vcxstat: the file id, the data version, any lock, the parent vnode,
3589  *      the parent unique id, the trunc position, the callback, cbExpires,
3590  *      what access is being made, what files are open,
3591  *      any users executing/writing, the flock count, the states,
3592  *      the move stat
3593  *
3594  * \retval EINVAL
3595  *      Error if some of the initial default arguments aren't set
3596  * \retval EACCES
3597  *      Error if access to check the mode bits is denied
3598  *
3599  * \post
3600  *      gets stats for the vnode, a struct listed in vcxstat
3601  */
3602 DECL_PIOCTL(PGetVnodeXStatus)
3603 {
3604     afs_int32 code;
3605     struct vcxstat stat;
3606     afs_int32 mode, i;
3607
3608 /*  AFS_STATCNT(PGetVnodeXStatus); */
3609     if (!avc)
3610         return EINVAL;
3611     code = afs_VerifyVCache(avc, areq);
3612     if (code)
3613         return code;
3614     if (vType(avc) == VDIR)
3615         mode = PRSFS_LOOKUP;
3616     else
3617         mode = PRSFS_READ;
3618     if (!afs_AccessOK(avc, mode, areq, CHECK_MODE_BITS))
3619         return EACCES;
3620
3621     memset(&stat, 0, sizeof(struct vcxstat));
3622     stat.fid = avc->f.fid;
3623     hset32(stat.DataVersion, hgetlo(avc->f.m.DataVersion));
3624     stat.lock = avc->lock;
3625     stat.parentVnode = avc->f.parent.vnode;
3626     stat.parentUnique = avc->f.parent.unique;
3627     hset(stat.flushDV, avc->flushDV);
3628     hset(stat.mapDV, avc->mapDV);
3629     stat.truncPos = avc->f.truncPos;
3630     {                   /* just grab the first two - won't break anything... */
3631         struct axscache *ac;
3632
3633         for (i = 0, ac = avc->Access; ac && i < CPSIZE; i++, ac = ac->next) {
3634             stat.randomUid[i] = ac->uid;
3635             stat.randomAccess[i] = ac->axess;
3636         }
3637     }
3638     stat.callback = afs_data_pointer_to_int32(avc->callback);
3639     stat.cbExpires = avc->cbExpires;
3640     stat.anyAccess = avc->f.anyAccess;
3641     stat.opens = avc->opens;
3642     stat.execsOrWriters = avc->execsOrWriters;
3643     stat.flockCount = avc->flockCount;
3644     stat.mvstat = avc->mvstat;
3645     stat.states = avc->f.states;
3646     return afs_pd_putBytes(aout, &stat, sizeof(struct vcxstat));
3647 }
3648
3649
3650 DECL_PIOCTL(PGetVnodeXStatus2)
3651 {
3652     afs_int32 code;
3653     struct vcxstat2 stat;
3654     afs_int32 mode;
3655
3656     if (!avc)
3657         return EINVAL;
3658     code = afs_VerifyVCache(avc, areq);
3659     if (code)
3660         return code;
3661     if (vType(avc) == VDIR)
3662         mode = PRSFS_LOOKUP;
3663     else
3664         mode = PRSFS_READ;
3665     if (!afs_AccessOK(avc, mode, areq, CHECK_MODE_BITS))
3666         return EACCES;
3667
3668     memset(&stat, 0, sizeof(struct vcxstat2));
3669
3670     stat.cbExpires = avc->cbExpires;
3671     stat.anyAccess = avc->f.anyAccess;
3672     stat.mvstat = avc->mvstat;
3673     stat.callerAccess = afs_GetAccessBits(avc, ~0, areq);
3674
3675     return afs_pd_putBytes(aout, &stat, sizeof(struct vcxstat2));
3676 }
3677
3678
3679 /*!
3680  * VIOC_AFS_SYSNAME (38) - Change @sys value
3681  *
3682  * \ingroup pioctl
3683  *
3684  * \param[in] ain       new value for @sys
3685  * \param[out] aout     count, entry, list (debug values?)
3686  *
3687  * \retval EINVAL
3688  *      Error if afsd isn't running, the new sysname is too large,
3689  *      the new sysname causes issues (starts with a . or ..),
3690  *      there is no PAG set in the credentials, or the user of a PAG
3691  *      can't be found
3692  * \retval EACCES
3693  *      Error if the user doesn't have super-user credentials
3694  *
3695  * \post
3696  *      Set the value of @sys if these things work: if the input isn't
3697  *      too long or if input doesn't start with . or ..
3698  *
3699  * \notes
3700  *      We require root for local sysname changes, but not for remote
3701  *      (since we don't really believe remote uids anyway)
3702  *      outname[] shouldn't really be needed- this is left as an
3703  *      exercise for the reader.
3704  */
3705 DECL_PIOCTL(PSetSysName)
3706 {
3707     char *inname = NULL;
3708     char outname[MAXSYSNAME];
3709     afs_int32 setsysname;
3710     int foundname = 0;
3711     struct afs_exporter *exporter;
3712     struct unixuser *au;
3713     afs_int32 pag, error;
3714     int t, count, num = 0, allpags = 0;
3715     char **sysnamelist;
3716     struct afs_pdata validate;
3717
3718     AFS_STATCNT(PSetSysName);
3719     if (!afs_globalVFS) {
3720         /* Afsd is NOT running; disable it */
3721 #if defined(KERNEL_HAVE_UERROR)
3722         return (setuerror(EINVAL), EINVAL);
3723 #else
3724         return (EINVAL);
3725 #endif
3726     }
3727     if (afs_pd_getInt(ain, &setsysname) != 0)
3728         return EINVAL;
3729     if (setsysname & 0x8000) {
3730         allpags = 1;
3731         setsysname &= ~0x8000;
3732     }
3733     if (setsysname) {
3734
3735         /* Check my args */
3736         if (setsysname < 0 || setsysname > MAXNUMSYSNAMES)
3737             return EINVAL;
3738         validate = *ain;
3739         for (count = 0; count < setsysname; count++) {
3740             if (afs_pd_getStringPtr(&validate, &inname) != 0)
3741                 return EINVAL;
3742             t = strlen(inname);
3743             if (t >= MAXSYSNAME || t <= 0)
3744                 return EINVAL;
3745             /* check for names that can shoot us in the foot */
3746             if (inname[0] == '.' && (inname[1] == 0
3747                 || (inname[1] == '.' && inname[2] == 0)))
3748                 return EINVAL;
3749         }
3750         /* args ok, so go back to the beginning of that section */
3751
3752         if (afs_pd_getStringPtr(ain, &inname) != 0)
3753             return EINVAL;
3754         num = count;
3755     }
3756     if (afs_cr_gid(*acred) == RMTUSER_REQ ||
3757         afs_cr_gid(*acred) == RMTUSER_REQ_PRIV) {   /* Handles all exporters */
3758         if (allpags && afs_cr_gid(*acred) != RMTUSER_REQ_PRIV) {
3759             return EPERM;
3760         }
3761         pag = PagInCred(*acred);
3762         if (pag == NOPAG) {
3763             return EINVAL;      /* Better than panicing */
3764         }
3765         if (!(au = afs_FindUser(pag, -1, READ_LOCK))) {
3766             return EINVAL;      /* Better than panicing */
3767         }
3768         if (!(exporter = au->exporter)) {
3769             afs_PutUser(au, READ_LOCK);
3770             return EINVAL;      /* Better than panicing */
3771         }
3772         error = EXP_SYSNAME(exporter, inname, &sysnamelist,
3773                             &num, allpags);
3774         if (error) {
3775             if (error == ENODEV)
3776                 foundname = 0;  /* sysname not set yet! */
3777             else {
3778                 afs_PutUser(au, READ_LOCK);
3779                 return error;
3780             }
3781         } else {
3782             foundname = num;
3783             strcpy(outname, sysnamelist[0]);
3784         }
3785         afs_PutUser(au, READ_LOCK);
3786         if (setsysname)
3787             afs_sysnamegen++;
3788     } else {
3789         /* Not xlating, so loc