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