xref: /dragonfly/usr.sbin/pstat/pstat.c (revision 8a7bdfea)
1 /*-
2  * Copyright (c) 1980, 1991, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * @(#) Copyright (c) 1980, 1991, 1993, 1994 The Regents of the University of California.  All rights reserved.
34  * @(#)pstat.c	8.16 (Berkeley) 5/9/95
35  * $FreeBSD: src/usr.sbin/pstat/pstat.c,v 1.49.2.5 2002/07/12 09:12:49 des Exp $
36  * $DragonFly: src/usr.sbin/pstat/pstat.c,v 1.22 2008/03/04 18:10:44 swildner Exp $
37  */
38 
39 #define _KERNEL_STRUCTURES
40 
41 #include <sys/param.h>
42 #include <sys/time.h>
43 #include <sys/vnode.h>
44 #include <sys/ucred.h>
45 #include <sys/file.h>
46 #include <vfs/ufs/quota.h>
47 #include <vfs/ufs/inode.h>
48 #include <sys/mount.h>
49 #include <sys/uio.h>
50 #include <sys/namei.h>
51 #include <vfs/union/union.h>
52 #include <sys/stat.h>
53 #include <nfs/rpcv2.h>
54 #include <nfs/nfsproto.h>
55 #include <nfs/nfs.h>
56 #include <nfs/nfsnode.h>
57 #include <sys/ioctl.h>
58 #include <sys/ioctl_compat.h>	/* XXX NTTYDISC is too well hidden */
59 #include <sys/tty.h>
60 #include <sys/conf.h>
61 #include <sys/blist.h>
62 
63 #include <sys/kinfo.h>
64 #include <sys/user.h>
65 #include <sys/sysctl.h>
66 
67 #include <err.h>
68 #include <fcntl.h>
69 #include <kvm.h>
70 #include <limits.h>
71 #include <nlist.h>
72 #include <stdio.h>
73 #include <stdlib.h>
74 #include <string.h>
75 #include <unistd.h>
76 
77 #ifdef USE_KCORE
78 #  define KCORE_KINFO_WRAPPER
79 #  include <kcore.h>
80 #else
81 #  include <kinfo.h>
82 #endif
83 
84 enum {
85 	NL_MOUNTLIST,
86 	NL_NUMVNODES,
87 	NL_RC_TTY,
88 	NL_NRC_TTY,
89 	NL_CY_TTY,
90 	NL_NCY_TTY,
91 	NL_SI_TTY,
92 	NL_SI_NPORTS,
93 };
94 
95 const size_t NL_LAST_MANDATORY = NL_NUMVNODES;
96 
97 struct nlist nl[] = {
98 	{ "_mountlist", 0, 0, 0, 0 },	/* address of head of mount list. */
99 	{ "_numvnodes", 0, 0, 0, 0 },
100 	{ "_rc_tty", 0, 0, 0, 0 },
101 	{ "_nrc_tty", 0, 0, 0, 0 },
102 	{ "_cy_tty", 0, 0, 0, 0 },
103 	{ "_ncy_tty", 0, 0, 0, 0 },
104 	{ "_si__tty", 0, 0, 0, 0 },
105 	{ "_si_Nports", 0, 0, 0, 0 },
106 	{ "", 0, 0, 0, 0 }
107 };
108 
109 int	usenumflag;
110 int	totalflag;
111 int	swapflag;
112 char	*nlistf	= NULL;
113 char	*memf	= NULL;
114 kvm_t	*kd;
115 
116 const char	*usagestr;
117 
118 struct {
119 	int m_flag;
120 	const char *m_name;
121 } mnt_flags[] = {
122 	{ MNT_RDONLY, "rdonly" },
123 	{ MNT_SYNCHRONOUS, "sync" },
124 	{ MNT_NOEXEC, "noexec" },
125 	{ MNT_NOSUID, "nosuid" },
126 	{ MNT_NODEV, "nodev" },
127 	{ MNT_UNION, "union" },
128 	{ MNT_ASYNC, "async" },
129 	{ MNT_SUIDDIR, "suiddir" },
130 	{ MNT_SOFTDEP, "softdep" },
131 	{ MNT_NOSYMFOLLOW, "nosymfollow" },
132 	{ MNT_NOATIME, "noatime" },
133 	{ MNT_NOCLUSTERR, "noclusterread" },
134 	{ MNT_NOCLUSTERW, "noclusterwrite" },
135 	{ MNT_EXRDONLY, "exrdonly" },
136 	{ MNT_EXPORTED, "exported" },
137 	{ MNT_DEFEXPORTED, "defexported" },
138 	{ MNT_EXPORTANON, "exportanon" },
139 	{ MNT_EXKERB, "exkerb" },
140 	{ MNT_EXPUBLIC, "public" },
141 	{ MNT_LOCAL, "local" },
142 	{ MNT_QUOTA, "quota" },
143 	{ MNT_ROOTFS, "rootfs" },
144 	{ MNT_USER, "user" },
145 	{ MNT_IGNORE, "ignore" },
146 	{ MNT_UPDATE, "update" },
147 	{ MNT_DELEXPORT, "delexport" },
148 	{ MNT_RELOAD, "reload" },
149 	{ MNT_FORCE, "force" },
150 	{ 0, NULL }
151 };
152 
153 
154 #define	SVAR(var) __STRING(var)	/* to force expansion */
155 #define	KGET(idx, var)							\
156 	KGET1(idx, &var, sizeof(var), SVAR(var))
157 #define	KGET1(idx, p, s, msg)						\
158 	KGET2(nl[idx].n_value, p, s, msg)
159 #define	KGET2(addr, p, s, msg)						\
160 	if (kvm_read(kd, (u_long)(addr), p, s) != s)			\
161 		warnx("cannot read %s: %s", msg, kvm_geterr(kd))
162 #define	KGETN(idx, var)							\
163 	KGET1N(idx, &var, sizeof(var), SVAR(var))
164 #define	KGET1N(idx, p, s, msg)						\
165 	KGET2N(nl[idx].n_value, p, s, msg)
166 #define	KGET2N(addr, p, s, msg)						\
167 	((kvm_read(kd, (u_long)(addr), p, s) == s) ? 1 : 0)
168 #define	KGETRET(addr, p, s, msg)					\
169 	if (kvm_read(kd, (u_long)(addr), p, s) != s) {			\
170 		warnx("cannot read %s: %s", msg, kvm_geterr(kd));	\
171 		return (0);						\
172 	}
173 
174 void	filemode(void);
175 int	getfiles(char **, int *);
176 struct mount *
177 	getmnt(struct mount *);
178 struct e_vnode *
179 	kinfo_vnodes(int *);
180 struct e_vnode *
181 	loadvnodes(int *);
182 void	mount_print(struct mount *);
183 void	nfs_header(void);
184 int	nfs_print(struct vnode *);
185 void	swapmode(void);
186 void	ttymode(void);
187 void	ttyprt(struct tty *, int);
188 void	ttytype(struct tty *, const char *, int, int, int);
189 void	ufs_header(void);
190 int	ufs_print(struct vnode *);
191 void	union_header(void);
192 int	union_print(struct vnode *);
193 static void usage(void);
194 void	vnode_header(void);
195 void	vnode_print(struct vnode *, struct vnode *);
196 void	vnodemode(void);
197 
198 int
199 main(int argc, char **argv)
200 {
201 	int ch, ret;
202 	int fileflag, ttyflag, vnodeflag;
203 	char buf[_POSIX2_LINE_MAX];
204 	const char *opts;
205 
206 	fileflag = swapflag = ttyflag = vnodeflag = 0;
207 
208 	/* We will behave like good old swapinfo if thus invoked */
209 	opts = strrchr(argv[0],'/');
210 	if (opts)
211 		opts++;
212 	else
213 		opts = argv[0];
214 	if (!strcmp(opts,"swapinfo")) {
215 		swapflag = 1;
216 		opts = "kM:N:";
217 		usagestr = "swapinfo [-k] [-M core] [-N system]";
218 	} else {
219 		opts = "TM:N:fiknstv";
220 		usagestr = "pstat [-Tfknst] [-M core] [-N system]";
221 	}
222 
223 	while ((ch = getopt(argc, argv, opts)) != -1)
224 		switch (ch) {
225 		case 'f':
226 			fileflag = 1;
227 			break;
228 		case 'k':
229 			if (putenv("BLOCKSIZE=1K") == -1)
230 				warn("putenv: cannot set BLOCKSIZE=1K");
231 			break;
232 		case 'M':
233 			memf = optarg;
234 			break;
235 		case 'N':
236 			nlistf = optarg;
237 			break;
238 		case 'n':
239 			usenumflag = 1;
240 			break;
241 		case 's':
242 			++swapflag;
243 			break;
244 		case 'T':
245 			totalflag = 1;
246 			break;
247 		case 't':
248 			ttyflag = 1;
249 			break;
250 		case 'v':
251 		case 'i':		/* Backward compatibility. */
252 			errx(1, "vnode mode not supported");
253 #if 0
254 			vnodeflag = 1;
255 			break;
256 #endif
257 		default:
258 			usage();
259 		}
260 	argc -= optind;
261 	argv += optind;
262 
263 	/*
264 	 * Discard setgid privileges if not the running kernel so that bad
265 	 * guys can't print interesting stuff from kernel memory.
266 	 */
267 	if (nlistf != NULL || memf != NULL)
268 		setgid(getgid());
269 
270 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, buf)) == 0)
271 		errx(1, "kvm_openfiles: %s", buf);
272 #ifdef USE_KCORE
273 	if (kcore_wrapper_open(nlistf, memf, buf))
274 		errx(1, "kcore_open: %s", buf);
275 #endif
276 	if ((ret = kvm_nlist(kd, nl)) != 0) {
277 		size_t i;
278 		int quit = 0;
279 
280 		if (ret == -1)
281 			errx(1, "kvm_nlist: %s", kvm_geterr(kd));
282 		for (i = 0; i < NL_LAST_MANDATORY; i++) {
283 			if (!nl[i].n_value) {
284 				quit = 1;
285 				warnx("undefined symbol: %s", nl[i].n_name);
286 			}
287 		}
288 		if (quit)
289 			exit(1);
290 	}
291 	if (!(fileflag | vnodeflag | ttyflag | swapflag | totalflag))
292 		usage();
293 	if (fileflag || totalflag)
294 		filemode();
295 	if (vnodeflag)
296 		vnodemode();
297 	if (ttyflag)
298 		ttymode();
299 	if (swapflag || totalflag)
300 		swapmode();
301 	exit (0);
302 }
303 
304 static void
305 usage(void)
306 {
307 	fprintf(stderr, "usage: %s\n", usagestr);
308 	exit (1);
309 }
310 
311 struct e_vnode {
312 	struct vnode *avnode;
313 	struct vnode vnode;
314 };
315 
316 void
317 vnodemode(void)
318 {
319 	struct e_vnode *e_vnodebase, *endvnode, *evp;
320 	struct vnode *vp;
321 	struct mount *maddr, *mp = NULL;
322 	int numvnodes;
323 
324 	e_vnodebase = loadvnodes(&numvnodes);
325 	if (totalflag) {
326 		printf("%7d vnodes\n", numvnodes);
327 		return;
328 	}
329 	endvnode = e_vnodebase + numvnodes;
330 	printf("%d active vnodes\n", numvnodes);
331 
332 
333 #define ST	mp->mnt_stat
334 	maddr = NULL;
335 	for (evp = e_vnodebase; evp < endvnode; evp++) {
336 		vp = &evp->vnode;
337 		if (vp->v_mount != maddr) {
338 			/*
339 			 * New filesystem
340 			 */
341 			if ((mp = getmnt(vp->v_mount)) == NULL)
342 				continue;
343 			maddr = vp->v_mount;
344 			mount_print(mp);
345 			vnode_header();
346 			if (!strcmp(ST.f_fstypename, "ufs") ||
347 			    !strcmp(ST.f_fstypename, "mfs"))
348 				ufs_header();
349 			else if (!strcmp(ST.f_fstypename, "nfs"))
350 				nfs_header();
351 			else if (!strcmp(ST.f_fstypename, "union"))
352 				union_header();
353 			printf("\n");
354 		}
355 		vnode_print(evp->avnode, vp);
356 		if (!strcmp(ST.f_fstypename, "ufs") ||
357 		    !strcmp(ST.f_fstypename, "mfs"))
358 			ufs_print(vp);
359 		else if (!strcmp(ST.f_fstypename, "nfs"))
360 			nfs_print(vp);
361 		else if (!strcmp(ST.f_fstypename, "union"))
362 			union_print(vp);
363 		printf("\n");
364 	}
365 	free(e_vnodebase);
366 }
367 
368 void
369 vnode_header(void)
370 {
371 	printf("ADDR     TYP VFLAG  USE HOLD");
372 }
373 
374 void
375 vnode_print(struct vnode *avnode, struct vnode *vp)
376 {
377 	const char *type;
378 	char flags[32];
379 	char *fp = flags;
380 	int flag;
381 	int refs;
382 
383 	/*
384 	 * set type
385 	 */
386 	switch (vp->v_type) {
387 	case VNON:
388 		type = "non"; break;
389 	case VREG:
390 		type = "reg"; break;
391 	case VDIR:
392 		type = "dir"; break;
393 	case VBLK:
394 		type = "blk"; break;
395 	case VCHR:
396 		type = "chr"; break;
397 	case VLNK:
398 		type = "lnk"; break;
399 	case VSOCK:
400 		type = "soc"; break;
401 	case VFIFO:
402 		type = "fif"; break;
403 	case VBAD:
404 		type = "bad"; break;
405 	default:
406 		type = "unk"; break;
407 	}
408 	/*
409 	 * gather flags
410 	 */
411 	flag = vp->v_flag;
412 	if (flag & VROOT)
413 		*fp++ = 'R';
414 	if (flag & VTEXT)
415 		*fp++ = 'T';
416 	if (flag & VSYSTEM)
417 		*fp++ = 'S';
418 	if (flag & VISTTY)
419 		*fp++ = 't';
420 #ifdef VXLOCK
421 	if (flag & VXLOCK)
422 		*fp++ = 'L';
423 	if (flag & VXWANT)
424 		*fp++ = 'W';
425 #endif
426 	if (flag & VOBJBUF)
427 		*fp++ = 'V';
428 	if (flag & VAGE)
429 		*fp++ = 'a';
430 	if (flag & VOLOCK)
431 		*fp++ = 'l';
432 	if (flag & VOWANT)
433 		*fp++ = 'w';
434 #ifdef VDOOMED
435 	if (flag & VDOOMED)
436 		*fp++ = 'D';
437 #endif
438 	if (flag & VFREE)
439 		*fp++ = 'F';
440 	if (flag & VONWORKLST)
441 		*fp++ = 'O';
442 	if (flag & VMOUNT)
443 		*fp++ = 'M';
444 #ifdef VRECLAIMED
445 	if (flag & VINACTIVE)
446 		*fp++ = 'I';
447 	if (flag & VRECLAIMED)
448 		*fp++ = 'X';
449 #endif
450 
451 	if (flag == 0)
452 		*fp++ = '-';
453 	*fp = '\0';
454 
455 	/*
456 	 * Convert SYSREF ref counts into something more
457 	 * human readable for display.
458 	 */
459 	if ((refs = vp->v_sysref.refcnt) < 0)
460 		refs = -(refs + 0x40000001);
461 	printf("%8lx %s %5s %4d %4d",
462 	    (u_long)(void *)avnode, type, flags, refs, vp->v_auxrefs);
463 }
464 
465 void
466 ufs_header(void)
467 {
468 	printf(" FILEID IFLAG RDEV|SZ");
469 }
470 
471 int
472 ufs_print(struct vnode *vp)
473 {
474 	int flag;
475 	struct inode inode, *ip = &inode;
476 	char flagbuf[16], *flags = flagbuf;
477 	char *name;
478 	mode_t type;
479 
480 	KGETRET(VTOI(vp), &inode, sizeof(struct inode), "vnode's inode");
481 	flag = ip->i_flag;
482 	if (flag & IN_ACCESS)
483 		*flags++ = 'A';
484 	if (flag & IN_CHANGE)
485 		*flags++ = 'C';
486 	if (flag & IN_UPDATE)
487 		*flags++ = 'U';
488 	if (flag & IN_MODIFIED)
489 		*flags++ = 'M';
490 	if (flag & IN_RENAME)
491 		*flags++ = 'R';
492 	if (flag & IN_SHLOCK)
493 		*flags++ = 'S';
494 	if (flag & IN_EXLOCK)
495 		*flags++ = 'E';
496 	if (flag & IN_HASHED)
497 		*flags++ = 'H';
498 	if (flag & IN_LAZYMOD)
499 		*flags++ = 'L';
500 	if (flag == 0)
501 		*flags++ = '-';
502 	*flags = '\0';
503 
504 	printf(" %6ju %5s", (uintmax_t)ip->i_number, flagbuf);
505 	type = ip->i_mode & S_IFMT;
506 	if (S_ISCHR(ip->i_mode) || S_ISBLK(ip->i_mode))
507 		if (usenumflag || ((name = devname(ip->i_rdev, type)) == NULL))
508 			printf("   %2d,%-2d",
509 			    major(ip->i_rdev), minor(ip->i_rdev));
510 		else
511 			printf(" %7s", name);
512 	else
513 		printf(" %7qd", ip->i_size);
514 	return (0);
515 }
516 
517 void
518 nfs_header(void)
519 {
520 	printf(" FILEID NFLAG RDEV|SZ");
521 }
522 
523 int
524 nfs_print(struct vnode *vp)
525 {
526 	struct nfsnode nfsnode, *np = &nfsnode;
527 	char flagbuf[16], *flags = flagbuf;
528 	int flag;
529 	char *name;
530 	mode_t type;
531 
532 	KGETRET(VTONFS(vp), &nfsnode, sizeof(nfsnode), "vnode's nfsnode");
533 	flag = np->n_flag;
534 	if (flag & NFLUSHWANT)
535 		*flags++ = 'W';
536 	if (flag & NFLUSHINPROG)
537 		*flags++ = 'P';
538 	if (flag & NLMODIFIED)
539 		*flags++ = 'M';
540 	if (flag & NRMODIFIED)
541 		*flags++ = 'R';
542 	if (flag & NWRITEERR)
543 		*flags++ = 'E';
544 	if (flag & NQNFSEVICTED)
545 		*flags++ = 'G';
546 	if (flag & NACC)
547 		*flags++ = 'A';
548 	if (flag & NUPD)
549 		*flags++ = 'U';
550 	if (flag & NCHG)
551 		*flags++ = 'C';
552 	if (flag & NLOCKED)
553 		*flags++ = 'L';
554 	if (flag & NWANTED)
555 		*flags++ = 'w';
556 	if (flag == 0)
557 		*flags++ = '-';
558 	*flags = '\0';
559 
560 #define VT	np->n_vattr
561 	printf(" %6ju %5s", (uintmax_t)VT.va_fileid, flagbuf);
562 	type = VT.va_mode & S_IFMT;
563 	if (S_ISCHR(VT.va_mode) || S_ISBLK(VT.va_mode))
564 		if (usenumflag || ((name = devname((VT.va_rmajor << 8) | VT.va_rminor, type)) == NULL))
565 			printf("   %2d,%-2d",
566 			    VT.va_rmajor, VT.va_rminor);
567 		else
568 			printf(" %7s", name);
569 	else
570 		printf(" %7qd", np->n_size);
571 	return (0);
572 }
573 
574 void
575 union_header(void)
576 {
577 	printf("    UPPER    LOWER");
578 }
579 
580 int
581 union_print(struct vnode *vp)
582 {
583 	struct union_node unode, *up = &unode;
584 
585 	KGETRET(VTOUNION(vp), &unode, sizeof(unode), "vnode's unode");
586 
587 	printf(" %8lx %8lx", (u_long)(void *)up->un_uppervp,
588 	    (u_long)(void *)up->un_lowervp);
589 	return (0);
590 }
591 
592 /*
593  * Given a pointer to a mount structure in kernel space,
594  * read it in and return a usable pointer to it.
595  */
596 struct mount *
597 getmnt(struct mount *maddr)
598 {
599 	static struct mtab {
600 		struct mtab *next;
601 		struct mount *maddr;
602 		struct mount mount;
603 	} *mhead = NULL;
604 	struct mtab *mt;
605 
606 	for (mt = mhead; mt != NULL; mt = mt->next)
607 		if (maddr == mt->maddr)
608 			return (&mt->mount);
609 	if ((mt = malloc(sizeof(struct mtab))) == NULL)
610 		errx(1, "malloc");
611 	KGETRET(maddr, &mt->mount, sizeof(struct mount), "mount table");
612 	mt->maddr = maddr;
613 	mt->next = mhead;
614 	mhead = mt;
615 	return (&mt->mount);
616 }
617 
618 void
619 mount_print(struct mount *mp)
620 {
621 	int flags;
622 
623 #define ST	mp->mnt_stat
624 	printf("*** MOUNT %s %s on %s", ST.f_fstypename,
625 	    ST.f_mntfromname, ST.f_mntonname);
626 	if ((flags = mp->mnt_flag)) {
627 		int i;
628 		const char *sep = " (";
629 
630 		for (i = 0; mnt_flags[i].m_flag; i++) {
631 			if (flags & mnt_flags[i].m_flag) {
632 				printf("%s%s", sep, mnt_flags[i].m_name);
633 				flags &= ~mnt_flags[i].m_flag;
634 				sep = ",";
635 			}
636 		}
637 		if (flags)
638 			printf("%sunknown_flags:%x", sep, flags);
639 		printf(")");
640 	}
641 	printf("\n");
642 #undef ST
643 }
644 
645 struct e_vnode *
646 loadvnodes(int *avnodes)
647 {
648 	int mib[2];
649 	size_t copysize;
650 	struct e_vnode *vnodebase;
651 
652 	if (memf != NULL) {
653 		/*
654 		 * do it by hand
655 		 */
656 		return (kinfo_vnodes(avnodes));
657 	}
658 	mib[0] = CTL_KERN;
659 	mib[1] = KERN_VNODE;
660 	if (sysctl(mib, 2, NULL, &copysize, NULL, 0) == -1)
661 		err(1, "sysctl: KERN_VNODE");
662 	if ((vnodebase = malloc(copysize)) == NULL)
663 		errx(1, "malloc");
664 	if (sysctl(mib, 2, vnodebase, &copysize, NULL, 0) == -1)
665 		err(1, "sysctl: KERN_VNODE");
666 	if (copysize % sizeof(struct e_vnode))
667 		errx(1, "vnode size mismatch");
668 	*avnodes = copysize / sizeof(struct e_vnode);
669 
670 	return (vnodebase);
671 }
672 
673 /*
674  * simulate what a running kernel does in in kinfo_vnode
675  */
676 struct e_vnode *
677 kinfo_vnodes(int *avnodes)
678 {
679 	struct mntlist mountlist;
680 	struct mount *mp, mounth, *mp_next;
681 	struct vnode *vp, vnode, *vp_next;
682 	char *vbuf, *evbuf, *bp;
683 	int num, numvnodes;
684 
685 #define VPTRSZ  sizeof(struct vnode *)
686 #define VNODESZ sizeof(struct vnode)
687 
688 	KGET(NL_NUMVNODES, numvnodes);
689 	if ((vbuf = malloc((numvnodes + 20) * (VPTRSZ + VNODESZ))) == NULL)
690 		errx(1, "malloc");
691 	bp = vbuf;
692 	evbuf = vbuf + (numvnodes + 20) * (VPTRSZ + VNODESZ);
693 	KGET(NL_MOUNTLIST, mountlist);
694 	for (num = 0, mp = TAILQ_FIRST(&mountlist); ; mp = mp_next) {
695 		KGET2(mp, &mounth, sizeof(mounth), "mount entry");
696 		mp_next = TAILQ_NEXT(&mounth, mnt_list);
697 		for (vp = TAILQ_FIRST(&mounth.mnt_nvnodelist);
698 		    vp != NULL; vp = vp_next) {
699 			KGET2(vp, &vnode, sizeof(vnode), "vnode");
700 			vp_next = TAILQ_NEXT(&vnode, v_nmntvnodes);
701 			if ((bp + VPTRSZ + VNODESZ) > evbuf)
702 				/* XXX - should realloc */
703 				errx(1, "no more room for vnodes");
704 			memmove(bp, &vp, VPTRSZ);
705 			bp += VPTRSZ;
706 			memmove(bp, &vnode, VNODESZ);
707 			bp += VNODESZ;
708 			num++;
709 		}
710 		if (mp == TAILQ_LAST(&mountlist, mntlist))
711 			break;
712 	}
713 	*avnodes = num;
714 	return ((struct e_vnode *)vbuf);
715 }
716 
717 char hdr[] =
718 "  LINE RAW CAN OUT IHIWT ILOWT OHWT LWT     COL STATE  SESS      PGID DISC\n";
719 int ttyspace = 128;
720 
721 void
722 ttymode(void)
723 {
724 	struct tty *tty;
725 	struct tty ttyb[1000];
726 	int error;
727 	size_t len, i;
728 
729 	printf(hdr);
730 	len = sizeof(ttyb);
731 	error = sysctlbyname("kern.ttys", &ttyb, &len, 0, 0);
732 	if (!error) {
733 		len /= sizeof(ttyb[0]);
734 		for (i = 0; i < len; i++) {
735 			ttyprt(&ttyb[i], 0);
736 		}
737 	}
738 	if ((tty = malloc(ttyspace * sizeof(*tty))) == NULL)
739 		errx(1, "malloc");
740 	if (nl[NL_NRC_TTY].n_type != 0)
741 		ttytype(tty, "rc", NL_RC_TTY, NL_NRC_TTY, 0);
742 	if (nl[NL_NCY_TTY].n_type != 0)
743 		ttytype(tty, "cy", NL_CY_TTY, NL_NCY_TTY, 0);
744 	if (nl[NL_SI_NPORTS].n_type != 0)
745 		ttytype(tty, "si", NL_SI_TTY, NL_SI_NPORTS, 1);
746 	free(tty);
747 }
748 
749 void
750 ttytype(struct tty *tty, const char *name, int type, int number, int indir)
751 {
752 	struct tty *tp;
753 	int ntty;
754 	struct tty **ttyaddr;
755 
756 	if (tty == NULL)
757 		return;
758 	KGET(number, ntty);
759 	printf("%d %s %s\n", ntty, name, (ntty == 1) ? "line" : "lines");
760 	if (ntty > ttyspace) {
761 		ttyspace = ntty;
762 		if ((tty = realloc(tty, ttyspace * sizeof(*tty))) == 0)
763 			errx(1, "realloc");
764 	}
765 	if (indir) {
766 		KGET(type, ttyaddr);
767 		KGET2(ttyaddr, tty, (ssize_t)(ntty * sizeof(struct tty)),
768 		      "tty structs");
769 	} else {
770 		KGET1(type, tty, (ssize_t)(ntty * sizeof(struct tty)),
771 		      "tty structs");
772 	}
773 	printf(hdr);
774 	for (tp = tty; tp < &tty[ntty]; tp++)
775 		ttyprt(tp, tp - tty);
776 }
777 
778 struct {
779 	int flag;
780 	char val;
781 } ttystates[] = {
782 #ifdef TS_WOPEN
783 	{ TS_WOPEN,	'W'},
784 #endif
785 	{ TS_ISOPEN,	'O'},
786 	{ TS_CARR_ON,	'C'},
787 #ifdef TS_CONNECTED
788 	{ TS_CONNECTED,	'c'},
789 #endif
790 	{ TS_TIMEOUT,	'T'},
791 	{ TS_FLUSH,	'F'},
792 	{ TS_BUSY,	'B'},
793 #ifdef TS_ASLEEP
794 	{ TS_ASLEEP,	'A'},
795 #endif
796 #ifdef TS_SO_OLOWAT
797 	{ TS_SO_OLOWAT,	'A'},
798 #endif
799 #ifdef TS_SO_OCOMPLETE
800 	{ TS_SO_OCOMPLETE, 'a'},
801 #endif
802 	{ TS_XCLUDE,	'X'},
803 	{ TS_TTSTOP,	'S'},
804 #ifdef TS_CAR_OFLOW
805 	{ TS_CAR_OFLOW,	'm'},
806 #endif
807 #ifdef TS_CTS_OFLOW
808 	{ TS_CTS_OFLOW,	'o'},
809 #endif
810 #ifdef TS_DSR_OFLOW
811 	{ TS_DSR_OFLOW,	'd'},
812 #endif
813 	{ TS_TBLOCK,	'K'},
814 	{ TS_ASYNC,	'Y'},
815 	{ TS_BKSL,	'D'},
816 	{ TS_ERASE,	'E'},
817 	{ TS_LNCH,	'L'},
818 	{ TS_TYPEN,	'P'},
819 	{ TS_CNTTB,	'N'},
820 #ifdef TS_CAN_BYPASS_L_RINT
821 	{ TS_CAN_BYPASS_L_RINT, 'l'},
822 #endif
823 #ifdef TS_SNOOP
824 	{ TS_SNOOP,     's'},
825 #endif
826 #ifdef TS_ZOMBIE
827 	{ TS_ZOMBIE,	'Z'},
828 #endif
829 	{ 0,	       '\0'},
830 };
831 
832 void
833 ttyprt(struct tty *tp, int line)
834 {
835 	int i, j;
836 	pid_t pgid;
837 	char *name, state[20];
838 
839 	if (usenumflag || tp->t_dev == 0 ||
840 	   (name = devname(tp->t_dev, S_IFCHR)) == NULL)
841 		printf("%7d ", line);
842 	else
843 		printf("%7s ", name);
844 	printf("%2d %3d ", tp->t_rawq.c_cc, tp->t_canq.c_cc);
845 	printf("%3d %5d %5d %4d %3d %7d ", tp->t_outq.c_cc,
846 		tp->t_ihiwat, tp->t_ilowat, tp->t_ohiwat, tp->t_olowat,
847 		tp->t_column);
848 	for (i = j = 0; ttystates[i].flag; i++)
849 		if (tp->t_state&ttystates[i].flag)
850 			state[j++] = ttystates[i].val;
851 	if (j == 0)
852 		state[j++] = '-';
853 	state[j] = '\0';
854 	printf("%-6s %8lx", state, (u_long)(void *)tp->t_session);
855 	pgid = 0;
856 	if (tp->t_pgrp != NULL)
857 		KGET2(&tp->t_pgrp->pg_id, &pgid, sizeof(pid_t), "pgid");
858 	printf("%6d ", pgid);
859 	switch (tp->t_line) {
860 	case TTYDISC:
861 		printf("term\n");
862 		break;
863 	case NTTYDISC:
864 		printf("ntty\n");
865 		break;
866 	case SLIPDISC:
867 		printf("slip\n");
868 		break;
869 	case PPPDISC:
870 		printf("ppp\n");
871 		break;
872 	default:
873 		printf("%d\n", tp->t_line);
874 		break;
875 	}
876 }
877 
878 void
879 filemode(void)
880 {
881 	struct kinfo_file *fp, *ofp;
882 	size_t len;
883 	char flagbuf[16], *fbp;
884 	int maxfile, nfile;
885 	static const char *dtypes[] = { "???", "inode", "socket" };
886 
887 	if (kinfo_get_maxfiles(&maxfile))
888 		err(1, "kinfo_get_maxfiles");
889 	if (totalflag) {
890 		if (kinfo_get_openfiles(&nfile))
891 			err(1, "kinfo_get_openfiles");
892 		printf("%3d/%3d files\n", nfile, maxfile);
893 		return;
894 	}
895 	if (kinfo_get_files(&fp, &len))
896 		err(1, "kinfo_get_files");
897 	ofp = fp;
898 
899 	printf("%d/%d open files\n", len, maxfile);
900 	printf("   LOC   TYPE    FLG     CNT  MSG    DATA    OFFSET\n");
901 	for (; len-- > 0; fp++) {
902 		if ((unsigned)fp->f_type > DTYPE_SOCKET)
903 			continue;
904 		printf("%p ", fp->f_file);
905 		printf("%-8.8s", dtypes[fp->f_type]);
906 		fbp = flagbuf;
907 		if (fp->f_flag & FREAD)
908 			*fbp++ = 'R';
909 		if (fp->f_flag & FWRITE)
910 			*fbp++ = 'W';
911 		if (fp->f_flag & FAPPEND)
912 			*fbp++ = 'A';
913 #ifdef FSHLOCK	/* currently gone */
914 		if (fp->f_flag & FSHLOCK)
915 			*fbp++ = 'S';
916 		if (fp->f_flag & FEXLOCK)
917 			*fbp++ = 'X';
918 #endif
919 		if (fp->f_flag & FASYNC)
920 			*fbp++ = 'I';
921 		*fbp = '\0';
922 		printf("%6s  %3d", flagbuf, fp->f_count);
923 		printf("  %3d", fp->f_msgcount);
924 		printf("  %8lx", (u_long)(void *)fp->f_data);
925 		if (fp->f_offset < 0)
926 			printf("  %qx\n", fp->f_offset);
927 		else
928 			printf("  %qd\n", fp->f_offset);
929 	}
930 	free(ofp);
931 }
932 
933 /*
934  * swapmode is based on a program called swapinfo written
935  * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
936  */
937 void
938 swapmode(void)
939 {
940 	struct kvm_swap kswap[16];
941 	int i;
942 	int n;
943 	int pagesize = getpagesize();
944 	const char *header;
945 	int hlen;
946 	long blocksize;
947 
948 	n = kvm_getswapinfo(
949 	    kd,
950 	    kswap,
951 	    sizeof(kswap)/sizeof(kswap[0]),
952 	    ((swapflag > 1) ? SWIF_DUMP_TREE : 0) | SWIF_DEV_PREFIX
953 	);
954 
955 #define CONVERT(v)	((int)((quad_t)(v) * pagesize / blocksize))
956 
957 	header = getbsize(&hlen, &blocksize);
958 	if (totalflag == 0) {
959 		printf("%-15s %*s %8s %8s %8s  %s\n",
960 		    "Device", hlen, header,
961 		    "Used", "Avail", "Capacity", "Type");
962 
963 		for (i = 0; i < n; ++i) {
964 			printf(
965 			    "%-15s %*d ",
966 			    kswap[i].ksw_devname,
967 			    hlen,
968 			    CONVERT(kswap[i].ksw_total)
969 			);
970 			printf(
971 			    "%8d %8d %5.0f%%    %s\n",
972 			    CONVERT(kswap[i].ksw_used),
973 			    CONVERT(kswap[i].ksw_total - kswap[i].ksw_used),
974 			    (double)kswap[i].ksw_used * 100.0 /
975 				(double)kswap[i].ksw_total,
976 			    (kswap[i].ksw_flags & SW_SEQUENTIAL) ?
977 				"Sequential" : "Interleaved"
978 			);
979 		}
980 	}
981 
982 	if (totalflag) {
983 		blocksize = 1024 * 1024;
984 
985 		printf(
986 		    "%dM/%dM swap space\n",
987 		    CONVERT(kswap[n].ksw_used),
988 		    CONVERT(kswap[n].ksw_total)
989 		);
990 	} else if (n > 1) {
991 		printf(
992 		    "%-15s %*d %8d %8d %5.0f%%\n",
993 		    "Total",
994 		    hlen,
995 		    CONVERT(kswap[n].ksw_total),
996 		    CONVERT(kswap[n].ksw_used),
997 		    CONVERT(kswap[n].ksw_total - kswap[n].ksw_used),
998 		    (double)kswap[n].ksw_used * 100.0 /
999 			(double)kswap[n].ksw_total
1000 		);
1001 	}
1002 }
1003