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