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