page-types.c 21.7 KB
Newer Older
W
Wu Fengguang 已提交
1 2 3
/*
 * page-types: Tool for querying page flags
 *
4 5 6 7 8 9 10 11 12 13 14 15 16
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; version 2.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
 *
 * You should find a copy of v2 of the GNU General Public License somewhere on
 * your Linux system; if not, write to the Free Software Foundation, Inc., 59
 * Temple Place, Suite 330, Boston, MA 02111-1307 USA.
 *
W
Wu Fengguang 已提交
17
 * Copyright (C) 2009 Intel corporation
W
Wu Fengguang 已提交
18 19
 *
 * Authors: Wu Fengguang <fengguang.wu@intel.com>
W
Wu Fengguang 已提交
20 21
 */

22
#define _LARGEFILE64_SOURCE
W
Wu Fengguang 已提交
23 24 25 26 27 28 29 30
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include <stdarg.h>
#include <string.h>
#include <getopt.h>
#include <limits.h>
31
#include <assert.h>
W
Wu Fengguang 已提交
32 33 34
#include <sys/types.h>
#include <sys/errno.h>
#include <sys/fcntl.h>
35 36
#include <sys/mount.h>
#include <sys/statfs.h>
37
#include "../../include/uapi/linux/magic.h"
D
David Howells 已提交
38
#include "../../include/uapi/linux/kernel-page-flags.h"
39
#include <lk/debugfs.h>
W
Wu Fengguang 已提交
40

41 42 43 44 45 46 47 48 49
#ifndef MAX_PATH
# define MAX_PATH 256
#endif

#ifndef STR
# define _STR(x) #x
# define STR(x) _STR(x)
#endif

50 51 52 53 54 55 56 57 58 59 60 61
/*
 * pagemap kernel ABI bits
 */

#define PM_ENTRY_BYTES      sizeof(uint64_t)
#define PM_STATUS_BITS      3
#define PM_STATUS_OFFSET    (64 - PM_STATUS_BITS)
#define PM_STATUS_MASK      (((1LL << PM_STATUS_BITS) - 1) << PM_STATUS_OFFSET)
#define PM_STATUS(nr)       (((nr) << PM_STATUS_OFFSET) & PM_STATUS_MASK)
#define PM_PSHIFT_BITS      6
#define PM_PSHIFT_OFFSET    (PM_STATUS_OFFSET - PM_PSHIFT_BITS)
#define PM_PSHIFT_MASK      (((1LL << PM_PSHIFT_BITS) - 1) << PM_PSHIFT_OFFSET)
62
#define __PM_PSHIFT(x)      (((uint64_t) (x) << PM_PSHIFT_OFFSET) & PM_PSHIFT_MASK)
63 64 65
#define PM_PFRAME_MASK      ((1LL << PM_PSHIFT_OFFSET) - 1)
#define PM_PFRAME(x)        ((x) & PM_PFRAME_MASK)

66
#define __PM_SOFT_DIRTY      (1LL)
67 68
#define PM_PRESENT          PM_STATUS(4LL)
#define PM_SWAP             PM_STATUS(2LL)
69
#define PM_SOFT_DIRTY       __PM_PSHIFT(__PM_SOFT_DIRTY)
70 71


W
Wu Fengguang 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
/*
 * kernel page flags
 */

#define KPF_BYTES		8
#define PROC_KPAGEFLAGS		"/proc/kpageflags"

/* [32-] kernel hacking assistances */
#define KPF_RESERVED		32
#define KPF_MLOCKED		33
#define KPF_MAPPEDTODISK	34
#define KPF_PRIVATE		35
#define KPF_PRIVATE_2		36
#define KPF_OWNER_PRIVATE	37
#define KPF_ARCH		38
#define KPF_UNCACHED		39
88
#define KPF_SOFTDIRTY		40
W
Wu Fengguang 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103

/* [48-] take some arbitrary free slots for expanding overloaded flags
 * not part of kernel API
 */
#define KPF_READAHEAD		48
#define KPF_SLOB_FREE		49
#define KPF_SLUB_FROZEN		50
#define KPF_SLUB_DEBUG		51

#define KPF_ALL_BITS		((uint64_t)~0ULL)
#define KPF_HACKERS_BITS	(0xffffULL << 32)
#define KPF_OVERLOADED_BITS	(0xffffULL << 48)
#define BIT(name)		(1ULL << KPF_##name)
#define BITS_COMPOUND		(BIT(COMPOUND_HEAD) | BIT(COMPOUND_TAIL))

104
static const char * const page_flag_names[] = {
W
Wu Fengguang 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
	[KPF_LOCKED]		= "L:locked",
	[KPF_ERROR]		= "E:error",
	[KPF_REFERENCED]	= "R:referenced",
	[KPF_UPTODATE]		= "U:uptodate",
	[KPF_DIRTY]		= "D:dirty",
	[KPF_LRU]		= "l:lru",
	[KPF_ACTIVE]		= "A:active",
	[KPF_SLAB]		= "S:slab",
	[KPF_WRITEBACK]		= "W:writeback",
	[KPF_RECLAIM]		= "I:reclaim",
	[KPF_BUDDY]		= "B:buddy",

	[KPF_MMAP]		= "M:mmap",
	[KPF_ANON]		= "a:anonymous",
	[KPF_SWAPCACHE]		= "s:swapcache",
	[KPF_SWAPBACKED]	= "b:swapbacked",
	[KPF_COMPOUND_HEAD]	= "H:compound_head",
	[KPF_COMPOUND_TAIL]	= "T:compound_tail",
	[KPF_HUGE]		= "G:huge",
	[KPF_UNEVICTABLE]	= "u:unevictable",
W
Wu Fengguang 已提交
125
	[KPF_HWPOISON]		= "X:hwpoison",
W
Wu Fengguang 已提交
126
	[KPF_NOPAGE]		= "n:nopage",
127
	[KPF_KSM]		= "x:ksm",
128
	[KPF_THP]		= "t:thp",
W
Wu Fengguang 已提交
129 130 131 132 133 134 135 136 137

	[KPF_RESERVED]		= "r:reserved",
	[KPF_MLOCKED]		= "m:mlocked",
	[KPF_MAPPEDTODISK]	= "d:mappedtodisk",
	[KPF_PRIVATE]		= "P:private",
	[KPF_PRIVATE_2]		= "p:private_2",
	[KPF_OWNER_PRIVATE]	= "O:owner_private",
	[KPF_ARCH]		= "h:arch",
	[KPF_UNCACHED]		= "c:uncached",
138
	[KPF_SOFTDIRTY]		= "f:softdirty",
W
Wu Fengguang 已提交
139 140 141 142 143 144 145 146

	[KPF_READAHEAD]		= "I:readahead",
	[KPF_SLOB_FREE]		= "P:slob_free",
	[KPF_SLUB_FROZEN]	= "A:slub_frozen",
	[KPF_SLUB_DEBUG]	= "E:slub_debug",
};


147
static const char * const debugfs_known_mountpoints[] = {
148 149 150 151 152
	"/sys/kernel/debug",
	"/debug",
	0,
};

W
Wu Fengguang 已提交
153 154 155 156 157 158 159 160 161 162 163 164 165 166
/*
 * data structures
 */

static int		opt_raw;	/* for kernel developers */
static int		opt_list;	/* list pages (in ranges) */
static int		opt_no_summary;	/* don't show summary */
static pid_t		opt_pid;	/* process to walk */

#define MAX_ADDR_RANGES	1024
static int		nr_addr_ranges;
static unsigned long	opt_offset[MAX_ADDR_RANGES];
static unsigned long	opt_size[MAX_ADDR_RANGES];

167 168 169 170 171
#define MAX_VMAS	10240
static int		nr_vmas;
static unsigned long	pg_start[MAX_VMAS];
static unsigned long	pg_end[MAX_VMAS];

W
Wu Fengguang 已提交
172 173 174 175 176 177 178
#define MAX_BIT_FILTERS	64
static int		nr_bit_filters;
static uint64_t		opt_mask[MAX_BIT_FILTERS];
static uint64_t		opt_bits[MAX_BIT_FILTERS];

static int		page_size;

179
static int		pagemap_fd;
W
Wu Fengguang 已提交
180 181
static int		kpageflags_fd;

182 183 184
static int		opt_hwpoison;
static int		opt_unpoison;

185
static char		*hwpoison_debug_fs;
186 187 188
static int		hwpoison_inject_fd;
static int		hwpoison_forget_fd;

W
Wu Fengguang 已提交
189 190 191 192 193 194 195
#define HASH_SHIFT	13
#define HASH_SIZE	(1 << HASH_SHIFT)
#define HASH_MASK	(HASH_SIZE - 1)
#define HASH_KEY(flags)	(flags & HASH_MASK)

static unsigned long	total_pages;
static unsigned long	nr_pages[HASH_SIZE];
196
static uint64_t		page_flags[HASH_SIZE];
W
Wu Fengguang 已提交
197 198 199 200 201 202 203 204 205 206 207 208 209


/*
 * helper functions
 */

#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))

#define min_t(type, x, y) ({			\
	type __min1 = (x);			\
	type __min2 = (y);			\
	__min1 < __min2 ? __min1 : __min2; })

210 211 212 213 214
#define max_t(type, x, y) ({			\
	type __max1 = (x);			\
	type __max2 = (y);			\
	__max1 > __max2 ? __max1 : __max2; })

215
static unsigned long pages2mb(unsigned long pages)
W
Wu Fengguang 已提交
216 217 218 219
{
	return (pages * page_size) >> 20;
}

220
static void fatal(const char *x, ...)
W
Wu Fengguang 已提交
221 222 223 224 225 226 227 228 229
{
	va_list ap;

	va_start(ap, x);
	vfprintf(stderr, x, ap);
	va_end(ap);
	exit(EXIT_FAILURE);
}

230
static int checked_open(const char *pathname, int flags)
231 232 233 234 235 236 237 238 239 240 241
{
	int fd = open(pathname, flags);

	if (fd < 0) {
		perror(pathname);
		exit(EXIT_FAILURE);
	}

	return fd;
}

242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
/*
 * pagemap/kpageflags routines
 */

static unsigned long do_u64_read(int fd, char *name,
				 uint64_t *buf,
				 unsigned long index,
				 unsigned long count)
{
	long bytes;

	if (index > ULONG_MAX / 8)
		fatal("index overflow: %lu\n", index);

	if (lseek(fd, index * 8, SEEK_SET) < 0) {
		perror(name);
		exit(EXIT_FAILURE);
	}

	bytes = read(fd, buf, count * 8);
	if (bytes < 0) {
		perror(name);
		exit(EXIT_FAILURE);
	}
	if (bytes % 8)
		fatal("partial read: %lu bytes\n", bytes);

	return bytes / 8;
}

static unsigned long kpageflags_read(uint64_t *buf,
				     unsigned long index,
				     unsigned long pages)
{
	return do_u64_read(kpageflags_fd, PROC_KPAGEFLAGS, buf, index, pages);
}

static unsigned long pagemap_read(uint64_t *buf,
				  unsigned long index,
				  unsigned long pages)
{
	return do_u64_read(pagemap_fd, "/proc/pid/pagemap", buf, index, pages);
}

static unsigned long pagemap_pfn(uint64_t val)
{
	unsigned long pfn;

	if (val & PM_PRESENT)
		pfn = PM_PFRAME(val);
	else
		pfn = 0;

	return pfn;
}

W
Wu Fengguang 已提交
298 299 300 301 302

/*
 * page flag names
 */

303
static char *page_flag_name(uint64_t flags)
W
Wu Fengguang 已提交
304 305 306
{
	static char buf[65];
	int present;
U
Ulrich Drepper 已提交
307
	size_t i, j;
W
Wu Fengguang 已提交
308 309 310 311 312

	for (i = 0, j = 0; i < ARRAY_SIZE(page_flag_names); i++) {
		present = (flags >> i) & 1;
		if (!page_flag_names[i]) {
			if (present)
313
				fatal("unknown flag bit %d\n", i);
W
Wu Fengguang 已提交
314 315 316 317 318 319 320 321
			continue;
		}
		buf[j++] = present ? page_flag_names[i][0] : '_';
	}

	return buf;
}

322
static char *page_flag_longname(uint64_t flags)
W
Wu Fengguang 已提交
323 324
{
	static char buf[1024];
U
Ulrich Drepper 已提交
325
	size_t i, n;
W
Wu Fengguang 已提交
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345

	for (i = 0, n = 0; i < ARRAY_SIZE(page_flag_names); i++) {
		if (!page_flag_names[i])
			continue;
		if ((flags >> i) & 1)
			n += snprintf(buf + n, sizeof(buf) - n, "%s,",
					page_flag_names[i] + 2);
	}
	if (n)
		n--;
	buf[n] = '\0';

	return buf;
}


/*
 * page list and summary
 */

346 347
static void show_page_range(unsigned long voffset,
			    unsigned long offset, uint64_t flags)
W
Wu Fengguang 已提交
348 349
{
	static uint64_t      flags0;
350
	static unsigned long voff;
W
Wu Fengguang 已提交
351 352 353
	static unsigned long index;
	static unsigned long count;

354 355
	if (flags == flags0 && offset == index + count &&
	    (!opt_pid || voffset == voff + count)) {
W
Wu Fengguang 已提交
356 357 358 359
		count++;
		return;
	}

360 361 362 363
	if (count) {
		if (opt_pid)
			printf("%lx\t", voff);
		printf("%lx\t%lx\t%s\n",
W
Wu Fengguang 已提交
364
				index, count, page_flag_name(flags0));
365
	}
W
Wu Fengguang 已提交
366 367 368

	flags0 = flags;
	index  = offset;
369
	voff   = voffset;
W
Wu Fengguang 已提交
370 371 372
	count  = 1;
}

373 374
static void show_page(unsigned long voffset,
		      unsigned long offset, uint64_t flags)
W
Wu Fengguang 已提交
375
{
376 377 378
	if (opt_pid)
		printf("%lx\t", voffset);
	printf("%lx\t%s\n", offset, page_flag_name(flags));
W
Wu Fengguang 已提交
379 380
}

381
static void show_summary(void)
W
Wu Fengguang 已提交
382
{
U
Ulrich Drepper 已提交
383
	size_t i;
W
Wu Fengguang 已提交
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406

	printf("             flags\tpage-count       MB"
		"  symbolic-flags\t\t\tlong-symbolic-flags\n");

	for (i = 0; i < ARRAY_SIZE(nr_pages); i++) {
		if (nr_pages[i])
			printf("0x%016llx\t%10lu %8lu  %s\t%s\n",
				(unsigned long long)page_flags[i],
				nr_pages[i],
				pages2mb(nr_pages[i]),
				page_flag_name(page_flags[i]),
				page_flag_longname(page_flags[i]));
	}

	printf("             total\t%10lu %8lu\n",
			total_pages, pages2mb(total_pages));
}


/*
 * page flag filters
 */

407
static int bit_mask_ok(uint64_t flags)
W
Wu Fengguang 已提交
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
{
	int i;

	for (i = 0; i < nr_bit_filters; i++) {
		if (opt_bits[i] == KPF_ALL_BITS) {
			if ((flags & opt_mask[i]) == 0)
				return 0;
		} else {
			if ((flags & opt_mask[i]) != opt_bits[i])
				return 0;
		}
	}

	return 1;
}

424
static uint64_t expand_overloaded_flags(uint64_t flags, uint64_t pme)
W
Wu Fengguang 已提交
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
{
	/* SLOB/SLUB overload several page flags */
	if (flags & BIT(SLAB)) {
		if (flags & BIT(PRIVATE))
			flags ^= BIT(PRIVATE) | BIT(SLOB_FREE);
		if (flags & BIT(ACTIVE))
			flags ^= BIT(ACTIVE) | BIT(SLUB_FROZEN);
		if (flags & BIT(ERROR))
			flags ^= BIT(ERROR) | BIT(SLUB_DEBUG);
	}

	/* PG_reclaim is overloaded as PG_readahead in the read path */
	if ((flags & (BIT(RECLAIM) | BIT(WRITEBACK))) == BIT(RECLAIM))
		flags ^= BIT(RECLAIM) | BIT(READAHEAD);

440 441 442
	if (pme & PM_SOFT_DIRTY)
		flags |= BIT(SOFTDIRTY);

W
Wu Fengguang 已提交
443 444 445
	return flags;
}

446
static uint64_t well_known_flags(uint64_t flags)
W
Wu Fengguang 已提交
447 448 449 450 451 452 453 454 455 456 457
{
	/* hide flags intended only for kernel hacker */
	flags &= ~KPF_HACKERS_BITS;

	/* hide non-hugeTLB compound pages */
	if ((flags & BITS_COMPOUND) && !(flags & BIT(HUGE)))
		flags &= ~BITS_COMPOUND;

	return flags;
}

458
static uint64_t kpageflags_flags(uint64_t flags, uint64_t pme)
459
{
460 461 462
	if (opt_raw)
		flags = expand_overloaded_flags(flags, pme);
	else
463 464 465 466 467
		flags = well_known_flags(flags);

	return flags;
}

468 469 470 471 472 473
/*
 * page actions
 */

static void prepare_hwpoison_fd(void)
{
474 475
	char buf[MAX_PATH + 1];

476 477 478 479 480
	hwpoison_debug_fs = debugfs_mount(NULL);
	if (!hwpoison_debug_fs) {
		perror("mount debugfs");
		exit(EXIT_FAILURE);
	}
481 482

	if (opt_hwpoison && !hwpoison_inject_fd) {
483 484
		snprintf(buf, MAX_PATH, "%s/hwpoison/corrupt-pfn",
			hwpoison_debug_fs);
485 486 487 488
		hwpoison_inject_fd = checked_open(buf, O_WRONLY);
	}

	if (opt_unpoison && !hwpoison_forget_fd) {
489 490
		snprintf(buf, MAX_PATH, "%s/hwpoison/unpoison-pfn",
			hwpoison_debug_fs);
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
		hwpoison_forget_fd = checked_open(buf, O_WRONLY);
	}
}

static int hwpoison_page(unsigned long offset)
{
	char buf[100];
	int len;

	len = sprintf(buf, "0x%lx\n", offset);
	len = write(hwpoison_inject_fd, buf, len);
	if (len < 0) {
		perror("hwpoison inject");
		return len;
	}
	return 0;
}

static int unpoison_page(unsigned long offset)
{
	char buf[100];
	int len;

	len = sprintf(buf, "0x%lx\n", offset);
	len = write(hwpoison_forget_fd, buf, len);
	if (len < 0) {
		perror("hwpoison forget");
		return len;
	}
	return 0;
}

W
Wu Fengguang 已提交
523 524 525 526
/*
 * page frame walker
 */

U
Ulrich Drepper 已提交
527
static size_t hash_slot(uint64_t flags)
W
Wu Fengguang 已提交
528
{
U
Ulrich Drepper 已提交
529 530
	size_t k = HASH_KEY(flags);
	size_t i;
W
Wu Fengguang 已提交
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553

	/* Explicitly reserve slot 0 for flags 0: the following logic
	 * cannot distinguish an unoccupied slot from slot (flags==0).
	 */
	if (flags == 0)
		return 0;

	/* search through the remaining (HASH_SIZE-1) slots */
	for (i = 1; i < ARRAY_SIZE(page_flags); i++, k++) {
		if (!k || k >= ARRAY_SIZE(page_flags))
			k = 1;
		if (page_flags[k] == 0) {
			page_flags[k] = flags;
			return k;
		}
		if (page_flags[k] == flags)
			return k;
	}

	fatal("hash table full: bump up HASH_SHIFT?\n");
	exit(EXIT_FAILURE);
}

554
static void add_page(unsigned long voffset,
555
		     unsigned long offset, uint64_t flags, uint64_t pme)
W
Wu Fengguang 已提交
556
{
557
	flags = kpageflags_flags(flags, pme);
W
Wu Fengguang 已提交
558 559 560 561

	if (!bit_mask_ok(flags))
		return;

562 563 564 565 566
	if (opt_hwpoison)
		hwpoison_page(offset);
	if (opt_unpoison)
		unpoison_page(offset);

W
Wu Fengguang 已提交
567
	if (opt_list == 1)
568
		show_page_range(voffset, offset, flags);
W
Wu Fengguang 已提交
569
	else if (opt_list == 2)
570
		show_page(voffset, offset, flags);
W
Wu Fengguang 已提交
571 572 573 574 575

	nr_pages[hash_slot(flags)]++;
	total_pages++;
}

576
#define KPAGEFLAGS_BATCH	(64 << 10)	/* 64k pages */
577 578
static void walk_pfn(unsigned long voffset,
		     unsigned long index,
579 580
		     unsigned long count,
		     uint64_t pme)
W
Wu Fengguang 已提交
581
{
582
	uint64_t buf[KPAGEFLAGS_BATCH];
W
Wu Fengguang 已提交
583
	unsigned long batch;
U
Ulrich Drepper 已提交
584
	unsigned long pages;
W
Wu Fengguang 已提交
585 586 587
	unsigned long i;

	while (count) {
588 589 590
		batch = min_t(unsigned long, count, KPAGEFLAGS_BATCH);
		pages = kpageflags_read(buf, index, batch);
		if (pages == 0)
W
Wu Fengguang 已提交
591 592
			break;

593
		for (i = 0; i < pages; i++)
594
			add_page(voffset + i, index + i, buf[i], pme);
W
Wu Fengguang 已提交
595

596 597
		index += pages;
		count -= pages;
W
Wu Fengguang 已提交
598 599 600
	}
}

601 602
#define PAGEMAP_BATCH	(64 << 10)
static void walk_vma(unsigned long index, unsigned long count)
603
{
604 605 606 607 608
	uint64_t buf[PAGEMAP_BATCH];
	unsigned long batch;
	unsigned long pages;
	unsigned long pfn;
	unsigned long i;
609

610 611 612 613 614
	while (count) {
		batch = min_t(unsigned long, count, PAGEMAP_BATCH);
		pages = pagemap_read(buf, index, batch);
		if (pages == 0)
			break;
615

616 617 618
		for (i = 0; i < pages; i++) {
			pfn = pagemap_pfn(buf[i]);
			if (pfn)
619
				walk_pfn(index + i, pfn, 1, buf[i]);
620 621 622 623 624
		}

		index += pages;
		count -= pages;
	}
625 626 627 628 629
}

static void walk_task(unsigned long index, unsigned long count)
{
	const unsigned long end = index + count;
630 631
	unsigned long start;
	int i = 0;
632 633 634 635 636 637 638 639 640

	while (index < end) {

		while (pg_end[i] <= index)
			if (++i >= nr_vmas)
				return;
		if (pg_start[i] >= end)
			return;

641 642
		start = max_t(unsigned long, pg_start[i], index);
		index = min_t(unsigned long, pg_end[i], end);
643

644 645
		assert(start < index);
		walk_vma(start, index - start);
646 647 648 649 650 651 652 653 654 655 656 657 658
	}
}

static void add_addr_range(unsigned long offset, unsigned long size)
{
	if (nr_addr_ranges >= MAX_ADDR_RANGES)
		fatal("too many addr ranges\n");

	opt_offset[nr_addr_ranges] = offset;
	opt_size[nr_addr_ranges] = min_t(unsigned long, size, ULONG_MAX-offset);
	nr_addr_ranges++;
}

659
static void walk_addr_ranges(void)
W
Wu Fengguang 已提交
660 661 662
{
	int i;

663
	kpageflags_fd = checked_open(PROC_KPAGEFLAGS, O_RDONLY);
W
Wu Fengguang 已提交
664 665

	if (!nr_addr_ranges)
666
		add_addr_range(0, ULONG_MAX);
W
Wu Fengguang 已提交
667 668

	for (i = 0; i < nr_addr_ranges; i++)
669
		if (!opt_pid)
670
			walk_pfn(0, opt_offset[i], opt_size[i], 0);
671 672
		else
			walk_task(opt_offset[i], opt_size[i]);
W
Wu Fengguang 已提交
673 674 675 676 677 678 679 680 681

	close(kpageflags_fd);
}


/*
 * user interface
 */

682
static const char *page_flag_type(uint64_t flag)
W
Wu Fengguang 已提交
683 684 685 686 687 688 689 690
{
	if (flag & KPF_HACKERS_BITS)
		return "(r)";
	if (flag & KPF_OVERLOADED_BITS)
		return "(o)";
	return "   ";
}

691
static void usage(void)
W
Wu Fengguang 已提交
692
{
U
Ulrich Drepper 已提交
693
	size_t i, j;
W
Wu Fengguang 已提交
694 695 696

	printf(
"page-types [options]\n"
A
Alex Chiang 已提交
697
"            -r|--raw                   Raw mode, for kernel developers\n"
698
"            -d|--describe flags        Describe flags\n"
A
Alex Chiang 已提交
699 700 701
"            -a|--addr    addr-spec     Walk a range of pages\n"
"            -b|--bits    bits-spec     Walk pages with specified bits\n"
"            -p|--pid     pid           Walk process address space\n"
702
#if 0 /* planned features */
A
Alex Chiang 已提交
703
"            -f|--file    filename      Walk file address space\n"
W
Wu Fengguang 已提交
704
#endif
A
Alex Chiang 已提交
705 706
"            -l|--list                  Show page details in ranges\n"
"            -L|--list-each             Show page details one by one\n"
707
"            -N|--no-summary            Don't show summary info\n"
A
Alex Chiang 已提交
708 709 710
"            -X|--hwpoison              hwpoison pages\n"
"            -x|--unpoison              unpoison pages\n"
"            -h|--help                  Show this usage message\n"
711
"flags:\n"
A
Alex Chiang 已提交
712 713 714
"            0x10                       bitfield format, e.g.\n"
"            anon                       bit-name, e.g.\n"
"            0x10,anon                  comma-separated list, e.g.\n"
W
Wu Fengguang 已提交
715
"addr-spec:\n"
A
Alex Chiang 已提交
716 717 718 719 720
"            N                          one page at offset N (unit: pages)\n"
"            N+M                        pages range from N to N+M-1\n"
"            N,M                        pages range from N to M-1\n"
"            N,                         pages range from N to end\n"
"            ,M                         pages range from 0 to M-1\n"
W
Wu Fengguang 已提交
721
"bits-spec:\n"
A
Alex Chiang 已提交
722 723 724 725
"            bit1,bit2                  (flags & (bit1|bit2)) != 0\n"
"            bit1,bit2=bit1             (flags & (bit1|bit2)) == bit1\n"
"            bit1,~bit2                 (flags & (bit1|bit2)) == bit1\n"
"            =bit1,bit2                 flags == (bit1|bit2)\n"
W
Wu Fengguang 已提交
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
"bit-names:\n"
	);

	for (i = 0, j = 0; i < ARRAY_SIZE(page_flag_names); i++) {
		if (!page_flag_names[i])
			continue;
		printf("%16s%s", page_flag_names[i] + 2,
				 page_flag_type(1ULL << i));
		if (++j > 3) {
			j = 0;
			putchar('\n');
		}
	}
	printf("\n                                   "
		"(r) raw mode bits  (o) overloaded bits\n");
}

743
static unsigned long long parse_number(const char *str)
W
Wu Fengguang 已提交
744 745 746 747 748 749 750 751 752 753 754
{
	unsigned long long n;

	n = strtoll(str, NULL, 0);

	if (n == 0 && str[0] != '0')
		fatal("invalid name or number: %s\n", str);

	return n;
}

755
static void parse_pid(const char *str)
W
Wu Fengguang 已提交
756
{
757 758 759
	FILE *file;
	char buf[5000];

W
Wu Fengguang 已提交
760 761
	opt_pid = parse_number(str);

762
	sprintf(buf, "/proc/%d/pagemap", opt_pid);
763
	pagemap_fd = checked_open(buf, O_RDONLY);
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799

	sprintf(buf, "/proc/%d/maps", opt_pid);
	file = fopen(buf, "r");
	if (!file) {
		perror(buf);
		exit(EXIT_FAILURE);
	}

	while (fgets(buf, sizeof(buf), file) != NULL) {
		unsigned long vm_start;
		unsigned long vm_end;
		unsigned long long pgoff;
		int major, minor;
		char r, w, x, s;
		unsigned long ino;
		int n;

		n = sscanf(buf, "%lx-%lx %c%c%c%c %llx %x:%x %lu",
			   &vm_start,
			   &vm_end,
			   &r, &w, &x, &s,
			   &pgoff,
			   &major, &minor,
			   &ino);
		if (n < 10) {
			fprintf(stderr, "unexpected line: %s\n", buf);
			continue;
		}
		pg_start[nr_vmas] = vm_start / page_size;
		pg_end[nr_vmas] = vm_end / page_size;
		if (++nr_vmas >= MAX_VMAS) {
			fprintf(stderr, "too many VMAs\n");
			break;
		}
	}
	fclose(file);
W
Wu Fengguang 已提交
800 801
}

802
static void parse_file(const char *name)
W
Wu Fengguang 已提交
803 804 805
{
}

806
static void parse_addr_range(const char *optarg)
W
Wu Fengguang 已提交
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
{
	unsigned long offset;
	unsigned long size;
	char *p;

	p = strchr(optarg, ',');
	if (!p)
		p = strchr(optarg, '+');

	if (p == optarg) {
		offset = 0;
		size   = parse_number(p + 1);
	} else if (p) {
		offset = parse_number(optarg);
		if (p[1] == '\0')
			size = ULONG_MAX;
		else {
			size = parse_number(p + 1);
			if (*p == ',') {
				if (size < offset)
					fatal("invalid range: %lu,%lu\n",
							offset, size);
				size -= offset;
			}
		}
	} else {
		offset = parse_number(optarg);
		size   = 1;
	}

	add_addr_range(offset, size);
}

840
static void add_bits_filter(uint64_t mask, uint64_t bits)
W
Wu Fengguang 已提交
841 842 843 844 845 846 847 848 849
{
	if (nr_bit_filters >= MAX_BIT_FILTERS)
		fatal("too much bit filters\n");

	opt_mask[nr_bit_filters] = mask;
	opt_bits[nr_bit_filters] = bits;
	nr_bit_filters++;
}

850
static uint64_t parse_flag_name(const char *str, int len)
W
Wu Fengguang 已提交
851
{
U
Ulrich Drepper 已提交
852
	size_t i;
W
Wu Fengguang 已提交
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869

	if (!*str || !len)
		return 0;

	if (len <= 8 && !strncmp(str, "compound", len))
		return BITS_COMPOUND;

	for (i = 0; i < ARRAY_SIZE(page_flag_names); i++) {
		if (!page_flag_names[i])
			continue;
		if (!strncmp(str, page_flag_names[i] + 2, len))
			return 1ULL << i;
	}

	return parse_number(str);
}

870
static uint64_t parse_flag_names(const char *str, int all)
W
Wu Fengguang 已提交
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
{
	const char *p    = str;
	uint64_t   flags = 0;

	while (1) {
		if (*p == ',' || *p == '=' || *p == '\0') {
			if ((*str != '~') || (*str == '~' && all && *++str))
				flags |= parse_flag_name(str, p - str);
			if (*p != ',')
				break;
			str = p + 1;
		}
		p++;
	}

	return flags;
}

889
static void parse_bits_mask(const char *optarg)
W
Wu Fengguang 已提交
890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
{
	uint64_t mask;
	uint64_t bits;
	const char *p;

	p = strchr(optarg, '=');
	if (p == optarg) {
		mask = KPF_ALL_BITS;
		bits = parse_flag_names(p + 1, 0);
	} else if (p) {
		mask = parse_flag_names(optarg, 0);
		bits = parse_flag_names(p + 1, 0);
	} else if (strchr(optarg, '~')) {
		mask = parse_flag_names(optarg, 1);
		bits = parse_flag_names(optarg, 0);
	} else {
		mask = parse_flag_names(optarg, 0);
		bits = KPF_ALL_BITS;
	}

	add_bits_filter(mask, bits);
}

913 914 915 916 917 918 919 920 921
static void describe_flags(const char *optarg)
{
	uint64_t flags = parse_flag_names(optarg, 0);

	printf("0x%016llx\t%s\t%s\n",
		(unsigned long long)flags,
		page_flag_name(flags),
		page_flag_longname(flags));
}
W
Wu Fengguang 已提交
922

923
static const struct option opts[] = {
W
Wu Fengguang 已提交
924 925 926 927 928
	{ "raw"       , 0, NULL, 'r' },
	{ "pid"       , 1, NULL, 'p' },
	{ "file"      , 1, NULL, 'f' },
	{ "addr"      , 1, NULL, 'a' },
	{ "bits"      , 1, NULL, 'b' },
929
	{ "describe"  , 1, NULL, 'd' },
W
Wu Fengguang 已提交
930 931 932
	{ "list"      , 0, NULL, 'l' },
	{ "list-each" , 0, NULL, 'L' },
	{ "no-summary", 0, NULL, 'N' },
933 934
	{ "hwpoison"  , 0, NULL, 'X' },
	{ "unpoison"  , 0, NULL, 'x' },
W
Wu Fengguang 已提交
935 936 937 938 939 940 941 942 943 944 945
	{ "help"      , 0, NULL, 'h' },
	{ NULL        , 0, NULL, 0 }
};

int main(int argc, char *argv[])
{
	int c;

	page_size = getpagesize();

	while ((c = getopt_long(argc, argv,
946
				"rp:f:a:b:d:lLNXxh", opts, NULL)) != -1) {
W
Wu Fengguang 已提交
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
		switch (c) {
		case 'r':
			opt_raw = 1;
			break;
		case 'p':
			parse_pid(optarg);
			break;
		case 'f':
			parse_file(optarg);
			break;
		case 'a':
			parse_addr_range(optarg);
			break;
		case 'b':
			parse_bits_mask(optarg);
			break;
963 964
		case 'd':
			describe_flags(optarg);
965
			exit(0);
W
Wu Fengguang 已提交
966 967 968 969 970 971 972 973 974
		case 'l':
			opt_list = 1;
			break;
		case 'L':
			opt_list = 2;
			break;
		case 'N':
			opt_no_summary = 1;
			break;
975 976 977 978 979 980 981 982
		case 'X':
			opt_hwpoison = 1;
			prepare_hwpoison_fd();
			break;
		case 'x':
			opt_unpoison = 1;
			prepare_hwpoison_fd();
			break;
W
Wu Fengguang 已提交
983 984 985 986 987 988 989 990 991
		case 'h':
			usage();
			exit(0);
		default:
			usage();
			exit(1);
		}
	}

992 993
	if (opt_list && opt_pid)
		printf("voffset\t");
W
Wu Fengguang 已提交
994
	if (opt_list == 1)
995
		printf("offset\tlen\tflags\n");
W
Wu Fengguang 已提交
996 997 998 999 1000 1001
	if (opt_list == 2)
		printf("offset\tflags\n");

	walk_addr_ranges();

	if (opt_list == 1)
1002
		show_page_range(0, 0, 0);  /* drain the buffer */
W
Wu Fengguang 已提交
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013

	if (opt_no_summary)
		return 0;

	if (opt_list)
		printf("\n\n");

	show_summary();

	return 0;
}