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