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