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