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