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