f89998b96de8ffc2c5b80636a9b3bcde2957c2db
[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)
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)
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     AFS_STATCNT(PGetVolumeStatus);
1961     if (!avc) {
1962         code = EINVAL;
1963         goto out;
1964     }
1965     Name = volName;
1966     do {
1967         tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK);
1968         if (tc) {
1969             XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_GETVOLUMESTATUS);
1970             RX_AFS_GUNLOCK();
1971             code =
1972                 RXAFS_GetVolumeStatus(tc->id, avc->f.fid.Fid.Volume, &volstat,
1973                                       &Name, &offLineMsg, &motd);
1974             RX_AFS_GLOCK();
1975             XSTATS_END_TIME;
1976         } else
1977             code = -1;
1978     } while (afs_Analyze
1979              (tc, code, &avc->f.fid, areq, AFS_STATS_FS_RPCIDX_GETVOLUMESTATUS,
1980               SHARED_LOCK, NULL));
1981
1982     if (code)
1983         goto out;
1984     /* Copy all this junk into msg->im_data, keeping track of the lengths. */
1985     if (afs_pd_putBytes(aout, &volstat, sizeof(VolumeStatus)) != 0)
1986         return E2BIG;
1987     if (afs_pd_putString(aout, volName) != 0)
1988         return E2BIG;
1989     if (afs_pd_putString(aout, offLineMsg) != 0)
1990         return E2BIG;
1991     if (afs_pd_putString(aout, motd) != 0)
1992         return E2BIG;
1993   out:
1994     afs_osi_Free(offLineMsg, 256);
1995     afs_osi_Free(motd, 256);
1996     return code;
1997 }
1998
1999 /*!
2000  * VIOCSETVOLSTAT (5) - Set volume status
2001  *
2002  * \ingroup pioctl
2003  *
2004  * \param[in] ain
2005  *      values to set the status at, offline message, message of the day,
2006  *      volume name, minimum quota, maximum quota
2007  * \param[out] aout
2008  *      status of a volume, offlines messages, minimum quota, maximumm quota
2009  *
2010  * \retval EINVAL
2011  *      Error if some of the standard args aren't set
2012  * \retval EROFS
2013  *      Error if the volume is read only, or a backup volume
2014  * \retval ENODEV
2015  *      Error if the volume can't be accessed
2016  * \retval E2BIG
2017  *      Error if the volume name, offline message, and motd are too big
2018  *
2019  * \post
2020  *      Set the status of a volume, including any offline messages,
2021  *      a minimum quota, and a maximum quota
2022  */
2023 DECL_PIOCTL(PSetVolumeStatus)
2024 {
2025     char *volName;
2026     char *offLineMsg;
2027     char *motd;
2028     struct afs_conn *tc;
2029     afs_int32 code = 0;
2030     struct AFSFetchVolumeStatus volstat;
2031     struct AFSStoreVolumeStatus storeStat;
2032     struct volume *tvp;
2033     XSTATS_DECLS;
2034
2035     AFS_STATCNT(PSetVolumeStatus);
2036     if (!avc)
2037         return EINVAL;
2038
2039     tvp = afs_GetVolume(&avc->f.fid, areq, READ_LOCK);
2040     if (tvp) {
2041         if (tvp->states & (VRO | VBackup)) {
2042             afs_PutVolume(tvp, READ_LOCK);
2043             return EROFS;
2044         }
2045         afs_PutVolume(tvp, READ_LOCK);
2046     } else
2047         return ENODEV;
2048
2049
2050     if (afs_pd_getBytes(ain, &volstat, sizeof(AFSFetchVolumeStatus)) != 0)
2051         return EINVAL;
2052
2053     if (afs_pd_getStringPtr(ain, &volName) != 0)
2054         return EINVAL;
2055     if (strlen(volName) > 32)
2056         return E2BIG;
2057
2058     if (afs_pd_getStringPtr(ain, &offLineMsg) != 0)
2059         return EINVAL;
2060     if (strlen(offLineMsg) > 256)
2061         return E2BIG;
2062
2063     if (afs_pd_getStringPtr(ain, &motd) != 0)
2064         return EINVAL;
2065     if (strlen(motd) > 256)
2066         return E2BIG;
2067
2068     /* Done reading ... */
2069
2070     storeStat.Mask = 0;
2071     if (volstat.MinQuota != -1) {
2072         storeStat.MinQuota = volstat.MinQuota;
2073         storeStat.Mask |= AFS_SETMINQUOTA;
2074     }
2075     if (volstat.MaxQuota != -1) {
2076         storeStat.MaxQuota = volstat.MaxQuota;
2077         storeStat.Mask |= AFS_SETMAXQUOTA;
2078     }
2079     do {
2080         tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK);
2081         if (tc) {
2082             XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_SETVOLUMESTATUS);
2083             RX_AFS_GUNLOCK();
2084             code =
2085                 RXAFS_SetVolumeStatus(tc->id, avc->f.fid.Fid.Volume, &storeStat,
2086                                       volName, offLineMsg, motd);
2087             RX_AFS_GLOCK();
2088             XSTATS_END_TIME;
2089         } else
2090             code = -1;
2091     } while (afs_Analyze
2092              (tc, code, &avc->f.fid, areq, AFS_STATS_FS_RPCIDX_SETVOLUMESTATUS,
2093               SHARED_LOCK, NULL));
2094
2095     if (code)
2096         return code;
2097     /* we are sending parms back to make compat. with prev system.  should
2098      * change interface later to not ask for current status, just set new
2099      * status */
2100
2101     if (afs_pd_putBytes(aout, &volstat, sizeof(VolumeStatus)) != 0)
2102         return EINVAL;
2103     if (afs_pd_putString(aout, volName) != 0)
2104         return EINVAL;
2105     if (afs_pd_putString(aout, offLineMsg) != 0)
2106         return EINVAL;
2107     if (afs_pd_putString(aout, motd) != 0)
2108         return EINVAL;
2109
2110     return code;
2111 }
2112
2113 /*!
2114  * VIOCFLUSH (6) - Invalidate cache entry
2115  *
2116  * \ingroup pioctl
2117  *
2118  * \param[in] ain       not in use
2119  * \param[out] aout     not in use
2120  *
2121  * \retval EINVAL       Error if some of the standard args aren't set
2122  *
2123  * \post Flush any information the cache manager has on an entry
2124  */
2125 DECL_PIOCTL(PFlush)
2126 {
2127     AFS_STATCNT(PFlush);
2128     if (!avc)
2129         return EINVAL;
2130 #ifdef AFS_BOZONLOCK_ENV
2131     afs_BozonLock(&avc->pvnLock, avc);  /* Since afs_TryToSmush will do a pvn_vptrunc */
2132 #endif
2133     ObtainWriteLock(&avc->lock, 225);
2134     afs_ResetVCache(avc, *acred);
2135     ReleaseWriteLock(&avc->lock);
2136 #ifdef AFS_BOZONLOCK_ENV
2137     afs_BozonUnlock(&avc->pvnLock, avc);
2138 #endif
2139     return 0;
2140 }
2141
2142 /*!
2143  * VIOC_AFS_STAT_MT_PT (29) - Stat mount point
2144  *
2145  * \ingroup pioctl
2146  *
2147  * \param[in] ain
2148  *      the last component in a path, related to mountpoint that we're
2149  *      looking for information about
2150  * \param[out] aout
2151  *      volume, cell, link data
2152  *
2153  * \retval EINVAL       Error if some of the standard args aren't set
2154  * \retval ENOTDIR      Error if the 'mount point' argument isn't a directory
2155  * \retval EIO          Error if the link data can't be accessed
2156  *
2157  * \post Get the volume, and cell, as well as the link data for a mount point
2158  */
2159 DECL_PIOCTL(PNewStatMount)
2160 {
2161     afs_int32 code;
2162     struct vcache *tvc;
2163     struct dcache *tdc;
2164     struct VenusFid tfid;
2165     char *bufp;
2166     char *name;
2167     struct sysname_info sysState;
2168     afs_size_t offset, len;
2169
2170     AFS_STATCNT(PNewStatMount);
2171     if (!avc)
2172         return EINVAL;
2173
2174     if (afs_pd_getStringPtr(ain, &name) != 0)
2175         return EINVAL;
2176
2177     code = afs_VerifyVCache(avc, areq);
2178     if (code)
2179         return code;
2180     if (vType(avc) != VDIR) {
2181         return ENOTDIR;
2182     }
2183     tdc = afs_GetDCache(avc, (afs_size_t) 0, areq, &offset, &len, 1);
2184     if (!tdc)
2185         return ENOENT;
2186     Check_AtSys(avc, name, &sysState, areq);
2187     ObtainReadLock(&tdc->lock);
2188     do {
2189         code = afs_dir_Lookup(tdc, sysState.name, &tfid.Fid);
2190     } while (code == ENOENT && Next_AtSys(avc, areq, &sysState));
2191     ReleaseReadLock(&tdc->lock);
2192     afs_PutDCache(tdc);         /* we're done with the data */
2193     bufp = sysState.name;
2194     if (code) {
2195         goto out;
2196     }
2197     tfid.Cell = avc->f.fid.Cell;
2198     tfid.Fid.Volume = avc->f.fid.Fid.Volume;
2199     if (!tfid.Fid.Unique && (avc->f.states & CForeign)) {
2200         tvc = afs_LookupVCache(&tfid, areq, NULL, avc, bufp);
2201     } else {
2202         tvc = afs_GetVCache(&tfid, areq, NULL, NULL);
2203     }
2204     if (!tvc) {
2205         code = ENOENT;
2206         goto out;
2207     }
2208     if (tvc->mvstat != 1) {
2209         afs_PutVCache(tvc);
2210         code = EINVAL;
2211         goto out;
2212     }
2213     ObtainWriteLock(&tvc->lock, 226);
2214     code = afs_HandleLink(tvc, areq);
2215     if (code == 0) {
2216         if (tvc->linkData) {
2217             if ((tvc->linkData[0] != '#') && (tvc->linkData[0] != '%'))
2218                 code = EINVAL;
2219             else {
2220                 /* we have the data */
2221                 if (afs_pd_putString(aout, tvc->linkData) != 0)
2222                     code = EINVAL;
2223             }
2224         } else
2225             code = EIO;
2226     }
2227     ReleaseWriteLock(&tvc->lock);
2228     afs_PutVCache(tvc);
2229   out:
2230     if (sysState.allocked)
2231         osi_FreeLargeSpace(bufp);
2232     return code;
2233 }
2234
2235 /*!
2236  * A helper function to get the n'th cell which a particular user has tokens
2237  * for. This is racy. If new tokens are added whilst we're iterating, then
2238  * we may return some cells twice. If tokens expire mid run, then we'll
2239  * miss some cells from our output. So, could be better, but that would
2240  * require an interface change.
2241  */
2242
2243 static struct unixuser *
2244 getNthCell(afs_int32 uid, afs_int32 iterator) {
2245     int i;
2246     struct unixuser *tu = NULL;
2247
2248     i = UHash(uid);
2249     ObtainReadLock(&afs_xuser);
2250     for (tu = afs_users[i]; tu; tu = tu->next) {
2251         if (tu->uid == uid && (tu->states & UHasTokens)) {
2252             if (iterator-- == 0)
2253             break;      /* are we done yet? */
2254         }
2255     }
2256     if (tu) {
2257         tu->refCount++;
2258     }
2259     ReleaseReadLock(&afs_xuser);
2260
2261     return tu;
2262 }
2263 /*!
2264  * VIOCGETTOK (8) - Get authentication tokens
2265  *
2266  * \ingroup pioctl
2267  *
2268  * \param[in] ain       cellid to return tokens for
2269  * \param[out] aout     token
2270  *
2271  * \retval EIO
2272  *      Error if the afs daemon hasn't started yet
2273  * \retval EDOM
2274  *      Error if the input parameter is out of the bounds of the available
2275  *      tokens
2276  * \retval ENOTCONN
2277  *      Error if there aren't tokens for this cell
2278  *
2279  * \post
2280  *      If the input paramater exists, get the token that corresponds to
2281  *      the parameter value, if there is no token at this value, get the
2282  *      token for the first cell
2283  *
2284  * \notes "it's a weird interface (from comments in the code)"
2285  */
2286
2287 DECL_PIOCTL(PGetTokens)
2288 {
2289     struct cell *tcell;
2290     struct unixuser *tu = NULL;
2291     union tokenUnion *token;
2292     afs_int32 iterator = 0;
2293     int newStyle;
2294     int cellNum;
2295     int code = E2BIG;
2296
2297     AFS_STATCNT(PGetTokens);
2298     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
2299         return EIO;             /* Inappropriate ioctl for device */
2300
2301     /* weird interface.  If input parameter is present, it is an integer and
2302      * we're supposed to return the parm'th tokens for this unix uid.
2303      * If not present, we just return tokens for cell 1.
2304      * If counter out of bounds, return EDOM.
2305      * If no tokens for the particular cell, return ENOTCONN.
2306      * Also, if this mysterious parm is present, we return, along with the
2307      * tokens, the primary cell indicator (an afs_int32 0) and the cell name
2308      * at the end, in that order.
2309      */
2310     newStyle = (afs_pd_remaining(ain) > 0);
2311     if (newStyle) {
2312         if (afs_pd_getInt(ain, &iterator) != 0)
2313             return EINVAL;
2314     }
2315     if (newStyle) {
2316         tu = getNthCell(areq->uid, iterator);
2317     } else {
2318         cellNum = afs_GetPrimaryCellNum();
2319         if (cellNum)
2320             tu = afs_FindUser(areq->uid, cellNum, READ_LOCK);
2321     }
2322     if (!tu) {
2323         return EDOM;
2324     }
2325     if (!(tu->states & UHasTokens)
2326         || !afs_HasUsableTokens(tu->tokens, osi_Time())) {
2327         tu->states |= (UTokensBad | UNeedsReset);
2328         afs_NotifyUser(tu, UTokensDropped);
2329         afs_PutUser(tu, READ_LOCK);
2330         return ENOTCONN;
2331     }
2332     token = afs_FindToken(tu->tokens, RX_SECIDX_KAD);
2333
2334     /* for compat, we try to return 56 byte tix if they fit */
2335     iterator = token->rxkad.ticketLen;
2336     if (iterator < 56)
2337         iterator = 56;          /* # of bytes we're returning */
2338
2339     if (afs_pd_putInt(aout, iterator) != 0)
2340         goto out;
2341     if (afs_pd_putBytes(aout, token->rxkad.ticket, token->rxkad.ticketLen) != 0)
2342         goto out;
2343     if (token->rxkad.ticketLen < 56) {
2344         /* Tokens are always 56 bytes or larger */
2345         if (afs_pd_skip(aout, iterator - token->rxkad.ticketLen) != 0) {
2346             goto out;
2347         }
2348     }
2349
2350     if (afs_pd_putInt(aout, sizeof(struct ClearToken)) != 0)
2351         goto out;
2352     if (afs_pd_putBytes(aout, &token->rxkad.clearToken,
2353                         sizeof(struct ClearToken)) != 0)
2354         goto out;
2355
2356     if (newStyle) {
2357         /* put out primary id and cell name, too */
2358         iterator = (tu->states & UPrimary ? 1 : 0);
2359         if (afs_pd_putInt(aout, iterator) != 0)
2360             goto out;
2361         tcell = afs_GetCell(tu->cell, READ_LOCK);
2362         if (tcell) {
2363             if (afs_pd_putString(aout, tcell->cellName) != 0)
2364                 goto out;
2365             afs_PutCell(tcell, READ_LOCK);
2366         } else
2367             if (afs_pd_putString(aout, "") != 0)
2368                 goto out;
2369     }
2370     /* Got here, all is good */
2371     code = 0;
2372 out:
2373     afs_PutUser(tu, READ_LOCK);
2374     return code;
2375 }
2376
2377 /*!
2378  * VIOCUNLOG (9) - Invalidate tokens
2379  *
2380  * \ingroup pioctl
2381  *
2382  * \param[in] ain       not in use
2383  * \param[out] aout     not in use
2384  *
2385  * \retval EIO  Error if the afs daemon hasn't been started yet
2386  *
2387  * \post remove tokens from a user, specified by the user id
2388  *
2389  * \notes sets the token's time to 0, which then causes it to be removed
2390  * \notes Unlog is the same as un-pag in OpenAFS
2391  */
2392 DECL_PIOCTL(PUnlog)
2393 {
2394     afs_int32 i;
2395     struct unixuser *tu;
2396
2397     AFS_STATCNT(PUnlog);
2398     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
2399         return EIO;             /* Inappropriate ioctl for device */
2400
2401     i = UHash(areq->uid);
2402     ObtainWriteLock(&afs_xuser, 227);
2403     for (tu = afs_users[i]; tu; tu = tu->next) {
2404         if (tu->uid == areq->uid) {
2405             tu->states &= ~UHasTokens;
2406             afs_FreeTokens(&tu->tokens);
2407             tu->refCount++;
2408             ReleaseWriteLock(&afs_xuser);
2409             afs_NotifyUser(tu, UTokensDropped);
2410             /* We have to drop the lock over the call to afs_ResetUserConns,
2411              * since it obtains the afs_xvcache lock.  We could also keep
2412              * the lock, and modify ResetUserConns to take parm saying we
2413              * obtained the lock already, but that is overkill.  By keeping
2414              * the "tu" pointer held over the released lock, we guarantee
2415              * that we won't lose our place, and that we'll pass over
2416              * every user conn that existed when we began this call.
2417              */
2418             afs_ResetUserConns(tu);
2419             tu->refCount--;
2420             ObtainWriteLock(&afs_xuser, 228);
2421 #ifdef UKERNEL
2422             /* set the expire times to 0, causes
2423              * afs_GCUserData to remove this entry
2424              */
2425             tu->tokenTime = 0;
2426 #endif /* UKERNEL */
2427         }
2428     }
2429     ReleaseWriteLock(&afs_xuser);
2430     return 0;
2431 }
2432
2433 /*!
2434  * VIOC_AFS_MARINER_HOST (32) - Get/set mariner (cache manager monitor) host
2435  *
2436  * \ingroup pioctl
2437  *
2438  * \param[in] ain       host address to be set
2439  * \param[out] aout     old host address
2440  *
2441  * \post
2442  *      depending on whether or not a variable is set, either get the host
2443  *      for the cache manager monitor, or set the old address and give it
2444  *      a new address
2445  *
2446  * \notes Errors turn off mariner
2447  */
2448 DECL_PIOCTL(PMariner)
2449 {
2450     afs_int32 newHostAddr;
2451     afs_int32 oldHostAddr;
2452
2453     AFS_STATCNT(PMariner);
2454     if (afs_mariner)
2455         memcpy((char *)&oldHostAddr, (char *)&afs_marinerHost,
2456                sizeof(afs_int32));
2457     else
2458         oldHostAddr = 0xffffffff;       /* disabled */
2459
2460     if (afs_pd_getInt(ain, &newHostAddr) != 0)
2461         return EINVAL;
2462
2463     if (newHostAddr == 0xffffffff) {
2464         /* disable mariner operations */
2465         afs_mariner = 0;
2466     } else if (newHostAddr) {
2467         afs_mariner = 1;
2468         afs_marinerHost = newHostAddr;
2469     }
2470
2471     if (afs_pd_putInt(aout, oldHostAddr) != 0)
2472         return E2BIG;
2473
2474     return 0;
2475 }
2476
2477 /*!
2478  * VIOCCKSERV (10) - Check that servers are up
2479  *
2480  * \ingroup pioctl
2481  *
2482  * \param[in] ain       name of the cell
2483  * \param[out] aout     current down server list
2484  *
2485  * \retval EIO          Error if the afs daemon hasn't started yet
2486  * \retval EACCES       Error if the user doesn't have super-user credentials
2487  * \retval ENOENT       Error if we are unable to obtain the cell
2488  *
2489  * \post
2490  *      Either a fast check (where it doesn't contact servers) or a
2491  *      local check (checks local cell only)
2492  */
2493 DECL_PIOCTL(PCheckServers)
2494 {
2495     int i;
2496     struct server *ts;
2497     afs_int32 temp;
2498     char *cellName = NULL;
2499     struct cell *cellp;
2500     struct chservinfo *pcheck;
2501
2502     AFS_STATCNT(PCheckServers);
2503
2504     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
2505         return EIO;             /* Inappropriate ioctl for device */
2506
2507     /* This is tricky, because we need to peak at the datastream to see
2508      * what we're getting. For now, let's cheat. */
2509
2510     /* ain contains either an int32 or a string */
2511     if (ain->remaining == 0)
2512         return EINVAL;
2513
2514     if (*(afs_int32 *)ain->ptr == 0x12345678) { /* For afs3.3 version */
2515         pcheck = afs_pd_inline(ain, sizeof(*pcheck));
2516         if (pcheck == NULL)
2517             return EINVAL;
2518
2519         if (pcheck->tinterval >= 0) {
2520             if (afs_pd_putInt(aout, afs_probe_interval) != 0)
2521                 return E2BIG;
2522             if (pcheck->tinterval > 0) {
2523                 if (!afs_osi_suser(*acred))
2524                     return EACCES;
2525                 afs_probe_interval = pcheck->tinterval;
2526             }
2527             return 0;
2528         }
2529         temp = pcheck->tflags;
2530         if (pcheck->tsize)
2531             cellName = pcheck->tbuffer;
2532     } else {                    /* For pre afs3.3 versions */
2533         if (afs_pd_getInt(ain, &temp) != 0)
2534             return EINVAL;
2535         if (afs_pd_remaining(ain) > 0) {
2536             if (afs_pd_getStringPtr(ain, &cellName) != 0)
2537                 return EINVAL;
2538         }
2539     }
2540
2541     /*
2542      * 1: fast check, don't contact servers.
2543      * 2: local cell only.
2544      */
2545     if (cellName) {
2546         /* have cell name, too */
2547         cellp = afs_GetCellByName(cellName, READ_LOCK);
2548         if (!cellp)
2549             return ENOENT;
2550     } else
2551         cellp = NULL;
2552     if (!cellp && (temp & 2)) {
2553         /* use local cell */
2554         cellp = afs_GetPrimaryCell(READ_LOCK);
2555     }
2556     if (!(temp & 1)) {          /* if not fast, call server checker routine */
2557         afs_CheckServers(1, cellp);     /* check down servers */
2558         afs_CheckServers(0, cellp);     /* check up servers */
2559     }
2560     /* now return the current down server list */
2561     ObtainReadLock(&afs_xserver);
2562     for (i = 0; i < NSERVERS; i++) {
2563         for (ts = afs_servers[i]; ts; ts = ts->next) {
2564             if (cellp && ts->cell != cellp)
2565                 continue;       /* cell spec'd and wrong */
2566             if ((ts->flags & SRVR_ISDOWN)
2567                 && ts->addr->sa_portal != ts->cell->vlport) {
2568                 afs_pd_putInt(aout, ts->addr->sa_ip);
2569             }
2570         }
2571     }
2572     ReleaseReadLock(&afs_xserver);
2573     if (cellp)
2574         afs_PutCell(cellp, READ_LOCK);
2575     return 0;
2576 }
2577
2578 /*!
2579  * VIOCCKBACK (11) - Check backup volume mappings
2580  *
2581  * \ingroup pioctl
2582  *
2583  * \param[in] ain       not in use
2584  * \param[out] aout     not in use
2585  *
2586  * \retval EIO          Error if the afs daemon hasn't started yet
2587  *
2588  * \post
2589  *      Check the root volume, and then check the names if the volume
2590  *      check variable is set to force, has expired, is busy, or if
2591  *      the mount points variable is set
2592  */
2593 DECL_PIOCTL(PCheckVolNames)
2594 {
2595     AFS_STATCNT(PCheckVolNames);
2596     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
2597         return EIO;             /* Inappropriate ioctl for device */
2598
2599     afs_CheckRootVolume();
2600     afs_CheckVolumeNames(AFS_VOLCHECK_FORCE | AFS_VOLCHECK_EXPIRED |
2601                          AFS_VOLCHECK_BUSY | AFS_VOLCHECK_MTPTS);
2602     return 0;
2603 }
2604
2605 /*!
2606  * VIOCCKCONN (12) - Check connections for a user
2607  *
2608  * \ingroup pioctl
2609  *
2610  * \param[in] ain       not in use
2611  * \param[out] aout     not in use
2612  *
2613  * \retval EACCESS
2614  *      Error if no user is specififed, the user has no tokens set,
2615  *      or if the user's tokens are bad
2616  *
2617  * \post
2618  *      check to see if a user has the correct authentication.
2619  *      If so, allow access.
2620  *
2621  * \notes Check the connections to all the servers specified
2622  */
2623 DECL_PIOCTL(PCheckAuth)
2624 {
2625     int i;
2626     struct srvAddr *sa;
2627     struct afs_conn *tc;
2628     struct unixuser *tu;
2629     afs_int32 retValue;
2630
2631     AFS_STATCNT(PCheckAuth);
2632     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
2633         return EIO;             /* Inappropriate ioctl for device */
2634
2635     retValue = 0;
2636     tu = afs_GetUser(areq->uid, 1, READ_LOCK);  /* check local cell authentication */
2637     if (!tu)
2638         retValue = EACCES;
2639     else {
2640         /* we have a user */
2641         ObtainReadLock(&afs_xsrvAddr);
2642         ObtainReadLock(&afs_xconn);
2643
2644         /* any tokens set? */
2645         if ((tu->states & UHasTokens) == 0)
2646             retValue = EACCES;
2647         /* all connections in cell 1 working? */
2648         for (i = 0; i < NSERVERS; i++) {
2649             for (sa = afs_srvAddrs[i]; sa; sa = sa->next_bkt) {
2650                 for (tc = sa->conns; tc; tc = tc->next) {
2651                     if (tc->user == tu && (tu->states & UTokensBad))
2652                         retValue = EACCES;
2653                 }
2654             }
2655         }
2656         ReleaseReadLock(&afs_xsrvAddr);
2657         ReleaseReadLock(&afs_xconn);
2658         afs_PutUser(tu, READ_LOCK);
2659     }
2660     if (afs_pd_putInt(aout, retValue) != 0)
2661         return E2BIG;
2662     return 0;
2663 }
2664
2665 static int
2666 Prefetch(uparmtype apath, struct afs_ioctl *adata, int afollow,
2667          afs_ucred_t *acred)
2668 {
2669     char *tp;
2670     afs_int32 code;
2671 #if defined(AFS_SGI61_ENV) || defined(AFS_SUN57_ENV) || defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
2672     size_t bufferSize;
2673 #else
2674     u_int bufferSize;
2675 #endif
2676
2677     AFS_STATCNT(Prefetch);
2678     if (!apath)
2679         return EINVAL;
2680     tp = osi_AllocLargeSpace(1024);
2681     AFS_COPYINSTR(apath, tp, 1024, &bufferSize, code);
2682     if (code) {
2683         osi_FreeLargeSpace(tp);
2684         return code;
2685     }
2686     if (afs_BBusy()) {          /* do this as late as possible */
2687         osi_FreeLargeSpace(tp);
2688         return EWOULDBLOCK;     /* pretty close */
2689     }
2690     afs_BQueue(BOP_PATH, (struct vcache *)0, 0, 0, acred, (afs_size_t) 0,
2691                (afs_size_t) 0, tp, (void *)0, (void *)0);
2692     return 0;
2693 }
2694
2695 /*!
2696  * VIOCWHEREIS (14) - Find out where a volume is located
2697  *
2698  * \ingroup pioctl
2699  *
2700  * \param[in] ain       not in use
2701  * \param[out] aout     volume location
2702  *
2703  * \retval EINVAL       Error if some of the default arguments don't exist
2704  * \retval ENODEV       Error if there is no such volume
2705  *
2706  * \post fine a volume, based on a volume file id
2707  *
2708  * \notes check each of the servers specified
2709  */
2710 DECL_PIOCTL(PFindVolume)
2711 {
2712     struct volume *tvp;
2713     struct server *ts;
2714     afs_int32 i;
2715     int code = 0;
2716
2717     AFS_STATCNT(PFindVolume);
2718     if (!avc)
2719         return EINVAL;
2720     tvp = afs_GetVolume(&avc->f.fid, areq, READ_LOCK);
2721     if (!tvp)
2722         return ENODEV;
2723
2724     for (i = 0; i < AFS_MAXHOSTS; i++) {
2725         ts = tvp->serverHost[i];
2726         if (!ts)
2727             break;
2728         if (afs_pd_putInt(aout, ts->addr->sa_ip) != 0) {
2729             code = E2BIG;
2730             goto out;
2731         }
2732     }
2733     if (i < AFS_MAXHOSTS) {
2734         /* still room for terminating NULL, add it on */
2735         if (afs_pd_putInt(aout, 0) != 0) {
2736             code = E2BIG;
2737             goto out;
2738         }
2739     }
2740 out:
2741     afs_PutVolume(tvp, READ_LOCK);
2742     return code;
2743 }
2744
2745 /*!
2746  * VIOCACCESS (20) - Access using PRS_FS bits
2747  *
2748  * \ingroup pioctl
2749  *
2750  * \param[in] ain       PRS_FS bits
2751  * \param[out] aout     not in use
2752  *
2753  * \retval EINVAL       Error if some of the initial arguments aren't set
2754  * \retval EACCES       Error if access is denied
2755  *
2756  * \post check to make sure access is allowed
2757  */
2758 DECL_PIOCTL(PViceAccess)
2759 {
2760     afs_int32 code;
2761     afs_int32 temp;
2762
2763     AFS_STATCNT(PViceAccess);
2764     if (!avc)
2765         return EINVAL;
2766
2767     code = afs_VerifyVCache(avc, areq);
2768     if (code)
2769         return code;
2770
2771     if (afs_pd_getInt(ain, &temp) != 0)
2772         return EINVAL;
2773
2774     code = afs_AccessOK(avc, temp, areq, CHECK_MODE_BITS);
2775     if (code)
2776         return 0;
2777     else
2778         return EACCES;
2779 }
2780
2781 /*!
2782  * VIOC_GETPAG (13) - Get PAG value
2783  *
2784  * \ingroup pioctl
2785  *
2786  * \param[in] ain       not in use
2787  * \param[out] aout     PAG value or NOPAG
2788  *
2789  * \post get PAG value for the caller's cred
2790  */
2791 DECL_PIOCTL(PGetPAG)
2792 {
2793     afs_int32 pag;
2794
2795     pag = PagInCred(*acred);
2796
2797     return afs_pd_putInt(aout, pag);
2798 }
2799
2800 DECL_PIOCTL(PPrecache)
2801 {
2802     afs_int32 newValue;
2803
2804     /*AFS_STATCNT(PPrecache);*/
2805     if (!afs_osi_suser(*acred))
2806         return EACCES;
2807
2808     if (afs_pd_getInt(ain, &newValue) != 0)
2809         return EINVAL;
2810
2811     afs_preCache = newValue*1024;
2812     return 0;
2813 }
2814
2815 /*!
2816  * VIOCSETCACHESIZE (24) - Set venus cache size in 1000 units
2817  *
2818  * \ingroup pioctl
2819  *
2820  * \param[in] ain       the size the venus cache should be set to
2821  * \param[out] aout     not in use
2822  *
2823  * \retval EACCES       Error if the user doesn't have super-user credentials
2824  * \retval EROFS        Error if the cache is set to be in memory
2825  *
2826  * \post
2827  *      Set the cache size based on user input.  If no size is given,
2828  *      set it to the default OpenAFS cache size.
2829  *
2830  * \notes
2831  *      recompute the general cache parameters for every single block allocated
2832  */
2833 DECL_PIOCTL(PSetCacheSize)
2834 {
2835     afs_int32 newValue;
2836     int waitcnt = 0;
2837
2838     AFS_STATCNT(PSetCacheSize);
2839
2840     if (!afs_osi_suser(*acred))
2841         return EACCES;
2842     /* too many things are setup initially in mem cache version */
2843     if (cacheDiskType == AFS_FCACHE_TYPE_MEM)
2844         return EROFS;
2845     if (afs_pd_getInt(ain, &newValue) != 0)
2846         return EINVAL;
2847     if (newValue == 0)
2848         afs_cacheBlocks = afs_stats_cmperf.cacheBlocksOrig;
2849     else {
2850         if (newValue < afs_min_cache)
2851             afs_cacheBlocks = afs_min_cache;
2852         else
2853             afs_cacheBlocks = newValue;
2854     }
2855     afs_stats_cmperf.cacheBlocksTotal = afs_cacheBlocks;
2856     afs_ComputeCacheParms();    /* recompute basic cache parameters */
2857     afs_MaybeWakeupTruncateDaemon();
2858     while (waitcnt++ < 100 && afs_cacheBlocks < afs_blocksUsed) {
2859         afs_osi_Wait(1000, 0, 0);
2860         afs_MaybeWakeupTruncateDaemon();
2861     }
2862     return 0;
2863 }
2864
2865 #define MAXGCSTATS      16
2866 /*!
2867  * VIOCGETCACHEPARMS (40) - Get cache stats
2868  *
2869  * \ingroup pioctl
2870  *
2871  * \param[in] ain       afs index flags
2872  * \param[out] aout     cache blocks, blocks used, blocks files (in an array)
2873  *
2874  * \post Get the cache blocks, and how many of the cache blocks there are
2875  */
2876 DECL_PIOCTL(PGetCacheSize)
2877 {
2878     afs_int32 results[MAXGCSTATS];
2879     afs_int32 flags;
2880     struct dcache * tdc;
2881     int i, size;
2882
2883     AFS_STATCNT(PGetCacheSize);
2884
2885     if (afs_pd_remaining(ain) == sizeof(afs_int32)) {
2886         afs_pd_getInt(ain, &flags); /* can't error, we just checked size */
2887     } else if (afs_pd_remaining(ain) == 0) {
2888         flags = 0;
2889     } else {
2890         return EINVAL;
2891     }
2892
2893     memset(results, 0, sizeof(results));
2894     results[0] = afs_cacheBlocks;
2895     results[1] = afs_blocksUsed;
2896     results[2] = afs_cacheFiles;
2897
2898     if (1 == flags){
2899         for (i = 0; i < afs_cacheFiles; i++) {
2900             if (afs_indexFlags[i] & IFFree) results[3]++;
2901         }
2902     } else if (2 == flags){
2903         for (i = 0; i < afs_cacheFiles; i++) {
2904             if (afs_indexFlags[i] & IFFree) results[3]++;
2905             if (afs_indexFlags[i] & IFEverUsed) results[4]++;
2906             if (afs_indexFlags[i] & IFDataMod) results[5]++;
2907             if (afs_indexFlags[i] & IFDirtyPages) results[6]++;
2908             if (afs_indexFlags[i] & IFAnyPages) results[7]++;
2909             if (afs_indexFlags[i] & IFDiscarded) results[8]++;
2910
2911             tdc = afs_indexTable[i];
2912             if (tdc){
2913                 results[9]++;
2914                 size = tdc->validPos;
2915                 if ( 0 < size && size < (1<<12) ) results[10]++;
2916                 else if (size < (1<<14) ) results[11]++;
2917                 else if (size < (1<<16) ) results[12]++;
2918                 else if (size < (1<<18) ) results[13]++;
2919                 else if (size < (1<<20) ) results[14]++;
2920                 else if (size >= (1<<20) ) results[15]++;
2921             }
2922         }
2923     }
2924     return afs_pd_putBytes(aout, results, sizeof(results));
2925 }
2926
2927 /*!
2928  * VIOCFLUSHCB (25) - Flush callback only
2929  *
2930  * \ingroup pioctl
2931  *
2932  * \param[in] ain       not in use
2933  * \param[out] aout     not in use
2934  *
2935  * \retval EINVAL       Error if some of the standard args aren't set
2936  * \retval 0            0 returned if the volume is set to read-only
2937  *
2938  * \post
2939  *      Flushes callbacks, by setting the length of callbacks to one,
2940  *      setting the next callback to be sent to the CB_DROPPED value,
2941  *      and then dequeues everything else.
2942  */
2943 DECL_PIOCTL(PRemoveCallBack)
2944 {
2945     struct afs_conn *tc;
2946     afs_int32 code = 0;
2947     struct AFSCallBack CallBacks_Array[1];
2948     struct AFSCBFids theFids;
2949     struct AFSCBs theCBs;
2950     XSTATS_DECLS;
2951
2952     AFS_STATCNT(PRemoveCallBack);
2953     if (!avc)
2954         return EINVAL;
2955     if (avc->f.states & CRO)
2956         return 0;               /* read-only-ness can't change */
2957     ObtainWriteLock(&avc->lock, 229);
2958     theFids.AFSCBFids_len = 1;
2959     theCBs.AFSCBs_len = 1;
2960     theFids.AFSCBFids_val = (struct AFSFid *)&avc->f.fid.Fid;
2961     theCBs.AFSCBs_val = CallBacks_Array;
2962     CallBacks_Array[0].CallBackType = CB_DROPPED;
2963     if (avc->callback) {
2964         do {
2965             tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK);
2966             if (tc) {
2967                 XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_GIVEUPCALLBACKS);
2968                 RX_AFS_GUNLOCK();
2969                 code = RXAFS_GiveUpCallBacks(tc->id, &theFids, &theCBs);
2970                 RX_AFS_GLOCK();
2971                 XSTATS_END_TIME;
2972             }
2973             /* don't set code on failure since we wouldn't use it */
2974         } while (afs_Analyze
2975                  (tc, code, &avc->f.fid, areq,
2976                   AFS_STATS_FS_RPCIDX_GIVEUPCALLBACKS, SHARED_LOCK, NULL));
2977
2978         ObtainWriteLock(&afs_xcbhash, 457);
2979         afs_DequeueCallback(avc);
2980         avc->callback = 0;
2981         avc->f.states &= ~(CStatd | CUnique);
2982         ReleaseWriteLock(&afs_xcbhash);
2983         if (avc->f.fid.Fid.Vnode & 1 || (vType(avc) == VDIR))
2984             osi_dnlc_purgedp(avc);
2985     }
2986     ReleaseWriteLock(&avc->lock);
2987     return 0;
2988 }
2989
2990 /*!
2991  * VIOCNEWCELL (26) - Configure new cell
2992  *
2993  * \ingroup pioctl
2994  *
2995  * \param[in] ain
2996  *      the name of the cell, the hosts that will be a part of the cell,
2997  *      whether or not it's linked with another cell, the other cell it's
2998  *      linked with, the file server port, and the volume server port
2999  * \param[out] aout
3000  *      not in use
3001  *
3002  * \retval EIO          Error if the afs daemon hasn't started yet
3003  * \retval EACCES       Error if the user doesn't have super-user cedentials
3004  * \retval EINVAL       Error if some 'magic' var doesn't have a certain bit set
3005  *
3006  * \post creates a new cell
3007  */
3008 DECL_PIOCTL(PNewCell)
3009 {
3010     afs_int32 cellHosts[AFS_MAXCELLHOSTS], magic = 0;
3011     char *newcell = NULL;
3012     char *linkedcell = NULL;
3013     afs_int32 code, ls;
3014     afs_int32 linkedstate = 0;
3015     afs_int32 fsport = 0, vlport = 0;
3016     int skip;
3017
3018     AFS_STATCNT(PNewCell);
3019     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
3020         return EIO;             /* Inappropriate ioctl for device */
3021
3022     if (!afs_osi_suser(*acred))
3023         return EACCES;
3024
3025     if (afs_pd_getInt(ain, &magic) != 0)
3026         return EINVAL;
3027     if (magic != 0x12345678)
3028         return EINVAL;
3029
3030     /* A 3.4 fs newcell command will pass an array of AFS_MAXCELLHOSTS
3031      * server addresses while the 3.5 fs newcell command passes
3032      * AFS_MAXHOSTS. To figure out which is which, check if the cellname
3033      * is good.
3034      *
3035      * This whole logic is bogus, because it relies on the newer command
3036      * sending its 12th address as 0.
3037      */
3038     if ((afs_pd_remaining(ain) < AFS_MAXCELLHOSTS +3) * sizeof(afs_int32))
3039         return EINVAL;
3040
3041     newcell = afs_pd_where(ain) + (AFS_MAXCELLHOSTS + 3) * sizeof(afs_int32);
3042     if (newcell[0] != '\0') {
3043         skip = 0;
3044     } else {
3045         skip = AFS_MAXHOSTS - AFS_MAXCELLHOSTS;
3046     }
3047
3048     /* AFS_MAXCELLHOSTS (=8) is less than AFS_MAXHOSTS (=13) */
3049     if (afs_pd_getBytes(ain, &cellHosts,
3050                         AFS_MAXCELLHOSTS * sizeof(afs_int32)) != 0)
3051         return EINVAL;
3052     if (afs_pd_skip(ain, skip * sizeof(afs_int32)) !=0)
3053         return EINVAL;
3054
3055     if (afs_pd_getInt(ain, &fsport) != 0)
3056         return EINVAL;
3057     if (fsport < 1024)
3058         fsport = 0;             /* Privileged ports not allowed */
3059
3060     if (afs_pd_getInt(ain, &vlport) != 0)
3061         return EINVAL;
3062     if (vlport < 1024)
3063         vlport = 0;             /* Privileged ports not allowed */
3064
3065     if (afs_pd_getInt(ain, &ls) != 0)
3066         return EINVAL;
3067
3068     if (afs_pd_getStringPtr(ain, &newcell) != 0)
3069         return EINVAL;
3070
3071     if (ls & 1) {
3072         if (afs_pd_getStringPtr(ain, &linkedcell) != 0)
3073             return EINVAL;
3074         linkedstate |= CLinkedCell;
3075     }
3076
3077     linkedstate |= CNoSUID;     /* setuid is disabled by default for fs newcell */
3078     code =
3079         afs_NewCell(newcell, cellHosts, linkedstate, linkedcell, fsport,
3080                     vlport, (int)0);
3081     return code;
3082 }
3083
3084 DECL_PIOCTL(PNewAlias)
3085 {
3086     /* create a new cell alias */
3087     char *realName, *aliasName;
3088
3089     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
3090         return EIO;             /* Inappropriate ioctl for device */
3091
3092     if (!afs_osi_suser(*acred))
3093         return EACCES;
3094
3095     if (afs_pd_getStringPtr(ain, &aliasName) != 0)
3096         return EINVAL;
3097     if (afs_pd_getStringPtr(ain, &realName) != 0)
3098         return EINVAL;
3099
3100     return afs_NewCellAlias(aliasName, realName);
3101 }
3102
3103 /*!
3104  * VIOCGETCELL (27) - Get cell info
3105  *
3106  * \ingroup pioctl
3107  *
3108  * \param[in] ain       The cell index of a specific cell
3109  * \param[out] aout     list of servers in the cell
3110  *
3111  * \retval EIO          Error if the afs daemon hasn't started yet
3112  * \retval EDOM         Error if there is no cell asked about
3113  *
3114  * \post Lists the cell's server names and and addresses
3115  */
3116 DECL_PIOCTL(PListCells)
3117 {
3118     afs_int32 whichCell;
3119     struct cell *tcell = 0;
3120     afs_int32 i;
3121     int code;
3122
3123     AFS_STATCNT(PListCells);
3124     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
3125         return EIO;             /* Inappropriate ioctl for device */
3126
3127     if (afs_pd_getInt(ain, &whichCell) != 0)
3128         return EINVAL;
3129
3130     tcell = afs_GetCellByIndex(whichCell, READ_LOCK);
3131     if (!tcell)
3132         return EDOM;
3133
3134     code = E2BIG;
3135
3136     for (i = 0; i < AFS_MAXCELLHOSTS; i++) {
3137         if (tcell->cellHosts[i] == 0)
3138             break;
3139         if (afs_pd_putInt(aout, tcell->cellHosts[i]->addr->sa_ip) != 0)
3140             goto out;
3141     }
3142     for (;i < AFS_MAXCELLHOSTS; i++) {
3143         if (afs_pd_putInt(aout, 0) != 0)
3144             goto out;
3145     }
3146     if (afs_pd_putString(aout, tcell->cellName) != 0)
3147         goto out;
3148     code = 0;
3149
3150 out:
3151     afs_PutCell(tcell, READ_LOCK);
3152     return code;
3153 }
3154
3155 DECL_PIOCTL(PListAliases)
3156 {
3157     afs_int32 whichAlias;
3158     struct cell_alias *tcalias = 0;
3159     int code;
3160
3161     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
3162         return EIO;             /* Inappropriate ioctl for device */
3163
3164     if (afs_pd_getInt(ain, &whichAlias) != 0)
3165         return EINVAL;
3166
3167     tcalias = afs_GetCellAlias(whichAlias);
3168     if (tcalias == NULL)
3169         return EDOM;
3170
3171     code = E2BIG;
3172     if (afs_pd_putString(aout, tcalias->alias) != 0)
3173         goto out;
3174     if (afs_pd_putString(aout, tcalias->cell) != 0)
3175         goto out;
3176
3177     code = 0;
3178 out:
3179     afs_PutCellAlias(tcalias);
3180     return code;
3181 }
3182
3183 /*!
3184  * VIOC_AFS_DELETE_MT_PT (28) - Delete mount point
3185  *
3186  * \ingroup pioctl
3187  *
3188  * \param[in] ain       the name of the file in this dir to remove
3189  * \param[out] aout     not in use
3190  *
3191  * \retval EINVAL
3192  *      Error if some of the standard args aren't set
3193  * \retval ENOTDIR
3194  *      Error if the argument to remove is not a directory
3195  * \retval ENOENT
3196  *      Error if there is no cache to remove the mount point from or
3197  *      if a vcache doesn't exist
3198  *
3199  * \post
3200  *      Ensure that everything is OK before deleting the mountpoint.
3201  *      If not, don't delete.  Delete a mount point based on a file id.
3202  */
3203 DECL_PIOCTL(PRemoveMount)
3204 {
3205     afs_int32 code;
3206     char *bufp;
3207     char *name;
3208     struct sysname_info sysState;
3209     afs_size_t offset, len;
3210     struct afs_conn *tc;
3211     struct dcache *tdc;
3212     struct vcache *tvc;
3213     struct AFSFetchStatus OutDirStatus;
3214     struct VenusFid tfid;
3215     struct AFSVolSync tsync;
3216     XSTATS_DECLS;
3217
3218     /* "ain" is the name of the file in this dir to remove */
3219
3220     AFS_STATCNT(PRemoveMount);
3221     if (!avc)
3222         return EINVAL;
3223     if (afs_pd_getStringPtr(ain, &name) != 0)
3224         return EINVAL;
3225
3226     code = afs_VerifyVCache(avc, areq);
3227     if (code)
3228         return code;
3229     if (vType(avc) != VDIR)
3230         return ENOTDIR;
3231
3232     tdc = afs_GetDCache(avc, (afs_size_t) 0, areq, &offset, &len, 1);   /* test for error below */
3233     if (!tdc)
3234         return ENOENT;
3235     Check_AtSys(avc, name, &sysState, areq);
3236     ObtainReadLock(&tdc->lock);
3237     do {
3238         code = afs_dir_Lookup(tdc, sysState.name, &tfid.Fid);
3239     } while (code == ENOENT && Next_AtSys(avc, areq, &sysState));
3240     ReleaseReadLock(&tdc->lock);
3241     bufp = sysState.name;
3242     if (code) {
3243         afs_PutDCache(tdc);
3244         goto out;
3245     }
3246     tfid.Cell = avc->f.fid.Cell;
3247     tfid.Fid.Volume = avc->f.fid.Fid.Volume;
3248     if (!tfid.Fid.Unique && (avc->f.states & CForeign)) {
3249         tvc = afs_LookupVCache(&tfid, areq, NULL, avc, bufp);
3250     } else {
3251         tvc = afs_GetVCache(&tfid, areq, NULL, NULL);
3252     }
3253     if (!tvc) {
3254         code = ENOENT;
3255         afs_PutDCache(tdc);
3256         goto out;
3257     }
3258     if (tvc->mvstat != 1) {
3259         afs_PutDCache(tdc);
3260         afs_PutVCache(tvc);
3261         code = EINVAL;
3262         goto out;
3263     }
3264     ObtainWriteLock(&tvc->lock, 230);
3265     code = afs_HandleLink(tvc, areq);
3266     if (!code) {
3267         if (tvc->linkData) {
3268             if ((tvc->linkData[0] != '#') && (tvc->linkData[0] != '%'))
3269                 code = EINVAL;
3270         } else
3271             code = EIO;
3272     }
3273     ReleaseWriteLock(&tvc->lock);
3274     osi_dnlc_purgedp(tvc);
3275     afs_PutVCache(tvc);
3276     if (code) {
3277         afs_PutDCache(tdc);
3278         goto out;
3279     }
3280     ObtainWriteLock(&avc->lock, 231);
3281     osi_dnlc_remove(avc, bufp, tvc);
3282     do {
3283         tc = afs_Conn(&avc->f.fid, areq, SHARED_LOCK);
3284         if (tc) {
3285             XSTATS_START_TIME(AFS_STATS_FS_RPCIDX_REMOVEFILE);
3286             RX_AFS_GUNLOCK();
3287             code =
3288                 RXAFS_RemoveFile(tc->id, (struct AFSFid *)&avc->f.fid.Fid, bufp,
3289                                  &OutDirStatus, &tsync);
3290             RX_AFS_GLOCK();
3291             XSTATS_END_TIME;
3292         } else
3293             code = -1;
3294     } while (afs_Analyze
3295              (tc, code, &avc->f.fid, areq, AFS_STATS_FS_RPCIDX_REMOVEFILE,
3296               SHARED_LOCK, NULL));
3297
3298     if (code) {
3299         if (tdc)
3300             afs_PutDCache(tdc);
3301         ReleaseWriteLock(&avc->lock);
3302         goto out;
3303     }
3304     if (tdc) {
3305         /* we have the thing in the cache */
3306         ObtainWriteLock(&tdc->lock, 661);
3307         if (afs_LocalHero(avc, tdc, &OutDirStatus, 1)) {
3308             /* we can do it locally */
3309             code = afs_dir_Delete(tdc, bufp);
3310             if (code) {
3311                 ZapDCE(tdc);    /* surprise error -- invalid value */
3312                 DZap(tdc);
3313             }
3314         }
3315         ReleaseWriteLock(&tdc->lock);
3316         afs_PutDCache(tdc);     /* drop ref count */
3317     }
3318     avc->f.states &= ~CUnique;  /* For the dfs xlator */
3319     ReleaseWriteLock(&avc->lock);
3320     code = 0;
3321   out:
3322     if (sysState.allocked)
3323         osi_FreeLargeSpace(bufp);
3324     return code;
3325 }
3326
3327 /*!
3328  * VIOC_GETCELLSTATUS (35) - Get cell status info
3329  *
3330  * \ingroup pioctl
3331  *
3332  * \param[in] ain       The cell you want status information on
3333  * \param[out] aout     cell state (as a struct)
3334  *
3335  * \retval EIO          Error if the afs daemon hasn't started yet
3336  * \retval ENOENT       Error if the cell doesn't exist
3337  *
3338  * \post Returns the state of the cell as defined in a struct cell
3339  */
3340 DECL_PIOCTL(PGetCellStatus)
3341 {
3342     struct cell *tcell;
3343     char *cellName;
3344     afs_int32 temp;
3345
3346     AFS_STATCNT(PGetCellStatus);
3347     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
3348         return EIO;             /* Inappropriate ioctl for device */
3349
3350     if (afs_pd_getStringPtr(ain, &cellName) != 0)
3351         return EINVAL;
3352
3353     tcell = afs_GetCellByName(cellName, READ_LOCK);
3354     if (!tcell)
3355         return ENOENT;
3356     temp = tcell->states;
3357     afs_PutCell(tcell, READ_LOCK);
3358
3359     return afs_pd_putInt(aout, temp);
3360 }
3361
3362 /*!
3363  * VIOC_SETCELLSTATUS (36) - Set corresponding info
3364  *
3365  * \ingroup pioctl
3366  *
3367  * \param[in] ain
3368  *      The cell you want to set information about, and the values you
3369  *      want to set
3370  * \param[out] aout
3371  *      not in use
3372  *
3373  * \retval EIO          Error if the afs daemon hasn't started yet
3374  * \retval EACCES       Error if the user doesn't have super-user credentials
3375  *
3376  * \post
3377  *      Set the state of the cell in a defined struct cell, based on
3378  *      whether or not SetUID is allowed
3379  */
3380 DECL_PIOCTL(PSetCellStatus)
3381 {
3382     struct cell *tcell;
3383     char *cellName;
3384     afs_int32 flags0, flags1;
3385
3386     if (!afs_osi_suser(*acred))
3387         return EACCES;
3388     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
3389         return EIO;             /* Inappropriate ioctl for device */
3390
3391     if (afs_pd_getInt(ain, &flags0) != 0)
3392         return EINVAL;
3393     if (afs_pd_getInt(ain, &flags1) != 0)
3394         return EINVAL;
3395     if (afs_pd_getStringPtr(ain, &cellName) != 0)
3396         return EINVAL;
3397
3398     tcell = afs_GetCellByName(cellName, WRITE_LOCK);
3399     if (!tcell)
3400         return ENOENT;
3401     if (flags0 & CNoSUID)
3402         tcell->states |= CNoSUID;
3403     else
3404         tcell->states &= ~CNoSUID;
3405     afs_PutCell(tcell, WRITE_LOCK);
3406     return 0;
3407 }
3408
3409 /*!
3410  * VIOC_FLUSHVOLUME (37) - Flush whole volume's data
3411  *
3412  * \ingroup pioctl
3413  *
3414  * \param[in] ain       not in use (args in avc)
3415  * \param[out] aout     not in use
3416  *
3417  * \retval EINVAL       Error if some of the standard args aren't set
3418  * \retval EIO          Error if the afs daemon hasn't started yet
3419  *
3420  * \post
3421  *      Flush all cached contents of a volume.  Exactly what stays and what
3422  *      goes depends on the platform.
3423  *
3424  * \notes
3425  *      Does not flush a file that a user has open and is using, because
3426  *      it will be re-created on next write.  Also purges the dnlc,
3427  *      because things are screwed up.
3428  */
3429 DECL_PIOCTL(PFlushVolumeData)
3430 {
3431     afs_int32 i;
3432     struct dcache *tdc;
3433     struct vcache *tvc;
3434     struct volume *tv;
3435     afs_int32 cell, volume;
3436     struct afs_q *tq, *uq;
3437 #ifdef AFS_DARWIN80_ENV
3438     vnode_t vp;
3439 #endif
3440
3441     AFS_STATCNT(PFlushVolumeData);
3442     if (!avc)
3443         return EINVAL;
3444     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
3445         return EIO;             /* Inappropriate ioctl for device */
3446
3447     volume = avc->f.fid.Fid.Volume;     /* who to zap */
3448     cell = avc->f.fid.Cell;
3449
3450     /*
3451      * Clear stat'd flag from all vnodes from this volume; this will
3452      * invalidate all the vcaches associated with the volume.
3453      */
3454  loop:
3455     ObtainReadLock(&afs_xvcache);
3456     i = VCHashV(&avc->f.fid);
3457     for (tq = afs_vhashTV[i].prev; tq != &afs_vhashTV[i]; tq = uq) {
3458             uq = QPrev(tq);
3459             tvc = QTOVH(tq);
3460             if (tvc->f.fid.Fid.Volume == volume && tvc->f.fid.Cell == cell) {
3461                 if (tvc->f.states & CVInit) {
3462                     ReleaseReadLock(&afs_xvcache);
3463                     afs_osi_Sleep(&tvc->f.states);
3464                     goto loop;
3465                 }
3466 #ifdef AFS_DARWIN80_ENV
3467                 if (tvc->f.states & CDeadVnode) {
3468                     if (!(tvc->f.states & CBulkFetching)) {
3469                         ReleaseReadLock(&afs_xvcache);
3470                         afs_osi_Sleep(&tvc->f.states);
3471                         goto loop;
3472                     }
3473                 }
3474                 vp = AFSTOV(tvc);
3475                 if (vnode_get(vp))
3476                     continue;
3477                 if (vnode_ref(vp)) {
3478                     AFS_GUNLOCK();
3479                     vnode_put(vp);
3480                     AFS_GLOCK();
3481                     continue;
3482                 }
3483                 if (tvc->f.states & (CBulkFetching|CDeadVnode)) {
3484                     AFS_GUNLOCK();
3485                     vnode_recycle(AFSTOV(tvc));
3486                     AFS_GLOCK();
3487                 }
3488 #else
3489                 AFS_FAST_HOLD(tvc);
3490 #endif
3491                 ReleaseReadLock(&afs_xvcache);
3492 #ifdef AFS_BOZONLOCK_ENV
3493                 afs_BozonLock(&tvc->pvnLock, tvc);      /* Since afs_TryToSmush will do a pvn_vptrunc */
3494 #endif
3495                 ObtainWriteLock(&tvc->lock, 232);
3496
3497                 ObtainWriteLock(&afs_xcbhash, 458);
3498                 afs_DequeueCallback(tvc);
3499                 tvc->f.states &= ~(CStatd | CDirty);
3500                 ReleaseWriteLock(&afs_xcbhash);
3501                 if (tvc->f.fid.Fid.Vnode & 1 || (vType(tvc) == VDIR))
3502                     osi_dnlc_purgedp(tvc);
3503                 afs_TryToSmush(tvc, *acred, 1);
3504                 ReleaseWriteLock(&tvc->lock);
3505 #ifdef AFS_BOZONLOCK_ENV
3506                 afs_BozonUnlock(&tvc->pvnLock, tvc);
3507 #endif
3508 #ifdef AFS_DARWIN80_ENV
3509                 vnode_put(AFSTOV(tvc));
3510 #endif
3511                 ObtainReadLock(&afs_xvcache);
3512                 uq = QPrev(tq);
3513                 /* our tvc ptr is still good until now */
3514                 AFS_FAST_RELE(tvc);
3515             }
3516         }
3517     ReleaseReadLock(&afs_xvcache);
3518
3519
3520     ObtainWriteLock(&afs_xdcache, 328); /* needed to flush any stuff */
3521     for (i = 0; i < afs_cacheFiles; i++) {
3522         if (!(afs_indexFlags[i] & IFEverUsed))
3523             continue;           /* never had any data */
3524         tdc = afs_GetDSlot(i, NULL);
3525         if (tdc->refCount <= 1) {    /* too high, in use by running sys call */
3526             ReleaseReadLock(&tdc->tlock);
3527             if (tdc->f.fid.Fid.Volume == volume && tdc->f.fid.Cell == cell) {
3528                 if (!(afs_indexFlags[i] & IFDataMod)) {
3529                     /* if the file is modified, but has a ref cnt of only 1,
3530                      * then someone probably has the file open and is writing
3531                      * into it. Better to skip flushing such a file, it will be
3532                      * brought back immediately on the next write anyway.
3533                      *
3534                      * If we *must* flush, then this code has to be rearranged
3535                      * to call afs_storeAllSegments() first */
3536                     afs_FlushDCache(tdc);
3537                 }
3538             }
3539         } else {
3540             ReleaseReadLock(&tdc->tlock);
3541         }
3542         afs_PutDCache(tdc);     /* bumped by getdslot */
3543     }
3544     ReleaseWriteLock(&afs_xdcache);
3545
3546     ObtainReadLock(&afs_xvolume);
3547     for (i = 0; i < NVOLS; i++) {
3548         for (tv = afs_volumes[i]; tv; tv = tv->next) {
3549             if (tv->volume == volume) {
3550                 afs_ResetVolumeInfo(tv);
3551                 break;
3552             }
3553         }
3554     }
3555     ReleaseReadLock(&afs_xvolume);
3556
3557     /* probably, a user is doing this, probably, because things are screwed up.
3558      * maybe it's the dnlc's fault? */
3559     osi_dnlc_purge();
3560     return 0;
3561 }
3562
3563
3564 /*!
3565  * VIOCGETVCXSTATUS (41) - gets vnode x status
3566  *
3567  * \ingroup pioctl
3568  *
3569  * \param[in] ain
3570  *      not in use (avc used)
3571  * \param[out] aout
3572  *      vcxstat: the file id, the data version, any lock, the parent vnode,
3573  *      the parent unique id, the trunc position, the callback, cbExpires,
3574  *      what access is being made, what files are open,
3575  *      any users executing/writing, the flock count, the states,
3576  *      the move stat
3577  *
3578  * \retval EINVAL
3579  *      Error if some of the initial default arguments aren't set
3580  * \retval EACCES
3581  *      Error if access to check the mode bits is denied
3582  *
3583  * \post
3584  *      gets stats for the vnode, a struct listed in vcxstat
3585  */
3586 DECL_PIOCTL(PGetVnodeXStatus)
3587 {
3588     afs_int32 code;
3589     struct vcxstat stat;
3590     afs_int32 mode, i;
3591
3592 /*  AFS_STATCNT(PGetVnodeXStatus); */
3593     if (!avc)
3594         return EINVAL;
3595     code = afs_VerifyVCache(avc, areq);
3596     if (code)
3597         return code;
3598     if (vType(avc) == VDIR)
3599         mode = PRSFS_LOOKUP;
3600     else
3601         mode = PRSFS_READ;
3602     if (!afs_AccessOK(avc, mode, areq, CHECK_MODE_BITS))
3603         return EACCES;
3604
3605     memset(&stat, 0, sizeof(struct vcxstat));
3606     stat.fid = avc->f.fid;
3607     hset32(stat.DataVersion, hgetlo(avc->f.m.DataVersion));
3608     stat.lock = avc->lock;
3609     stat.parentVnode = avc->f.parent.vnode;
3610     stat.parentUnique = avc->f.parent.unique;
3611     hset(stat.flushDV, avc->flushDV);
3612     hset(stat.mapDV, avc->mapDV);
3613     stat.truncPos = avc->f.truncPos;
3614     {                   /* just grab the first two - won't break anything... */
3615         struct axscache *ac;
3616
3617         for (i = 0, ac = avc->Access; ac && i < CPSIZE; i++, ac = ac->next) {
3618             stat.randomUid[i] = ac->uid;
3619             stat.randomAccess[i] = ac->axess;
3620         }
3621     }
3622     stat.callback = afs_data_pointer_to_int32(avc->callback);
3623     stat.cbExpires = avc->cbExpires;
3624     stat.anyAccess = avc->f.anyAccess;
3625     stat.opens = avc->opens;
3626     stat.execsOrWriters = avc->execsOrWriters;
3627     stat.flockCount = avc->flockCount;
3628     stat.mvstat = avc->mvstat;
3629     stat.states = avc->f.states;
3630     return afs_pd_putBytes(aout, &stat, sizeof(struct vcxstat));
3631 }
3632
3633
3634 DECL_PIOCTL(PGetVnodeXStatus2)
3635 {
3636     afs_int32 code;
3637     struct vcxstat2 stat;
3638     afs_int32 mode;
3639
3640     if (!avc)
3641         return EINVAL;
3642     code = afs_VerifyVCache(avc, areq);
3643     if (code)
3644         return code;
3645     if (vType(avc) == VDIR)
3646         mode = PRSFS_LOOKUP;
3647     else
3648         mode = PRSFS_READ;
3649     if (!afs_AccessOK(avc, mode, areq, CHECK_MODE_BITS))
3650         return EACCES;
3651
3652     memset(&stat, 0, sizeof(struct vcxstat2));
3653
3654     stat.cbExpires = avc->cbExpires;
3655     stat.anyAccess = avc->f.anyAccess;
3656     stat.mvstat = avc->mvstat;
3657     stat.callerAccess = afs_GetAccessBits(avc, ~0, areq);
3658
3659     return afs_pd_putBytes(aout, &stat, sizeof(struct vcxstat2));
3660 }
3661
3662
3663 /*!
3664  * VIOC_AFS_SYSNAME (38) - Change @sys value
3665  *
3666  * \ingroup pioctl
3667  *
3668  * \param[in] ain       new value for @sys
3669  * \param[out] aout     count, entry, list (debug values?)
3670  *
3671  * \retval EINVAL
3672  *      Error if afsd isn't running, the new sysname is too large,
3673  *      the new sysname causes issues (starts with a . or ..),
3674  *      there is no PAG set in the credentials, or the user of a PAG
3675  *      can't be found
3676  * \retval EACCES
3677  *      Error if the user doesn't have super-user credentials
3678  *
3679  * \post
3680  *      Set the value of @sys if these things work: if the input isn't
3681  *      too long or if input doesn't start with . or ..
3682  *
3683  * \notes
3684  *      We require root for local sysname changes, but not for remote
3685  *      (since we don't really believe remote uids anyway)
3686  *      outname[] shouldn't really be needed- this is left as an
3687  *      exercise for the reader.
3688  */
3689 DECL_PIOCTL(PSetSysName)
3690 {
3691     char *inname = NULL;
3692     char outname[MAXSYSNAME];
3693     afs_int32 setsysname;
3694     int foundname = 0;
3695     struct afs_exporter *exporter;
3696     struct unixuser *au;
3697     afs_int32 pag, error;
3698     int t, count, num = 0, allpags = 0;
3699     char **sysnamelist;
3700     struct afs_pdata validate;
3701
3702     AFS_STATCNT(PSetSysName);
3703     if (!afs_globalVFS) {
3704         /* Afsd is NOT running; disable it */
3705 #if defined(KERNEL_HAVE_UERROR)
3706         return (setuerror(EINVAL), EINVAL);
3707 #else
3708         return (EINVAL);
3709 #endif
3710     }
3711     if (afs_pd_getInt(ain, &setsysname) != 0)
3712         return EINVAL;
3713     if (setsysname & 0x8000) {
3714         allpags = 1;
3715         setsysname &= ~0x8000;
3716     }
3717     if (setsysname) {
3718
3719         /* Check my args */
3720         if (setsysname < 0 || setsysname > MAXNUMSYSNAMES)
3721             return EINVAL;
3722         validate = *ain;
3723         for (count = 0; count < setsysname; count++) {
3724             if (afs_pd_getStringPtr(&validate, &inname) != 0)
3725                 return EINVAL;
3726             t = strlen(inname);
3727             if (t >= MAXSYSNAME || t <= 0)
3728                 return EINVAL;
3729             /* check for names that can shoot us in the foot */
3730             if (inname[0] == '.' && (inname[1] == 0
3731                 || (inname[1] == '.' && inname[2] == 0)))
3732                 return EINVAL;
3733         }
3734         /* args ok, so go back to the beginning of that section */
3735
3736         if (afs_pd_getStringPtr(ain, &inname) != 0)
3737             return EINVAL;
3738         num = count;
3739     }
3740     if (afs_cr_gid(*acred) == RMTUSER_REQ ||
3741         afs_cr_gid(*acred) == RMTUSER_REQ_PRIV) {   /* Handles all exporters */
3742         if (allpags && afs_cr_gid(*acred) != RMTUSER_REQ_PRIV) {
3743             return EPERM;
3744         }
3745         pag = PagInCred(*acred);
3746         if (pag == NOPAG) {
3747             return EINVAL;      /* Better than panicing */
3748         }
3749         if (!(au = afs_FindUser(pag, -1, READ_LOCK))) {
3750             return EINVAL;      /* Better than panicing */
3751         }
3752         if (!(exporter = au->exporter)) {
3753             afs_PutUser(au, READ_LOCK);
3754             return EINVAL;      /* Better than panicing */
3755         }
3756         error = EXP_SYSNAME(exporter, inname, &sysnamelist,
3757                             &num, allpags);
3758         if (error) {
3759             if (error == ENODEV)
3760                 foundname = 0;  /* sysname not set yet! */
3761             else {
3762                 afs_PutUser(au, READ_LOCK);
3763                 return error;
3764             }
3765         } else {
3766             foundname = num;
3767             strcpy(outname, sysnamelist[0]);
3768         }
3769         afs_PutUser(au, READ_LOCK);
3770         if (setsysname)
3771             afs_sysnamegen++;
3772     } else {
3773         /* Not xlating, so local case */
3774         if (!afs_sysname)
3775             osi_Panic("PSetSysName: !afs_sysname\n");
3776         if (!setsysname) {      /* user just wants the info */
3777             strcpy(outname, afs_sysname);
3778             foundname = afs_sysnamecount;
3779             sysnamelist = afs_sysnamelist;
3780         } else {                /* Local guy; only root can change sysname */
3781             if (!afs_osi_suser(*acred))
3782                 return EACCES;
3783
3784             /* allpags makes no sense for local use */
3785             if (allpags)
3786                 return EINVAL;
3787
3788             /* clear @sys entries from the dnlc, once afs_lookup can
3789              * do lookups of @sys entries and thinks it can trust them */
3790             /* privs ok, store the entry, ... */
3791
3792             if (strlen(inname) >= MAXSYSNAME-1)
3793                 return EINVAL;
3794             strcpy(afs_sysname, inname);
3795
3796             if (setsysname > 1) {       /* ... or list */
3797                 for (count = 1; count < setsysname; ++count) {
3798                     if (!afs_sysnamelist[count])
3799                         osi_Panic
3800                            ("PSetSysName: no afs_sysnamelist entry to write\n");
3801                     if (afs_pd_getString(ain, afs_sysnamelist[count],
3802                                          MAXSYSNAME) != 0)
3803                         return EINVAL;
3804                 }
3805             }
3806             afs_sysnamecount = setsysname;
3807             afs_sysnamegen++;
3808         }
3809     }
3810     if (!setsysname) {
3811         if (afs_pd_putInt(aout, foundname) != 0)
3812             return E2BIG;
3813         if (foundname) {
3814             if (afs_pd_putString(aout, outname) != 0)
3815                 return E2BIG;
3816             for (count = 1; count < foundname; ++count) {    /* ... or list. */
3817                 if (!sysnamelist[count])
3818                     osi_Panic
3819                         ("PSetSysName: no afs_sysnamelist entry to read\n");
3820                 t = strlen(sysnamelist[count]);
3821                 if (t >= MAXSYSNAME)
3822                     osi_Panic("PSetSysName: sysname entry garbled\n");
3823                 if (afs_pd_putString(aout, sysnamelist[count]) != 0)
3824                     return E2BIG;
3825             }
3826         }
3827     }
3828     return 0;
3829 }
3830
3831 /* sequential search through the list of touched cells is not a good
3832  * long-term solution here. For small n, though, it should be just
3833  * fine.  Should consider special-casing the local cell for large n.
3834  * Likewise for PSetSPrefs.
3835  *
3836  * s - number of ids in array l[] -- NOT index of last id
3837  * l - array of cell ids which have volumes that need to be sorted
3838  * vlonly - sort vl servers or file servers?
3839  */
3840 static void *
3841 ReSortCells_cb(struct cell *cell, void *arg)
3842 {
3843     afs_int32 *p = (afs_int32 *) arg;
3844     afs_int32 *l = p + 1;
3845     int i, s = p[0];
3846
3847     for (i = 0; i < s; i++) {
3848         if (l[i] == cell->cellNum) {
3849             ObtainWriteLock(&cell->lock, 690);
3850             afs_SortServers(cell->cellHosts, AFS_MAXCELLHOSTS);
3851             ReleaseWriteLock(&cell->lock);
3852         }
3853     }
3854
3855     return NULL;
3856 }
3857
3858 static void
3859 ReSortCells(int s, afs_int32 * l, int vlonly)
3860 {
3861     int i;
3862     struct volume *j;
3863     int k;
3864
3865     if (vlonly) {
3866         afs_int32 *p;
3867         p = (afs_int32 *) afs_osi_Alloc(sizeof(afs_int32) * (s + 1));
3868         p[0] = s;
3869         memcpy(p + 1, l, s * sizeof(afs_int32));
3870         afs_TraverseCells(&ReSortCells_cb, p);
3871         afs_osi_Free(p, sizeof(afs_int32) * (s + 1));
3872         return;
3873     }
3874
3875     ObtainReadLock(&afs_xvolume);
3876     for (i = 0; i < NVOLS; i++) {
3877         for (j = afs_volumes[i]; j; j = j->next) {
3878             for (k = 0; k < s; k++)
3879                 if (j->cell == l[k]) {
3880                     ObtainWriteLock(&j->lock, 233);
3881                     afs_SortServers(j->serverHost, AFS_MAXHOSTS);
3882                     ReleaseWriteLock(&j->lock);
3883                     break;
3884                 }
3885         }
3886     }
3887     ReleaseReadLock(&afs_xvolume);
3888 }
3889
3890
3891 static int debugsetsp = 0;
3892 static int
3893 afs_setsprefs(struct spref *sp, unsigned int num, unsigned int vlonly)
3894 {
3895     struct srvAddr *sa;
3896     int i, j, k, matches, touchedSize;
3897     struct server *srvr = NULL;
3898     afs_int32 touched[34];
3899     int isfs;
3900
3901     touchedSize = 0;
3902     for (k = 0; k < num; sp++, k++) {
3903         if (debugsetsp) {
3904             afs_warn("sp host=%x, rank=%d\n", sp->host.s_addr, sp->rank);
3905         }
3906         matches = 0;
3907         ObtainReadLock(&afs_xserver);
3908
3909         i = SHash(sp->host.s_addr);
3910         for (sa = afs_srvAddrs[i]; sa; sa = sa->next_bkt) {
3911             if (sa->sa_ip == sp->host.s_addr) {
3912                 srvr = sa->server;
3913                 isfs = (srvr->cell && (sa->sa_portal == srvr->cell->fsport))
3914                     || (sa->sa_portal == AFS_FSPORT);
3915                 if ((!vlonly && isfs) || (vlonly && !isfs)) {
3916                     matches++;
3917                     break;
3918                 }
3919             }
3920         }
3921
3922         if (sa && matches) {    /* found one! */
3923             if (debugsetsp) {
3924                 afs_warn("sa ip=%x, ip_rank=%d\n", sa->sa_ip, sa->sa_iprank);
3925             }
3926             sa->sa_iprank = sp->rank + afs_randomMod15();
3927             afs_SortOneServer(sa->server);
3928
3929             if (srvr->cell) {
3930                 /* if we don't know yet what cell it's in, this is moot */
3931                 for (j = touchedSize - 1;
3932                      j >= 0 && touched[j] != srvr->cell->cellNum; j--)
3933                     /* is it in our list of touched cells ?  */ ;
3934                 if (j < 0) {    /* no, it's not */
3935                     touched[touchedSize++] = srvr->cell->cellNum;
3936                     if (touchedSize >= 32) {    /* watch for ovrflow */
3937                         ReleaseReadLock(&afs_xserver);
3938                         ReSortCells(touchedSize, touched, vlonly);
3939                         touchedSize = 0;
3940                         ObtainReadLock(&afs_xserver);
3941                     }
3942                 }
3943             }
3944         }
3945
3946         ReleaseReadLock(&afs_xserver);
3947         /* if we didn't find one, start to create one. */
3948         /* Note that it doesn't have a cell yet...     */
3949         if (!matches) {
3950             afs_uint32 temp = sp->host.s_addr;
3951             srvr =
3952                 afs_GetServer(&temp, 1, 0, (vlonly ? AFS_VLPORT : AFS_FSPORT),
3953                               WRITE_LOCK, (afsUUID *) 0, 0);
3954             srvr->addr->sa_iprank = sp->rank + afs_randomMod15();
3955             afs_PutServer(srvr, WRITE_LOCK);
3956         }
3957     }                           /* for all cited preferences */
3958
3959     ReSortCells(touchedSize, touched, vlonly);
3960     return 0;
3961 }
3962
3963 /*!
3964  * VIOC_SETPREFS (46) - Set server ranks
3965  *
3966  * \param[in] ain       the sprefs value you want the sprefs to be set to
3967  * \param[out] aout     not in use
3968  *
3969  * \retval EIO
3970  *      Error if the afs daemon hasn't started yet
3971  * \retval EACCES
3972  *      Error if the user doesn't have super-user credentials
3973  * \retval EINVAL
3974  *      Error if the struct setsprefs is too large or if it multiplied
3975  *      by the number of servers is too large
3976  *
3977  * \post set the sprefs using the afs_setsprefs() function
3978  */
3979 DECL_PIOCTL(PSetSPrefs)
3980 {
3981     struct setspref *ssp;
3982     char *ainPtr;
3983     size_t ainSize;
3984
3985     AFS_STATCNT(PSetSPrefs);
3986
3987     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
3988         return EIO;             /* Inappropriate ioctl for device */
3989
3990     if (!afs_osi_suser(*acred))
3991         return EACCES;
3992
3993     /* The I/O handling here is ghastly, as it relies on overrunning the ends
3994      * of arrays. But, i'm not quite brave enough to change it yet. */
3995     ainPtr = ain->ptr;
3996     ainSize = ain->remaining;
3997
3998     if (ainSize < sizeof(struct setspref))
3999         return EINVAL;
4000
4001     ssp = (struct setspref *)ainPtr;
4002     if (ainSize < (sizeof(struct setspref)
4003                    + sizeof(struct spref) * ssp->num_servers-1))
4004         return EINVAL;
4005
4006     afs_setsprefs(&(ssp->servers[0]), ssp->num_servers,
4007                   (ssp->flags & DBservers));
4008     return 0;
4009 }
4010
4011 /*
4012  * VIOC_SETPREFS33 (42) - Set server ranks (deprecated)
4013  *
4014  * \param[in] ain       the server preferences to be set
4015  * \param[out] aout     not in use
4016  *
4017  * \retval EIO          Error if the afs daemon hasn't started yet
4018  * \retval EACCES       Error if the user doesn't have super-user credentials
4019  *
4020  * \post set the server preferences, calling a function
4021  *
4022  * \notes this may only be performed by the local root user.
4023  */
4024 DECL_PIOCTL(PSetSPrefs33)
4025 {
4026     AFS_STATCNT(PSetSPrefs);
4027     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
4028         return EIO;             /* Inappropriate ioctl for device */
4029
4030
4031     if (!afs_osi_suser(*acred))
4032         return EACCES;
4033
4034     afs_setsprefs((struct spref *)afs_pd_where(ain),
4035                   afs_pd_remaining(ain) / sizeof(struct spref),
4036                   0 /*!vlonly */ );
4037     return 0;
4038 }
4039
4040 /*
4041  * VIOC_GETSPREFS (43) - Get server ranks
4042  *
4043  * \ingroup pioctl
4044  *
4045  * \param[in] ain       the server preferences to get
4046  * \param[out] aout     the server preferences information
4047  *
4048  * \retval EIO          Error if the afs daemon hasn't started yet
4049  * \retval ENOENT       Error if the sprefrequest is too large
4050  *
4051  * \post Get the sprefs
4052  *
4053  * \notes
4054  *      in the hash table of server structs, all servers with the same
4055  *      IP address; will be on the same overflow chain; This could be
4056  *      sped slightly in some circumstances by having it cache the
4057  *      immediately previous slot in the hash table and some
4058  *      supporting information; Only reports file servers now.
4059  */
4060 DECL_PIOCTL(PGetSPrefs)
4061 {
4062     struct sprefrequest spin;   /* input */
4063     struct sprefinfo *spout;    /* output */
4064     struct spref *srvout;       /* one output component */
4065     int i, j;                   /* counters for hash table traversal */
4066     struct server *srvr;        /* one of CM's server structs */
4067     struct srvAddr *sa;
4068     int vlonly;                 /* just return vlservers ? */
4069     int isfs;
4070
4071     AFS_STATCNT(PGetSPrefs);
4072     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
4073         return EIO;             /* Inappropriate ioctl for device */
4074
4075     /* Work out from the size whether we've got a new, or old, style pioctl */
4076     if (afs_pd_remaining(ain) < sizeof(struct sprefrequest)) {
4077         if (afs_pd_getBytes(ain, &spin, sizeof(struct sprefrequest_33)) != 0)
4078            return ENOENT;
4079         vlonly = 0;
4080         spin.flags = 0;
4081     } else {
4082         if (afs_pd_getBytes(ain, &spin, sizeof(struct sprefrequest)) != 0)
4083            return EINVAL;
4084         vlonly = (spin.flags & DBservers);
4085     }
4086
4087     /* This code relies on overflowing arrays. It's ghastly, but I'm not
4088      * quite brave enough to tackle it yet ...
4089      */
4090
4091     /* struct sprefinfo includes 1 server struct...  that size gets added
4092      * in during the loop that follows.
4093      */
4094     spout = afs_pd_inline(aout,
4095                           sizeof(struct sprefinfo) - sizeof(struct spref));
4096     spout->next_offset = spin.offset;
4097     spout->num_servers = 0;
4098     srvout = spout->servers;
4099
4100     ObtainReadLock(&afs_xserver);
4101     for (i = 0, j = 0; j < NSERVERS; j++) {     /* sift through hash table */
4102         for (sa = afs_srvAddrs[j]; sa; sa = sa->next_bkt, i++) {
4103             if (spin.offset > (unsigned short)i) {
4104                 continue;       /* catch up to where we left off */
4105             }
4106             spout->next_offset++;
4107
4108             srvr = sa->server;
4109             isfs = (srvr->cell && (sa->sa_portal == srvr->cell->fsport))
4110                 || (sa->sa_portal == AFS_FSPORT);
4111
4112             if ((vlonly && isfs) || (!vlonly && !isfs)) {
4113                 /* only report ranks for vl servers */
4114                 continue;
4115             }
4116
4117             /* Check we've actually got the space we're about to use */
4118             if (afs_pd_inline(aout, sizeof(struct spref)) == NULL) {
4119                 ReleaseReadLock(&afs_xserver);  /* no more room! */
4120                 return 0;
4121             }
4122
4123             srvout->host.s_addr = sa->sa_ip;
4124             srvout->rank = sa->sa_iprank;
4125             spout->num_servers++;
4126             srvout++;
4127         }
4128     }
4129     ReleaseReadLock(&afs_xserver);
4130
4131     spout->next_offset = 0;     /* start over from the beginning next time */
4132
4133     return 0;
4134 }
4135
4136 /* Enable/Disable the specified exporter. Must be root to disable an exporter */
4137 int afs_NFSRootOnly = 1;
4138 /*!
4139  * VIOC_EXPORTAFS (39) - Export afs to nfs clients
4140  *
4141  * \ingroup pioctl
4142  *
4143  * \param[in] ain
4144  *      an integer containing the desired exportee flags
4145  * \param[out] aout
4146  *      an integer containing the current exporter flags
4147  *
4148  * \retval ENODEV       Error if the exporter doesn't exist
4149  * \retval EACCES       Error if the user doesn't have super-user credentials
4150  *
4151  * \post
4152  *      Changes the state of various values to reflect the change
4153  *      of the export values between nfs and afs.
4154  *
4155  * \notes Legacy code obtained from IBM.
4156  */
4157 DECL_PIOCTL(PExportAfs)
4158 {
4159     afs_int32 export, newint = 0;
4160     afs_int32 type, changestate, handleValue, convmode, pwsync, smounts;
4161     afs_int32 rempags = 0, pagcb = 0;
4162     struct afs_exporter *exporter;
4163
4164     AFS_STATCNT(PExportAfs);
4165     if (afs_pd_getInt(ain, &handleValue) != 0)
4166         return EINVAL;
4167     type = handleValue >> 24;
4168     if (type == 0x71) {
4169         newint = 1;
4170         type = 1;               /* nfs */
4171     }
4172     exporter = exporter_find(type);
4173     if (newint) {
4174         export = handleValue & 3;
4175         changestate = handleValue & 0xfff;
4176         smounts = (handleValue >> 2) & 3;
4177         pwsync = (handleValue >> 4) & 3;
4178         convmode = (handleValue >> 6) & 3;
4179         rempags = (handleValue >> 8) & 3;
4180         pagcb = (handleValue >> 10) & 3;
4181     } else {
4182         changestate = (handleValue >> 16) & 0x1;
4183         convmode = (handleValue >> 16) & 0x2;
4184         pwsync = (handleValue >> 16) & 0x4;
4185         smounts = (handleValue >> 16) & 0x8;
4186         export = handleValue & 0xff;
4187     }
4188     if (!exporter) {
4189         /*  Failed finding desired exporter; */
4190         return ENODEV;
4191     }
4192     if (!changestate) {
4193         handleValue = exporter->exp_states;
4194         if (afs_pd_putInt(aout, handleValue) != 0)
4195             return E2BIG;
4196     } else {
4197         if (!afs_osi_suser(*acred))
4198             return EACCES;      /* Only superuser can do this */
4199         if (newint) {
4200             if (export & 2) {
4201                 if (export & 1)
4202                     exporter->exp_states |= EXP_EXPORTED;
4203                 else
4204                     exporter->exp_states &= ~EXP_EXPORTED;
4205             }
4206             if (convmode & 2) {
4207                 if (convmode & 1)
4208                     exporter->exp_states |= EXP_UNIXMODE;
4209                 else
4210                     exporter->exp_states &= ~EXP_UNIXMODE;
4211             }
4212             if (pwsync & 2) {
4213                 if (pwsync & 1)
4214                     exporter->exp_states |= EXP_PWSYNC;
4215                 else
4216                     exporter->exp_states &= ~EXP_PWSYNC;
4217             }
4218             if (smounts & 2) {
4219                 if (smounts & 1) {
4220                     afs_NFSRootOnly = 0;
4221                     exporter->exp_states |= EXP_SUBMOUNTS;
4222                 } else {
4223                     afs_NFSRootOnly = 1;
4224                     exporter->exp_states &= ~EXP_SUBMOUNTS;
4225                 }
4226             }
4227             if (rempags & 2) {
4228                 if (rempags & 1)
4229                     exporter->exp_states |= EXP_CLIPAGS;
4230                 else
4231                     exporter->exp_states &= ~EXP_CLIPAGS;
4232             }
4233             if (pagcb & 2) {
4234                 if (pagcb & 1)
4235                     exporter->exp_states |= EXP_CALLBACK;
4236                 else
4237                     exporter->exp_states &= ~EXP_CALLBACK;
4238             }
4239             handleValue = exporter->exp_states;
4240             if (afs_pd_putInt(aout, handleValue) != 0)
4241                 return E2BIG;
4242         } else {
4243             if (export)
4244                 exporter->exp_states |= EXP_EXPORTED;
4245             else
4246                 exporter->exp_states &= ~EXP_EXPORTED;
4247             if (convmode)
4248                 exporter->exp_states |= EXP_UNIXMODE;
4249             else
4250                 exporter->exp_states &= ~EXP_UNIXMODE;
4251             if (pwsync)
4252                 exporter->exp_states |= EXP_PWSYNC;
4253             else
4254                 exporter->exp_states &= ~EXP_PWSYNC;
4255             if (smounts) {
4256                 afs_NFSRootOnly = 0;
4257                 exporter->exp_states |= EXP_SUBMOUNTS;
4258             } else {
4259                 afs_NFSRootOnly = 1;
4260                 exporter->exp_states &= ~EXP_SUBMOUNTS;
4261             }
4262         }
4263     }
4264
4265     return 0;
4266 }
4267
4268 /*!
4269  * VIOC_GAG (44) - Silence Cache Manager
4270  *
4271  * \ingroup pioctl
4272  *
4273  * \param[in] ain       the flags to either gag or de-gag the cache manager
4274  * \param[out] aout     not in use
4275  *
4276  * \retval EACCES       Error if the user doesn't have super-user credentials
4277  *
4278  * \post set the gag flags, then show these flags
4279  */
4280 DECL_PIOCTL(PGag)
4281 {
4282     struct gaginfo *gagflags;
4283
4284     if (!afs_osi_suser(*acred))
4285         return EACCES;
4286
4287     gagflags = afs_pd_inline(ain, sizeof(*gagflags));
4288     if (gagflags == NULL)
4289         return EINVAL;
4290     afs_showflags = gagflags->showflags;
4291
4292     return 0;
4293 }
4294
4295 /*!
4296  * VIOC_TWIDDLE (45) - Adjust RX knobs
4297  *
4298  * \ingroup pioctl
4299  *
4300  * \param[in] ain       the previous settings of the 'knobs'
4301  * \param[out] aout     not in use
4302  *
4303  * \retval EACCES       Error if the user doesn't have super-user credentials
4304  *
4305  * \post build out the struct rxp, from a struct rx
4306  */
4307 DECL_PIOCTL(PTwiddleRx)
4308 {
4309     struct rxparams *rxp;
4310
4311     if (!afs_osi_suser(*acred))
4312         return EACCES;
4313
4314     rxp = afs_pd_inline(ain, sizeof(*rxp));
4315     if (rxp == NULL)
4316         return EINVAL;
4317
4318     if (rxp->rx_initReceiveWindow)
4319         rx_initReceiveWindow = rxp->rx_initReceiveWindow;
4320     if (rxp->rx_maxReceiveWindow)
4321         rx_maxReceiveWindow = rxp->rx_maxReceiveWindow;
4322     if (rxp->rx_initSendWindow)
4323         rx_initSendWindow = rxp->rx_initSendWindow;
4324     if (rxp->rx_maxSendWindow)
4325         rx_maxSendWindow = rxp->rx_maxSendWindow;
4326     if (rxp->rxi_nSendFrags)
4327         rxi_nSendFrags = rxp->rxi_nSendFrags;
4328     if (rxp->rxi_nRecvFrags)
4329         rxi_nRecvFrags = rxp->rxi_nRecvFrags;
4330     if (rxp->rxi_OrphanFragSize)
4331         rxi_OrphanFragSize = rxp->rxi_OrphanFragSize;
4332     if (rxp->rx_maxReceiveSize) {
4333         rx_maxReceiveSize = rxp->rx_maxReceiveSize;
4334         rx_maxReceiveSizeUser = rxp->rx_maxReceiveSize;
4335     }
4336     if (rxp->rx_MyMaxSendSize)
4337         rx_MyMaxSendSize = rxp->rx_MyMaxSendSize;
4338
4339     return 0;
4340 }
4341
4342 /*!
4343  * VIOC_GETINITPARAMS (49) - Get initial cache manager parameters
4344  *
4345  * \ingroup pioctl
4346  *
4347  * \param[in] ain       not in use
4348  * \param[out] aout     initial cache manager params
4349  *
4350  * \retval E2BIG
4351  *      Error if the initial parameters are bigger than some PIGGYSIZE
4352  *
4353  * \post return the initial cache manager parameters
4354  */
4355 DECL_PIOCTL(PGetInitParams)
4356 {
4357     if (sizeof(struct cm_initparams) > PIGGYSIZE)
4358         return E2BIG;
4359
4360     return afs_pd_putBytes(aout, &cm_initParams,
4361                            sizeof(struct cm_initparams));
4362     return 0;
4363 }
4364
4365 #ifdef AFS_SGI65_ENV
4366 /* They took crget() from us, so fake it. */
4367 static cred_t *
4368 crget(void)
4369 {
4370     cred_t *cr;
4371     cr = crdup(get_current_cred());
4372     memset(cr, 0, sizeof(cred_t));
4373 #if CELL || CELL_PREPARE
4374     cr->cr_id = -1;
4375 #endif
4376     return cr;
4377 }
4378 #endif
4379
4380 /*!
4381  * VIOC_GETRXKCRYPT (55) - Get rxkad encryption flag
4382  *
4383  * \ingroup pioctl
4384  *
4385  * \param[in] ain       not in use
4386  * \param[out] aout     value of cryptall
4387  *
4388  * \post Turns on, or disables, rxkad encryption by setting the cryptall global
4389  */
4390 DECL_PIOCTL(PGetRxkcrypt)
4391 {
4392     return afs_pd_putInt(aout, cryptall);
4393 }
4394
4395 /*!
4396  * VIOC_SETRXKCRYPT (56) - Set rxkad encryption flag
4397  *
4398  * \ingroup pioctl
4399  *
4400  * \param[in] ain       the argument whether or not things should be encrypted
4401  * \param[out] aout     not in use
4402  *
4403  * \retval EPERM
4404  *      Error if the user doesn't have super-user credentials
4405  * \retval EINVAL
4406  *      Error if the input is too big, or if the input is outside the
4407  *      bounds of what it can be set to
4408  *
4409  * \post set whether or not things should be encrypted
4410  *
4411  * \notes
4412  *      may need to be modified at a later date to take into account
4413  *      other values for cryptall (beyond true or false)
4414  */
4415 DECL_PIOCTL(PSetRxkcrypt)
4416 {
4417     afs_int32 tmpval;
4418
4419     if (!afs_osi_suser(*acred))
4420         return EPERM;
4421     if (afs_pd_getInt(ain, &tmpval) != 0)
4422         return EINVAL;
4423     /* if new mappings added later this will need to be changed */
4424     if (tmpval != 0 && tmpval != 1)
4425         return EINVAL;
4426     cryptall = tmpval;
4427     return 0;
4428 }
4429
4430 #ifdef AFS_NEED_CLIENTCONTEXT
4431 /*
4432  * Create new credentials to correspond to a remote user with given
4433  * <hostaddr, uid, g0, g1>.  This allows a server running as root to
4434  * provide pioctl (and other) services to foreign clients (i.e. nfs
4435  * clients) by using this call to `become' the client.
4436  */
4437 #define PSETPAG         110
4438 #define PIOCTL_HEADER   6
4439 static int
4440 HandleClientContext(struct afs_ioctl *ablob, int *com,
4441                     afs_ucred_t **acred, afs_ucred_t *credp)
4442 {
4443     char *ain, *inData;
4444     afs_uint32 hostaddr;
4445     afs_int32 uid, g0, g1, i, code, pag, exporter_type, isroot = 0;
4446     struct afs_exporter *exporter, *outexporter;
4447     afs_ucred_t *newcred;
4448     struct unixuser *au;
4449     afs_uint32 comp = *com & 0xff00;
4450     afs_uint32 h, l;
4451 #if defined(AFS_SUN510_ENV)
4452     gid_t gids[2];
4453 #endif
4454
4455 #if defined(AFS_SGIMP_ENV)
4456     osi_Assert(ISAFS_GLOCK());
4457 #endif
4458     AFS_STATCNT(HandleClientContext);
4459     if (ablob->in_size < PIOCTL_HEADER * sizeof(afs_int32)) {
4460         /* Must at least include the PIOCTL_HEADER header words
4461          * required by the protocol */
4462         return EINVAL;          /* Too small to be good  */
4463     }
4464     ain = inData = osi_AllocLargeSpace(AFS_LRALLOCSIZ);
4465     AFS_COPYIN(ablob->in, ain, PIOCTL_HEADER * sizeof(afs_int32), code);
4466     if (code) {
4467         osi_FreeLargeSpace(inData);
4468         return code;
4469     }
4470
4471     /* Extract information for remote user */
4472     hostaddr = *((afs_uint32 *) ain);
4473     ain += sizeof(hostaddr);
4474     uid = *((afs_uint32 *) ain);
4475     ain += sizeof(uid);
4476     g0 = *((afs_uint32 *) ain);
4477     ain += sizeof(g0);
4478     g1 = *((afs_uint32 *) ain);
4479     ain += sizeof(g1);
4480     *com = *((afs_uint32 *) ain);
4481     ain += sizeof(afs_int32);
4482     exporter_type = *((afs_uint32 *) ain);/* In case we support more than NFS */
4483
4484     /*
4485      * Of course, one must be root for most of these functions, but
4486      * we'll allow (for knfs) you to set things if the pag is 0 and
4487      * you're setting tokens or unlogging.
4488      */
4489     i = (*com) & 0xff;
4490     if (!afs_osi_suser(credp)) {
4491 #if defined(AFS_SGI_ENV) && !defined(AFS_SGI64_ENV)
4492         /* Since SGI's suser() returns explicit failure after the call.. */
4493         u.u_error = 0;
4494 #endif
4495         /* check for acceptable opcodes for normal folks, which are, so far,
4496          * get/set tokens, sysname, and unlog.
4497          */
4498         if (i != 9 && i != 3 && i != 38 && i != 8) {
4499             osi_FreeLargeSpace(inData);
4500             return EACCES;
4501         }
4502     }
4503
4504     ablob->in_size -= PIOCTL_HEADER * sizeof(afs_int32);
4505     ablob->in += PIOCTL_HEADER * sizeof(afs_int32);
4506     osi_FreeLargeSpace(inData);
4507     if (uid == 0) {
4508         /*
4509          * We map uid 0 to nobody to match the mapping that the nfs
4510          * server does and to ensure that the suser() calls in the afs
4511          * code fails for remote client roots.
4512          */
4513         uid = afs_nobody;       /* NFS_NOBODY == -2 */
4514         isroot = 1;
4515     }
4516     newcred = crget();
4517 #ifdef  AFS_AIX41_ENV
4518     setuerror(0);
4519 #endif
4520     afs_set_cr_gid(newcred, isroot ? RMTUSER_REQ_PRIV : RMTUSER_REQ);
4521 #ifdef AFS_AIX51_ENV
4522     newcred->cr_groupset.gs_union.un_groups[0] = g0;
4523     newcred->cr_groupset.gs_union.un_groups[1] = g1;
4524 #elif defined(AFS_LINUX26_ENV)
4525 # ifdef AFS_LINUX26_ONEGROUP_ENV
4526     afs_set_cr_group_info(newcred, groups_alloc(1)); /* nothing sets this */
4527     l = (((g0-0x3f00) & 0x3fff) << 14) | ((g1-0x3f00) & 0x3fff);
4528     h = ((g0-0x3f00) >> 14);
4529     h = ((g1-0x3f00) >> 14) + h + h + h;
4530     GROUP_AT(afs_cr_group_info(newcred), 0) = ((h << 28) | l);
4531 # else
4532     afs_set_cr_group_info(newcred, groups_alloc(2));
4533     GROUP_AT(afs_cr_group_info(newcred), 0) = g0;
4534     GROUP_AT(afs_cr_group_info(newcred), 1) = g1;
4535 # endif
4536 #elif defined(AFS_SUN510_ENV)
4537     gids[0] = g0;
4538     gids[1] = g1;
4539     crsetgroups(newcred, 2, gids);
4540 #else
4541     newcred->cr_groups[0] = g0;
4542     newcred->cr_groups[1] = g1;
4543 #endif
4544 #ifdef AFS_AIX_ENV
4545     newcred->cr_ngrps = 2;
4546 #elif !defined(AFS_LINUX26_ENV) && !defined(AFS_SUN510_ENV)
4547 # if defined(AFS_SGI_ENV) || defined(AFS_SUN5_ENV) || defined(AFS_LINUX22_ENV) || defined(AFS_FBSD80_ENV)
4548     newcred->cr_ngroups = 2;
4549 # else
4550     for (i = 2; i < NGROUPS; i++)
4551         newcred->cr_groups[i] = NOGROUP;
4552 # endif
4553 #endif
4554     if (!(exporter = exporter_find(exporter_type))) {
4555         /* Exporter wasn't initialized or an invalid exporter type */
4556         crfree(newcred);
4557         return EINVAL;
4558     }
4559     if (exporter->exp_states & EXP_PWSYNC) {
4560         if (uid != afs_cr_uid(credp)) {
4561             crfree(newcred);
4562             return ENOEXEC;     /* XXX Find a better errno XXX */
4563         }
4564     }
4565     afs_set_cr_uid(newcred, uid);       /* Only temporary  */
4566     code = EXP_REQHANDLER(exporter, &newcred, hostaddr, &pag, &outexporter);
4567     /* The client's pag is the only unique identifier for it */
4568     afs_set_cr_uid(newcred, pag);
4569     *acred = newcred;
4570     if (!code && *com == PSETPAG) {
4571         /* Special case for 'setpag' */
4572         afs_uint32 pagvalue = genpag();
4573
4574         au = afs_GetUser(pagvalue, -1, WRITE_LOCK); /* a new unixuser struct */
4575         /*
4576          * Note that we leave the 'outexporter' struct held so it won't
4577          * dissappear on us
4578          */
4579         au->exporter = outexporter;
4580         if (ablob->out_size >= 4) {
4581             AFS_COPYOUT((char *)&pagvalue, ablob->out, sizeof(afs_int32),
4582                         code);
4583         }
4584         afs_PutUser(au, WRITE_LOCK);
4585         if (code)
4586             return code;
4587         return PSETPAG;         /*  Special return for setpag  */
4588     } else if (!code) {
4589         EXP_RELE(outexporter);
4590     }
4591     if (!code)
4592         *com = (*com) | comp;
4593     return code;
4594 }
4595 #endif /* AFS_NEED_CLIENTCONTEXT */
4596
4597
4598 /*!
4599  * VIOC_GETCPREFS (50) - Get client interface
4600  *
4601  * \ingroup pioctl
4602  *
4603  * \param[in] ain       sprefrequest input
4604  * \param[out] aout     spref information
4605  *
4606  * \retval EIO          Error if the afs daemon hasn't started yet
4607  * \retval EINVAL       Error if some of the standard args aren't set
4608  *
4609  * \post
4610  *      get all interface addresses and other information of the client
4611  *      interface
4612  */
4613 DECL_PIOCTL(PGetCPrefs)
4614 {
4615     struct sprefrequest *spin;  /* input */
4616     struct sprefinfo *spout;    /* output */
4617     struct spref *srvout;       /* one output component */
4618     int maxNumber;
4619     int i, j;
4620
4621     AFS_STATCNT(PGetCPrefs);
4622     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
4623         return EIO;             /* Inappropriate ioctl for device */
4624
4625     spin = afs_pd_inline(ain, sizeof(*spin));
4626     if (spin == NULL)
4627         return EINVAL;
4628
4629     /* Output spout relies on writing past the end of arrays. It's horrible,
4630      * but I'm not quite brave enough to tackle it yet */
4631     spout = (struct sprefinfo *)aout->ptr;
4632
4633     maxNumber = spin->num_servers;      /* max addrs this time */
4634     srvout = spout->servers;
4635
4636     ObtainReadLock(&afs_xinterface);
4637
4638     /* copy out the client interface information from the
4639      * kernel data structure "interface" to the output buffer
4640      */
4641     for (i = spin->offset, j = 0; (i < afs_cb_interface.numberOfInterfaces)
4642          && (j < maxNumber); i++, j++, srvout++)
4643         srvout->host.s_addr = afs_cb_interface.addr_in[i];
4644
4645     spout->num_servers = j;
4646     aout->ptr += sizeof(struct sprefinfo) + (j - 1) * sizeof(struct spref);
4647
4648     if (i >= afs_cb_interface.numberOfInterfaces)
4649         spout->next_offset = 0; /* start from beginning again */
4650     else
4651         spout->next_offset = spin->offset + j;
4652
4653     ReleaseReadLock(&afs_xinterface);
4654     return 0;
4655 }
4656
4657 /*!
4658  * VIOC_SETCPREFS (51) - Set client interface
4659  *
4660  * \ingroup pioctl
4661  *
4662  * \param[in] ain       the interfaces you want set
4663  * \param[out] aout     not in use
4664  *
4665  * \retval EIO          Error if the afs daemon hasn't started yet
4666  * \retval EINVAL       Error if the input is too large for the struct
4667  * \retval ENOMEM       Error if there are too many servers
4668  *
4669  * \post set the callbak interfaces addresses to those of the hosts
4670  */
4671 DECL_PIOCTL(PSetCPrefs)
4672 {
4673     char *ainPtr;
4674     size_t ainSize;
4675     struct setspref *sin;
4676     int i;
4677
4678     AFS_STATCNT(PSetCPrefs);
4679     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
4680         return EIO;             /* Inappropriate ioctl for device */
4681
4682     /* Yuck. Input to this function relies on reading past the end of
4683      * structures. Bodge it for now.
4684      */
4685     ainPtr = ain->ptr;
4686     ainSize = ain->remaining;
4687
4688     sin = (struct setspref *)ainPtr;
4689
4690     if (ainSize < sizeof(struct setspref))
4691         return EINVAL;
4692 #if 0                           /* num_servers is unsigned */
4693     if (sin->num_servers < 0)
4694         return EINVAL;
4695 #endif
4696     if (sin->num_servers > AFS_MAX_INTERFACE_ADDR)
4697         return ENOMEM;
4698
4699     ObtainWriteLock(&afs_xinterface, 412);
4700     afs_cb_interface.numberOfInterfaces = sin->num_servers;
4701     for (i = 0; (unsigned short)i < sin->num_servers; i++)
4702         afs_cb_interface.addr_in[i] = sin->servers[i].host.s_addr;
4703
4704     ReleaseWriteLock(&afs_xinterface);
4705     return 0;
4706 }
4707
4708 /*!
4709  * VIOC_AFS_FLUSHMOUNT (52) - Flush mount symlink data
4710  *
4711  * \ingroup pioctl
4712  *
4713  * \param[in] ain
4714  *      the last part of a path to a mount point, which tells us what to flush
4715  * \param[out] aout
4716  *      not in use
4717  *
4718  * \retval EINVAL
4719  *      Error if some of the initial arguments aren't set
4720  * \retval ENOTDIR
4721  *      Error if the initial argument for the mount point isn't a directory
4722  * \retval ENOENT
4723  *      Error if the dcache entry isn't set
4724  *
4725  * \post
4726  *      remove all of the mount data from the dcache regarding a
4727  *      certain mount point
4728  */
4729 DECL_PIOCTL(PFlushMount)
4730 {
4731     afs_int32 code;
4732     struct vcache *tvc;
4733     struct dcache *tdc;
4734     struct VenusFid tfid;
4735     char *bufp;
4736     char *mount;
4737     struct sysname_info sysState;
4738     afs_size_t offset, len;
4739
4740     AFS_STATCNT(PFlushMount);
4741     if (!avc)
4742         return EINVAL;
4743
4744     if (afs_pd_getStringPtr(ain, &mount) != 0)
4745         return EINVAL;
4746
4747     code = afs_VerifyVCache(avc, areq);
4748     if (code)
4749         return code;
4750     if (vType(avc) != VDIR) {
4751         return ENOTDIR;
4752     }
4753     tdc = afs_GetDCache(avc, (afs_size_t) 0, areq, &offset, &len, 1);
4754     if (!tdc)
4755         return ENOENT;
4756     Check_AtSys(avc, mount, &sysState, areq);
4757     ObtainReadLock(&tdc->lock);
4758     do {
4759         code = afs_dir_Lookup(tdc, sysState.name, &tfid.Fid);
4760     } while (code == ENOENT && Next_AtSys(avc, areq, &sysState));
4761     ReleaseReadLock(&tdc->lock);
4762     afs_PutDCache(tdc);         /* we're done with the data */
4763     bufp = sysState.name;
4764     if (code) {
4765         goto out;
4766     }
4767     tfid.Cell = avc->f.fid.Cell;
4768     tfid.Fid.Volume = avc->f.fid.Fid.Volume;
4769     if (!tfid.Fid.Unique && (avc->f.states & CForeign)) {
4770         tvc = afs_LookupVCache(&tfid, areq, NULL, avc, bufp);
4771     } else {
4772         tvc = afs_GetVCache(&tfid, areq, NULL, NULL);
4773     }
4774     if (!tvc) {
4775         code = ENOENT;
4776         goto out;
4777     }
4778     if (tvc->mvstat != 1) {
4779         afs_PutVCache(tvc);
4780         code = EINVAL;
4781         goto out;
4782     }
4783 #ifdef AFS_BOZONLOCK_ENV
4784     afs_BozonLock(&tvc->pvnLock, tvc);  /* Since afs_TryToSmush will do a pvn_vptrunc */
4785 #endif
4786     ObtainWriteLock(&tvc->lock, 649);
4787     ObtainWriteLock(&afs_xcbhash, 650);
4788     afs_DequeueCallback(tvc);
4789     tvc->f.states &= ~(CStatd | CDirty); /* next reference will re-stat cache entry */
4790     ReleaseWriteLock(&afs_xcbhash);
4791     /* now find the disk cache entries */
4792     afs_TryToSmush(tvc, *acred, 1);
4793     osi_dnlc_purgedp(tvc);
4794     if (tvc->linkData && !(tvc->f.states & CCore)) {
4795         afs_osi_Free(tvc->linkData, strlen(tvc->linkData) + 1);
4796         tvc->linkData = NULL;
4797     }
4798     ReleaseWriteLock(&tvc->lock);
4799 #ifdef AFS_BOZONLOCK_ENV
4800     afs_BozonUnlock(&tvc->pvnLock, tvc);
4801 #endif
4802     afs_PutVCache(tvc);
4803   out:
4804     if (sysState.allocked)
4805         osi_FreeLargeSpace(bufp);
4806     return code;
4807 }
4808
4809 /*!
4810  * VIOC_RXSTAT_PROC (53) - Control process RX statistics
4811  *
4812  * \ingroup pioctl
4813  *
4814  * \param[in] ain       the flags that control which stats to use
4815  * \param[out] aout     not in use
4816  *
4817  * \retval EACCES       Error if the user doesn't have super-user credentials
4818  * \retval EINVAL       Error if the flag input is too long
4819  *
4820  * \post
4821  *      either enable process RPCStats, disable process RPCStats,
4822  *      or clear the process RPCStats
4823  */
4824 DECL_PIOCTL(PRxStatProc)
4825 {
4826     afs_int32 flags;
4827
4828     if (!afs_osi_suser(*acred))
4829         return EACCES;
4830
4831     if (afs_pd_getInt(ain, &flags) != 0)
4832         return EINVAL;
4833
4834     if (!(flags & AFSCALL_RXSTATS_MASK) || (flags & ~AFSCALL_RXSTATS_MASK))
4835         return EINVAL;
4836
4837     if (flags & AFSCALL_RXSTATS_ENABLE) {
4838         rx_enableProcessRPCStats();
4839     }
4840     if (flags & AFSCALL_RXSTATS_DISABLE) {
4841         rx_disableProcessRPCStats();
4842     }
4843     if (flags & AFSCALL_RXSTATS_CLEAR) {
4844         rx_clearProcessRPCStats(AFS_RX_STATS_CLEAR_ALL);
4845     }
4846     return 0;
4847 }
4848
4849
4850 /*!
4851  * VIOC_RXSTAT_PEER (54) - Control peer RX statistics
4852  *
4853  * \ingroup pioctl
4854  *
4855  * \param[in] ain       the flags that control which statistics to use
4856  * \param[out] aout     not in use
4857  *
4858  * \retval EACCES       Error if the user doesn't have super-user credentials
4859  * \retval EINVAL       Error if the flag input is too long
4860  *
4861  * \post
4862  *      either enable peer RPCStatws, disable peer RPCStats,
4863  *      or clear the peer RPCStats
4864  */
4865 DECL_PIOCTL(PRxStatPeer)
4866 {
4867     afs_int32 flags;
4868
4869     if (!afs_osi_suser(*acred))
4870         return EACCES;
4871
4872     if (afs_pd_getInt(ain, &flags) != 0)
4873         return EINVAL;
4874
4875     if (!(flags & AFSCALL_RXSTATS_MASK) || (flags & ~AFSCALL_RXSTATS_MASK))
4876         return EINVAL;
4877
4878     if (flags & AFSCALL_RXSTATS_ENABLE) {
4879         rx_enablePeerRPCStats();
4880     }
4881     if (flags & AFSCALL_RXSTATS_DISABLE) {
4882         rx_disablePeerRPCStats();
4883     }
4884     if (flags & AFSCALL_RXSTATS_CLEAR) {
4885         rx_clearPeerRPCStats(AFS_RX_STATS_CLEAR_ALL);
4886     }
4887     return 0;
4888 }
4889
4890 DECL_PIOCTL(PPrefetchFromTape)
4891 {
4892     afs_int32 code, code1;
4893     afs_int32 bytes, outval;
4894     struct afs_conn *tc;
4895     struct rx_call *tcall;
4896     struct AFSVolSync tsync;
4897     struct AFSFetchStatus OutStatus;
4898     struct AFSCallBack CallBack;
4899     struct VenusFid tfid;
4900     struct AFSFid *Fid;
4901     struct vcache *tvc;
4902
4903     AFS_STATCNT(PSetAcl);
4904     if (!avc)
4905         return EINVAL;
4906
4907     Fid = afs_pd_inline(ain, sizeof(struct AFSFid));
4908     if (Fid == NULL)
4909         Fid = &avc->f.fid.Fid;
4910
4911     tfid.Cell = avc->f.fid.Cell;
4912     tfid.Fid.Volume = Fid->Volume;
4913     tfid.Fid.Vnode = Fid->Vnode;
4914     tfid.Fid.Unique = Fid->Unique;
4915
4916     tvc = afs_GetVCache(&tfid, areq, NULL, NULL);
4917     if (!tvc) {
4918         afs_Trace3(afs_iclSetp, CM_TRACE_PREFETCHCMD, ICL_TYPE_POINTER, tvc,
4919                    ICL_TYPE_FID, &tfid, ICL_TYPE_FID, &avc->f.fid);
4920         return ENOENT;
4921     }
4922     afs_Trace3(afs_iclSetp, CM_TRACE_PREFETCHCMD, ICL_TYPE_POINTER, tvc,
4923                ICL_TYPE_FID, &tfid, ICL_TYPE_FID, &tvc->f.fid);
4924
4925     do {
4926         tc = afs_Conn(&tvc->f.fid, areq, SHARED_LOCK);
4927         if (tc) {
4928
4929             RX_AFS_GUNLOCK();
4930             tcall = rx_NewCall(tc->id);
4931             code =
4932                 StartRXAFS_FetchData(tcall, (struct AFSFid *)&tvc->f.fid.Fid, 0,
4933                                      0);
4934             if (!code) {
4935                 bytes = rx_Read(tcall, (char *)&outval, sizeof(afs_int32));
4936                 code =
4937                     EndRXAFS_FetchData(tcall, &OutStatus, &CallBack, &tsync);
4938             }
4939             code1 = rx_EndCall(tcall, code);
4940             RX_AFS_GLOCK();
4941         } else
4942             code = -1;
4943     } while (afs_Analyze
4944              (tc, code, &tvc->f.fid, areq, AFS_STATS_FS_RPCIDX_RESIDENCYRPCS,
4945               SHARED_LOCK, NULL));
4946     /* This call is done only to have the callback things handled correctly */
4947     afs_FetchStatus(tvc, &tfid, areq, &OutStatus);
4948     afs_PutVCache(tvc);
4949
4950     if (code)
4951         return code;
4952
4953     return afs_pd_putInt(aout, outval);
4954 }
4955
4956 DECL_PIOCTL(PFsCmd)
4957 {
4958     afs_int32 code;
4959     struct afs_conn *tc;
4960     struct vcache *tvc;
4961     struct FsCmdInputs *Inputs;
4962     struct FsCmdOutputs *Outputs;
4963     struct VenusFid tfid;
4964     struct AFSFid *Fid;
4965
4966     if (!avc)
4967         return EINVAL;
4968
4969     Inputs = afs_pd_inline(ain, sizeof(*Inputs));
4970     if (Inputs == NULL)
4971         return EINVAL;
4972
4973     Outputs = afs_pd_inline(aout, sizeof(*Outputs));
4974     if (Outputs == NULL)
4975         return E2BIG;
4976
4977     Fid = &Inputs->fid;
4978     if (!Fid->Volume)
4979         Fid = &avc->f.fid.Fid;
4980
4981     tfid.Cell = avc->f.fid.Cell;
4982     tfid.Fid.Volume = Fid->Volume;
4983     tfid.Fid.Vnode = Fid->Vnode;
4984     tfid.Fid.Unique = Fid->Unique;
4985
4986     tvc = afs_GetVCache(&tfid, areq, NULL, NULL);
4987     afs_Trace3(afs_iclSetp, CM_TRACE_RESIDCMD, ICL_TYPE_POINTER, tvc,
4988                ICL_TYPE_INT32, Inputs->command, ICL_TYPE_FID, &tfid);
4989     if (!tvc)
4990         return ENOENT;
4991
4992     if (Inputs->command) {
4993         do {
4994             tc = afs_Conn(&tvc->f.fid, areq, SHARED_LOCK);
4995             if (tc) {
4996                 RX_AFS_GUNLOCK();
4997                 code =
4998                     RXAFS_FsCmd(tc->id, Fid, Inputs,
4999                                         (struct FsCmdOutputs *)aout);
5000                 RX_AFS_GLOCK();
5001             } else
5002                 code = -1;
5003         } while (afs_Analyze
5004                  (tc, code, &tvc->f.fid, areq,
5005                   AFS_STATS_FS_RPCIDX_RESIDENCYRPCS, SHARED_LOCK, NULL));
5006         /* This call is done to have the callback things handled correctly */
5007         afs_FetchStatus(tvc, &tfid, areq, &Outputs->status);
5008     } else {            /* just a status request, return also link data */
5009         code = 0;
5010         Outputs->code = afs_FetchStatus(tvc, &tfid, areq, &Outputs->status);
5011         Outputs->chars[0] = 0;
5012         if (vType(tvc) == VLNK) {
5013             ObtainWriteLock(&tvc->lock, 555);
5014             if (afs_HandleLink(tvc, areq) == 0)
5015                 strncpy((char *)&Outputs->chars, tvc->linkData, MAXCMDCHARS);
5016             ReleaseWriteLock(&tvc->lock);
5017         }
5018     }
5019
5020     afs_PutVCache(tvc);
5021
5022     return code;
5023 }
5024
5025 DECL_PIOCTL(PNewUuid)
5026 {
5027     /*AFS_STATCNT(PNewUuid); */
5028     if (!afs_resourceinit_flag) /* afs deamons havn't started yet */
5029         return EIO;             /* Inappropriate ioctl for device */
5030
5031     if (!afs_osi_suser(*acred))
5032         return EACCES;
5033
5034     ObtainWriteLock(&afs_xinterface, 555);
5035     afs_uuid_create(&afs_cb_interface.uuid);
5036     ReleaseWriteLock(&afs_xinterface);
5037     ForceAllNewConnections();
5038     return 0;
5039 }
5040
5041 #if defined(AFS_CACHE_BYPASS)
5042
5043 DECL_PIOCTL(PSetCachingThreshold)
5044 {
5045     afs_int32 getting = 1;
5046     afs_int32 setting = 1;
5047     afs_int32 threshold = AFS_CACHE_BYPASS_DISABLED;
5048
5049     if (afs_pd_getInt(ain, &threshold) != 0)
5050         setting = 0;
5051
5052     if (aout == NULL)
5053         getting = 0;
5054
5055     if (setting == 0 && getting == 0)
5056         return EINVAL;
5057
5058     /*
5059      * If setting, set first, and return the value now in effect
5060      */
5061     if (setting) {
5062         if (!afs_osi_suser(*acred))
5063             return EPERM;
5064         cache_bypass_threshold = threshold;
5065         afs_warn("Cache Bypass Threshold set to: %d\n", threshold);
5066         /* TODO:  move to separate pioctl, or enhance pioctl */
5067         cache_bypass_strategy = LARGE_FILES_BYPASS_CACHE;
5068     }
5069
5070     /* Return the current size threshold */
5071     if (getting)
5072         return afs_pd_putInt(aout, cache_bypass_threshold);
5073
5074     return(0);
5075 }
5076
5077 #endif /* defined(AFS_CACHE_BYPASS) */
5078
5079 DECL_PIOCTL(PCallBackAddr)
5080 {
5081 #ifndef UKERNEL
5082     afs_uint32 addr, code;
5083     int srvAddrCount;
5084     struct server *ts;
5085     struct srvAddr *sa;
5086     struct afs_conn *tc;
5087     afs_int32 i, j;
5088     struct unixuser *tu;
5089     struct srvAddr **addrs;
5090
5091     /*AFS_STATCNT(PCallBackAddr); */
5092     if (!afs_resourceinit_flag) /* afs deamons havn't started yet */
5093         return EIO;             /* Inappropriate ioctl for device */
5094
5095     if (!afs_osi_suser(acred))
5096         return EACCES;
5097
5098     if (afs_pd_getInt(ain, &addr) != 0)
5099         return EINVAL;
5100
5101     ObtainReadLock(&afs_xinterface);
5102     for (i = 0; (unsigned short)i < afs_cb_interface.numberOfInterfaces; i++) {
5103         if (afs_cb_interface.addr_in[i] == addr)
5104             break;
5105     }
5106
5107     ReleaseWriteLock(&afs_xinterface);
5108
5109     if (afs_cb_interface.addr_in[i] != addr)
5110         return EINVAL;
5111
5112     ObtainReadLock(&afs_xserver);       /* Necessary? */
5113     ObtainReadLock(&afs_xsrvAddr);
5114
5115     srvAddrCount = 0;
5116     for (i = 0; i < NSERVERS; i++) {
5117         for (sa = afs_srvAddrs[i]; sa; sa = sa->next_bkt) {
5118             srvAddrCount++;
5119         }
5120     }
5121
5122     addrs = afs_osi_Alloc(srvAddrCount * sizeof(*addrs));
5123     j = 0;
5124     for (i = 0; i < NSERVERS; i++) {
5125         for (sa = afs_srvAddrs[i]; sa; sa = sa->next_bkt) {
5126             if (j >= srvAddrCount)
5127                 break;
5128             addrs[j++] = sa;
5129         }
5130     }
5131
5132     ReleaseReadLock(&afs_xsrvAddr);
5133     ReleaseReadLock(&afs_xserver);
5134
5135     for (i = 0; i < j; i++) {
5136         sa = addrs[i];
5137         ts = sa->server;
5138         if (!ts)
5139             continue;
5140
5141         /* vlserver has no callback conn */
5142         if (sa->sa_portal == AFS_VLPORT) {
5143             continue;
5144         }
5145
5146         if (!ts->cell)          /* not really an active server, anyway, it must */
5147             continue;           /* have just been added by setsprefs */
5148
5149         /* get a connection, even if host is down; bumps conn ref count */
5150         tu = afs_GetUser(areq->uid, ts->cell->cellNum, SHARED_LOCK);
5151         tc = afs_ConnBySA(sa, ts->cell->fsport, ts->cell->cellNum, tu,
5152                           1 /*force */ , 1 /*create */ , SHARED_LOCK);
5153         afs_PutUser(tu, SHARED_LOCK);
5154         if (!tc)
5155             continue;
5156
5157         if ((sa->sa_flags & SRVADDR_ISDOWN) || afs_HaveCallBacksFrom(ts)) {
5158             if (sa->sa_flags & SRVADDR_ISDOWN) {
5159                 rx_SetConnDeadTime(tc->id, 3);
5160             }
5161 #ifdef RX_ENABLE_LOCKS
5162             AFS_GUNLOCK();
5163 #endif /* RX_ENABLE_LOCKS */
5164             code = RXAFS_CallBackRxConnAddr(tc->id, &addr);
5165 #ifdef RX_ENABLE_LOCKS
5166             AFS_GLOCK();
5167 #endif /* RX_ENABLE_LOCKS */
5168         }
5169         afs_PutConn(tc, SHARED_LOCK);   /* done with it now */
5170     }                           /* Outer loop over addrs */
5171 #endif /* UKERNEL */
5172     return 0;
5173 }
5174
5175 DECL_PIOCTL(PDiscon)
5176 {
5177     static afs_int32 mode = 1; /* Start up in 'off' */
5178     afs_int32 force = 0;
5179     int code = 0;
5180     char flags[4];
5181     struct vrequest lreq;
5182
5183     if (afs_pd_getBytes(ain, &flags, 4) == 0) {
5184         if (!afs_osi_suser(*acred))
5185             return EPERM;
5186
5187         if (flags[0])
5188             mode = flags[0] - 1;
5189         if (flags[1])
5190             afs_ConflictPolicy = flags[1] - 1;
5191         if (flags[2])
5192             force = 1;
5193         if (flags[3]) {
5194             /* Fake InitReq support for UID override */
5195             memset(&lreq, 0, sizeof(lreq));
5196             lreq.uid = flags[3];
5197             areq = &lreq; /* override areq we got */
5198         }
5199
5200         /*
5201          * All of these numbers are hard coded in fs.c. If they
5202          * change here, they should change there and vice versa
5203          */
5204         switch (mode) {
5205         case 0: /* Disconnect ("offline" mode), breaking all callbacks */
5206             if (!AFS_IS_DISCONNECTED) {
5207                 ObtainWriteLock(&afs_discon_lock, 999);
5208                 afs_DisconGiveUpCallbacks();
5209                 afs_RemoveAllConns();
5210                 afs_is_disconnected = 1;
5211                 afs_is_discon_rw = 1;
5212                 ReleaseWriteLock(&afs_discon_lock);
5213             }
5214             break;
5215         case 1: /* Fully connected, ("online" mode). */
5216             ObtainWriteLock(&afs_discon_lock, 998);
5217
5218             afs_in_sync = 1;
5219             afs_MarkAllServersUp();
5220             code = afs_ResyncDisconFiles(areq, *acred);
5221             afs_in_sync = 0;
5222
5223             if (code && !force) {
5224                 afs_warnuser("Files not synchronized properly, still in discon state. \n"
5225                        "Please retry or use \"force\".\n");
5226                 mode = 0;
5227             } else {
5228                 if (force) {
5229                     afs_DisconDiscardAll(*acred);
5230                 }
5231                 afs_ClearAllStatdFlag();
5232                 afs_is_disconnected = 0;
5233                 afs_is_discon_rw = 0;
5234                 afs_warnuser("\nSync succeeded. You are back online.\n");
5235             }
5236
5237             ReleaseWriteLock(&afs_discon_lock);
5238             break;
5239         default:
5240             return EINVAL;
5241         }
5242     } else {
5243         return EINVAL;
5244     }
5245
5246     if (code)
5247         return code;
5248
5249     return afs_pd_putInt(aout, mode);
5250 }
5251
5252 #define MAX_PIOCTL_TOKENS 10
5253
5254 DECL_PIOCTL(PSetTokens2)
5255 {
5256     int code =0;
5257     int i, cellNum, primaryFlag;
5258     XDR xdrs;
5259     struct unixuser *tu;
5260     struct vrequest treq;
5261     struct ktc_setTokenData tokenSet;
5262     struct ktc_tokenUnion decodedToken;
5263
5264     memset(&tokenSet, 0, sizeof(tokenSet));
5265
5266     AFS_STATCNT(PSetTokens2);
5267     if (!afs_resourceinit_flag)
5268         return EIO;
5269
5270     afs_pd_xdrStart(ain, &xdrs, XDR_DECODE);
5271
5272     if (!xdr_ktc_setTokenData(&xdrs, &tokenSet)) {
5273         afs_pd_xdrEnd(ain, &xdrs);
5274         return EINVAL;
5275     }
5276
5277     afs_pd_xdrEnd(ain, &xdrs);
5278
5279     /* We limit each PAG to 10 tokens to prevent a malicous (or runaway)
5280      * process from using up the whole of the kernel memory by allocating
5281      * tokens.
5282      */
5283     if (tokenSet.tokens.tokens_len > MAX_PIOCTL_TOKENS) {
5284         xdr_free((xdrproc_t) xdr_ktc_setTokenData, &tokenSet);
5285         return E2BIG;
5286     }
5287
5288     code = _settok_tokenCell(tokenSet.cell, &cellNum, &primaryFlag);
5289     if (code) {
5290         xdr_free((xdrproc_t) xdr_ktc_setTokenData, &tokenSet);
5291         return code;
5292     }
5293
5294     if (tokenSet.flags & AFSTOKEN_EX_SETPAG) {
5295         if (_settok_setParentPag(acred) == 0) {
5296             afs_InitReq(&treq, *acred);
5297             areq = &treq;
5298         }
5299     }
5300
5301     tu = afs_GetUser(areq->uid, cellNum, WRITE_LOCK);
5302     /* Free any tokens that we've already got */
5303     afs_FreeTokens(&tu->tokens);
5304
5305     /* Iterate across the set of tokens we've received, and stuff them
5306      * into this user's tokenJar
5307      */
5308     for (i=0; i < tokenSet.tokens.tokens_len; i++) {
5309         xdrmem_create(&xdrs,
5310                       tokenSet.tokens.tokens_val[i].token_opaque_val,
5311                       tokenSet.tokens.tokens_val[i].token_opaque_len,
5312                       XDR_DECODE);
5313
5314         memset(&decodedToken, 0, sizeof(decodedToken));
5315         if (!xdr_ktc_tokenUnion(&xdrs, &decodedToken)) {
5316             xdr_destroy(&xdrs);
5317             code = EINVAL;
5318             goto out;
5319         }
5320
5321         xdr_destroy(&xdrs);
5322
5323         afs_AddTokenFromPioctl(&tu->tokens, &decodedToken);
5324         /* This is untidy - the old token interface supported passing
5325          * the primaryFlag as part of the token interface. Current
5326          * OpenAFS userland never sets this, but it's specified as being
5327          * part of the XG interface, so we should probably still support
5328          * it. Rather than add it to our AddToken interface, just handle
5329          * it here.
5330          */
5331         if (decodedToken.at_type == AFSTOKEN_UNION_KAD) {
5332             if (decodedToken.ktc_tokenUnion_u.at_kad.rk_primary_flag)
5333                 primaryFlag = 1;
5334         }
5335
5336         /* XXX - We should think more about destruction here. It's likely that
5337          * there is key material in what we're about to throw away, which
5338          * we really should zero out before giving back to the allocator */
5339         xdr_free((xdrproc_t) xdr_ktc_tokenUnion, &decodedToken);
5340     }
5341
5342     tu->states |= UHasTokens;
5343     tu->states &= ~UTokensBad;
5344     afs_SetPrimary(tu, primaryFlag);
5345     tu->tokenTime = osi_Time();
5346
5347     xdr_free((xdrproc_t) xdr_ktc_setTokenData, &tokenSet);
5348
5349 out:
5350     afs_ResetUserConns(tu);
5351     afs_PutUser(tu, WRITE_LOCK);
5352
5353     return code;
5354 }
5355
5356 DECL_PIOCTL(PGetTokens2)
5357 {
5358     struct cell *cell;
5359     struct unixuser *tu = NULL;
5360     afs_int32 iterator;
5361     char *cellName = NULL;
5362     afs_int32 cellNum;
5363     int code = 0;
5364     time_t now;
5365     XDR xdrs;
5366     struct ktc_setTokenData tokenSet;
5367
5368     AFS_STATCNT(PGetTokens);
5369     if (!afs_resourceinit_flag)
5370         return EIO;
5371
5372     memset(&tokenSet, 0, sizeof(tokenSet));
5373
5374     /* No input data - return tokens for primary cell */
5375     /* 4 octets of data is an iterator count */
5376     /* Otherwise, treat as string & return tokens for that cell name */
5377
5378     if (afs_pd_remaining(ain) == sizeof(afs_int32)) {
5379         /* Integer iterator - return tokens for the n'th cell found for user */
5380         if (afs_pd_getInt(ain, &iterator) != 0)
5381             return EINVAL;
5382         tu = getNthCell(areq->uid, iterator);
5383     } else {
5384         if (afs_pd_remaining(ain) > 0) {
5385             if (afs_pd_getStringPtr(ain, &cellName) != 0)
5386                 return EINVAL;
5387         } else {
5388             cellName = NULL;
5389         }
5390         code = _settok_tokenCell(cellName, &cellNum, NULL);
5391         if (code)
5392             return code;
5393         tu = afs_FindUser(areq->uid, cellNum, READ_LOCK);
5394     }
5395     if (tu == NULL)
5396         return EDOM;
5397
5398     now = osi_Time();
5399
5400     if (!(tu->states & UHasTokens)
5401         || !afs_HasValidTokens(tu->tokens, now)) {
5402         tu->states |= (UTokensBad | UNeedsReset);
5403         afs_PutUser(tu, READ_LOCK);
5404         return ENOTCONN;
5405     }
5406
5407     code = afs_ExtractTokensForPioctl(tu->tokens, now, &tokenSet);
5408     if (code)
5409         goto out;
5410
5411     cell = afs_GetCell(tu->cell, READ_LOCK);
5412     tokenSet.cell = cell->cellName;
5413     afs_pd_xdrStart(aout, &xdrs, XDR_ENCODE);
5414     if (!xdr_ktc_setTokenData(&xdrs, &tokenSet)) {
5415         code = E2BIG;
5416         goto out;
5417     }
5418     afs_pd_xdrEnd(aout, &xdrs);
5419
5420 out:
5421     tokenSet.cell = NULL;
5422
5423     if (tu)
5424         afs_PutUser(tu, READ_LOCK);
5425     if (cell)
5426         afs_PutCell(cell, READ_LOCK);
5427     xdr_free((xdrproc_t)xdr_ktc_setTokenData, &tokenSet);
5428
5429     return code;
5430 };
5431
5432 DECL_PIOCTL(PNFSNukeCreds)
5433 {
5434     afs_uint32 addr;
5435     afs_int32 i;
5436     struct unixuser *tu;
5437
5438     AFS_STATCNT(PUnlog);
5439     if (!afs_resourceinit_flag) /* afs daemons haven't started yet */
5440         return EIO;             /* Inappropriate ioctl for device */
5441
5442     if (afs_pd_getUint(ain, &addr) != 0)
5443         return EINVAL;
5444
5445     if (afs_cr_gid(*acred) == RMTUSER_REQ_PRIV && !addr) {
5446         tu = afs_GetUser(areq->uid, -1, SHARED_LOCK);
5447         if (!tu->exporter || !(addr = EXP_GETHOST(tu->exporter))) {
5448             afs_PutUser(tu, SHARED_LOCK);
5449             return EACCES;
5450         }
5451         afs_PutUser(tu, SHARED_LOCK);
5452     } else if (!afs_osi_suser(acred)) {
5453         return EACCES;
5454     }
5455
5456     ObtainWriteLock(&afs_xuser, 227);
5457     for (i = 0; i < NUSERS; i++) {
5458         for (tu = afs_users[i]; tu; tu = tu->next) {
5459             if (tu->exporter && EXP_CHECKHOST(tu->exporter, addr)) {
5460                 tu->states &= ~UHasTokens;
5461                 afs_FreeTokens(&tu->tokens);
5462                 tu->refCount++;
5463                 ReleaseWriteLock(&afs_xuser);
5464                 afs_ResetUserConns(tu);
5465                 tu->refCount--;
5466                 ObtainWriteLock(&afs_xuser, 228);
5467 #ifdef UKERNEL
5468                 /* set the expire times to 0, causes
5469                  * afs_GCUserData to remove this entry
5470                  */
5471                 tu->tokenTime = 0;
5472 #endif /* UKERNEL */
5473             }
5474         }
5475     }
5476     ReleaseWriteLock(&afs_xuser);
5477     return 0;
5478 }