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