1/*
2 * page-types: Tool for querying page flags
3 *
4 * This program is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License as published by the Free
6 * Software Foundation; version 2.
7 *
8 * This program is distributed in the hope that it will be useful, but WITHOUT
9 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
11 * more details.
12 *
13 * You should find a copy of v2 of the GNU General Public License somewhere on
14 * your Linux system; if not, write to the Free Software Foundation, Inc., 59
15 * Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16 *
17 * Copyright (C) 2009 Intel corporation
18 *
19 * Authors: Wu Fengguang <fengguang.wu@intel.com>
20 */
21
22#define _FILE_OFFSET_BITS 64
23#define _GNU_SOURCE
24#include <stdio.h>
25#include <stdlib.h>
26#include <unistd.h>
27#include <stdint.h>
28#include <stdarg.h>
29#include <string.h>
30#include <getopt.h>
31#include <limits.h>
32#include <assert.h>
33#include <ftw.h>
34#include <time.h>
35#include <setjmp.h>
36#include <signal.h>
37#include <sys/types.h>
38#include <sys/errno.h>
39#include <sys/fcntl.h>
40#include <sys/mount.h>
41#include <sys/statfs.h>
42#include <sys/mman.h>
43#include "../../include/uapi/linux/magic.h"
44#include "../../include/uapi/linux/kernel-page-flags.h"
45#include <api/fs/debugfs.h>
46
47#ifndef MAX_PATH
48# define MAX_PATH 256
49#endif
50
51#ifndef STR
52# define _STR(x) #x
53# define STR(x) _STR(x)
54#endif
55
56/*
57 * pagemap kernel ABI bits
58 */
59
60#define PM_ENTRY_BYTES      sizeof(uint64_t)
61#define PM_STATUS_BITS      3
62#define PM_STATUS_OFFSET    (64 - PM_STATUS_BITS)
63#define PM_STATUS_MASK      (((1LL << PM_STATUS_BITS) - 1) << PM_STATUS_OFFSET)
64#define PM_STATUS(nr)       (((nr) << PM_STATUS_OFFSET) & PM_STATUS_MASK)
65#define PM_PSHIFT_BITS      6
66#define PM_PSHIFT_OFFSET    (PM_STATUS_OFFSET - PM_PSHIFT_BITS)
67#define PM_PSHIFT_MASK      (((1LL << PM_PSHIFT_BITS) - 1) << PM_PSHIFT_OFFSET)
68#define __PM_PSHIFT(x)      (((uint64_t) (x) << PM_PSHIFT_OFFSET) & PM_PSHIFT_MASK)
69#define PM_PFRAME_MASK      ((1LL << PM_PSHIFT_OFFSET) - 1)
70#define PM_PFRAME(x)        ((x) & PM_PFRAME_MASK)
71
72#define __PM_SOFT_DIRTY      (1LL)
73#define PM_PRESENT          PM_STATUS(4LL)
74#define PM_SWAP             PM_STATUS(2LL)
75#define PM_SOFT_DIRTY       __PM_PSHIFT(__PM_SOFT_DIRTY)
76
77
78/*
79 * kernel page flags
80 */
81
82#define KPF_BYTES		8
83#define PROC_KPAGEFLAGS		"/proc/kpageflags"
84
85/* [32-] kernel hacking assistances */
86#define KPF_RESERVED		32
87#define KPF_MLOCKED		33
88#define KPF_MAPPEDTODISK	34
89#define KPF_PRIVATE		35
90#define KPF_PRIVATE_2		36
91#define KPF_OWNER_PRIVATE	37
92#define KPF_ARCH		38
93#define KPF_UNCACHED		39
94#define KPF_SOFTDIRTY		40
95
96/* [48-] take some arbitrary free slots for expanding overloaded flags
97 * not part of kernel API
98 */
99#define KPF_READAHEAD		48
100#define KPF_SLOB_FREE		49
101#define KPF_SLUB_FROZEN		50
102#define KPF_SLUB_DEBUG		51
103
104#define KPF_ALL_BITS		((uint64_t)~0ULL)
105#define KPF_HACKERS_BITS	(0xffffULL << 32)
106#define KPF_OVERLOADED_BITS	(0xffffULL << 48)
107#define BIT(name)		(1ULL << KPF_##name)
108#define BITS_COMPOUND		(BIT(COMPOUND_HEAD) | BIT(COMPOUND_TAIL))
109
110static const char * const page_flag_names[] = {
111	[KPF_LOCKED]		= "L:locked",
112	[KPF_ERROR]		= "E:error",
113	[KPF_REFERENCED]	= "R:referenced",
114	[KPF_UPTODATE]		= "U:uptodate",
115	[KPF_DIRTY]		= "D:dirty",
116	[KPF_LRU]		= "l:lru",
117	[KPF_ACTIVE]		= "A:active",
118	[KPF_SLAB]		= "S:slab",
119	[KPF_WRITEBACK]		= "W:writeback",
120	[KPF_RECLAIM]		= "I:reclaim",
121	[KPF_BUDDY]		= "B:buddy",
122
123	[KPF_MMAP]		= "M:mmap",
124	[KPF_ANON]		= "a:anonymous",
125	[KPF_SWAPCACHE]		= "s:swapcache",
126	[KPF_SWAPBACKED]	= "b:swapbacked",
127	[KPF_COMPOUND_HEAD]	= "H:compound_head",
128	[KPF_COMPOUND_TAIL]	= "T:compound_tail",
129	[KPF_HUGE]		= "G:huge",
130	[KPF_UNEVICTABLE]	= "u:unevictable",
131	[KPF_HWPOISON]		= "X:hwpoison",
132	[KPF_NOPAGE]		= "n:nopage",
133	[KPF_KSM]		= "x:ksm",
134	[KPF_THP]		= "t:thp",
135	[KPF_BALLOON]		= "o:balloon",
136	[KPF_ZERO_PAGE]		= "z:zero_page",
137
138	[KPF_RESERVED]		= "r:reserved",
139	[KPF_MLOCKED]		= "m:mlocked",
140	[KPF_MAPPEDTODISK]	= "d:mappedtodisk",
141	[KPF_PRIVATE]		= "P:private",
142	[KPF_PRIVATE_2]		= "p:private_2",
143	[KPF_OWNER_PRIVATE]	= "O:owner_private",
144	[KPF_ARCH]		= "h:arch",
145	[KPF_UNCACHED]		= "c:uncached",
146	[KPF_SOFTDIRTY]		= "f:softdirty",
147
148	[KPF_READAHEAD]		= "I:readahead",
149	[KPF_SLOB_FREE]		= "P:slob_free",
150	[KPF_SLUB_FROZEN]	= "A:slub_frozen",
151	[KPF_SLUB_DEBUG]	= "E:slub_debug",
152};
153
154
155static const char * const debugfs_known_mountpoints[] = {
156	"/sys/kernel/debug",
157	"/debug",
158	0,
159};
160
161/*
162 * data structures
163 */
164
165static int		opt_raw;	/* for kernel developers */
166static int		opt_list;	/* list pages (in ranges) */
167static int		opt_no_summary;	/* don't show summary */
168static pid_t		opt_pid;	/* process to walk */
169const char *		opt_file;
170
171#define MAX_ADDR_RANGES	1024
172static int		nr_addr_ranges;
173static unsigned long	opt_offset[MAX_ADDR_RANGES];
174static unsigned long	opt_size[MAX_ADDR_RANGES];
175
176#define MAX_VMAS	10240
177static int		nr_vmas;
178static unsigned long	pg_start[MAX_VMAS];
179static unsigned long	pg_end[MAX_VMAS];
180
181#define MAX_BIT_FILTERS	64
182static int		nr_bit_filters;
183static uint64_t		opt_mask[MAX_BIT_FILTERS];
184static uint64_t		opt_bits[MAX_BIT_FILTERS];
185
186static int		page_size;
187
188static int		pagemap_fd;
189static int		kpageflags_fd;
190
191static int		opt_hwpoison;
192static int		opt_unpoison;
193
194static char		*hwpoison_debug_fs;
195static int		hwpoison_inject_fd;
196static int		hwpoison_forget_fd;
197
198#define HASH_SHIFT	13
199#define HASH_SIZE	(1 << HASH_SHIFT)
200#define HASH_MASK	(HASH_SIZE - 1)
201#define HASH_KEY(flags)	(flags & HASH_MASK)
202
203static unsigned long	total_pages;
204static unsigned long	nr_pages[HASH_SIZE];
205static uint64_t		page_flags[HASH_SIZE];
206
207
208/*
209 * helper functions
210 */
211
212#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
213
214#define min_t(type, x, y) ({			\
215	type __min1 = (x);			\
216	type __min2 = (y);			\
217	__min1 < __min2 ? __min1 : __min2; })
218
219#define max_t(type, x, y) ({			\
220	type __max1 = (x);			\
221	type __max2 = (y);			\
222	__max1 > __max2 ? __max1 : __max2; })
223
224static unsigned long pages2mb(unsigned long pages)
225{
226	return (pages * page_size) >> 20;
227}
228
229static void fatal(const char *x, ...)
230{
231	va_list ap;
232
233	va_start(ap, x);
234	vfprintf(stderr, x, ap);
235	va_end(ap);
236	exit(EXIT_FAILURE);
237}
238
239static int checked_open(const char *pathname, int flags)
240{
241	int fd = open(pathname, flags);
242
243	if (fd < 0) {
244		perror(pathname);
245		exit(EXIT_FAILURE);
246	}
247
248	return fd;
249}
250
251/*
252 * pagemap/kpageflags routines
253 */
254
255static unsigned long do_u64_read(int fd, char *name,
256				 uint64_t *buf,
257				 unsigned long index,
258				 unsigned long count)
259{
260	long bytes;
261
262	if (index > ULONG_MAX / 8)
263		fatal("index overflow: %lu\n", index);
264
265	bytes = pread(fd, buf, count * 8, (off_t)index * 8);
266	if (bytes < 0) {
267		perror(name);
268		exit(EXIT_FAILURE);
269	}
270	if (bytes % 8)
271		fatal("partial read: %lu bytes\n", bytes);
272
273	return bytes / 8;
274}
275
276static unsigned long kpageflags_read(uint64_t *buf,
277				     unsigned long index,
278				     unsigned long pages)
279{
280	return do_u64_read(kpageflags_fd, PROC_KPAGEFLAGS, buf, index, pages);
281}
282
283static unsigned long pagemap_read(uint64_t *buf,
284				  unsigned long index,
285				  unsigned long pages)
286{
287	return do_u64_read(pagemap_fd, "/proc/pid/pagemap", buf, index, pages);
288}
289
290static unsigned long pagemap_pfn(uint64_t val)
291{
292	unsigned long pfn;
293
294	if (val & PM_PRESENT)
295		pfn = PM_PFRAME(val);
296	else
297		pfn = 0;
298
299	return pfn;
300}
301
302
303/*
304 * page flag names
305 */
306
307static char *page_flag_name(uint64_t flags)
308{
309	static char buf[65];
310	int present;
311	size_t i, j;
312
313	for (i = 0, j = 0; i < ARRAY_SIZE(page_flag_names); i++) {
314		present = (flags >> i) & 1;
315		if (!page_flag_names[i]) {
316			if (present)
317				fatal("unknown flag bit %d\n", i);
318			continue;
319		}
320		buf[j++] = present ? page_flag_names[i][0] : '_';
321	}
322
323	return buf;
324}
325
326static char *page_flag_longname(uint64_t flags)
327{
328	static char buf[1024];
329	size_t i, n;
330
331	for (i = 0, n = 0; i < ARRAY_SIZE(page_flag_names); i++) {
332		if (!page_flag_names[i])
333			continue;
334		if ((flags >> i) & 1)
335			n += snprintf(buf + n, sizeof(buf) - n, "%s,",
336					page_flag_names[i] + 2);
337	}
338	if (n)
339		n--;
340	buf[n] = '\0';
341
342	return buf;
343}
344
345
346/*
347 * page list and summary
348 */
349
350static void show_page_range(unsigned long voffset, unsigned long offset,
351			    unsigned long size, uint64_t flags)
352{
353	static uint64_t      flags0;
354	static unsigned long voff;
355	static unsigned long index;
356	static unsigned long count;
357
358	if (flags == flags0 && offset == index + count &&
359	    size && voffset == voff + count) {
360		count += size;
361		return;
362	}
363
364	if (count) {
365		if (opt_pid)
366			printf("%lx\t", voff);
367		if (opt_file)
368			printf("%lu\t", voff);
369		printf("%lx\t%lx\t%s\n",
370				index, count, page_flag_name(flags0));
371	}
372
373	flags0 = flags;
374	index  = offset;
375	voff   = voffset;
376	count  = size;
377}
378
379static void flush_page_range(void)
380{
381	show_page_range(0, 0, 0, 0);
382}
383
384static void show_page(unsigned long voffset,
385		      unsigned long offset, uint64_t flags)
386{
387	if (opt_pid)
388		printf("%lx\t", voffset);
389	if (opt_file)
390		printf("%lu\t", voffset);
391	printf("%lx\t%s\n", offset, page_flag_name(flags));
392}
393
394static void show_summary(void)
395{
396	size_t i;
397
398	printf("             flags\tpage-count       MB"
399		"  symbolic-flags\t\t\tlong-symbolic-flags\n");
400
401	for (i = 0; i < ARRAY_SIZE(nr_pages); i++) {
402		if (nr_pages[i])
403			printf("0x%016llx\t%10lu %8lu  %s\t%s\n",
404				(unsigned long long)page_flags[i],
405				nr_pages[i],
406				pages2mb(nr_pages[i]),
407				page_flag_name(page_flags[i]),
408				page_flag_longname(page_flags[i]));
409	}
410
411	printf("             total\t%10lu %8lu\n",
412			total_pages, pages2mb(total_pages));
413}
414
415
416/*
417 * page flag filters
418 */
419
420static int bit_mask_ok(uint64_t flags)
421{
422	int i;
423
424	for (i = 0; i < nr_bit_filters; i++) {
425		if (opt_bits[i] == KPF_ALL_BITS) {
426			if ((flags & opt_mask[i]) == 0)
427				return 0;
428		} else {
429			if ((flags & opt_mask[i]) != opt_bits[i])
430				return 0;
431		}
432	}
433
434	return 1;
435}
436
437static uint64_t expand_overloaded_flags(uint64_t flags, uint64_t pme)
438{
439	/* SLOB/SLUB overload several page flags */
440	if (flags & BIT(SLAB)) {
441		if (flags & BIT(PRIVATE))
442			flags ^= BIT(PRIVATE) | BIT(SLOB_FREE);
443		if (flags & BIT(ACTIVE))
444			flags ^= BIT(ACTIVE) | BIT(SLUB_FROZEN);
445		if (flags & BIT(ERROR))
446			flags ^= BIT(ERROR) | BIT(SLUB_DEBUG);
447	}
448
449	/* PG_reclaim is overloaded as PG_readahead in the read path */
450	if ((flags & (BIT(RECLAIM) | BIT(WRITEBACK))) == BIT(RECLAIM))
451		flags ^= BIT(RECLAIM) | BIT(READAHEAD);
452
453	if (pme & PM_SOFT_DIRTY)
454		flags |= BIT(SOFTDIRTY);
455
456	return flags;
457}
458
459static uint64_t well_known_flags(uint64_t flags)
460{
461	/* hide flags intended only for kernel hacker */
462	flags &= ~KPF_HACKERS_BITS;
463
464	/* hide non-hugeTLB compound pages */
465	if ((flags & BITS_COMPOUND) && !(flags & BIT(HUGE)))
466		flags &= ~BITS_COMPOUND;
467
468	return flags;
469}
470
471static uint64_t kpageflags_flags(uint64_t flags, uint64_t pme)
472{
473	if (opt_raw)
474		flags = expand_overloaded_flags(flags, pme);
475	else
476		flags = well_known_flags(flags);
477
478	return flags;
479}
480
481/*
482 * page actions
483 */
484
485static void prepare_hwpoison_fd(void)
486{
487	char buf[MAX_PATH + 1];
488
489	hwpoison_debug_fs = debugfs_mount(NULL);
490	if (!hwpoison_debug_fs) {
491		perror("mount debugfs");
492		exit(EXIT_FAILURE);
493	}
494
495	if (opt_hwpoison && !hwpoison_inject_fd) {
496		snprintf(buf, MAX_PATH, "%s/hwpoison/corrupt-pfn",
497			hwpoison_debug_fs);
498		hwpoison_inject_fd = checked_open(buf, O_WRONLY);
499	}
500
501	if (opt_unpoison && !hwpoison_forget_fd) {
502		snprintf(buf, MAX_PATH, "%s/hwpoison/unpoison-pfn",
503			hwpoison_debug_fs);
504		hwpoison_forget_fd = checked_open(buf, O_WRONLY);
505	}
506}
507
508static int hwpoison_page(unsigned long offset)
509{
510	char buf[100];
511	int len;
512
513	len = sprintf(buf, "0x%lx\n", offset);
514	len = write(hwpoison_inject_fd, buf, len);
515	if (len < 0) {
516		perror("hwpoison inject");
517		return len;
518	}
519	return 0;
520}
521
522static int unpoison_page(unsigned long offset)
523{
524	char buf[100];
525	int len;
526
527	len = sprintf(buf, "0x%lx\n", offset);
528	len = write(hwpoison_forget_fd, buf, len);
529	if (len < 0) {
530		perror("hwpoison forget");
531		return len;
532	}
533	return 0;
534}
535
536/*
537 * page frame walker
538 */
539
540static size_t hash_slot(uint64_t flags)
541{
542	size_t k = HASH_KEY(flags);
543	size_t i;
544
545	/* Explicitly reserve slot 0 for flags 0: the following logic
546	 * cannot distinguish an unoccupied slot from slot (flags==0).
547	 */
548	if (flags == 0)
549		return 0;
550
551	/* search through the remaining (HASH_SIZE-1) slots */
552	for (i = 1; i < ARRAY_SIZE(page_flags); i++, k++) {
553		if (!k || k >= ARRAY_SIZE(page_flags))
554			k = 1;
555		if (page_flags[k] == 0) {
556			page_flags[k] = flags;
557			return k;
558		}
559		if (page_flags[k] == flags)
560			return k;
561	}
562
563	fatal("hash table full: bump up HASH_SHIFT?\n");
564	exit(EXIT_FAILURE);
565}
566
567static void add_page(unsigned long voffset,
568		     unsigned long offset, uint64_t flags, uint64_t pme)
569{
570	flags = kpageflags_flags(flags, pme);
571
572	if (!bit_mask_ok(flags))
573		return;
574
575	if (opt_hwpoison)
576		hwpoison_page(offset);
577	if (opt_unpoison)
578		unpoison_page(offset);
579
580	if (opt_list == 1)
581		show_page_range(voffset, offset, 1, flags);
582	else if (opt_list == 2)
583		show_page(voffset, offset, flags);
584
585	nr_pages[hash_slot(flags)]++;
586	total_pages++;
587}
588
589#define KPAGEFLAGS_BATCH	(64 << 10)	/* 64k pages */
590static void walk_pfn(unsigned long voffset,
591		     unsigned long index,
592		     unsigned long count,
593		     uint64_t pme)
594{
595	uint64_t buf[KPAGEFLAGS_BATCH];
596	unsigned long batch;
597	unsigned long pages;
598	unsigned long i;
599
600	while (count) {
601		batch = min_t(unsigned long, count, KPAGEFLAGS_BATCH);
602		pages = kpageflags_read(buf, index, batch);
603		if (pages == 0)
604			break;
605
606		for (i = 0; i < pages; i++)
607			add_page(voffset + i, index + i, buf[i], pme);
608
609		index += pages;
610		count -= pages;
611	}
612}
613
614#define PAGEMAP_BATCH	(64 << 10)
615static void walk_vma(unsigned long index, unsigned long count)
616{
617	uint64_t buf[PAGEMAP_BATCH];
618	unsigned long batch;
619	unsigned long pages;
620	unsigned long pfn;
621	unsigned long i;
622
623	while (count) {
624		batch = min_t(unsigned long, count, PAGEMAP_BATCH);
625		pages = pagemap_read(buf, index, batch);
626		if (pages == 0)
627			break;
628
629		for (i = 0; i < pages; i++) {
630			pfn = pagemap_pfn(buf[i]);
631			if (pfn)
632				walk_pfn(index + i, pfn, 1, buf[i]);
633		}
634
635		index += pages;
636		count -= pages;
637	}
638}
639
640static void walk_task(unsigned long index, unsigned long count)
641{
642	const unsigned long end = index + count;
643	unsigned long start;
644	int i = 0;
645
646	while (index < end) {
647
648		while (pg_end[i] <= index)
649			if (++i >= nr_vmas)
650				return;
651		if (pg_start[i] >= end)
652			return;
653
654		start = max_t(unsigned long, pg_start[i], index);
655		index = min_t(unsigned long, pg_end[i], end);
656
657		assert(start < index);
658		walk_vma(start, index - start);
659	}
660}
661
662static void add_addr_range(unsigned long offset, unsigned long size)
663{
664	if (nr_addr_ranges >= MAX_ADDR_RANGES)
665		fatal("too many addr ranges\n");
666
667	opt_offset[nr_addr_ranges] = offset;
668	opt_size[nr_addr_ranges] = min_t(unsigned long, size, ULONG_MAX-offset);
669	nr_addr_ranges++;
670}
671
672static void walk_addr_ranges(void)
673{
674	int i;
675
676	kpageflags_fd = checked_open(PROC_KPAGEFLAGS, O_RDONLY);
677
678	if (!nr_addr_ranges)
679		add_addr_range(0, ULONG_MAX);
680
681	for (i = 0; i < nr_addr_ranges; i++)
682		if (!opt_pid)
683			walk_pfn(opt_offset[i], opt_offset[i], opt_size[i], 0);
684		else
685			walk_task(opt_offset[i], opt_size[i]);
686
687	close(kpageflags_fd);
688}
689
690
691/*
692 * user interface
693 */
694
695static const char *page_flag_type(uint64_t flag)
696{
697	if (flag & KPF_HACKERS_BITS)
698		return "(r)";
699	if (flag & KPF_OVERLOADED_BITS)
700		return "(o)";
701	return "   ";
702}
703
704static void usage(void)
705{
706	size_t i, j;
707
708	printf(
709"page-types [options]\n"
710"            -r|--raw                   Raw mode, for kernel developers\n"
711"            -d|--describe flags        Describe flags\n"
712"            -a|--addr    addr-spec     Walk a range of pages\n"
713"            -b|--bits    bits-spec     Walk pages with specified bits\n"
714"            -p|--pid     pid           Walk process address space\n"
715"            -f|--file    filename      Walk file address space\n"
716"            -l|--list                  Show page details in ranges\n"
717"            -L|--list-each             Show page details one by one\n"
718"            -N|--no-summary            Don't show summary info\n"
719"            -X|--hwpoison              hwpoison pages\n"
720"            -x|--unpoison              unpoison pages\n"
721"            -h|--help                  Show this usage message\n"
722"flags:\n"
723"            0x10                       bitfield format, e.g.\n"
724"            anon                       bit-name, e.g.\n"
725"            0x10,anon                  comma-separated list, e.g.\n"
726"addr-spec:\n"
727"            N                          one page at offset N (unit: pages)\n"
728"            N+M                        pages range from N to N+M-1\n"
729"            N,M                        pages range from N to M-1\n"
730"            N,                         pages range from N to end\n"
731"            ,M                         pages range from 0 to M-1\n"
732"bits-spec:\n"
733"            bit1,bit2                  (flags & (bit1|bit2)) != 0\n"
734"            bit1,bit2=bit1             (flags & (bit1|bit2)) == bit1\n"
735"            bit1,~bit2                 (flags & (bit1|bit2)) == bit1\n"
736"            =bit1,bit2                 flags == (bit1|bit2)\n"
737"bit-names:\n"
738	);
739
740	for (i = 0, j = 0; i < ARRAY_SIZE(page_flag_names); i++) {
741		if (!page_flag_names[i])
742			continue;
743		printf("%16s%s", page_flag_names[i] + 2,
744				 page_flag_type(1ULL << i));
745		if (++j > 3) {
746			j = 0;
747			putchar('\n');
748		}
749	}
750	printf("\n                                   "
751		"(r) raw mode bits  (o) overloaded bits\n");
752}
753
754static unsigned long long parse_number(const char *str)
755{
756	unsigned long long n;
757
758	n = strtoll(str, NULL, 0);
759
760	if (n == 0 && str[0] != '0')
761		fatal("invalid name or number: %s\n", str);
762
763	return n;
764}
765
766static void parse_pid(const char *str)
767{
768	FILE *file;
769	char buf[5000];
770
771	opt_pid = parse_number(str);
772
773	sprintf(buf, "/proc/%d/pagemap", opt_pid);
774	pagemap_fd = checked_open(buf, O_RDONLY);
775
776	sprintf(buf, "/proc/%d/maps", opt_pid);
777	file = fopen(buf, "r");
778	if (!file) {
779		perror(buf);
780		exit(EXIT_FAILURE);
781	}
782
783	while (fgets(buf, sizeof(buf), file) != NULL) {
784		unsigned long vm_start;
785		unsigned long vm_end;
786		unsigned long long pgoff;
787		int major, minor;
788		char r, w, x, s;
789		unsigned long ino;
790		int n;
791
792		n = sscanf(buf, "%lx-%lx %c%c%c%c %llx %x:%x %lu",
793			   &vm_start,
794			   &vm_end,
795			   &r, &w, &x, &s,
796			   &pgoff,
797			   &major, &minor,
798			   &ino);
799		if (n < 10) {
800			fprintf(stderr, "unexpected line: %s\n", buf);
801			continue;
802		}
803		pg_start[nr_vmas] = vm_start / page_size;
804		pg_end[nr_vmas] = vm_end / page_size;
805		if (++nr_vmas >= MAX_VMAS) {
806			fprintf(stderr, "too many VMAs\n");
807			break;
808		}
809	}
810	fclose(file);
811}
812
813static void show_file(const char *name, const struct stat *st)
814{
815	unsigned long long size = st->st_size;
816	char atime[64], mtime[64];
817	long now = time(NULL);
818
819	printf("%s\tInode: %u\tSize: %llu (%llu pages)\n",
820			name, (unsigned)st->st_ino,
821			size, (size + page_size - 1) / page_size);
822
823	strftime(atime, sizeof(atime), "%c", localtime(&st->st_atime));
824	strftime(mtime, sizeof(mtime), "%c", localtime(&st->st_mtime));
825
826	printf("Modify: %s (%ld seconds ago)\nAccess: %s (%ld seconds ago)\n",
827			mtime, now - st->st_mtime,
828			atime, now - st->st_atime);
829}
830
831static sigjmp_buf sigbus_jmp;
832
833static void * volatile sigbus_addr;
834
835static void sigbus_handler(int sig, siginfo_t *info, void *ucontex)
836{
837	(void)sig;
838	(void)ucontex;
839	sigbus_addr = info ? info->si_addr : NULL;
840	siglongjmp(sigbus_jmp, 1);
841}
842
843static struct sigaction sigbus_action = {
844	.sa_sigaction = sigbus_handler,
845	.sa_flags = SA_SIGINFO,
846};
847
848static void walk_file(const char *name, const struct stat *st)
849{
850	uint8_t vec[PAGEMAP_BATCH];
851	uint64_t buf[PAGEMAP_BATCH], flags;
852	unsigned long nr_pages, pfn, i;
853	off_t off, end = st->st_size;
854	int fd;
855	ssize_t len;
856	void *ptr;
857	int first = 1;
858
859	fd = checked_open(name, O_RDONLY|O_NOATIME|O_NOFOLLOW);
860
861	for (off = 0; off < end; off += len) {
862		nr_pages = (end - off + page_size - 1) / page_size;
863		if (nr_pages > PAGEMAP_BATCH)
864			nr_pages = PAGEMAP_BATCH;
865		len = nr_pages * page_size;
866
867		ptr = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, off);
868		if (ptr == MAP_FAILED)
869			fatal("mmap failed: %s", name);
870
871		/* determine cached pages */
872		if (mincore(ptr, len, vec))
873			fatal("mincore failed: %s", name);
874
875		/* turn off readahead */
876		if (madvise(ptr, len, MADV_RANDOM))
877			fatal("madvice failed: %s", name);
878
879		if (sigsetjmp(sigbus_jmp, 1)) {
880			end = off + sigbus_addr ? sigbus_addr - ptr : 0;
881			fprintf(stderr, "got sigbus at offset %lld: %s\n",
882					(long long)end, name);
883			goto got_sigbus;
884		}
885
886		/* populate ptes */
887		for (i = 0; i < nr_pages ; i++) {
888			if (vec[i] & 1)
889				(void)*(volatile int *)(ptr + i * page_size);
890		}
891got_sigbus:
892
893		/* turn off harvesting reference bits */
894		if (madvise(ptr, len, MADV_SEQUENTIAL))
895			fatal("madvice failed: %s", name);
896
897		if (pagemap_read(buf, (unsigned long)ptr / page_size,
898					nr_pages) != nr_pages)
899			fatal("cannot read pagemap");
900
901		munmap(ptr, len);
902
903		for (i = 0; i < nr_pages; i++) {
904			pfn = pagemap_pfn(buf[i]);
905			if (!pfn)
906				continue;
907			if (!kpageflags_read(&flags, pfn, 1))
908				continue;
909			if (first && opt_list) {
910				first = 0;
911				flush_page_range();
912				show_file(name, st);
913			}
914			add_page(off / page_size + i, pfn, flags, buf[i]);
915		}
916	}
917
918	close(fd);
919}
920
921int walk_tree(const char *name, const struct stat *st, int type, struct FTW *f)
922{
923	(void)f;
924	switch (type) {
925	case FTW_F:
926		if (S_ISREG(st->st_mode))
927			walk_file(name, st);
928		break;
929	case FTW_DNR:
930		fprintf(stderr, "cannot read dir: %s\n", name);
931		break;
932	}
933	return 0;
934}
935
936static void walk_page_cache(void)
937{
938	struct stat st;
939
940	kpageflags_fd = checked_open(PROC_KPAGEFLAGS, O_RDONLY);
941	pagemap_fd = checked_open("/proc/self/pagemap", O_RDONLY);
942	sigaction(SIGBUS, &sigbus_action, NULL);
943
944	if (stat(opt_file, &st))
945		fatal("stat failed: %s\n", opt_file);
946
947	if (S_ISREG(st.st_mode)) {
948		walk_file(opt_file, &st);
949	} else if (S_ISDIR(st.st_mode)) {
950		/* do not follow symlinks and mountpoints */
951		if (nftw(opt_file, walk_tree, 64, FTW_MOUNT | FTW_PHYS) < 0)
952			fatal("nftw failed: %s\n", opt_file);
953	} else
954		fatal("unhandled file type: %s\n", opt_file);
955
956	close(kpageflags_fd);
957	close(pagemap_fd);
958	signal(SIGBUS, SIG_DFL);
959}
960
961static void parse_file(const char *name)
962{
963	opt_file = name;
964}
965
966static void parse_addr_range(const char *optarg)
967{
968	unsigned long offset;
969	unsigned long size;
970	char *p;
971
972	p = strchr(optarg, ',');
973	if (!p)
974		p = strchr(optarg, '+');
975
976	if (p == optarg) {
977		offset = 0;
978		size   = parse_number(p + 1);
979	} else if (p) {
980		offset = parse_number(optarg);
981		if (p[1] == '\0')
982			size = ULONG_MAX;
983		else {
984			size = parse_number(p + 1);
985			if (*p == ',') {
986				if (size < offset)
987					fatal("invalid range: %lu,%lu\n",
988							offset, size);
989				size -= offset;
990			}
991		}
992	} else {
993		offset = parse_number(optarg);
994		size   = 1;
995	}
996
997	add_addr_range(offset, size);
998}
999
1000static void add_bits_filter(uint64_t mask, uint64_t bits)
1001{
1002	if (nr_bit_filters >= MAX_BIT_FILTERS)
1003		fatal("too much bit filters\n");
1004
1005	opt_mask[nr_bit_filters] = mask;
1006	opt_bits[nr_bit_filters] = bits;
1007	nr_bit_filters++;
1008}
1009
1010static uint64_t parse_flag_name(const char *str, int len)
1011{
1012	size_t i;
1013
1014	if (!*str || !len)
1015		return 0;
1016
1017	if (len <= 8 && !strncmp(str, "compound", len))
1018		return BITS_COMPOUND;
1019
1020	for (i = 0; i < ARRAY_SIZE(page_flag_names); i++) {
1021		if (!page_flag_names[i])
1022			continue;
1023		if (!strncmp(str, page_flag_names[i] + 2, len))
1024			return 1ULL << i;
1025	}
1026
1027	return parse_number(str);
1028}
1029
1030static uint64_t parse_flag_names(const char *str, int all)
1031{
1032	const char *p    = str;
1033	uint64_t   flags = 0;
1034
1035	while (1) {
1036		if (*p == ',' || *p == '=' || *p == '\0') {
1037			if ((*str != '~') || (*str == '~' && all && *++str))
1038				flags |= parse_flag_name(str, p - str);
1039			if (*p != ',')
1040				break;
1041			str = p + 1;
1042		}
1043		p++;
1044	}
1045
1046	return flags;
1047}
1048
1049static void parse_bits_mask(const char *optarg)
1050{
1051	uint64_t mask;
1052	uint64_t bits;
1053	const char *p;
1054
1055	p = strchr(optarg, '=');
1056	if (p == optarg) {
1057		mask = KPF_ALL_BITS;
1058		bits = parse_flag_names(p + 1, 0);
1059	} else if (p) {
1060		mask = parse_flag_names(optarg, 0);
1061		bits = parse_flag_names(p + 1, 0);
1062	} else if (strchr(optarg, '~')) {
1063		mask = parse_flag_names(optarg, 1);
1064		bits = parse_flag_names(optarg, 0);
1065	} else {
1066		mask = parse_flag_names(optarg, 0);
1067		bits = KPF_ALL_BITS;
1068	}
1069
1070	add_bits_filter(mask, bits);
1071}
1072
1073static void describe_flags(const char *optarg)
1074{
1075	uint64_t flags = parse_flag_names(optarg, 0);
1076
1077	printf("0x%016llx\t%s\t%s\n",
1078		(unsigned long long)flags,
1079		page_flag_name(flags),
1080		page_flag_longname(flags));
1081}
1082
1083static const struct option opts[] = {
1084	{ "raw"       , 0, NULL, 'r' },
1085	{ "pid"       , 1, NULL, 'p' },
1086	{ "file"      , 1, NULL, 'f' },
1087	{ "addr"      , 1, NULL, 'a' },
1088	{ "bits"      , 1, NULL, 'b' },
1089	{ "describe"  , 1, NULL, 'd' },
1090	{ "list"      , 0, NULL, 'l' },
1091	{ "list-each" , 0, NULL, 'L' },
1092	{ "no-summary", 0, NULL, 'N' },
1093	{ "hwpoison"  , 0, NULL, 'X' },
1094	{ "unpoison"  , 0, NULL, 'x' },
1095	{ "help"      , 0, NULL, 'h' },
1096	{ NULL        , 0, NULL, 0 }
1097};
1098
1099int main(int argc, char *argv[])
1100{
1101	int c;
1102
1103	page_size = getpagesize();
1104
1105	while ((c = getopt_long(argc, argv,
1106				"rp:f:a:b:d:lLNXxh", opts, NULL)) != -1) {
1107		switch (c) {
1108		case 'r':
1109			opt_raw = 1;
1110			break;
1111		case 'p':
1112			parse_pid(optarg);
1113			break;
1114		case 'f':
1115			parse_file(optarg);
1116			break;
1117		case 'a':
1118			parse_addr_range(optarg);
1119			break;
1120		case 'b':
1121			parse_bits_mask(optarg);
1122			break;
1123		case 'd':
1124			describe_flags(optarg);
1125			exit(0);
1126		case 'l':
1127			opt_list = 1;
1128			break;
1129		case 'L':
1130			opt_list = 2;
1131			break;
1132		case 'N':
1133			opt_no_summary = 1;
1134			break;
1135		case 'X':
1136			opt_hwpoison = 1;
1137			prepare_hwpoison_fd();
1138			break;
1139		case 'x':
1140			opt_unpoison = 1;
1141			prepare_hwpoison_fd();
1142			break;
1143		case 'h':
1144			usage();
1145			exit(0);
1146		default:
1147			usage();
1148			exit(1);
1149		}
1150	}
1151
1152	if (opt_list && opt_pid)
1153		printf("voffset\t");
1154	if (opt_list && opt_file)
1155		printf("foffset\t");
1156	if (opt_list == 1)
1157		printf("offset\tlen\tflags\n");
1158	if (opt_list == 2)
1159		printf("offset\tflags\n");
1160
1161	if (opt_file)
1162		walk_page_cache();
1163	else
1164		walk_addr_ranges();
1165
1166	if (opt_list == 1)
1167		flush_page_range();
1168
1169	if (opt_no_summary)
1170		return 0;
1171
1172	if (opt_list)
1173		printf("\n\n");
1174
1175	show_summary();
1176
1177	return 0;
1178}
1179