pstat.c revision 1.113
1/*	$OpenBSD: pstat.c,v 1.113 2017/02/09 22:21:53 jca Exp $	*/
2/*	$NetBSD: pstat.c,v 1.27 1996/10/23 22:50:06 cgd Exp $	*/
3
4/*-
5 * Copyright (c) 1980, 1991, 1993
6 *	The Regents of the University of California.  All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the University nor the names of its contributors
17 *    may be used to endorse or promote products derived from this software
18 *    without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33#include <sys/param.h>	/* MAXCOMLEN DEV_BSIZE */
34#include <sys/types.h>
35#include <sys/proc.h>
36#include <sys/time.h>
37#include <sys/vnode.h>
38#include <sys/ucred.h>
39#include <sys/stat.h>
40#define _KERNEL
41#include <sys/file.h>
42#include <ufs/ufs/quota.h>
43#include <ufs/ufs/inode.h>
44#include <sys/mount.h>
45#undef _KERNEL
46#include <nfs/nfsproto.h>
47#include <nfs/rpcv2.h>
48#include <nfs/nfsnode.h>
49#include <sys/ioctl.h>
50#include <sys/tty.h>
51#include <sys/conf.h>
52#include <sys/device.h>
53#include <sys/swap.h>
54
55#include <sys/sysctl.h>
56
57#include <stdint.h>
58#include <endian.h>
59#include <err.h>
60#include <kvm.h>
61#include <limits.h>
62#include <nlist.h>
63#include <paths.h>
64#include <stdio.h>
65#include <stdlib.h>
66#include <string.h>
67#include <unistd.h>
68
69struct nlist vnodenl[] = {
70#define	FNL_NFILE	0		/* sysctl */
71	{"_nfiles"},
72#define FNL_MAXFILE	1		/* sysctl */
73	{"_maxfiles"},
74#define TTY_NTTY	2		/* sysctl */
75	{"_tty_count"},
76#define V_NUMV		3		/* sysctl */
77	{ "_numvnodes" },
78#define TTY_TTYLIST	4		/* sysctl */
79	{"_ttylist"},
80#define	V_MOUNTLIST	5		/* no sysctl */
81	{ "_mountlist" },
82	{ NULL }
83};
84
85struct itty *globalitp;
86struct kinfo_file *kf;
87struct nlist *globalnl;
88
89struct e_vnode {
90	struct vnode *vptr;
91	struct vnode vnode;
92};
93
94int	kflag;
95int	totalflag;
96int	usenumflag;
97int	hideroot;
98int	maxfile;
99int	need_nlist;
100int	nfile;
101int	ntty;
102int	numvnodes;
103char	*nlistf	= NULL;
104char	*memf	= NULL;
105kvm_t	*kd = NULL;
106
107#define	SVAR(var) __STRING(var)	/* to force expansion */
108#define	KGET(idx, var)							\
109	KGET1(idx, &var, sizeof(var), SVAR(var))
110#define	KGET1(idx, p, s, msg)						\
111	KGET2(globalnl[idx].n_value, p, s, msg)
112#define	KGET2(addr, p, s, msg)						\
113	if (kvm_read(kd, (u_long)(addr), p, s) != s)			\
114		warnx("cannot read %s: %s", msg, kvm_geterr(kd))
115#define	KGETRET(addr, p, s, msg)					\
116	if (kvm_read(kd, (u_long)(addr), p, s) != s) {			\
117		warnx("cannot read %s: %s", msg, kvm_geterr(kd));	\
118		return (0);						\
119	}
120
121void	filemode(void);
122void	filemodeprep(void);
123struct mount *
124	getmnt(struct mount *);
125struct e_vnode *
126	kinfo_vnodes(void);
127void	mount_print(struct mount *);
128void	nfs_header(void);
129int	nfs_print(struct vnode *);
130void	swapmode(void);
131void	ttymode(void);
132void	ttymodeprep(void);
133void	ttyprt(struct itty *);
134void	tty2itty(struct tty *tp, struct itty *itp);
135void	ufs_header(void);
136int	ufs_print(struct vnode *);
137void	ext2fs_header(void);
138int	ext2fs_print(struct vnode *);
139static void __dead	usage(void);
140void	vnode_header(void);
141void	vnode_print(struct vnode *, struct vnode *);
142void	vnodemode(void);
143void	vnodemodeprep(void);
144
145
146int
147main(int argc, char *argv[])
148{
149	int fileflag = 0, swapflag = 0, ttyflag = 0, vnodeflag = 0, ch;
150	char buf[_POSIX2_LINE_MAX];
151	const char *dformat = NULL;
152	extern char *optarg;
153	extern int optind;
154	int i;
155
156	hideroot = getuid();
157
158	while ((ch = getopt(argc, argv, "d:TM:N:fiknstv")) != -1)
159		switch (ch) {
160		case 'd':
161			dformat = optarg;
162			break;
163		case 'f':
164			fileflag = 1;
165			break;
166		case 'M':
167			memf = optarg;
168			break;
169		case 'N':
170			nlistf = optarg;
171			break;
172		case 'n':
173			usenumflag = 1;
174			break;
175		case 's':
176			swapflag = 1;
177			break;
178		case 'T':
179			totalflag = 1;
180			break;
181		case 't':
182			ttyflag = 1;
183			break;
184		case 'k':
185			kflag = 1;
186			break;
187		case 'v':
188		case 'i':		/* Backward compatibility. */
189			vnodeflag = 1;
190			break;
191		default:
192			usage();
193		}
194	argc -= optind;
195	argv += optind;
196
197	if (dformat && getuid())
198		errx(1, "Only root can use -d");
199
200	if ((dformat == NULL && argc > 0) || (dformat && argc == 0))
201		usage();
202
203	need_nlist = dformat || vnodeflag;
204
205	if (nlistf != NULL || memf != NULL) {
206		if (fileflag || totalflag)
207			need_nlist = 1;
208	}
209
210	if (vnodeflag || fileflag || dformat || need_nlist)
211		if ((kd = kvm_openfiles(nlistf, memf, NULL,
212		    O_RDONLY | (need_nlist ? 0 : KVM_NO_FILES), buf)) == 0)
213			errx(1, "kvm_openfiles: %s", buf);
214
215	if (need_nlist)
216		if (kvm_nlist(kd, vnodenl) == -1)
217			errx(1, "kvm_nlist: %s", kvm_geterr(kd));
218
219	if (!(fileflag | vnodeflag | ttyflag | swapflag | totalflag || dformat))
220		usage();
221
222	if(!dformat) {
223		if (fileflag || totalflag)
224			filemodeprep();
225		if (vnodeflag || totalflag)
226			vnodemodeprep();
227		if (ttyflag)
228			ttymodeprep();
229	}
230
231	if (pledge("stdio rpath vminfo", NULL) == -1)
232		err(1, "pledge");
233
234	if (dformat) {
235		struct nlist *nl;
236		int longformat = 0, stringformat = 0, error = 0, n;
237		uint32_t mask = ~0;
238		char format[10], buf[1024];
239
240		n = strlen(dformat);
241		if (n == 0)
242			errx(1, "illegal format");
243
244		/*
245		 * Support p, c, s, and {l, ll, h, hh, j, t, z, }[diouxX]
246		 */
247		if (strcmp(dformat, "p") == 0)
248			longformat = sizeof(long) == 8;
249		else if (strcmp(dformat, "c") == 0)
250			mask = 0xff;
251		else if (strcmp(dformat, "s") == 0)
252			stringformat = 1;
253		else if (strchr("diouxX", dformat[n - 1])) {
254			char *ptbl[]= {"l", "ll", "h", "hh", "j", "t", "z", ""};
255			int i;
256
257			char *mod;
258			for (i = 0; i < sizeof(ptbl)/sizeof(ptbl[0]); i++) {
259				mod = ptbl[i];
260				if (strlen(mod) == n - 1 &&
261				    strncmp(mod, dformat, strlen(mod)) == 0)
262					break;
263			}
264			if (i == sizeof(ptbl)/sizeof(ptbl[0])
265			    && dformat[1] != '\0')
266				errx(1, "illegal format");
267			if (strcmp(mod, "l") == 0)
268				longformat = sizeof(long) == sizeof(long long);
269			else if (strcmp(mod, "h") == 0)
270				mask = 0xffff;
271			else if (strcmp(mod, "hh") == 0)
272				mask = 0xff;
273			else if (strcmp(mod, "") != 0)
274				longformat = 1;
275
276		} else
277			errx(1, "illegal format");
278
279		if (*dformat == 's') {
280			stringformat = 1;
281			snprintf(format, sizeof(format), "%%.%zus",
282			    sizeof buf);
283		} else
284			snprintf(format, sizeof(format), "%%%s", dformat);
285
286		nl = calloc(argc + 1, sizeof *nl);
287		if (!nl)
288			err(1, "calloc nl: ");
289		for (i = 0; i < argc; i++) {
290			if (asprintf(&nl[i].n_name, "_%s",
291			    argv[i]) == -1)
292				warn("asprintf");
293		}
294		kvm_nlist(kd, nl);
295		globalnl = nl;
296		for (i = 0; i < argc; i++) {
297			uint64_t v;
298
299			printf("%s ", argv[i]);
300			if (!nl[i].n_value && argv[i][0] == '0') {
301				nl[i].n_value = strtoul(argv[i], NULL, 16);
302				nl[i].n_type = N_DATA;
303			}
304			if (!nl[i].n_value) {
305				printf("not found\n");
306				error++;
307				continue;
308			}
309
310			printf("at %p: ", (void *)nl[i].n_value);
311			if ((nl[i].n_type & N_TYPE) == N_DATA ||
312			    (nl[i].n_type & N_TYPE) == N_COMM) {
313				if (stringformat) {
314					KGET1(i, &buf, sizeof(buf), argv[i]);
315					buf[sizeof(buf) - 1] = '\0';
316				} else
317					KGET1(i, &v, sizeof(v), argv[i]);
318				if (stringformat)
319					printf(format, &buf);
320				else if (longformat)
321					printf(format, v);
322				else {
323#if BYTE_ORDER == BIG_ENDIAN
324					switch (mask) {
325					case 0xff:
326						v >>= 8;
327						/* FALLTHROUGH */
328					case 0xffff:
329						v >>= 16;
330						/* FALLTHROUGH */
331					case 0xffffffff:
332						v >>= 32;
333						break;
334					}
335#endif
336					printf(format, ((uint32_t)v) & mask);
337				}
338			}
339			printf("\n");
340		}
341		for (i = 0; i < argc; i++)
342			free(nl[i].n_name);
343		free(nl);
344		return error;
345	}
346
347	if (fileflag || totalflag)
348		filemode();
349	if (vnodeflag || totalflag)
350		vnodemode();
351	if (ttyflag)
352		ttymode();
353	if (swapflag || totalflag)
354		swapmode();
355	return 0;
356}
357
358void
359vnodemode(void)
360{
361	struct e_vnode *e_vnodebase, *endvnode, *evp;
362	struct vnode *vp;
363	struct mount *maddr, *mp = NULL;
364
365	globalnl = vnodenl;
366
367	e_vnodebase = kinfo_vnodes();
368	if (totalflag) {
369		(void)printf("%7d vnodes\n", numvnodes);
370		return;
371	}
372	if (!e_vnodebase)
373		return;
374	endvnode = e_vnodebase + numvnodes;
375	(void)printf("%d active vnodes\n", numvnodes);
376
377	maddr = NULL;
378	for (evp = e_vnodebase; evp < endvnode; evp++) {
379		vp = &evp->vnode;
380		if (vp->v_mount != maddr) {
381			/*
382			 * New filesystem
383			 */
384			if ((mp = getmnt(vp->v_mount)) == NULL)
385				continue;
386			maddr = vp->v_mount;
387			mount_print(mp);
388			vnode_header();
389			if (!strncmp(mp->mnt_stat.f_fstypename, MOUNT_FFS, MFSNAMELEN) ||
390			    !strncmp(mp->mnt_stat.f_fstypename, MOUNT_MFS, MFSNAMELEN)) {
391				ufs_header();
392			} else if (!strncmp(mp->mnt_stat.f_fstypename, MOUNT_NFS,
393			    MFSNAMELEN)) {
394				nfs_header();
395			} else if (!strncmp(mp->mnt_stat.f_fstypename, MOUNT_EXT2FS,
396			    MFSNAMELEN)) {
397				ext2fs_header();
398			}
399			(void)printf("\n");
400		}
401		vnode_print(evp->vptr, vp);
402
403		/* Syncer vnodes have no associated fs-specific data */
404		if (vp->v_data == NULL) {
405			printf(" %6c %5c %7c\n", '-', '-', '-');
406			continue;
407		}
408
409		if (!strncmp(mp->mnt_stat.f_fstypename, MOUNT_FFS, MFSNAMELEN) ||
410		    !strncmp(mp->mnt_stat.f_fstypename, MOUNT_MFS, MFSNAMELEN)) {
411			ufs_print(vp);
412		} else if (!strncmp(mp->mnt_stat.f_fstypename, MOUNT_NFS, MFSNAMELEN)) {
413			nfs_print(vp);
414		} else if (!strncmp(mp->mnt_stat.f_fstypename, MOUNT_EXT2FS,
415		    MFSNAMELEN)) {
416			ext2fs_print(vp);
417		}
418		(void)printf("\n");
419	}
420	free(e_vnodebase);
421}
422
423void
424vnodemodeprep(void)
425{
426	int mib[2];
427	size_t num;
428
429	if (kd == NULL) {
430		mib[0] = CTL_KERN;
431		mib[1] = KERN_NUMVNODES;
432		num = sizeof(numvnodes);
433		if (sysctl(mib, 2, &numvnodes, &num, NULL, 0) < 0)
434			err(1, "sysctl(KERN_NUMVNODES) failed");
435	}
436}
437
438void
439vnode_header(void)
440{
441	(void)printf("%*s TYP VFLAG  USE HOLD", 2 * (int)sizeof(long), "ADDR");
442}
443
444void
445vnode_print(struct vnode *avnode, struct vnode *vp)
446{
447	char *type, flags[16];
448	char *fp;
449	int flag;
450
451	/*
452	 * set type
453	 */
454	switch (vp->v_type) {
455	case VNON:
456		type = "non"; break;
457	case VREG:
458		type = "reg"; break;
459	case VDIR:
460		type = "dir"; break;
461	case VBLK:
462		type = "blk"; break;
463	case VCHR:
464		type = "chr"; break;
465	case VLNK:
466		type = "lnk"; break;
467	case VSOCK:
468		type = "soc"; break;
469	case VFIFO:
470		type = "fif"; break;
471	case VBAD:
472		type = "bad"; break;
473	default:
474		type = "unk"; break;
475	}
476	/*
477	 * gather flags
478	 */
479	fp = flags;
480	flag = vp->v_flag;
481	if (flag & VROOT)
482		*fp++ = 'R';
483	if (flag & VTEXT)
484		*fp++ = 'T';
485	if (flag & VSYSTEM)
486		*fp++ = 'S';
487	if (flag & VISTTY)
488		*fp++ = 'I';
489	if (flag & VXLOCK)
490		*fp++ = 'L';
491	if (flag & VXWANT)
492		*fp++ = 'W';
493	if (vp->v_bioflag & VBIOWAIT)
494		*fp++ = 'B';
495	if (flag & VALIASED)
496		*fp++ = 'A';
497	if (vp->v_bioflag & VBIOONFREELIST)
498		*fp++ = 'F';
499	if (flag & VLOCKSWORK)
500		*fp++ = 'l';
501	if (vp->v_bioflag & VBIOONSYNCLIST)
502		*fp++ = 's';
503	if (fp == flags)
504		*fp++ = '-';
505	*fp = '\0';
506	(void)printf("%0*lx %s %5s %4d %4u",
507	    2 * (int)sizeof(long), hideroot ? 0L : (long)avnode,
508	    type, flags, vp->v_usecount, vp->v_holdcnt);
509}
510
511void
512ufs_header(void)
513{
514	(void)printf(" FILEID IFLAG RDEV|SZ");
515}
516
517int
518ufs_print(struct vnode *vp)
519{
520	int flag;
521	struct inode inode, *ip = &inode;
522	struct ufs1_dinode di1;
523	char flagbuf[16], *flags = flagbuf;
524	char *name;
525	mode_t type;
526
527	KGETRET(VTOI(vp), &inode, sizeof(struct inode), "vnode's inode");
528	KGETRET(inode.i_din1, &di1, sizeof(struct ufs1_dinode),
529	    "vnode's dinode");
530
531	inode.i_din1 = &di1;
532	flag = ip->i_flag;
533#if 0
534	if (flag & IN_LOCKED)
535		*flags++ = 'L';
536	if (flag & IN_WANTED)
537		*flags++ = 'W';
538	if (flag & IN_LWAIT)
539		*flags++ = 'Z';
540#endif
541	if (flag & IN_ACCESS)
542		*flags++ = 'A';
543	if (flag & IN_CHANGE)
544		*flags++ = 'C';
545	if (flag & IN_UPDATE)
546		*flags++ = 'U';
547	if (flag & IN_MODIFIED)
548		*flags++ = 'M';
549	if (flag & IN_LAZYMOD)
550		*flags++ = 'm';
551	if (flag & IN_RENAME)
552		*flags++ = 'R';
553	if (flag & IN_SHLOCK)
554		*flags++ = 'S';
555	if (flag & IN_EXLOCK)
556		*flags++ = 'E';
557	if (flag == 0)
558		*flags++ = '-';
559	*flags = '\0';
560
561	(void)printf(" %6d %5s", ip->i_number, flagbuf);
562	type = ip->i_ffs1_mode & S_IFMT;
563	if (S_ISCHR(ip->i_ffs1_mode) || S_ISBLK(ip->i_ffs1_mode))
564		if (usenumflag ||
565		    ((name = devname(ip->i_ffs1_rdev, type)) == NULL))
566			(void)printf("   %2d,%-2d",
567			    major(ip->i_ffs1_rdev), minor(ip->i_ffs1_rdev));
568		else
569			(void)printf(" %7s", name);
570	else
571		(void)printf(" %7lld", (long long)ip->i_ffs1_size);
572	return (0);
573}
574
575void
576ext2fs_header(void)
577{
578	(void)printf(" FILEID IFLAG SZ");
579}
580
581int
582ext2fs_print(struct vnode *vp)
583{
584	int flag;
585	struct inode inode, *ip = &inode;
586	struct ext2fs_dinode di;
587	char flagbuf[16], *flags = flagbuf;
588
589	KGETRET(VTOI(vp), &inode, sizeof(struct inode), "vnode's inode");
590	KGETRET(inode.i_e2din, &di, sizeof(struct ext2fs_dinode),
591	    "vnode's dinode");
592
593	inode.i_e2din = &di;
594	flag = ip->i_flag;
595
596#if 0
597	if (flag & IN_LOCKED)
598		*flags++ = 'L';
599	if (flag & IN_WANTED)
600		*flags++ = 'W';
601	if (flag & IN_LWAIT)
602		*flags++ = 'Z';
603#endif
604	if (flag & IN_ACCESS)
605		*flags++ = 'A';
606	if (flag & IN_CHANGE)
607		*flags++ = 'C';
608	if (flag & IN_UPDATE)
609		*flags++ = 'U';
610	if (flag & IN_MODIFIED)
611		*flags++ = 'M';
612	if (flag & IN_RENAME)
613		*flags++ = 'R';
614	if (flag & IN_SHLOCK)
615		*flags++ = 'S';
616	if (flag & IN_EXLOCK)
617		*flags++ = 'E';
618	if (flag == 0)
619		*flags++ = '-';
620	*flags = '\0';
621
622	(void)printf(" %6d %5s %2d", ip->i_number, flagbuf, ip->i_e2fs_size);
623	return (0);
624}
625
626void
627nfs_header(void)
628{
629	(void)printf(" FILEID NFLAG RDEV|SZ");
630}
631
632int
633nfs_print(struct vnode *vp)
634{
635	struct nfsnode nfsnode, *np = &nfsnode;
636	char flagbuf[16], *flags = flagbuf;
637	int flag;
638	char *name;
639	mode_t type;
640
641	KGETRET(VTONFS(vp), &nfsnode, sizeof(nfsnode), "vnode's nfsnode");
642	flag = np->n_flag;
643	if (flag & NFLUSHWANT)
644		*flags++ = 'W';
645	if (flag & NFLUSHINPROG)
646		*flags++ = 'P';
647	if (flag & NMODIFIED)
648		*flags++ = 'M';
649	if (flag & NWRITEERR)
650		*flags++ = 'E';
651	if (flag & NACC)
652		*flags++ = 'A';
653	if (flag & NUPD)
654		*flags++ = 'U';
655	if (flag & NCHG)
656		*flags++ = 'C';
657	if (flag == 0)
658		*flags++ = '-';
659	*flags = '\0';
660
661	(void)printf(" %6lld %5s", (long long)np->n_vattr.va_fileid, flagbuf);
662	type = np->n_vattr.va_mode & S_IFMT;
663	if (S_ISCHR(np->n_vattr.va_mode) || S_ISBLK(np->n_vattr.va_mode))
664		if (usenumflag ||
665		    ((name = devname(np->n_vattr.va_rdev, type)) == NULL))
666			(void)printf("   %2d,%-2d", major(np->n_vattr.va_rdev),
667			    minor(np->n_vattr.va_rdev));
668		else
669			(void)printf(" %7s", name);
670	else
671		(void)printf(" %7lld", (long long)np->n_size);
672	return (0);
673}
674
675/*
676 * Given a pointer to a mount structure in kernel space,
677 * read it in and return a usable pointer to it.
678 */
679struct mount *
680getmnt(struct mount *maddr)
681{
682	static struct mtab {
683		struct mtab *next;
684		struct mount *maddr;
685		struct mount mount;
686	} *mhead = NULL;
687	struct mtab *mt;
688
689	for (mt = mhead; mt != NULL; mt = mt->next)
690		if (maddr == mt->maddr)
691			return (&mt->mount);
692	if ((mt = malloc(sizeof(struct mtab))) == NULL)
693		err(1, "malloc: mount table");
694	KGETRET(maddr, &mt->mount, sizeof(struct mount), "mount table");
695	mt->maddr = maddr;
696	mt->next = mhead;
697	mhead = mt;
698	return (&mt->mount);
699}
700
701void
702mount_print(struct mount *mp)
703{
704	int flags;
705
706	(void)printf("*** MOUNT ");
707	(void)printf("%.*s %s on %s", MFSNAMELEN,
708	    mp->mnt_stat.f_fstypename, mp->mnt_stat.f_mntfromname,
709	    mp->mnt_stat.f_mntonname);
710	if ((flags = mp->mnt_flag)) {
711		char *comma = "(";
712
713		putchar(' ');
714		/* user visible flags */
715		if (flags & MNT_RDONLY) {
716			(void)printf("%srdonly", comma);
717			flags &= ~MNT_RDONLY;
718			comma = ",";
719		}
720		if (flags & MNT_SYNCHRONOUS) {
721			(void)printf("%ssynchronous", comma);
722			flags &= ~MNT_SYNCHRONOUS;
723			comma = ",";
724		}
725		if (flags & MNT_NOEXEC) {
726			(void)printf("%snoexec", comma);
727			flags &= ~MNT_NOEXEC;
728			comma = ",";
729		}
730		if (flags & MNT_NOSUID) {
731			(void)printf("%snosuid", comma);
732			flags &= ~MNT_NOSUID;
733			comma = ",";
734		}
735		if (flags & MNT_NODEV) {
736			(void)printf("%snodev", comma);
737			flags &= ~MNT_NODEV;
738			comma = ",";
739		}
740		if (flags & MNT_ASYNC) {
741			(void)printf("%sasync", comma);
742			flags &= ~MNT_ASYNC;
743			comma = ",";
744		}
745		if (flags & MNT_EXRDONLY) {
746			(void)printf("%sexrdonly", comma);
747			flags &= ~MNT_EXRDONLY;
748			comma = ",";
749		}
750		if (flags & MNT_EXPORTED) {
751			(void)printf("%sexport", comma);
752			flags &= ~MNT_EXPORTED;
753			comma = ",";
754		}
755		if (flags & MNT_DEFEXPORTED) {
756			(void)printf("%sdefdexported", comma);
757			flags &= ~MNT_DEFEXPORTED;
758			comma = ",";
759		}
760		if (flags & MNT_EXPORTANON) {
761			(void)printf("%sexportanon", comma);
762			flags &= ~MNT_EXPORTANON;
763			comma = ",";
764		}
765		if (flags & MNT_WXALLOWED) {
766			(void)printf("%swxallowed", comma);
767			flags &= ~MNT_WXALLOWED;
768			comma = ",";
769		}
770		if (flags & MNT_LOCAL) {
771			(void)printf("%slocal", comma);
772			flags &= ~MNT_LOCAL;
773			comma = ",";
774		}
775		if (flags & MNT_QUOTA) {
776			(void)printf("%squota", comma);
777			flags &= ~MNT_QUOTA;
778			comma = ",";
779		}
780		if (flags & MNT_ROOTFS) {
781			(void)printf("%srootfs", comma);
782			flags &= ~MNT_ROOTFS;
783			comma = ",";
784		}
785		if (flags & MNT_NOATIME) {
786			(void)printf("%snoatime", comma);
787			flags &= ~MNT_NOATIME;
788			comma = ",";
789		}
790		/* filesystem control flags */
791		if (flags & MNT_UPDATE) {
792			(void)printf("%supdate", comma);
793			flags &= ~MNT_UPDATE;
794			comma = ",";
795		}
796		if (flags & MNT_DELEXPORT) {
797			(void)printf("%sdelexport", comma);
798			flags &= ~MNT_DELEXPORT;
799			comma = ",";
800		}
801		if (flags & MNT_RELOAD) {
802			(void)printf("%sreload", comma);
803			flags &= ~MNT_RELOAD;
804			comma = ",";
805		}
806		if (flags & MNT_FORCE) {
807			(void)printf("%sforce", comma);
808			flags &= ~MNT_FORCE;
809			comma = ",";
810		}
811		if (flags & MNT_WANTRDWR) {
812			(void)printf("%swantrdwr", comma);
813			flags &= ~MNT_WANTRDWR;
814			comma = ",";
815		}
816		if (flags & MNT_SOFTDEP) {
817			(void)printf("%ssoftdep", comma);
818			flags &= ~MNT_SOFTDEP;
819			comma = ",";
820		}
821		if (flags)
822			(void)printf("%sunknown_flags:%x", comma, flags);
823		(void)printf(")");
824	}
825	(void)printf("\n");
826}
827
828/*
829 * simulate what a running kernel does in kinfo_vnode
830 */
831struct e_vnode *
832kinfo_vnodes(void)
833{
834	struct mntlist kvm_mountlist;
835	struct mount *mp, mount;
836	struct vnode *vp, vnode;
837	char *vbuf, *evbuf, *bp;
838	size_t num;
839
840	if (kd != NULL)
841		KGET(V_NUMV, numvnodes);
842	if (totalflag)
843		return NULL;
844	if ((vbuf = calloc(numvnodes + 20,
845	    sizeof(struct vnode *) + sizeof(struct vnode))) == NULL)
846		err(1, "malloc: vnode buffer");
847	bp = vbuf;
848	evbuf = vbuf + (numvnodes + 20) *
849	    (sizeof(struct vnode *) + sizeof(struct vnode));
850	KGET(V_MOUNTLIST, kvm_mountlist);
851	num = 0;
852	for (mp = TAILQ_FIRST(&kvm_mountlist); mp != NULL;
853	    mp = TAILQ_NEXT(&mount, mnt_list)) {
854		KGETRET(mp, &mount, sizeof(mount), "mount entry");
855		for (vp = LIST_FIRST(&mount.mnt_vnodelist);
856		    vp != NULL; vp = LIST_NEXT(&vnode, v_mntvnodes)) {
857			KGETRET(vp, &vnode, sizeof(vnode), "vnode");
858			if ((bp + sizeof(struct vnode *) +
859			    sizeof(struct vnode)) > evbuf)
860				/* XXX - should realloc */
861				errx(1, "no more room for vnodes");
862			memmove(bp, &vp, sizeof(struct vnode *));
863			bp += sizeof(struct vnode *);
864			memmove(bp, &vnode, sizeof(struct vnode));
865			bp += sizeof(struct vnode);
866			num++;
867		}
868	}
869	numvnodes = num;
870	return ((struct e_vnode *)vbuf);
871}
872
873const char hdr[] =
874"   LINE RAW  CAN  OUT  HWT LWT    COL STATE      SESS  PGID DISC\n";
875
876void
877tty2itty(struct tty *tp, struct itty *itp)
878{
879	itp->t_dev = tp->t_dev;
880	itp->t_rawq_c_cc = tp->t_rawq.c_cc;
881	itp->t_canq_c_cc = tp->t_canq.c_cc;
882	itp->t_outq_c_cc = tp->t_outq.c_cc;
883	itp->t_hiwat = tp->t_hiwat;
884	itp->t_lowat = tp->t_lowat;
885	itp->t_column = tp->t_column;
886	itp->t_state = tp->t_state;
887	itp->t_session = tp->t_session;
888	if (tp->t_pgrp != NULL)
889		KGET2(&tp->t_pgrp->pg_id, &itp->t_pgrp_pg_id, sizeof(pid_t), "pgid");
890	itp->t_line = tp->t_line;
891}
892
893void
894ttymode(void)
895{
896	struct ttylist_head tty_head;
897	struct tty *tp, tty;
898	int i;
899	struct itty itty;
900
901	if (need_nlist)
902		KGET(TTY_NTTY, ntty);
903	(void)printf("%d terminal device%s\n", ntty, ntty == 1 ? "" : "s");
904	(void)printf("%s", hdr);
905	if (!need_nlist) {
906		for (i = 0; i < ntty; i++)
907			ttyprt(&globalitp[i]);
908		free(globalitp);
909	} else {
910		KGET(TTY_TTYLIST, tty_head);
911		for (tp = TAILQ_FIRST(&tty_head); tp;
912		    tp = TAILQ_NEXT(&tty, tty_link)) {
913			KGET2(tp, &tty, sizeof tty, "tty struct");
914			tty2itty(&tty, &itty);
915			ttyprt(&itty);
916		}
917	}
918}
919
920void
921ttymodeprep(void)
922{
923	int mib[3];
924	size_t nlen;
925
926	if (!need_nlist) {
927		mib[0] = CTL_KERN;
928		mib[1] = KERN_TTYCOUNT;
929		nlen = sizeof(ntty);
930		if (sysctl(mib, 2, &ntty, &nlen, NULL, 0) < 0)
931			err(1, "sysctl(KERN_TTYCOUNT) failed");
932
933		mib[0] = CTL_KERN;
934		mib[1] = KERN_TTY;
935		mib[2] = KERN_TTY_INFO;
936		if ((globalitp = reallocarray(NULL, ntty, sizeof(struct itty))) == NULL)
937			err(1, "malloc");
938		nlen = ntty * sizeof(struct itty);
939		if (sysctl(mib, 3, globalitp, &nlen, NULL, 0) < 0)
940			err(1, "sysctl(KERN_TTY_INFO) failed");
941	}
942}
943
944struct {
945	int flag;
946	char val;
947} ttystates[] = {
948	{ TS_WOPEN,	'W'},
949	{ TS_ISOPEN,	'O'},
950	{ TS_CARR_ON,	'C'},
951	{ TS_TIMEOUT,	'T'},
952	{ TS_FLUSH,	'F'},
953	{ TS_BUSY,	'B'},
954	{ TS_ASLEEP,	'A'},
955	{ TS_XCLUDE,	'X'},
956	{ TS_TTSTOP,	'S'},
957	{ TS_TBLOCK,	'K'},
958	{ TS_ASYNC,	'Y'},
959	{ TS_BKSL,	'D'},
960	{ TS_ERASE,	'E'},
961	{ TS_LNCH,	'L'},
962	{ TS_TYPEN,	'P'},
963	{ TS_CNTTB,	'N'},
964	{ 0,		'\0'},
965};
966
967void
968ttyprt(struct itty *tp)
969{
970	char *name, state[20];
971	int i, j;
972
973	if (usenumflag || (name = devname(tp->t_dev, S_IFCHR)) == NULL)
974		(void)printf("%2d,%-3d   ", major(tp->t_dev), minor(tp->t_dev));
975	else
976		(void)printf("%7s ", name);
977	(void)printf("%3d %4d ", tp->t_rawq_c_cc, tp->t_canq_c_cc);
978	(void)printf("%4d %4d %3d %6d ", tp->t_outq_c_cc,
979		tp->t_hiwat, tp->t_lowat, tp->t_column);
980	for (i = j = 0; ttystates[i].flag; i++)
981		if (tp->t_state&ttystates[i].flag)
982			state[j++] = ttystates[i].val;
983	if (j == 0)
984		state[j++] = '-';
985	state[j] = '\0';
986	(void)printf("%-6s %8lx", state,
987		hideroot ? 0 : (u_long)tp->t_session & 0xffffffff);
988	(void)printf("%6d ", tp->t_pgrp_pg_id);
989	switch (tp->t_line) {
990	case TTYDISC:
991		(void)printf("term\n");
992		break;
993	case PPPDISC:
994		(void)printf("ppp\n");
995		break;
996	case NMEADISC:
997		(void)printf("nmea\n");
998		break;
999	default:
1000		(void)printf("%d\n", tp->t_line);
1001		break;
1002	}
1003}
1004
1005void
1006filemode(void)
1007{
1008	char flagbuf[16], *fbp;
1009	static char *dtypes[] = { "???", "inode", "socket", "pipe", "kqueue", "???", "???" };
1010
1011	globalnl = vnodenl;
1012
1013	if (nlistf != NULL || memf != NULL) {
1014		KGET(FNL_MAXFILE, maxfile);
1015		if (totalflag) {
1016			KGET(FNL_NFILE, nfile);
1017			(void)printf("%3d/%3d files\n", nfile, maxfile);
1018			return;
1019		}
1020	}
1021
1022	(void)printf("%d/%d open files\n", nfile, maxfile);
1023	if (totalflag)
1024		return;
1025
1026	(void)printf("%*s TYPE       FLG  CNT  MSG  %*s  OFFSET\n",
1027	    2 * (int)sizeof(long), "LOC", 2 * (int)sizeof(long), "DATA");
1028	for (; nfile-- > 0; kf++) {
1029		(void)printf("%0*llx ", 2 * (int)sizeof(long),
1030		    hideroot ? 0LL : kf->f_fileaddr);
1031		(void)printf("%-8.8s", dtypes[
1032		    (kf->f_type >= (sizeof(dtypes)/sizeof(dtypes[0])))
1033		    ? 0 : kf->f_type]);
1034		fbp = flagbuf;
1035		if (kf->f_flag & FREAD)
1036			*fbp++ = 'R';
1037		if (kf->f_flag & FWRITE)
1038			*fbp++ = 'W';
1039		if (kf->f_flag & FAPPEND)
1040			*fbp++ = 'A';
1041		if (kf->f_flag & FASYNC)
1042			*fbp++ = 'I';
1043
1044		if (kf->f_iflags & FIF_HASLOCK)
1045			*fbp++ = 'L';
1046		if (kf->f_iflags & FIF_LARVAL)
1047			*fbp++ = 'l';
1048
1049		*fbp = '\0';
1050		(void)printf("%6s  %3ld", flagbuf, (long)kf->f_count);
1051		(void)printf("  %3ld", (long)kf->f_msgcount);
1052		(void)printf("  %0*lx", 2 * (int)sizeof(long),
1053		    hideroot ? 0L : (long)kf->f_data);
1054
1055		if (kf->f_offset == (uint64_t)-1)
1056			(void)printf("  *\n");
1057		else if (kf->f_offset > INT64_MAX) {
1058			/* would have been negative */
1059			(void)printf("  %llx\n",
1060			    hideroot ? 0LL : (long long)kf->f_offset);
1061		} else
1062			(void)printf("  %lld\n",
1063			    hideroot ? 0LL : (long long)kf->f_offset);
1064	}
1065}
1066
1067void
1068filemodeprep(void)
1069{
1070	int mib[2];
1071	size_t len;
1072
1073	if (nlistf == NULL && memf == NULL) {
1074		mib[0] = CTL_KERN;
1075		mib[1] = KERN_MAXFILES;
1076		len = sizeof(maxfile);
1077		if (sysctl(mib, 2, &maxfile, &len, NULL, 0) < 0)
1078			err(1, "sysctl(KERN_MAXFILES) failed");
1079		if (totalflag) {
1080			mib[0] = CTL_KERN;
1081			mib[1] = KERN_NFILES;
1082			len = sizeof(nfile);
1083			if (sysctl(mib, 2, &nfile, &len, NULL, 0) < 0)
1084				err(1, "sysctl(KERN_NFILES) failed");
1085		}
1086	}
1087
1088	if (!totalflag) {
1089		kf = kvm_getfiles(kd, KERN_FILE_BYFILE, 0, sizeof *kf, &nfile);
1090		if (kf == NULL) {
1091			warnx("kvm_getfiles: %s", kvm_geterr(kd));
1092			return;
1093		}
1094	}
1095}
1096
1097/*
1098 * swapmode is based on a program called swapinfo written
1099 * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
1100 */
1101void
1102swapmode(void)
1103{
1104	char *header;
1105	int hlen = 10, nswap;
1106	int bdiv, i, avail, nfree, npfree, used;
1107	long blocksize;
1108	struct swapent *swdev;
1109
1110	if (kflag) {
1111		header = "1K-blocks";
1112		blocksize = 1024;
1113		hlen = strlen(header);
1114	} else
1115		header = getbsize(&hlen, &blocksize);
1116
1117	nswap = swapctl(SWAP_NSWAP, 0, 0);
1118	if (nswap == 0) {
1119		if (!totalflag)
1120			(void)printf("%-11s %*s %8s %8s %8s  %s\n",
1121			    "Device", hlen, header,
1122			    "Used", "Avail", "Capacity", "Priority");
1123		(void)printf("%-11s %*d %8d %8d %5.0f%%\n",
1124		    "Total", hlen, 0, 0, 0, 0.0);
1125		return;
1126	}
1127	if ((swdev = calloc(nswap, sizeof(*swdev))) == NULL)
1128		err(1, "malloc");
1129	if (swapctl(SWAP_STATS, swdev, nswap) == -1)
1130		err(1, "swapctl");
1131
1132	if (!totalflag)
1133		(void)printf("%-11s %*s %8s %8s %8s  %s\n",
1134		    "Device", hlen, header,
1135		    "Used", "Avail", "Capacity", "Priority");
1136
1137	/* Run through swap list, doing the funky monkey. */
1138	bdiv = blocksize / DEV_BSIZE;
1139	avail = nfree = npfree = 0;
1140	for (i = 0; i < nswap; i++) {
1141		int xsize, xfree;
1142
1143		if (!(swdev[i].se_flags & SWF_ENABLE))
1144			continue;
1145
1146		if (!totalflag) {
1147			if (usenumflag)
1148				(void)printf("%2d,%-2d       %*d ",
1149				    major(swdev[i].se_dev),
1150				    minor(swdev[i].se_dev),
1151				    hlen, swdev[i].se_nblks / bdiv);
1152			else
1153				(void)printf("%-11s %*d ", swdev[i].se_path,
1154				    hlen, swdev[i].se_nblks / bdiv);
1155		}
1156
1157		xsize = swdev[i].se_nblks;
1158		used = swdev[i].se_inuse;
1159		xfree = xsize - used;
1160		nfree += (xsize - used);
1161		npfree++;
1162		avail += xsize;
1163		if (totalflag)
1164			continue;
1165		(void)printf("%8d %8d %5.0f%%    %d\n",
1166		    used / bdiv, xfree / bdiv,
1167		    (double)used / (double)xsize * 100.0,
1168		    swdev[i].se_priority);
1169	}
1170	free(swdev);
1171
1172	/*
1173	 * If only one partition has been set up via swapon(8), we don't
1174	 * need to bother with totals.
1175	 */
1176	used = avail - nfree;
1177	if (totalflag) {
1178		(void)printf("%dM/%dM swap space\n",
1179		    used / (1048576 / DEV_BSIZE),
1180		    avail / (1048576 / DEV_BSIZE));
1181		return;
1182	}
1183	if (npfree > 1) {
1184		(void)printf("%-11s %*d %8d %8d %5.0f%%\n",
1185		    "Total", hlen, avail / bdiv, used / bdiv, nfree / bdiv,
1186		    (double)used / (double)avail * 100.0);
1187	}
1188}
1189
1190static void __dead
1191usage(void)
1192{
1193	(void)fprintf(stderr, "usage: "
1194	    "pstat [-fknsTtv] [-M core] [-N system] [-d format symbol ...]\n");
1195	exit(1);
1196}
1197