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