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