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