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