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