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