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