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