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