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