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