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