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