xref: /netbsd-src/sys/miscfs/procfs/procfs_vnops.c (revision a536ee5124e62c9a0051a252f7833dc8f50f44c9)
1 /*	$NetBSD: procfs_vnops.c,v 1.185 2012/11/25 01:03:05 christos Exp $	*/
2 
3 /*-
4  * Copyright (c) 2006, 2007, 2008 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Andrew Doran.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /*
33  * Copyright (c) 1993, 1995
34  *	The Regents of the University of California.  All rights reserved.
35  *
36  * This code is derived from software contributed to Berkeley by
37  * Jan-Simon Pendry.
38  *
39  * Redistribution and use in source and binary forms, with or without
40  * modification, are permitted provided that the following conditions
41  * are met:
42  * 1. Redistributions of source code must retain the above copyright
43  *    notice, this list of conditions and the following disclaimer.
44  * 2. Redistributions in binary form must reproduce the above copyright
45  *    notice, this list of conditions and the following disclaimer in the
46  *    documentation and/or other materials provided with the distribution.
47  * 3. Neither the name of the University nor the names of its contributors
48  *    may be used to endorse or promote products derived from this software
49  *    without specific prior written permission.
50  *
51  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
52  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
53  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
54  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
55  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
56  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
57  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
58  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
59  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
60  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
61  * SUCH DAMAGE.
62  *
63  *	@(#)procfs_vnops.c	8.18 (Berkeley) 5/21/95
64  */
65 
66 /*
67  * Copyright (c) 1993 Jan-Simon Pendry
68  *
69  * This code is derived from software contributed to Berkeley by
70  * Jan-Simon Pendry.
71  *
72  * Redistribution and use in source and binary forms, with or without
73  * modification, are permitted provided that the following conditions
74  * are met:
75  * 1. Redistributions of source code must retain the above copyright
76  *    notice, this list of conditions and the following disclaimer.
77  * 2. Redistributions in binary form must reproduce the above copyright
78  *    notice, this list of conditions and the following disclaimer in the
79  *    documentation and/or other materials provided with the distribution.
80  * 3. All advertising materials mentioning features or use of this software
81  *    must display the following acknowledgement:
82  *	This product includes software developed by the University of
83  *	California, Berkeley and its contributors.
84  * 4. Neither the name of the University nor the names of its contributors
85  *    may be used to endorse or promote products derived from this software
86  *    without specific prior written permission.
87  *
88  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
89  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
90  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
91  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
92  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
93  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
94  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
95  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
96  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
97  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
98  * SUCH DAMAGE.
99  *
100  *	@(#)procfs_vnops.c	8.18 (Berkeley) 5/21/95
101  */
102 
103 /*
104  * procfs vnode interface
105  */
106 
107 #include <sys/cdefs.h>
108 __KERNEL_RCSID(0, "$NetBSD: procfs_vnops.c,v 1.185 2012/11/25 01:03:05 christos Exp $");
109 
110 #include <sys/param.h>
111 #include <sys/systm.h>
112 #include <sys/time.h>
113 #include <sys/kernel.h>
114 #include <sys/file.h>
115 #include <sys/filedesc.h>
116 #include <sys/proc.h>
117 #include <sys/vnode.h>
118 #include <sys/namei.h>
119 #include <sys/malloc.h>
120 #include <sys/mount.h>
121 #include <sys/dirent.h>
122 #include <sys/resourcevar.h>
123 #include <sys/stat.h>
124 #include <sys/ptrace.h>
125 #include <sys/kauth.h>
126 
127 #include <uvm/uvm_extern.h>	/* for PAGE_SIZE */
128 
129 #include <machine/reg.h>
130 
131 #include <miscfs/genfs/genfs.h>
132 #include <miscfs/procfs/procfs.h>
133 
134 /*
135  * Vnode Operations.
136  *
137  */
138 
139 static int procfs_validfile_linux(struct lwp *, struct mount *);
140 static int procfs_root_readdir_callback(struct proc *, void *);
141 static void procfs_dir(pfstype, struct lwp *, struct proc *, char **, char *,
142     size_t);
143 
144 /*
145  * This is a list of the valid names in the
146  * process-specific sub-directories.  It is
147  * used in procfs_lookup and procfs_readdir
148  */
149 static const struct proc_target {
150 	u_char	pt_type;
151 	u_char	pt_namlen;
152 	const char	*pt_name;
153 	pfstype	pt_pfstype;
154 	int	(*pt_valid)(struct lwp *, struct mount *);
155 } proc_targets[] = {
156 #define N(s) sizeof(s)-1, s
157 	/*	  name		type		validp */
158 	{ DT_DIR, N("."),	PFSproc,	NULL },
159 	{ DT_DIR, N(".."),	PFSroot,	NULL },
160 	{ DT_DIR, N("fd"),	PFSfd,		NULL },
161 	{ DT_REG, N("file"),	PFSfile,	procfs_validfile },
162 	{ DT_REG, N("mem"),	PFSmem,		NULL },
163 	{ DT_REG, N("regs"),	PFSregs,	procfs_validregs },
164 	{ DT_REG, N("fpregs"),	PFSfpregs,	procfs_validfpregs },
165 	{ DT_REG, N("ctl"),	PFSctl,		NULL },
166 	{ DT_REG, N("stat"),	PFSstat,	procfs_validfile_linux },
167 	{ DT_REG, N("status"),	PFSstatus,	NULL },
168 	{ DT_REG, N("note"),	PFSnote,	NULL },
169 	{ DT_REG, N("notepg"),	PFSnotepg,	NULL },
170 	{ DT_REG, N("map"),	PFSmap,		procfs_validmap },
171 	{ DT_REG, N("maps"),	PFSmaps,	procfs_validmap },
172 	{ DT_REG, N("cmdline"), PFScmdline,	NULL },
173 	{ DT_REG, N("exe"),	PFSexe,		procfs_validfile },
174 	{ DT_LNK, N("cwd"),	PFScwd,		NULL },
175 	{ DT_LNK, N("root"),	PFSchroot,	NULL },
176 	{ DT_LNK, N("emul"),	PFSemul,	NULL },
177 	{ DT_REG, N("statm"),	PFSstatm,	procfs_validfile_linux },
178 	{ DT_DIR, N("task"),	PFStask,	procfs_validfile_linux },
179 #ifdef __HAVE_PROCFS_MACHDEP
180 	PROCFS_MACHDEP_NODETYPE_DEFNS
181 #endif
182 #undef N
183 };
184 static const int nproc_targets = sizeof(proc_targets) / sizeof(proc_targets[0]);
185 
186 /*
187  * List of files in the root directory. Note: the validate function will
188  * be called with p == NULL for these ones.
189  */
190 static const struct proc_target proc_root_targets[] = {
191 #define N(s) sizeof(s)-1, s
192 	/*	  name		    type	    validp */
193 	{ DT_REG, N("meminfo"),     PFSmeminfo,        procfs_validfile_linux },
194 	{ DT_REG, N("cpuinfo"),     PFScpuinfo,        procfs_validfile_linux },
195 	{ DT_REG, N("uptime"),      PFSuptime,         procfs_validfile_linux },
196 	{ DT_REG, N("mounts"),	    PFSmounts,	       procfs_validfile_linux },
197 	{ DT_REG, N("devices"),     PFSdevices,        procfs_validfile_linux },
198 	{ DT_REG, N("stat"),	    PFScpustat,        procfs_validfile_linux },
199 	{ DT_REG, N("loadavg"),	    PFSloadavg,        procfs_validfile_linux },
200 	{ DT_REG, N("version"),     PFSversion,        procfs_validfile_linux },
201 #undef N
202 };
203 static const int nproc_root_targets =
204     sizeof(proc_root_targets) / sizeof(proc_root_targets[0]);
205 
206 int	procfs_lookup(void *);
207 #define	procfs_create	genfs_eopnotsupp
208 #define	procfs_mknod	genfs_eopnotsupp
209 int	procfs_open(void *);
210 int	procfs_close(void *);
211 int	procfs_access(void *);
212 int	procfs_getattr(void *);
213 int	procfs_setattr(void *);
214 #define	procfs_read	procfs_rw
215 #define	procfs_write	procfs_rw
216 #define	procfs_fcntl	genfs_fcntl
217 #define	procfs_ioctl	genfs_enoioctl
218 #define	procfs_poll	genfs_poll
219 #define procfs_revoke	genfs_revoke
220 #define	procfs_fsync	genfs_nullop
221 #define	procfs_seek	genfs_nullop
222 #define	procfs_remove	genfs_eopnotsupp
223 int	procfs_link(void *);
224 #define	procfs_rename	genfs_eopnotsupp
225 #define	procfs_mkdir	genfs_eopnotsupp
226 #define	procfs_rmdir	genfs_eopnotsupp
227 int	procfs_symlink(void *);
228 int	procfs_readdir(void *);
229 int	procfs_readlink(void *);
230 #define	procfs_abortop	genfs_abortop
231 int	procfs_inactive(void *);
232 int	procfs_reclaim(void *);
233 #define	procfs_lock	genfs_lock
234 #define	procfs_unlock	genfs_unlock
235 #define	procfs_bmap	genfs_badop
236 #define	procfs_strategy	genfs_badop
237 int	procfs_print(void *);
238 int	procfs_pathconf(void *);
239 #define	procfs_islocked	genfs_islocked
240 #define	procfs_advlock	genfs_einval
241 #define	procfs_bwrite	genfs_eopnotsupp
242 #define procfs_putpages	genfs_null_putpages
243 
244 static int atoi(const char *, size_t);
245 
246 /*
247  * procfs vnode operations.
248  */
249 int (**procfs_vnodeop_p)(void *);
250 const struct vnodeopv_entry_desc procfs_vnodeop_entries[] = {
251 	{ &vop_default_desc, vn_default_error },
252 	{ &vop_lookup_desc, procfs_lookup },		/* lookup */
253 	{ &vop_create_desc, procfs_create },		/* create */
254 	{ &vop_mknod_desc, procfs_mknod },		/* mknod */
255 	{ &vop_open_desc, procfs_open },		/* open */
256 	{ &vop_close_desc, procfs_close },		/* close */
257 	{ &vop_access_desc, procfs_access },		/* access */
258 	{ &vop_getattr_desc, procfs_getattr },		/* getattr */
259 	{ &vop_setattr_desc, procfs_setattr },		/* setattr */
260 	{ &vop_read_desc, procfs_read },		/* read */
261 	{ &vop_write_desc, procfs_write },		/* write */
262 	{ &vop_fcntl_desc, procfs_fcntl },		/* fcntl */
263 	{ &vop_ioctl_desc, procfs_ioctl },		/* ioctl */
264 	{ &vop_poll_desc, procfs_poll },		/* poll */
265 	{ &vop_revoke_desc, procfs_revoke },		/* revoke */
266 	{ &vop_fsync_desc, procfs_fsync },		/* fsync */
267 	{ &vop_seek_desc, procfs_seek },		/* seek */
268 	{ &vop_remove_desc, procfs_remove },		/* remove */
269 	{ &vop_link_desc, procfs_link },		/* link */
270 	{ &vop_rename_desc, procfs_rename },		/* rename */
271 	{ &vop_mkdir_desc, procfs_mkdir },		/* mkdir */
272 	{ &vop_rmdir_desc, procfs_rmdir },		/* rmdir */
273 	{ &vop_symlink_desc, procfs_symlink },		/* symlink */
274 	{ &vop_readdir_desc, procfs_readdir },		/* readdir */
275 	{ &vop_readlink_desc, procfs_readlink },	/* readlink */
276 	{ &vop_abortop_desc, procfs_abortop },		/* abortop */
277 	{ &vop_inactive_desc, procfs_inactive },	/* inactive */
278 	{ &vop_reclaim_desc, procfs_reclaim },		/* reclaim */
279 	{ &vop_lock_desc, procfs_lock },		/* lock */
280 	{ &vop_unlock_desc, procfs_unlock },		/* unlock */
281 	{ &vop_bmap_desc, procfs_bmap },		/* bmap */
282 	{ &vop_strategy_desc, procfs_strategy },	/* strategy */
283 	{ &vop_print_desc, procfs_print },		/* print */
284 	{ &vop_islocked_desc, procfs_islocked },	/* islocked */
285 	{ &vop_pathconf_desc, procfs_pathconf },	/* pathconf */
286 	{ &vop_advlock_desc, procfs_advlock },		/* advlock */
287 	{ &vop_putpages_desc, procfs_putpages },	/* putpages */
288 	{ NULL, NULL }
289 };
290 const struct vnodeopv_desc procfs_vnodeop_opv_desc =
291 	{ &procfs_vnodeop_p, procfs_vnodeop_entries };
292 /*
293  * set things up for doing i/o on
294  * the pfsnode (vp).  (vp) is locked
295  * on entry, and should be left locked
296  * on exit.
297  *
298  * for procfs we don't need to do anything
299  * in particular for i/o.  all that is done
300  * is to support exclusive open on process
301  * memory images.
302  */
303 int
304 procfs_open(void *v)
305 {
306 	struct vop_open_args /* {
307 		struct vnode *a_vp;
308 		int  a_mode;
309 		kauth_cred_t a_cred;
310 	} */ *ap = v;
311 	struct pfsnode *pfs = VTOPFS(ap->a_vp);
312 	struct lwp *l1;
313 	struct proc *p2;
314 	int error;
315 
316 	if ((error = procfs_proc_lock(pfs->pfs_pid, &p2, ENOENT)) != 0)
317 		return error;
318 
319 	l1 = curlwp;				/* tracer */
320 
321 #define	M2K(m)	(((m) & FREAD) && ((m) & FWRITE) ? \
322 		 KAUTH_REQ_PROCESS_PROCFS_RW : \
323 		 (m) & FWRITE ? KAUTH_REQ_PROCESS_PROCFS_WRITE : \
324 		 KAUTH_REQ_PROCESS_PROCFS_READ)
325 
326 	mutex_enter(p2->p_lock);
327 	error = kauth_authorize_process(l1->l_cred, KAUTH_PROCESS_PROCFS,
328 	    p2, pfs, KAUTH_ARG(M2K(ap->a_mode)), NULL);
329 	mutex_exit(p2->p_lock);
330 	if (error) {
331 		procfs_proc_unlock(p2);
332 		return (error);
333 	}
334 
335 #undef M2K
336 
337 	switch (pfs->pfs_type) {
338 	case PFSmem:
339 		if (((pfs->pfs_flags & FWRITE) && (ap->a_mode & O_EXCL)) ||
340 		    ((pfs->pfs_flags & O_EXCL) && (ap->a_mode & FWRITE))) {
341 			error = EBUSY;
342 			break;
343 		}
344 
345 		if (!proc_isunder(p2, l1)) {
346 			error = EPERM;
347 			break;
348 		}
349 
350 		if (ap->a_mode & FWRITE)
351 			pfs->pfs_flags = ap->a_mode & (FWRITE|O_EXCL);
352 
353 		break;
354 
355 	case PFSregs:
356 	case PFSfpregs:
357 		if (!proc_isunder(p2, l1)) {
358 			error = EPERM;
359 			break;
360 		}
361 		break;
362 
363 	default:
364 		break;
365 	}
366 
367 	procfs_proc_unlock(p2);
368 	return (error);
369 }
370 
371 /*
372  * close the pfsnode (vp) after doing i/o.
373  * (vp) is not locked on entry or exit.
374  *
375  * nothing to do for procfs other than undo
376  * any exclusive open flag (see _open above).
377  */
378 int
379 procfs_close(void *v)
380 {
381 	struct vop_close_args /* {
382 		struct vnode *a_vp;
383 		int  a_fflag;
384 		kauth_cred_t a_cred;
385 	} */ *ap = v;
386 	struct pfsnode *pfs = VTOPFS(ap->a_vp);
387 
388 	switch (pfs->pfs_type) {
389 	case PFSmem:
390 		if ((ap->a_fflag & FWRITE) && (pfs->pfs_flags & O_EXCL))
391 			pfs->pfs_flags &= ~(FWRITE|O_EXCL);
392 		break;
393 
394 	default:
395 		break;
396 	}
397 
398 	return (0);
399 }
400 
401 /*
402  * _inactive is called when the pfsnode
403  * is vrele'd and the reference count goes
404  * to zero.  (vp) will be on the vnode free
405  * list, so to get it back vget() must be
406  * used.
407  *
408  * (vp) is locked on entry, but must be unlocked on exit.
409  */
410 int
411 procfs_inactive(void *v)
412 {
413 	struct vop_inactive_args /* {
414 		struct vnode *a_vp;
415 		bool *a_recycle;
416 	} */ *ap = v;
417 	struct vnode *vp = ap->a_vp;
418 	struct pfsnode *pfs = VTOPFS(vp);
419 
420 	mutex_enter(proc_lock);
421 	*ap->a_recycle = (proc_find(pfs->pfs_pid) == NULL);
422 	mutex_exit(proc_lock);
423 
424 	VOP_UNLOCK(vp);
425 
426 	return (0);
427 }
428 
429 /*
430  * _reclaim is called when getnewvnode()
431  * wants to make use of an entry on the vnode
432  * free list.  at this time the filesystem needs
433  * to free any private data and remove the node
434  * from any private lists.
435  */
436 int
437 procfs_reclaim(void *v)
438 {
439 	struct vop_reclaim_args /* {
440 		struct vnode *a_vp;
441 	} */ *ap = v;
442 
443 	return (procfs_freevp(ap->a_vp));
444 }
445 
446 /*
447  * Return POSIX pathconf information applicable to special devices.
448  */
449 int
450 procfs_pathconf(void *v)
451 {
452 	struct vop_pathconf_args /* {
453 		struct vnode *a_vp;
454 		int a_name;
455 		register_t *a_retval;
456 	} */ *ap = v;
457 
458 	switch (ap->a_name) {
459 	case _PC_LINK_MAX:
460 		*ap->a_retval = LINK_MAX;
461 		return (0);
462 	case _PC_MAX_CANON:
463 		*ap->a_retval = MAX_CANON;
464 		return (0);
465 	case _PC_MAX_INPUT:
466 		*ap->a_retval = MAX_INPUT;
467 		return (0);
468 	case _PC_PIPE_BUF:
469 		*ap->a_retval = PIPE_BUF;
470 		return (0);
471 	case _PC_CHOWN_RESTRICTED:
472 		*ap->a_retval = 1;
473 		return (0);
474 	case _PC_VDISABLE:
475 		*ap->a_retval = _POSIX_VDISABLE;
476 		return (0);
477 	case _PC_SYNC_IO:
478 		*ap->a_retval = 1;
479 		return (0);
480 	default:
481 		return (EINVAL);
482 	}
483 	/* NOTREACHED */
484 }
485 
486 /*
487  * _print is used for debugging.
488  * just print a readable description
489  * of (vp).
490  */
491 int
492 procfs_print(void *v)
493 {
494 	struct vop_print_args /* {
495 		struct vnode *a_vp;
496 	} */ *ap = v;
497 	struct pfsnode *pfs = VTOPFS(ap->a_vp);
498 
499 	printf("tag VT_PROCFS, type %d, pid %d, mode %x, flags %lx\n",
500 	    pfs->pfs_type, pfs->pfs_pid, pfs->pfs_mode, pfs->pfs_flags);
501 	return 0;
502 }
503 
504 int
505 procfs_link(void *v)
506 {
507 	struct vop_link_args /* {
508 		struct vnode *a_dvp;
509 		struct vnode *a_vp;
510 		struct componentname *a_cnp;
511 	} */ *ap = v;
512 
513 	VOP_ABORTOP(ap->a_dvp, ap->a_cnp);
514 	vput(ap->a_dvp);
515 	return (EROFS);
516 }
517 
518 int
519 procfs_symlink(void *v)
520 {
521 	struct vop_symlink_args /* {
522 		struct vnode *a_dvp;
523 		struct vnode **a_vpp;
524 		struct componentname *a_cnp;
525 		struct vattr *a_vap;
526 		char *a_target;
527 	} */ *ap = v;
528 
529 	VOP_ABORTOP(ap->a_dvp, ap->a_cnp);
530 	vput(ap->a_dvp);
531 	return (EROFS);
532 }
533 
534 /*
535  * Works out the path to (and vnode of) the target process's current
536  * working directory or chroot.  If the caller is in a chroot and
537  * can't "reach" the target's cwd or root (or some other error
538  * occurs), a "/" is returned for the path and a NULL pointer is
539  * returned for the vnode.
540  */
541 static void
542 procfs_dir(pfstype t, struct lwp *caller, struct proc *target, char **bpp,
543     char *path, size_t len)
544 {
545 	struct cwdinfo *cwdi;
546 	struct vnode *vp, *rvp;
547 	char *bp;
548 
549 	cwdi = caller->l_proc->p_cwdi;
550 	rw_enter(&cwdi->cwdi_lock, RW_READER);
551 
552 	rvp = cwdi->cwdi_rdir;
553 	bp = bpp ? *bpp : NULL;
554 
555 	switch (t) {
556 	case PFScwd:
557 		vp = target->p_cwdi->cwdi_cdir;
558 		break;
559 	case PFSchroot:
560 		vp = target->p_cwdi->cwdi_rdir;
561 		break;
562 	case PFSexe:
563 		vp = target->p_textvp;
564 		break;
565 	default:
566 		rw_exit(&cwdi->cwdi_lock);
567 		return;
568 	}
569 
570 	/*
571 	 * XXX: this horrible kludge avoids locking panics when
572 	 * attempting to lookup links that point to within procfs
573 	 */
574 	if (vp != NULL && vp->v_tag == VT_PROCFS) {
575 		if (bpp) {
576 			*--bp = '/';
577 			*bpp = bp;
578 		}
579 		rw_exit(&cwdi->cwdi_lock);
580 		return;
581 	}
582 
583 	if (rvp == NULL)
584 		rvp = rootvnode;
585 	if (vp == NULL || getcwd_common(vp, rvp, bp ? &bp : NULL, path,
586 	    len / 2, 0, caller) != 0) {
587 		vp = NULL;
588 		if (bpp) {
589 /*
590 			if (t == PFSexe) {
591 				snprintf(path, len, "%s/%d/file"
592 				    mp->mnt_stat.f_mntonname, pfs->pfs_pid);
593 			} else */ {
594 				bp = *bpp;
595 				*--bp = '/';
596 			}
597 		}
598 	}
599 
600 	if (bpp)
601 		*bpp = bp;
602 
603 	rw_exit(&cwdi->cwdi_lock);
604 }
605 
606 /*
607  * Invent attributes for pfsnode (vp) and store
608  * them in (vap).
609  * Directories lengths are returned as zero since
610  * any real length would require the genuine size
611  * to be computed, and nothing cares anyway.
612  *
613  * this is relatively minimal for procfs.
614  */
615 int
616 procfs_getattr(void *v)
617 {
618 	struct vop_getattr_args /* {
619 		struct vnode *a_vp;
620 		struct vattr *a_vap;
621 		kauth_cred_t a_cred;
622 	} */ *ap = v;
623 	struct pfsnode *pfs = VTOPFS(ap->a_vp);
624 	struct vattr *vap = ap->a_vap;
625 	struct proc *procp;
626 	char *path;
627 	int error;
628 
629 	/* first check the process still exists */
630 	switch (pfs->pfs_type) {
631 	case PFSroot:
632 	case PFScurproc:
633 	case PFSself:
634 		procp = NULL;
635 		break;
636 
637 	default:
638 		error = procfs_proc_lock(pfs->pfs_pid, &procp, ENOENT);
639 		if (error != 0)
640 			return (error);
641 		break;
642 	}
643 
644 	switch (pfs->pfs_type) {
645 	case PFStask:
646 		if (pfs->pfs_fd == -1) {
647 			path = NULL;
648 			break;
649 		}
650 		/*FALLTHROUGH*/
651 	case PFScwd:
652 	case PFSchroot:
653 	case PFSexe:
654 		path = malloc(MAXPATHLEN + 4, M_TEMP, M_WAITOK|M_CANFAIL);
655 		if (path == NULL && procp != NULL) {
656 			procfs_proc_unlock(procp);
657 			return (ENOMEM);
658 		}
659 		break;
660 
661 	default:
662 		path = NULL;
663 		break;
664 	}
665 
666 	if (procp != NULL) {
667 		mutex_enter(procp->p_lock);
668 		error = kauth_authorize_process(kauth_cred_get(),
669 		    KAUTH_PROCESS_CANSEE, procp,
670 		    KAUTH_ARG(KAUTH_REQ_PROCESS_CANSEE_ENTRY), NULL, NULL);
671 		mutex_exit(procp->p_lock);
672 		if (error != 0) {
673 		    	procfs_proc_unlock(procp);
674 		    	if (path != NULL)
675 		    		free(path, M_TEMP);
676 			return (ENOENT);
677 		}
678 	}
679 
680 	error = 0;
681 
682 	/* start by zeroing out the attributes */
683 	vattr_null(vap);
684 
685 	/* next do all the common fields */
686 	vap->va_type = ap->a_vp->v_type;
687 	vap->va_mode = pfs->pfs_mode;
688 	vap->va_fileid = pfs->pfs_fileno;
689 	vap->va_flags = 0;
690 	vap->va_blocksize = PAGE_SIZE;
691 
692 	/*
693 	 * Make all times be current TOD.
694 	 *
695 	 * It would be possible to get the process start
696 	 * time from the p_stats structure, but there's
697 	 * no "file creation" time stamp anyway, and the
698 	 * p_stats structure is not addressable if u. gets
699 	 * swapped out for that process.
700 	 */
701 	getnanotime(&vap->va_ctime);
702 	vap->va_atime = vap->va_mtime = vap->va_ctime;
703 	if (procp)
704 		TIMEVAL_TO_TIMESPEC(&procp->p_stats->p_start,
705 		    &vap->va_birthtime);
706 	else
707 		getnanotime(&vap->va_birthtime);
708 
709 	switch (pfs->pfs_type) {
710 	case PFSmem:
711 	case PFSregs:
712 	case PFSfpregs:
713 #if defined(__HAVE_PROCFS_MACHDEP) && defined(PROCFS_MACHDEP_PROTECT_CASES)
714 	PROCFS_MACHDEP_PROTECT_CASES
715 #endif
716 		/*
717 		 * If the process has exercised some setuid or setgid
718 		 * privilege, then rip away read/write permission so
719 		 * that only root can gain access.
720 		 */
721 		if (procp->p_flag & PK_SUGID)
722 			vap->va_mode &= ~(S_IRUSR|S_IWUSR);
723 		/* FALLTHROUGH */
724 	case PFSctl:
725 	case PFSstatus:
726 	case PFSstat:
727 	case PFSnote:
728 	case PFSnotepg:
729 	case PFSmap:
730 	case PFSmaps:
731 	case PFScmdline:
732 	case PFSemul:
733 	case PFSstatm:
734 		if (pfs->pfs_type == PFSmap || pfs->pfs_type == PFSmaps)
735 			vap->va_mode = S_IRUSR;
736 		vap->va_nlink = 1;
737 		vap->va_uid = kauth_cred_geteuid(procp->p_cred);
738 		vap->va_gid = kauth_cred_getegid(procp->p_cred);
739 		break;
740 	case PFSmeminfo:
741 	case PFSdevices:
742 	case PFScpuinfo:
743 	case PFSuptime:
744 	case PFSmounts:
745 	case PFScpustat:
746 	case PFSloadavg:
747 	case PFSversion:
748 		vap->va_nlink = 1;
749 		vap->va_uid = vap->va_gid = 0;
750 		break;
751 
752 	default:
753 		break;
754 	}
755 
756 	/*
757 	 * now do the object specific fields
758 	 *
759 	 * The size could be set from struct reg, but it's hardly
760 	 * worth the trouble, and it puts some (potentially) machine
761 	 * dependent data into this machine-independent code.  If it
762 	 * becomes important then this function should break out into
763 	 * a per-file stat function in the corresponding .c file.
764 	 */
765 
766 	switch (pfs->pfs_type) {
767 	case PFSroot:
768 		/*
769 		 * Set nlink to 1 to tell fts(3) we don't actually know.
770 		 */
771 		vap->va_nlink = 1;
772 		vap->va_uid = 0;
773 		vap->va_gid = 0;
774 		vap->va_bytes = vap->va_size = DEV_BSIZE;
775 		break;
776 
777 	case PFSself:
778 	case PFScurproc: {
779 		char bf[16];		/* should be enough */
780 		vap->va_nlink = 1;
781 		vap->va_uid = 0;
782 		vap->va_gid = 0;
783 		vap->va_bytes = vap->va_size =
784 		    snprintf(bf, sizeof(bf), "%ld", (long)curproc->p_pid);
785 		break;
786 	}
787 	case PFStask:
788 		if (pfs->pfs_fd != -1) {
789 			char bf[4];		/* should be enough */
790 			vap->va_nlink = 1;
791 			vap->va_uid = 0;
792 			vap->va_gid = 0;
793 			vap->va_bytes = vap->va_size =
794 			    snprintf(bf, sizeof(bf), "..");
795 			break;
796 		}
797 		/*FALLTHROUGH*/
798 	case PFSfd:
799 		if (pfs->pfs_fd != -1) {
800 			file_t *fp;
801 
802 			fp = fd_getfile2(procp, pfs->pfs_fd);
803 			if (fp == NULL) {
804 				error = EBADF;
805 				break;
806 			}
807 			vap->va_nlink = 1;
808 			vap->va_uid = kauth_cred_geteuid(fp->f_cred);
809 			vap->va_gid = kauth_cred_getegid(fp->f_cred);
810 			switch (fp->f_type) {
811 			case DTYPE_VNODE:
812 				vap->va_bytes = vap->va_size =
813 				    ((struct vnode *)fp->f_data)->v_size;
814 				break;
815 			default:
816 				vap->va_bytes = vap->va_size = 0;
817 				break;
818 			}
819 			closef(fp);
820 			break;
821 		}
822 		/*FALLTHROUGH*/
823 	case PFSproc:
824 		vap->va_nlink = 2;
825 		vap->va_uid = kauth_cred_geteuid(procp->p_cred);
826 		vap->va_gid = kauth_cred_getegid(procp->p_cred);
827 		vap->va_bytes = vap->va_size = DEV_BSIZE;
828 		break;
829 
830 	case PFSfile:
831 		error = EOPNOTSUPP;
832 		break;
833 
834 	case PFSmem:
835 		vap->va_bytes = vap->va_size =
836 			ctob(procp->p_vmspace->vm_tsize +
837 				    procp->p_vmspace->vm_dsize +
838 				    procp->p_vmspace->vm_ssize);
839 		break;
840 
841 #if defined(PT_GETREGS) || defined(PT_SETREGS)
842 	case PFSregs:
843 		vap->va_bytes = vap->va_size = sizeof(struct reg);
844 		break;
845 #endif
846 
847 #if defined(PT_GETFPREGS) || defined(PT_SETFPREGS)
848 	case PFSfpregs:
849 		vap->va_bytes = vap->va_size = sizeof(struct fpreg);
850 		break;
851 #endif
852 
853 	case PFSctl:
854 	case PFSstatus:
855 	case PFSstat:
856 	case PFSnote:
857 	case PFSnotepg:
858 	case PFScmdline:
859 	case PFSmeminfo:
860 	case PFSdevices:
861 	case PFScpuinfo:
862 	case PFSuptime:
863 	case PFSmounts:
864 	case PFScpustat:
865 	case PFSloadavg:
866 	case PFSstatm:
867 	case PFSversion:
868 		vap->va_bytes = vap->va_size = 0;
869 		break;
870 	case PFSmap:
871 	case PFSmaps:
872 		/*
873 		 * Advise a larger blocksize for the map files, so that
874 		 * they may be read in one pass.
875 		 */
876 		vap->va_blocksize = 4 * PAGE_SIZE;
877 		vap->va_bytes = vap->va_size = 0;
878 		break;
879 
880 	case PFScwd:
881 	case PFSchroot:
882 	case PFSexe: {
883 		char *bp;
884 
885 		vap->va_nlink = 1;
886 		vap->va_uid = 0;
887 		vap->va_gid = 0;
888 		bp = path + MAXPATHLEN;
889 		*--bp = '\0';
890 		procfs_dir(pfs->pfs_type, curlwp, procp, &bp, path,
891 		     MAXPATHLEN);
892 		vap->va_bytes = vap->va_size = strlen(bp);
893 		break;
894 	}
895 
896 	case PFSemul:
897 		vap->va_bytes = vap->va_size = strlen(procp->p_emul->e_name);
898 		break;
899 
900 #ifdef __HAVE_PROCFS_MACHDEP
901 	PROCFS_MACHDEP_NODETYPE_CASES
902 		error = procfs_machdep_getattr(ap->a_vp, vap, procp);
903 		break;
904 #endif
905 
906 	default:
907 		panic("procfs_getattr");
908 	}
909 
910 	if (procp != NULL)
911 		procfs_proc_unlock(procp);
912 	if (path != NULL)
913 		free(path, M_TEMP);
914 
915 	return (error);
916 }
917 
918 /*ARGSUSED*/
919 int
920 procfs_setattr(void *v)
921 {
922 	/*
923 	 * just fake out attribute setting
924 	 * it's not good to generate an error
925 	 * return, otherwise things like creat()
926 	 * will fail when they try to set the
927 	 * file length to 0.  worse, this means
928 	 * that echo $note > /proc/$pid/note will fail.
929 	 */
930 
931 	return (0);
932 }
933 
934 /*
935  * implement access checking.
936  *
937  * actually, the check for super-user is slightly
938  * broken since it will allow read access to write-only
939  * objects.  this doesn't cause any particular trouble
940  * but does mean that the i/o entry points need to check
941  * that the operation really does make sense.
942  */
943 int
944 procfs_access(void *v)
945 {
946 	struct vop_access_args /* {
947 		struct vnode *a_vp;
948 		int a_mode;
949 		kauth_cred_t a_cred;
950 	} */ *ap = v;
951 	struct vattr va;
952 	int error;
953 
954 	if ((error = VOP_GETATTR(ap->a_vp, &va, ap->a_cred)) != 0)
955 		return (error);
956 
957 	return kauth_authorize_vnode(ap->a_cred,
958 	    kauth_access_action(ap->a_mode, ap->a_vp->v_type, va.va_mode),
959 	    ap->a_vp, NULL, genfs_can_access(va.va_type, va.va_mode,
960 	    va.va_uid, va.va_gid, ap->a_mode, ap->a_cred));
961 }
962 
963 /*
964  * lookup.  this is incredibly complicated in the
965  * general case, however for most pseudo-filesystems
966  * very little needs to be done.
967  *
968  * Locking isn't hard here, just poorly documented.
969  *
970  * If we're looking up ".", just vref the parent & return it.
971  *
972  * If we're looking up "..", unlock the parent, and lock "..". If everything
973  * went ok, and we're on the last component and the caller requested the
974  * parent locked, try to re-lock the parent. We do this to prevent lock
975  * races.
976  *
977  * For anything else, get the needed node. Then unlock the parent if not
978  * the last component or not LOCKPARENT (i.e. if we wouldn't re-lock the
979  * parent in the .. case).
980  *
981  * We try to exit with the parent locked in error cases.
982  */
983 int
984 procfs_lookup(void *v)
985 {
986 	struct vop_lookup_args /* {
987 		struct vnode * a_dvp;
988 		struct vnode ** a_vpp;
989 		struct componentname * a_cnp;
990 	} */ *ap = v;
991 	struct componentname *cnp = ap->a_cnp;
992 	struct vnode **vpp = ap->a_vpp;
993 	struct vnode *dvp = ap->a_dvp;
994 	const char *pname = cnp->cn_nameptr;
995 	const struct proc_target *pt = NULL;
996 	struct vnode *fvp;
997 	pid_t pid, vnpid;
998 	struct pfsnode *pfs;
999 	struct proc *p = NULL;
1000 	struct lwp *plwp;
1001 	int i, error;
1002 	pfstype type;
1003 
1004 	*vpp = NULL;
1005 
1006 	if (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)
1007 		return (EROFS);
1008 
1009 	if (cnp->cn_namelen == 1 && *pname == '.') {
1010 		*vpp = dvp;
1011 		vref(dvp);
1012 		return (0);
1013 	}
1014 
1015 	pfs = VTOPFS(dvp);
1016 	switch (pfs->pfs_type) {
1017 	case PFSroot:
1018 		/*
1019 		 * Shouldn't get here with .. in the root node.
1020 		 */
1021 		if (cnp->cn_flags & ISDOTDOT)
1022 			return (EIO);
1023 
1024 		for (i = 0; i < nproc_root_targets; i++) {
1025 			pt = &proc_root_targets[i];
1026 			/*
1027 			 * check for node match.  proc is always NULL here,
1028 			 * so call pt_valid with constant NULL lwp.
1029 			 */
1030 			if (cnp->cn_namelen == pt->pt_namlen &&
1031 			    memcmp(pt->pt_name, pname, cnp->cn_namelen) == 0 &&
1032 			    (pt->pt_valid == NULL ||
1033 			     (*pt->pt_valid)(NULL, dvp->v_mount)))
1034 				break;
1035 		}
1036 
1037 		if (i != nproc_root_targets) {
1038 			error = procfs_allocvp(dvp->v_mount, vpp, 0,
1039 			    pt->pt_pfstype, -1, NULL);
1040 			return (error);
1041 		}
1042 
1043 		if (CNEQ(cnp, "curproc", 7)) {
1044 			pid = curproc->p_pid;
1045 			vnpid = 0;
1046 			type = PFScurproc;
1047 		} else if (CNEQ(cnp, "self", 4)) {
1048 			pid = curproc->p_pid;
1049 			vnpid = 0;
1050 			type = PFSself;
1051 		} else {
1052 			pid = (pid_t)atoi(pname, cnp->cn_namelen);
1053 			vnpid = pid;
1054 			type = PFSproc;
1055 		}
1056 
1057 		if (procfs_proc_lock(pid, &p, ESRCH) != 0)
1058 			break;
1059 		error = procfs_allocvp(dvp->v_mount, vpp, vnpid, type, -1, p);
1060 		procfs_proc_unlock(p);
1061 		return (error);
1062 
1063 	case PFSproc:
1064 		/*
1065 		 * do the .. dance. We unlock the directory, and then
1066 		 * get the root dir. That will automatically return ..
1067 		 * locked. Then if the caller wanted dvp locked, we
1068 		 * re-lock.
1069 		 */
1070 		if (cnp->cn_flags & ISDOTDOT) {
1071 			VOP_UNLOCK(dvp);
1072 			error = procfs_root(dvp->v_mount, vpp);
1073 			vn_lock(dvp, LK_EXCLUSIVE | LK_RETRY);
1074 			return (error);
1075 		}
1076 
1077 		if (procfs_proc_lock(pfs->pfs_pid, &p, ESRCH) != 0)
1078 			break;
1079 
1080 		mutex_enter(p->p_lock);
1081 		LIST_FOREACH(plwp, &p->p_lwps, l_sibling) {
1082 			if (plwp->l_stat != LSZOMB)
1083 				break;
1084 		}
1085 		/* Process is exiting if no-LWPS or all LWPs are LSZOMB */
1086 		if (plwp == NULL) {
1087 			mutex_exit(p->p_lock);
1088 			procfs_proc_unlock(p);
1089 			return ESRCH;
1090 		}
1091 
1092 		lwp_addref(plwp);
1093 		mutex_exit(p->p_lock);
1094 
1095 		for (pt = proc_targets, i = 0; i < nproc_targets; pt++, i++) {
1096 			int found;
1097 
1098 			found = cnp->cn_namelen == pt->pt_namlen &&
1099 			    memcmp(pt->pt_name, pname, cnp->cn_namelen) == 0 &&
1100 			    (pt->pt_valid == NULL
1101 			      || (*pt->pt_valid)(plwp, dvp->v_mount));
1102 			if (found)
1103 				break;
1104 		}
1105 		lwp_delref(plwp);
1106 
1107 		if (i == nproc_targets) {
1108 			procfs_proc_unlock(p);
1109 			break;
1110 		}
1111 		if (pt->pt_pfstype == PFSfile) {
1112 			fvp = p->p_textvp;
1113 			/* We already checked that it exists. */
1114 			vref(fvp);
1115 			procfs_proc_unlock(p);
1116 			vn_lock(fvp, LK_EXCLUSIVE | LK_RETRY);
1117 			*vpp = fvp;
1118 			return (0);
1119 		}
1120 
1121 		error = procfs_allocvp(dvp->v_mount, vpp, pfs->pfs_pid,
1122 		    pt->pt_pfstype, -1, p);
1123 		procfs_proc_unlock(p);
1124 		return (error);
1125 
1126 	case PFSfd: {
1127 		int fd;
1128 		file_t *fp;
1129 
1130 		if ((error = procfs_proc_lock(pfs->pfs_pid, &p, ENOENT)) != 0)
1131 			return error;
1132 
1133 		/*
1134 		 * do the .. dance. We unlock the directory, and then
1135 		 * get the proc dir. That will automatically return ..
1136 		 * locked. Then re-lock the directory.
1137 		 */
1138 		if (cnp->cn_flags & ISDOTDOT) {
1139 			VOP_UNLOCK(dvp);
1140 			error = procfs_allocvp(dvp->v_mount, vpp, pfs->pfs_pid,
1141 			    PFSproc, -1, p);
1142 			procfs_proc_unlock(p);
1143 			vn_lock(dvp, LK_EXCLUSIVE | LK_RETRY);
1144 			return (error);
1145 		}
1146 		fd = atoi(pname, cnp->cn_namelen);
1147 
1148 		fp = fd_getfile2(p, fd);
1149 		if (fp == NULL) {
1150 			procfs_proc_unlock(p);
1151 			return ENOENT;
1152 		}
1153 		fvp = fp->f_data;
1154 
1155 		/* Don't show directories */
1156 		if (fp->f_type == DTYPE_VNODE && fvp->v_type != VDIR) {
1157 			vref(fvp);
1158 			closef(fp);
1159 			procfs_proc_unlock(p);
1160 			vn_lock(fvp, LK_EXCLUSIVE | LK_RETRY);
1161 			*vpp = fvp;
1162 			return 0;
1163 		}
1164 
1165 		closef(fp);
1166 		error = procfs_allocvp(dvp->v_mount, vpp, pfs->pfs_pid,
1167 		    PFSfd, fd, p);
1168 		procfs_proc_unlock(p);
1169 		return error;
1170 	}
1171 	case PFStask: {
1172 		int xpid;
1173 
1174 		if ((error = procfs_proc_lock(pfs->pfs_pid, &p, ENOENT)) != 0)
1175 			return error;
1176 
1177 		/*
1178 		 * do the .. dance. We unlock the directory, and then
1179 		 * get the proc dir. That will automatically return ..
1180 		 * locked. Then re-lock the directory.
1181 		 */
1182 		if (cnp->cn_flags & ISDOTDOT) {
1183 			VOP_UNLOCK(dvp);
1184 			error = procfs_allocvp(dvp->v_mount, vpp, pfs->pfs_pid,
1185 			    PFSproc, -1, p);
1186 			procfs_proc_unlock(p);
1187 			vn_lock(dvp, LK_EXCLUSIVE | LK_RETRY);
1188 			return (error);
1189 		}
1190 		xpid = atoi(pname, cnp->cn_namelen);
1191 
1192 		if (xpid != pfs->pfs_pid) {
1193 			procfs_proc_unlock(p);
1194 			return ENOENT;
1195 		}
1196 		error = procfs_allocvp(dvp->v_mount, vpp, pfs->pfs_pid,
1197 		    PFStask, 0, p);
1198 		procfs_proc_unlock(p);
1199 		return error;
1200 	}
1201 	default:
1202 		return (ENOTDIR);
1203 	}
1204 
1205 	return (cnp->cn_nameiop == LOOKUP ? ENOENT : EROFS);
1206 }
1207 
1208 int
1209 procfs_validfile(struct lwp *l, struct mount *mp)
1210 {
1211 	return l != NULL && l->l_proc != NULL && l->l_proc->p_textvp != NULL;
1212 }
1213 
1214 static int
1215 procfs_validfile_linux(struct lwp *l, struct mount *mp)
1216 {
1217 	int flags;
1218 
1219 	flags = VFSTOPROC(mp)->pmnt_flags;
1220 	return (flags & PROCFSMNT_LINUXCOMPAT) &&
1221 	    (l == NULL || l->l_proc == NULL || procfs_validfile(l, mp));
1222 }
1223 
1224 struct procfs_root_readdir_ctx {
1225 	struct uio *uiop;
1226 	off_t *cookies;
1227 	int ncookies;
1228 	off_t off;
1229 	off_t startoff;
1230 	int error;
1231 };
1232 
1233 static int
1234 procfs_root_readdir_callback(struct proc *p, void *arg)
1235 {
1236 	struct procfs_root_readdir_ctx *ctxp = arg;
1237 	struct dirent d;
1238 	struct uio *uiop;
1239 	int error;
1240 
1241 	uiop = ctxp->uiop;
1242 	if (uiop->uio_resid < UIO_MX)
1243 		return -1; /* no space */
1244 
1245 	if (ctxp->off < ctxp->startoff) {
1246 		ctxp->off++;
1247 		return 0;
1248 	}
1249 
1250 	if (kauth_authorize_process(kauth_cred_get(),
1251 	    KAUTH_PROCESS_CANSEE, p,
1252 	    KAUTH_ARG(KAUTH_REQ_PROCESS_CANSEE_ENTRY), NULL, NULL) != 0)
1253 		return 0;
1254 
1255 	memset(&d, 0, UIO_MX);
1256 	d.d_reclen = UIO_MX;
1257 	d.d_fileno = PROCFS_FILENO(p->p_pid, PFSproc, -1);
1258 	d.d_namlen = snprintf(d.d_name,
1259 	    UIO_MX - offsetof(struct dirent, d_name), "%ld", (long)p->p_pid);
1260 	d.d_type = DT_DIR;
1261 
1262 	mutex_exit(proc_lock);
1263 	error = uiomove(&d, UIO_MX, uiop);
1264 	mutex_enter(proc_lock);
1265 	if (error) {
1266 		ctxp->error = error;
1267 		return -1;
1268 	}
1269 
1270 	ctxp->ncookies++;
1271 	if (ctxp->cookies)
1272 		*(ctxp->cookies)++ = ctxp->off + 1;
1273 	ctxp->off++;
1274 
1275 	return 0;
1276 }
1277 
1278 /*
1279  * readdir returns directory entries from pfsnode (vp).
1280  *
1281  * the strategy here with procfs is to generate a single
1282  * directory entry at a time (struct dirent) and then
1283  * copy that out to userland using uiomove.  a more efficent
1284  * though more complex implementation, would try to minimize
1285  * the number of calls to uiomove().  for procfs, this is
1286  * hardly worth the added code complexity.
1287  *
1288  * this should just be done through read()
1289  */
1290 int
1291 procfs_readdir(void *v)
1292 {
1293 	struct vop_readdir_args /* {
1294 		struct vnode *a_vp;
1295 		struct uio *a_uio;
1296 		kauth_cred_t a_cred;
1297 		int *a_eofflag;
1298 		off_t **a_cookies;
1299 		int *a_ncookies;
1300 	} */ *ap = v;
1301 	struct uio *uio = ap->a_uio;
1302 	struct dirent d;
1303 	struct pfsnode *pfs;
1304 	off_t i;
1305 	int error;
1306 	off_t *cookies = NULL;
1307 	int ncookies;
1308 	struct vnode *vp;
1309 	const struct proc_target *pt;
1310 	struct procfs_root_readdir_ctx ctx;
1311 	struct lwp *l;
1312 	int nfd;
1313 
1314 	vp = ap->a_vp;
1315 	pfs = VTOPFS(vp);
1316 
1317 	if (uio->uio_resid < UIO_MX)
1318 		return (EINVAL);
1319 	if (uio->uio_offset < 0)
1320 		return (EINVAL);
1321 
1322 	error = 0;
1323 	i = uio->uio_offset;
1324 	memset(&d, 0, UIO_MX);
1325 	d.d_reclen = UIO_MX;
1326 	ncookies = uio->uio_resid / UIO_MX;
1327 
1328 	switch (pfs->pfs_type) {
1329 	/*
1330 	 * this is for the process-specific sub-directories.
1331 	 * all that is needed to is copy out all the entries
1332 	 * from the procent[] table (top of this file).
1333 	 */
1334 	case PFSproc: {
1335 		struct proc *p;
1336 
1337 		if (i >= nproc_targets)
1338 			return 0;
1339 
1340 		if (procfs_proc_lock(pfs->pfs_pid, &p, ESRCH) != 0)
1341 			break;
1342 
1343 		if (ap->a_ncookies) {
1344 			ncookies = min(ncookies, (nproc_targets - i));
1345 			cookies = malloc(ncookies * sizeof (off_t),
1346 			    M_TEMP, M_WAITOK);
1347 			*ap->a_cookies = cookies;
1348 		}
1349 
1350 		for (pt = &proc_targets[i];
1351 		     uio->uio_resid >= UIO_MX && i < nproc_targets; pt++, i++) {
1352 			if (pt->pt_valid) {
1353 				/* XXXSMP LWP can disappear */
1354 				mutex_enter(p->p_lock);
1355 				l = LIST_FIRST(&p->p_lwps);
1356 				KASSERT(l != NULL);
1357 				mutex_exit(p->p_lock);
1358 				if ((*pt->pt_valid)(l, vp->v_mount) == 0)
1359 					continue;
1360 			}
1361 
1362 			d.d_fileno = PROCFS_FILENO(pfs->pfs_pid,
1363 			    pt->pt_pfstype, -1);
1364 			d.d_namlen = pt->pt_namlen;
1365 			memcpy(d.d_name, pt->pt_name, pt->pt_namlen + 1);
1366 			d.d_type = pt->pt_type;
1367 
1368 			if ((error = uiomove(&d, UIO_MX, uio)) != 0)
1369 				break;
1370 			if (cookies)
1371 				*cookies++ = i + 1;
1372 		}
1373 
1374 		procfs_proc_unlock(p);
1375 	    	break;
1376 	}
1377 	case PFSfd: {
1378 		struct proc *p;
1379 		file_t *fp;
1380 		int lim, nc = 0;
1381 
1382 		if ((error = procfs_proc_lock(pfs->pfs_pid, &p, ESRCH)) != 0)
1383 			return error;
1384 
1385 		/* XXX Should this be by file as well? */
1386 		if (kauth_authorize_process(kauth_cred_get(),
1387 		    KAUTH_PROCESS_CANSEE, p,
1388 		    KAUTH_ARG(KAUTH_REQ_PROCESS_CANSEE_OPENFILES), NULL,
1389 		    NULL) != 0) {
1390 		    	procfs_proc_unlock(p);
1391 			return ESRCH;
1392 		}
1393 
1394 		nfd = p->p_fd->fd_dt->dt_nfiles;
1395 
1396 		lim = min((int)p->p_rlimit[RLIMIT_NOFILE].rlim_cur, maxfiles);
1397 		if (i >= lim) {
1398 		    	procfs_proc_unlock(p);
1399 			return 0;
1400 		}
1401 
1402 		if (ap->a_ncookies) {
1403 			ncookies = min(ncookies, (nfd + 2 - i));
1404 			cookies = malloc(ncookies * sizeof (off_t),
1405 			    M_TEMP, M_WAITOK);
1406 			*ap->a_cookies = cookies;
1407 		}
1408 
1409 		for (; i < 2 && uio->uio_resid >= UIO_MX; i++) {
1410 			pt = &proc_targets[i];
1411 			d.d_namlen = pt->pt_namlen;
1412 			d.d_fileno = PROCFS_FILENO(pfs->pfs_pid,
1413 			    pt->pt_pfstype, -1);
1414 			(void)memcpy(d.d_name, pt->pt_name, pt->pt_namlen + 1);
1415 			d.d_type = pt->pt_type;
1416 			if ((error = uiomove(&d, UIO_MX, uio)) != 0)
1417 				break;
1418 			if (cookies)
1419 				*cookies++ = i + 1;
1420 			nc++;
1421 		}
1422 		if (error) {
1423 			ncookies = nc;
1424 			break;
1425 		}
1426 		for (; uio->uio_resid >= UIO_MX && i < nfd; i++) {
1427 			/* check the descriptor exists */
1428 			if ((fp = fd_getfile2(p, i - 2)) == NULL)
1429 				continue;
1430 			closef(fp);
1431 
1432 			d.d_fileno = PROCFS_FILENO(pfs->pfs_pid, PFSfd, i - 2);
1433 			d.d_namlen = snprintf(d.d_name, sizeof(d.d_name),
1434 			    "%lld", (long long)(i - 2));
1435 			d.d_type = VREG;
1436 			if ((error = uiomove(&d, UIO_MX, uio)) != 0)
1437 				break;
1438 			if (cookies)
1439 				*cookies++ = i + 1;
1440 			nc++;
1441 		}
1442 		ncookies = nc;
1443 		procfs_proc_unlock(p);
1444 		break;
1445 	}
1446 	case PFStask: {
1447 		struct proc *p;
1448 		int nc = 0;
1449 
1450 		if ((error = procfs_proc_lock(pfs->pfs_pid, &p, ESRCH)) != 0)
1451 			return error;
1452 
1453 		nfd = 3;	/* ., .., pid */
1454 
1455 		if (ap->a_ncookies) {
1456 			ncookies = min(ncookies, (nfd + 2 - i));
1457 			cookies = malloc(ncookies * sizeof (off_t),
1458 			    M_TEMP, M_WAITOK);
1459 			*ap->a_cookies = cookies;
1460 		}
1461 
1462 		for (; i < 2 && uio->uio_resid >= UIO_MX; i++) {
1463 			pt = &proc_targets[i];
1464 			d.d_namlen = pt->pt_namlen;
1465 			d.d_fileno = PROCFS_FILENO(pfs->pfs_pid,
1466 			    pt->pt_pfstype, -1);
1467 			(void)memcpy(d.d_name, pt->pt_name, pt->pt_namlen + 1);
1468 			d.d_type = pt->pt_type;
1469 			if ((error = uiomove(&d, UIO_MX, uio)) != 0)
1470 				break;
1471 			if (cookies)
1472 				*cookies++ = i + 1;
1473 			nc++;
1474 		}
1475 		if (error) {
1476 			ncookies = nc;
1477 			break;
1478 		}
1479 		for (; uio->uio_resid >= UIO_MX && i < nfd; i++) {
1480 			/* check the descriptor exists */
1481 			d.d_fileno = PROCFS_FILENO(pfs->pfs_pid, PFStask,
1482 			    i - 2);
1483 			d.d_namlen = snprintf(d.d_name, sizeof(d.d_name),
1484 			    "%ld", (long)pfs->pfs_pid);
1485 			d.d_type = DT_LNK;
1486 			if ((error = uiomove(&d, UIO_MX, uio)) != 0)
1487 				break;
1488 			if (cookies)
1489 				*cookies++ = i + 1;
1490 			nc++;
1491 		}
1492 		ncookies = nc;
1493 		procfs_proc_unlock(p);
1494 		break;
1495 	}
1496 
1497 	/*
1498 	 * this is for the root of the procfs filesystem
1499 	 * what is needed are special entries for "curproc"
1500 	 * and "self" followed by an entry for each process
1501 	 * on allproc.
1502 	 */
1503 
1504 	case PFSroot: {
1505 		int nc = 0;
1506 
1507 		if (ap->a_ncookies) {
1508 			/*
1509 			 * XXX Potentially allocating too much space here,
1510 			 * but I'm lazy. This loop needs some work.
1511 			 */
1512 			cookies = malloc(ncookies * sizeof (off_t),
1513 			    M_TEMP, M_WAITOK);
1514 			*ap->a_cookies = cookies;
1515 		}
1516 		error = 0;
1517 		/* 0 ... 3 are static entries. */
1518 		for (; i <= 3 && uio->uio_resid >= UIO_MX; i++) {
1519 			switch (i) {
1520 			case 0:		/* `.' */
1521 			case 1:		/* `..' */
1522 				d.d_fileno = PROCFS_FILENO(0, PFSroot, -1);
1523 				d.d_namlen = i + 1;
1524 				memcpy(d.d_name, "..", d.d_namlen);
1525 				d.d_name[i + 1] = '\0';
1526 				d.d_type = DT_DIR;
1527 				break;
1528 
1529 			case 2:
1530 				d.d_fileno = PROCFS_FILENO(0, PFScurproc, -1);
1531 				d.d_namlen = sizeof("curproc") - 1;
1532 				memcpy(d.d_name, "curproc", sizeof("curproc"));
1533 				d.d_type = DT_LNK;
1534 				break;
1535 
1536 			case 3:
1537 				d.d_fileno = PROCFS_FILENO(0, PFSself, -1);
1538 				d.d_namlen = sizeof("self") - 1;
1539 				memcpy(d.d_name, "self", sizeof("self"));
1540 				d.d_type = DT_LNK;
1541 				break;
1542 			}
1543 
1544 			if ((error = uiomove(&d, UIO_MX, uio)) != 0)
1545 				break;
1546 			nc++;
1547 			if (cookies)
1548 				*cookies++ = i + 1;
1549 		}
1550 		/* 4 ... are process entries. */
1551 		ctx.uiop = uio;
1552 		ctx.error = 0;
1553 		ctx.off = 4;
1554 		ctx.startoff = i;
1555 		ctx.cookies = cookies;
1556 		ctx.ncookies = nc;
1557 		proclist_foreach_call(&allproc,
1558 		    procfs_root_readdir_callback, &ctx);
1559 		cookies = ctx.cookies;
1560 		nc = ctx.ncookies;
1561 		error = ctx.error;
1562 		if (error)
1563 			break;
1564 
1565 		/* misc entries. */
1566 		if (i < ctx.off)
1567 			i = ctx.off;
1568 		if (i >= ctx.off + nproc_root_targets)
1569 			break;
1570 		for (pt = &proc_root_targets[i - ctx.off];
1571 		    uio->uio_resid >= UIO_MX &&
1572 		    pt < &proc_root_targets[nproc_root_targets];
1573 		    pt++, i++) {
1574 			if (pt->pt_valid &&
1575 			    (*pt->pt_valid)(NULL, vp->v_mount) == 0)
1576 				continue;
1577 			d.d_fileno = PROCFS_FILENO(0, pt->pt_pfstype, -1);
1578 			d.d_namlen = pt->pt_namlen;
1579 			memcpy(d.d_name, pt->pt_name, pt->pt_namlen + 1);
1580 			d.d_type = pt->pt_type;
1581 
1582 			if ((error = uiomove(&d, UIO_MX, uio)) != 0)
1583 				break;
1584 			nc++;
1585 			if (cookies)
1586 				*cookies++ = i + 1;
1587 		}
1588 
1589 		ncookies = nc;
1590 		break;
1591 	}
1592 
1593 	default:
1594 		error = ENOTDIR;
1595 		break;
1596 	}
1597 
1598 	if (ap->a_ncookies) {
1599 		if (error) {
1600 			if (cookies)
1601 				free(*ap->a_cookies, M_TEMP);
1602 			*ap->a_ncookies = 0;
1603 			*ap->a_cookies = NULL;
1604 		} else
1605 			*ap->a_ncookies = ncookies;
1606 	}
1607 	uio->uio_offset = i;
1608 	return (error);
1609 }
1610 
1611 /*
1612  * readlink reads the link of `curproc' and others
1613  */
1614 int
1615 procfs_readlink(void *v)
1616 {
1617 	struct vop_readlink_args *ap = v;
1618 	char bf[16];		/* should be enough */
1619 	char *bp = bf;
1620 	char *path = NULL;
1621 	int len = 0;
1622 	int error = 0;
1623 	struct pfsnode *pfs = VTOPFS(ap->a_vp);
1624 	struct proc *pown;
1625 
1626 	if (pfs->pfs_fileno == PROCFS_FILENO(0, PFScurproc, -1))
1627 		len = snprintf(bf, sizeof(bf), "%ld", (long)curproc->p_pid);
1628 	else if (pfs->pfs_fileno == PROCFS_FILENO(0, PFSself, -1))
1629 		len = snprintf(bf, sizeof(bf), "%s", "curproc");
1630 	else if (pfs->pfs_fileno == PROCFS_FILENO(pfs->pfs_pid, PFStask, 0))
1631 		len = snprintf(bf, sizeof(bf), "..");
1632 	else if (pfs->pfs_fileno == PROCFS_FILENO(pfs->pfs_pid, PFScwd, -1) ||
1633 	    pfs->pfs_fileno == PROCFS_FILENO(pfs->pfs_pid, PFSchroot, -1) ||
1634 	    pfs->pfs_fileno == PROCFS_FILENO(pfs->pfs_pid, PFSexe, -1)) {
1635 		if ((error = procfs_proc_lock(pfs->pfs_pid, &pown, ESRCH)) != 0)
1636 			return error;
1637 		path = malloc(MAXPATHLEN + 4, M_TEMP, M_WAITOK|M_CANFAIL);
1638 		if (path == NULL) {
1639 			procfs_proc_unlock(pown);
1640 			return (ENOMEM);
1641 		}
1642 		bp = path + MAXPATHLEN;
1643 		*--bp = '\0';
1644 		procfs_dir(PROCFS_TYPE(pfs->pfs_fileno), curlwp, pown,
1645 		    &bp, path, MAXPATHLEN);
1646 		procfs_proc_unlock(pown);
1647 		len = strlen(bp);
1648 	} else {
1649 		file_t *fp;
1650 		struct vnode *vxp, *vp;
1651 
1652 		if ((error = procfs_proc_lock(pfs->pfs_pid, &pown, ESRCH)) != 0)
1653 			return error;
1654 
1655 		fp = fd_getfile2(pown, pfs->pfs_fd);
1656 		if (fp == NULL) {
1657 			procfs_proc_unlock(pown);
1658 			return EBADF;
1659 		}
1660 
1661 		switch (fp->f_type) {
1662 		case DTYPE_VNODE:
1663 			vxp = (struct vnode *)fp->f_data;
1664 			if (vxp->v_type != VDIR) {
1665 				error = EINVAL;
1666 				break;
1667 			}
1668 			if ((path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK))
1669 			    == NULL) {
1670 				error = ENOMEM;
1671 				break;
1672 			}
1673 			bp = path + MAXPATHLEN;
1674 			*--bp = '\0';
1675 
1676 			/*
1677 			 * XXX: kludge to avoid locking against ourselves
1678 			 * in getcwd()
1679 			 */
1680 			if (vxp->v_tag == VT_PROCFS) {
1681 				*--bp = '/';
1682 			} else {
1683 				rw_enter(&curproc->p_cwdi->cwdi_lock,
1684 				    RW_READER);
1685 				vp = curproc->p_cwdi->cwdi_rdir;
1686 				if (vp == NULL)
1687 					vp = rootvnode;
1688 				error = getcwd_common(vxp, vp, &bp, path,
1689 				    MAXPATHLEN / 2, 0, curlwp);
1690 				rw_exit(&curproc->p_cwdi->cwdi_lock);
1691 			}
1692 			if (error)
1693 				break;
1694 			len = strlen(bp);
1695 			break;
1696 
1697 		case DTYPE_MISC:
1698 			len = snprintf(bf, sizeof(bf), "%s", "[misc]");
1699 			break;
1700 
1701 		case DTYPE_KQUEUE:
1702 			len = snprintf(bf, sizeof(bf), "%s", "[kqueue]");
1703 			break;
1704 
1705 		case DTYPE_SEM:
1706 			len = snprintf(bf, sizeof(bf), "%s", "[ksem]");
1707 			break;
1708 
1709 		default:
1710 			error = EINVAL;
1711 			break;
1712 		}
1713 		closef(fp);
1714 		procfs_proc_unlock(pown);
1715 	}
1716 
1717 	if (error == 0)
1718 		error = uiomove(bp, len, ap->a_uio);
1719 	if (path)
1720 		free(path, M_TEMP);
1721 	return error;
1722 }
1723 
1724 /*
1725  * convert decimal ascii to int
1726  */
1727 static int
1728 atoi(const char *b, size_t len)
1729 {
1730 	int p = 0;
1731 
1732 	while (len--) {
1733 		char c = *b++;
1734 		if (c < '0' || c > '9')
1735 			return -1;
1736 		p = 10 * p + (c - '0');
1737 	}
1738 
1739 	return p;
1740 }
1741