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