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