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