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