xref: /openbmc/linux/fs/proc/task_mmu.c (revision 8795a739)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/pagewalk.h>
3 #include <linux/vmacache.h>
4 #include <linux/hugetlb.h>
5 #include <linux/huge_mm.h>
6 #include <linux/mount.h>
7 #include <linux/seq_file.h>
8 #include <linux/highmem.h>
9 #include <linux/ptrace.h>
10 #include <linux/slab.h>
11 #include <linux/pagemap.h>
12 #include <linux/mempolicy.h>
13 #include <linux/rmap.h>
14 #include <linux/swap.h>
15 #include <linux/sched/mm.h>
16 #include <linux/swapops.h>
17 #include <linux/mmu_notifier.h>
18 #include <linux/page_idle.h>
19 #include <linux/shmem_fs.h>
20 #include <linux/uaccess.h>
21 #include <linux/pkeys.h>
22 
23 #include <asm/elf.h>
24 #include <asm/tlb.h>
25 #include <asm/tlbflush.h>
26 #include "internal.h"
27 
28 #define SEQ_PUT_DEC(str, val) \
29 		seq_put_decimal_ull_width(m, str, (val) << (PAGE_SHIFT-10), 8)
30 void task_mem(struct seq_file *m, struct mm_struct *mm)
31 {
32 	unsigned long text, lib, swap, anon, file, shmem;
33 	unsigned long hiwater_vm, total_vm, hiwater_rss, total_rss;
34 
35 	anon = get_mm_counter(mm, MM_ANONPAGES);
36 	file = get_mm_counter(mm, MM_FILEPAGES);
37 	shmem = get_mm_counter(mm, MM_SHMEMPAGES);
38 
39 	/*
40 	 * Note: to minimize their overhead, mm maintains hiwater_vm and
41 	 * hiwater_rss only when about to *lower* total_vm or rss.  Any
42 	 * collector of these hiwater stats must therefore get total_vm
43 	 * and rss too, which will usually be the higher.  Barriers? not
44 	 * worth the effort, such snapshots can always be inconsistent.
45 	 */
46 	hiwater_vm = total_vm = mm->total_vm;
47 	if (hiwater_vm < mm->hiwater_vm)
48 		hiwater_vm = mm->hiwater_vm;
49 	hiwater_rss = total_rss = anon + file + shmem;
50 	if (hiwater_rss < mm->hiwater_rss)
51 		hiwater_rss = mm->hiwater_rss;
52 
53 	/* split executable areas between text and lib */
54 	text = PAGE_ALIGN(mm->end_code) - (mm->start_code & PAGE_MASK);
55 	text = min(text, mm->exec_vm << PAGE_SHIFT);
56 	lib = (mm->exec_vm << PAGE_SHIFT) - text;
57 
58 	swap = get_mm_counter(mm, MM_SWAPENTS);
59 	SEQ_PUT_DEC("VmPeak:\t", hiwater_vm);
60 	SEQ_PUT_DEC(" kB\nVmSize:\t", total_vm);
61 	SEQ_PUT_DEC(" kB\nVmLck:\t", mm->locked_vm);
62 	SEQ_PUT_DEC(" kB\nVmPin:\t", atomic64_read(&mm->pinned_vm));
63 	SEQ_PUT_DEC(" kB\nVmHWM:\t", hiwater_rss);
64 	SEQ_PUT_DEC(" kB\nVmRSS:\t", total_rss);
65 	SEQ_PUT_DEC(" kB\nRssAnon:\t", anon);
66 	SEQ_PUT_DEC(" kB\nRssFile:\t", file);
67 	SEQ_PUT_DEC(" kB\nRssShmem:\t", shmem);
68 	SEQ_PUT_DEC(" kB\nVmData:\t", mm->data_vm);
69 	SEQ_PUT_DEC(" kB\nVmStk:\t", mm->stack_vm);
70 	seq_put_decimal_ull_width(m,
71 		    " kB\nVmExe:\t", text >> 10, 8);
72 	seq_put_decimal_ull_width(m,
73 		    " kB\nVmLib:\t", lib >> 10, 8);
74 	seq_put_decimal_ull_width(m,
75 		    " kB\nVmPTE:\t", mm_pgtables_bytes(mm) >> 10, 8);
76 	SEQ_PUT_DEC(" kB\nVmSwap:\t", swap);
77 	seq_puts(m, " kB\n");
78 	hugetlb_report_usage(m, mm);
79 }
80 #undef SEQ_PUT_DEC
81 
82 unsigned long task_vsize(struct mm_struct *mm)
83 {
84 	return PAGE_SIZE * mm->total_vm;
85 }
86 
87 unsigned long task_statm(struct mm_struct *mm,
88 			 unsigned long *shared, unsigned long *text,
89 			 unsigned long *data, unsigned long *resident)
90 {
91 	*shared = get_mm_counter(mm, MM_FILEPAGES) +
92 			get_mm_counter(mm, MM_SHMEMPAGES);
93 	*text = (PAGE_ALIGN(mm->end_code) - (mm->start_code & PAGE_MASK))
94 								>> PAGE_SHIFT;
95 	*data = mm->data_vm + mm->stack_vm;
96 	*resident = *shared + get_mm_counter(mm, MM_ANONPAGES);
97 	return mm->total_vm;
98 }
99 
100 #ifdef CONFIG_NUMA
101 /*
102  * Save get_task_policy() for show_numa_map().
103  */
104 static void hold_task_mempolicy(struct proc_maps_private *priv)
105 {
106 	struct task_struct *task = priv->task;
107 
108 	task_lock(task);
109 	priv->task_mempolicy = get_task_policy(task);
110 	mpol_get(priv->task_mempolicy);
111 	task_unlock(task);
112 }
113 static void release_task_mempolicy(struct proc_maps_private *priv)
114 {
115 	mpol_put(priv->task_mempolicy);
116 }
117 #else
118 static void hold_task_mempolicy(struct proc_maps_private *priv)
119 {
120 }
121 static void release_task_mempolicy(struct proc_maps_private *priv)
122 {
123 }
124 #endif
125 
126 static void vma_stop(struct proc_maps_private *priv)
127 {
128 	struct mm_struct *mm = priv->mm;
129 
130 	release_task_mempolicy(priv);
131 	up_read(&mm->mmap_sem);
132 	mmput(mm);
133 }
134 
135 static struct vm_area_struct *
136 m_next_vma(struct proc_maps_private *priv, struct vm_area_struct *vma)
137 {
138 	if (vma == priv->tail_vma)
139 		return NULL;
140 	return vma->vm_next ?: priv->tail_vma;
141 }
142 
143 static void m_cache_vma(struct seq_file *m, struct vm_area_struct *vma)
144 {
145 	if (m->count < m->size)	/* vma is copied successfully */
146 		m->version = m_next_vma(m->private, vma) ? vma->vm_end : -1UL;
147 }
148 
149 static void *m_start(struct seq_file *m, loff_t *ppos)
150 {
151 	struct proc_maps_private *priv = m->private;
152 	unsigned long last_addr = m->version;
153 	struct mm_struct *mm;
154 	struct vm_area_struct *vma;
155 	unsigned int pos = *ppos;
156 
157 	/* See m_cache_vma(). Zero at the start or after lseek. */
158 	if (last_addr == -1UL)
159 		return NULL;
160 
161 	priv->task = get_proc_task(priv->inode);
162 	if (!priv->task)
163 		return ERR_PTR(-ESRCH);
164 
165 	mm = priv->mm;
166 	if (!mm || !mmget_not_zero(mm))
167 		return NULL;
168 
169 	if (down_read_killable(&mm->mmap_sem)) {
170 		mmput(mm);
171 		return ERR_PTR(-EINTR);
172 	}
173 
174 	hold_task_mempolicy(priv);
175 	priv->tail_vma = get_gate_vma(mm);
176 
177 	if (last_addr) {
178 		vma = find_vma(mm, last_addr - 1);
179 		if (vma && vma->vm_start <= last_addr)
180 			vma = m_next_vma(priv, vma);
181 		if (vma)
182 			return vma;
183 	}
184 
185 	m->version = 0;
186 	if (pos < mm->map_count) {
187 		for (vma = mm->mmap; pos; pos--) {
188 			m->version = vma->vm_start;
189 			vma = vma->vm_next;
190 		}
191 		return vma;
192 	}
193 
194 	/* we do not bother to update m->version in this case */
195 	if (pos == mm->map_count && priv->tail_vma)
196 		return priv->tail_vma;
197 
198 	vma_stop(priv);
199 	return NULL;
200 }
201 
202 static void *m_next(struct seq_file *m, void *v, loff_t *pos)
203 {
204 	struct proc_maps_private *priv = m->private;
205 	struct vm_area_struct *next;
206 
207 	(*pos)++;
208 	next = m_next_vma(priv, v);
209 	if (!next)
210 		vma_stop(priv);
211 	return next;
212 }
213 
214 static void m_stop(struct seq_file *m, void *v)
215 {
216 	struct proc_maps_private *priv = m->private;
217 
218 	if (!IS_ERR_OR_NULL(v))
219 		vma_stop(priv);
220 	if (priv->task) {
221 		put_task_struct(priv->task);
222 		priv->task = NULL;
223 	}
224 }
225 
226 static int proc_maps_open(struct inode *inode, struct file *file,
227 			const struct seq_operations *ops, int psize)
228 {
229 	struct proc_maps_private *priv = __seq_open_private(file, ops, psize);
230 
231 	if (!priv)
232 		return -ENOMEM;
233 
234 	priv->inode = inode;
235 	priv->mm = proc_mem_open(inode, PTRACE_MODE_READ);
236 	if (IS_ERR(priv->mm)) {
237 		int err = PTR_ERR(priv->mm);
238 
239 		seq_release_private(inode, file);
240 		return err;
241 	}
242 
243 	return 0;
244 }
245 
246 static int proc_map_release(struct inode *inode, struct file *file)
247 {
248 	struct seq_file *seq = file->private_data;
249 	struct proc_maps_private *priv = seq->private;
250 
251 	if (priv->mm)
252 		mmdrop(priv->mm);
253 
254 	return seq_release_private(inode, file);
255 }
256 
257 static int do_maps_open(struct inode *inode, struct file *file,
258 			const struct seq_operations *ops)
259 {
260 	return proc_maps_open(inode, file, ops,
261 				sizeof(struct proc_maps_private));
262 }
263 
264 /*
265  * Indicate if the VMA is a stack for the given task; for
266  * /proc/PID/maps that is the stack of the main task.
267  */
268 static int is_stack(struct vm_area_struct *vma)
269 {
270 	/*
271 	 * We make no effort to guess what a given thread considers to be
272 	 * its "stack".  It's not even well-defined for programs written
273 	 * languages like Go.
274 	 */
275 	return vma->vm_start <= vma->vm_mm->start_stack &&
276 		vma->vm_end >= vma->vm_mm->start_stack;
277 }
278 
279 static void show_vma_header_prefix(struct seq_file *m,
280 				   unsigned long start, unsigned long end,
281 				   vm_flags_t flags, unsigned long long pgoff,
282 				   dev_t dev, unsigned long ino)
283 {
284 	seq_setwidth(m, 25 + sizeof(void *) * 6 - 1);
285 	seq_put_hex_ll(m, NULL, start, 8);
286 	seq_put_hex_ll(m, "-", end, 8);
287 	seq_putc(m, ' ');
288 	seq_putc(m, flags & VM_READ ? 'r' : '-');
289 	seq_putc(m, flags & VM_WRITE ? 'w' : '-');
290 	seq_putc(m, flags & VM_EXEC ? 'x' : '-');
291 	seq_putc(m, flags & VM_MAYSHARE ? 's' : 'p');
292 	seq_put_hex_ll(m, " ", pgoff, 8);
293 	seq_put_hex_ll(m, " ", MAJOR(dev), 2);
294 	seq_put_hex_ll(m, ":", MINOR(dev), 2);
295 	seq_put_decimal_ull(m, " ", ino);
296 	seq_putc(m, ' ');
297 }
298 
299 static void
300 show_map_vma(struct seq_file *m, struct vm_area_struct *vma)
301 {
302 	struct mm_struct *mm = vma->vm_mm;
303 	struct file *file = vma->vm_file;
304 	vm_flags_t flags = vma->vm_flags;
305 	unsigned long ino = 0;
306 	unsigned long long pgoff = 0;
307 	unsigned long start, end;
308 	dev_t dev = 0;
309 	const char *name = NULL;
310 
311 	if (file) {
312 		struct inode *inode = file_inode(vma->vm_file);
313 		dev = inode->i_sb->s_dev;
314 		ino = inode->i_ino;
315 		pgoff = ((loff_t)vma->vm_pgoff) << PAGE_SHIFT;
316 	}
317 
318 	start = vma->vm_start;
319 	end = vma->vm_end;
320 	show_vma_header_prefix(m, start, end, flags, pgoff, dev, ino);
321 
322 	/*
323 	 * Print the dentry name for named mappings, and a
324 	 * special [heap] marker for the heap:
325 	 */
326 	if (file) {
327 		seq_pad(m, ' ');
328 		seq_file_path(m, file, "\n");
329 		goto done;
330 	}
331 
332 	if (vma->vm_ops && vma->vm_ops->name) {
333 		name = vma->vm_ops->name(vma);
334 		if (name)
335 			goto done;
336 	}
337 
338 	name = arch_vma_name(vma);
339 	if (!name) {
340 		if (!mm) {
341 			name = "[vdso]";
342 			goto done;
343 		}
344 
345 		if (vma->vm_start <= mm->brk &&
346 		    vma->vm_end >= mm->start_brk) {
347 			name = "[heap]";
348 			goto done;
349 		}
350 
351 		if (is_stack(vma))
352 			name = "[stack]";
353 	}
354 
355 done:
356 	if (name) {
357 		seq_pad(m, ' ');
358 		seq_puts(m, name);
359 	}
360 	seq_putc(m, '\n');
361 }
362 
363 static int show_map(struct seq_file *m, void *v)
364 {
365 	show_map_vma(m, v);
366 	m_cache_vma(m, v);
367 	return 0;
368 }
369 
370 static const struct seq_operations proc_pid_maps_op = {
371 	.start	= m_start,
372 	.next	= m_next,
373 	.stop	= m_stop,
374 	.show	= show_map
375 };
376 
377 static int pid_maps_open(struct inode *inode, struct file *file)
378 {
379 	return do_maps_open(inode, file, &proc_pid_maps_op);
380 }
381 
382 const struct file_operations proc_pid_maps_operations = {
383 	.open		= pid_maps_open,
384 	.read		= seq_read,
385 	.llseek		= seq_lseek,
386 	.release	= proc_map_release,
387 };
388 
389 /*
390  * Proportional Set Size(PSS): my share of RSS.
391  *
392  * PSS of a process is the count of pages it has in memory, where each
393  * page is divided by the number of processes sharing it.  So if a
394  * process has 1000 pages all to itself, and 1000 shared with one other
395  * process, its PSS will be 1500.
396  *
397  * To keep (accumulated) division errors low, we adopt a 64bit
398  * fixed-point pss counter to minimize division errors. So (pss >>
399  * PSS_SHIFT) would be the real byte count.
400  *
401  * A shift of 12 before division means (assuming 4K page size):
402  * 	- 1M 3-user-pages add up to 8KB errors;
403  * 	- supports mapcount up to 2^24, or 16M;
404  * 	- supports PSS up to 2^52 bytes, or 4PB.
405  */
406 #define PSS_SHIFT 12
407 
408 #ifdef CONFIG_PROC_PAGE_MONITOR
409 struct mem_size_stats {
410 	unsigned long resident;
411 	unsigned long shared_clean;
412 	unsigned long shared_dirty;
413 	unsigned long private_clean;
414 	unsigned long private_dirty;
415 	unsigned long referenced;
416 	unsigned long anonymous;
417 	unsigned long lazyfree;
418 	unsigned long anonymous_thp;
419 	unsigned long shmem_thp;
420 	unsigned long file_thp;
421 	unsigned long swap;
422 	unsigned long shared_hugetlb;
423 	unsigned long private_hugetlb;
424 	u64 pss;
425 	u64 pss_anon;
426 	u64 pss_file;
427 	u64 pss_shmem;
428 	u64 pss_locked;
429 	u64 swap_pss;
430 	bool check_shmem_swap;
431 };
432 
433 static void smaps_page_accumulate(struct mem_size_stats *mss,
434 		struct page *page, unsigned long size, unsigned long pss,
435 		bool dirty, bool locked, bool private)
436 {
437 	mss->pss += pss;
438 
439 	if (PageAnon(page))
440 		mss->pss_anon += pss;
441 	else if (PageSwapBacked(page))
442 		mss->pss_shmem += pss;
443 	else
444 		mss->pss_file += pss;
445 
446 	if (locked)
447 		mss->pss_locked += pss;
448 
449 	if (dirty || PageDirty(page)) {
450 		if (private)
451 			mss->private_dirty += size;
452 		else
453 			mss->shared_dirty += size;
454 	} else {
455 		if (private)
456 			mss->private_clean += size;
457 		else
458 			mss->shared_clean += size;
459 	}
460 }
461 
462 static void smaps_account(struct mem_size_stats *mss, struct page *page,
463 		bool compound, bool young, bool dirty, bool locked)
464 {
465 	int i, nr = compound ? compound_nr(page) : 1;
466 	unsigned long size = nr * PAGE_SIZE;
467 
468 	/*
469 	 * First accumulate quantities that depend only on |size| and the type
470 	 * of the compound page.
471 	 */
472 	if (PageAnon(page)) {
473 		mss->anonymous += size;
474 		if (!PageSwapBacked(page) && !dirty && !PageDirty(page))
475 			mss->lazyfree += size;
476 	}
477 
478 	mss->resident += size;
479 	/* Accumulate the size in pages that have been accessed. */
480 	if (young || page_is_young(page) || PageReferenced(page))
481 		mss->referenced += size;
482 
483 	/*
484 	 * Then accumulate quantities that may depend on sharing, or that may
485 	 * differ page-by-page.
486 	 *
487 	 * page_count(page) == 1 guarantees the page is mapped exactly once.
488 	 * If any subpage of the compound page mapped with PTE it would elevate
489 	 * page_count().
490 	 */
491 	if (page_count(page) == 1) {
492 		smaps_page_accumulate(mss, page, size, size << PSS_SHIFT, dirty,
493 			locked, true);
494 		return;
495 	}
496 	for (i = 0; i < nr; i++, page++) {
497 		int mapcount = page_mapcount(page);
498 		unsigned long pss = PAGE_SIZE << PSS_SHIFT;
499 		if (mapcount >= 2)
500 			pss /= mapcount;
501 		smaps_page_accumulate(mss, page, PAGE_SIZE, pss, dirty, locked,
502 				      mapcount < 2);
503 	}
504 }
505 
506 #ifdef CONFIG_SHMEM
507 static int smaps_pte_hole(unsigned long addr, unsigned long end,
508 		struct mm_walk *walk)
509 {
510 	struct mem_size_stats *mss = walk->private;
511 
512 	mss->swap += shmem_partial_swap_usage(
513 			walk->vma->vm_file->f_mapping, addr, end);
514 
515 	return 0;
516 }
517 #else
518 #define smaps_pte_hole		NULL
519 #endif /* CONFIG_SHMEM */
520 
521 static void smaps_pte_entry(pte_t *pte, unsigned long addr,
522 		struct mm_walk *walk)
523 {
524 	struct mem_size_stats *mss = walk->private;
525 	struct vm_area_struct *vma = walk->vma;
526 	bool locked = !!(vma->vm_flags & VM_LOCKED);
527 	struct page *page = NULL;
528 
529 	if (pte_present(*pte)) {
530 		page = vm_normal_page(vma, addr, *pte);
531 	} else if (is_swap_pte(*pte)) {
532 		swp_entry_t swpent = pte_to_swp_entry(*pte);
533 
534 		if (!non_swap_entry(swpent)) {
535 			int mapcount;
536 
537 			mss->swap += PAGE_SIZE;
538 			mapcount = swp_swapcount(swpent);
539 			if (mapcount >= 2) {
540 				u64 pss_delta = (u64)PAGE_SIZE << PSS_SHIFT;
541 
542 				do_div(pss_delta, mapcount);
543 				mss->swap_pss += pss_delta;
544 			} else {
545 				mss->swap_pss += (u64)PAGE_SIZE << PSS_SHIFT;
546 			}
547 		} else if (is_migration_entry(swpent))
548 			page = migration_entry_to_page(swpent);
549 		else if (is_device_private_entry(swpent))
550 			page = device_private_entry_to_page(swpent);
551 	} else if (unlikely(IS_ENABLED(CONFIG_SHMEM) && mss->check_shmem_swap
552 							&& pte_none(*pte))) {
553 		page = find_get_entry(vma->vm_file->f_mapping,
554 						linear_page_index(vma, addr));
555 		if (!page)
556 			return;
557 
558 		if (xa_is_value(page))
559 			mss->swap += PAGE_SIZE;
560 		else
561 			put_page(page);
562 
563 		return;
564 	}
565 
566 	if (!page)
567 		return;
568 
569 	smaps_account(mss, page, false, pte_young(*pte), pte_dirty(*pte), locked);
570 }
571 
572 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
573 static void smaps_pmd_entry(pmd_t *pmd, unsigned long addr,
574 		struct mm_walk *walk)
575 {
576 	struct mem_size_stats *mss = walk->private;
577 	struct vm_area_struct *vma = walk->vma;
578 	bool locked = !!(vma->vm_flags & VM_LOCKED);
579 	struct page *page;
580 
581 	/* FOLL_DUMP will return -EFAULT on huge zero page */
582 	page = follow_trans_huge_pmd(vma, addr, pmd, FOLL_DUMP);
583 	if (IS_ERR_OR_NULL(page))
584 		return;
585 	if (PageAnon(page))
586 		mss->anonymous_thp += HPAGE_PMD_SIZE;
587 	else if (PageSwapBacked(page))
588 		mss->shmem_thp += HPAGE_PMD_SIZE;
589 	else if (is_zone_device_page(page))
590 		/* pass */;
591 	else
592 		mss->file_thp += HPAGE_PMD_SIZE;
593 	smaps_account(mss, page, true, pmd_young(*pmd), pmd_dirty(*pmd), locked);
594 }
595 #else
596 static void smaps_pmd_entry(pmd_t *pmd, unsigned long addr,
597 		struct mm_walk *walk)
598 {
599 }
600 #endif
601 
602 static int smaps_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end,
603 			   struct mm_walk *walk)
604 {
605 	struct vm_area_struct *vma = walk->vma;
606 	pte_t *pte;
607 	spinlock_t *ptl;
608 
609 	ptl = pmd_trans_huge_lock(pmd, vma);
610 	if (ptl) {
611 		if (pmd_present(*pmd))
612 			smaps_pmd_entry(pmd, addr, walk);
613 		spin_unlock(ptl);
614 		goto out;
615 	}
616 
617 	if (pmd_trans_unstable(pmd))
618 		goto out;
619 	/*
620 	 * The mmap_sem held all the way back in m_start() is what
621 	 * keeps khugepaged out of here and from collapsing things
622 	 * in here.
623 	 */
624 	pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
625 	for (; addr != end; pte++, addr += PAGE_SIZE)
626 		smaps_pte_entry(pte, addr, walk);
627 	pte_unmap_unlock(pte - 1, ptl);
628 out:
629 	cond_resched();
630 	return 0;
631 }
632 
633 static void show_smap_vma_flags(struct seq_file *m, struct vm_area_struct *vma)
634 {
635 	/*
636 	 * Don't forget to update Documentation/ on changes.
637 	 */
638 	static const char mnemonics[BITS_PER_LONG][2] = {
639 		/*
640 		 * In case if we meet a flag we don't know about.
641 		 */
642 		[0 ... (BITS_PER_LONG-1)] = "??",
643 
644 		[ilog2(VM_READ)]	= "rd",
645 		[ilog2(VM_WRITE)]	= "wr",
646 		[ilog2(VM_EXEC)]	= "ex",
647 		[ilog2(VM_SHARED)]	= "sh",
648 		[ilog2(VM_MAYREAD)]	= "mr",
649 		[ilog2(VM_MAYWRITE)]	= "mw",
650 		[ilog2(VM_MAYEXEC)]	= "me",
651 		[ilog2(VM_MAYSHARE)]	= "ms",
652 		[ilog2(VM_GROWSDOWN)]	= "gd",
653 		[ilog2(VM_PFNMAP)]	= "pf",
654 		[ilog2(VM_DENYWRITE)]	= "dw",
655 #ifdef CONFIG_X86_INTEL_MPX
656 		[ilog2(VM_MPX)]		= "mp",
657 #endif
658 		[ilog2(VM_LOCKED)]	= "lo",
659 		[ilog2(VM_IO)]		= "io",
660 		[ilog2(VM_SEQ_READ)]	= "sr",
661 		[ilog2(VM_RAND_READ)]	= "rr",
662 		[ilog2(VM_DONTCOPY)]	= "dc",
663 		[ilog2(VM_DONTEXPAND)]	= "de",
664 		[ilog2(VM_ACCOUNT)]	= "ac",
665 		[ilog2(VM_NORESERVE)]	= "nr",
666 		[ilog2(VM_HUGETLB)]	= "ht",
667 		[ilog2(VM_SYNC)]	= "sf",
668 		[ilog2(VM_ARCH_1)]	= "ar",
669 		[ilog2(VM_WIPEONFORK)]	= "wf",
670 		[ilog2(VM_DONTDUMP)]	= "dd",
671 #ifdef CONFIG_MEM_SOFT_DIRTY
672 		[ilog2(VM_SOFTDIRTY)]	= "sd",
673 #endif
674 		[ilog2(VM_MIXEDMAP)]	= "mm",
675 		[ilog2(VM_HUGEPAGE)]	= "hg",
676 		[ilog2(VM_NOHUGEPAGE)]	= "nh",
677 		[ilog2(VM_MERGEABLE)]	= "mg",
678 		[ilog2(VM_UFFD_MISSING)]= "um",
679 		[ilog2(VM_UFFD_WP)]	= "uw",
680 #ifdef CONFIG_ARCH_HAS_PKEYS
681 		/* These come out via ProtectionKey: */
682 		[ilog2(VM_PKEY_BIT0)]	= "",
683 		[ilog2(VM_PKEY_BIT1)]	= "",
684 		[ilog2(VM_PKEY_BIT2)]	= "",
685 		[ilog2(VM_PKEY_BIT3)]	= "",
686 #if VM_PKEY_BIT4
687 		[ilog2(VM_PKEY_BIT4)]	= "",
688 #endif
689 #endif /* CONFIG_ARCH_HAS_PKEYS */
690 	};
691 	size_t i;
692 
693 	seq_puts(m, "VmFlags: ");
694 	for (i = 0; i < BITS_PER_LONG; i++) {
695 		if (!mnemonics[i][0])
696 			continue;
697 		if (vma->vm_flags & (1UL << i)) {
698 			seq_putc(m, mnemonics[i][0]);
699 			seq_putc(m, mnemonics[i][1]);
700 			seq_putc(m, ' ');
701 		}
702 	}
703 	seq_putc(m, '\n');
704 }
705 
706 #ifdef CONFIG_HUGETLB_PAGE
707 static int smaps_hugetlb_range(pte_t *pte, unsigned long hmask,
708 				 unsigned long addr, unsigned long end,
709 				 struct mm_walk *walk)
710 {
711 	struct mem_size_stats *mss = walk->private;
712 	struct vm_area_struct *vma = walk->vma;
713 	struct page *page = NULL;
714 
715 	if (pte_present(*pte)) {
716 		page = vm_normal_page(vma, addr, *pte);
717 	} else if (is_swap_pte(*pte)) {
718 		swp_entry_t swpent = pte_to_swp_entry(*pte);
719 
720 		if (is_migration_entry(swpent))
721 			page = migration_entry_to_page(swpent);
722 		else if (is_device_private_entry(swpent))
723 			page = device_private_entry_to_page(swpent);
724 	}
725 	if (page) {
726 		int mapcount = page_mapcount(page);
727 
728 		if (mapcount >= 2)
729 			mss->shared_hugetlb += huge_page_size(hstate_vma(vma));
730 		else
731 			mss->private_hugetlb += huge_page_size(hstate_vma(vma));
732 	}
733 	return 0;
734 }
735 #else
736 #define smaps_hugetlb_range	NULL
737 #endif /* HUGETLB_PAGE */
738 
739 static const struct mm_walk_ops smaps_walk_ops = {
740 	.pmd_entry		= smaps_pte_range,
741 	.hugetlb_entry		= smaps_hugetlb_range,
742 };
743 
744 static const struct mm_walk_ops smaps_shmem_walk_ops = {
745 	.pmd_entry		= smaps_pte_range,
746 	.hugetlb_entry		= smaps_hugetlb_range,
747 	.pte_hole		= smaps_pte_hole,
748 };
749 
750 static void smap_gather_stats(struct vm_area_struct *vma,
751 			     struct mem_size_stats *mss)
752 {
753 #ifdef CONFIG_SHMEM
754 	/* In case of smaps_rollup, reset the value from previous vma */
755 	mss->check_shmem_swap = false;
756 	if (vma->vm_file && shmem_mapping(vma->vm_file->f_mapping)) {
757 		/*
758 		 * For shared or readonly shmem mappings we know that all
759 		 * swapped out pages belong to the shmem object, and we can
760 		 * obtain the swap value much more efficiently. For private
761 		 * writable mappings, we might have COW pages that are
762 		 * not affected by the parent swapped out pages of the shmem
763 		 * object, so we have to distinguish them during the page walk.
764 		 * Unless we know that the shmem object (or the part mapped by
765 		 * our VMA) has no swapped out pages at all.
766 		 */
767 		unsigned long shmem_swapped = shmem_swap_usage(vma);
768 
769 		if (!shmem_swapped || (vma->vm_flags & VM_SHARED) ||
770 					!(vma->vm_flags & VM_WRITE)) {
771 			mss->swap += shmem_swapped;
772 		} else {
773 			mss->check_shmem_swap = true;
774 			walk_page_vma(vma, &smaps_shmem_walk_ops, mss);
775 			return;
776 		}
777 	}
778 #endif
779 	/* mmap_sem is held in m_start */
780 	walk_page_vma(vma, &smaps_walk_ops, mss);
781 }
782 
783 #define SEQ_PUT_DEC(str, val) \
784 		seq_put_decimal_ull_width(m, str, (val) >> 10, 8)
785 
786 /* Show the contents common for smaps and smaps_rollup */
787 static void __show_smap(struct seq_file *m, const struct mem_size_stats *mss,
788 	bool rollup_mode)
789 {
790 	SEQ_PUT_DEC("Rss:            ", mss->resident);
791 	SEQ_PUT_DEC(" kB\nPss:            ", mss->pss >> PSS_SHIFT);
792 	if (rollup_mode) {
793 		/*
794 		 * These are meaningful only for smaps_rollup, otherwise two of
795 		 * them are zero, and the other one is the same as Pss.
796 		 */
797 		SEQ_PUT_DEC(" kB\nPss_Anon:       ",
798 			mss->pss_anon >> PSS_SHIFT);
799 		SEQ_PUT_DEC(" kB\nPss_File:       ",
800 			mss->pss_file >> PSS_SHIFT);
801 		SEQ_PUT_DEC(" kB\nPss_Shmem:      ",
802 			mss->pss_shmem >> PSS_SHIFT);
803 	}
804 	SEQ_PUT_DEC(" kB\nShared_Clean:   ", mss->shared_clean);
805 	SEQ_PUT_DEC(" kB\nShared_Dirty:   ", mss->shared_dirty);
806 	SEQ_PUT_DEC(" kB\nPrivate_Clean:  ", mss->private_clean);
807 	SEQ_PUT_DEC(" kB\nPrivate_Dirty:  ", mss->private_dirty);
808 	SEQ_PUT_DEC(" kB\nReferenced:     ", mss->referenced);
809 	SEQ_PUT_DEC(" kB\nAnonymous:      ", mss->anonymous);
810 	SEQ_PUT_DEC(" kB\nLazyFree:       ", mss->lazyfree);
811 	SEQ_PUT_DEC(" kB\nAnonHugePages:  ", mss->anonymous_thp);
812 	SEQ_PUT_DEC(" kB\nShmemPmdMapped: ", mss->shmem_thp);
813 	SEQ_PUT_DEC(" kB\nFilePmdMapped: ", mss->file_thp);
814 	SEQ_PUT_DEC(" kB\nShared_Hugetlb: ", mss->shared_hugetlb);
815 	seq_put_decimal_ull_width(m, " kB\nPrivate_Hugetlb: ",
816 				  mss->private_hugetlb >> 10, 7);
817 	SEQ_PUT_DEC(" kB\nSwap:           ", mss->swap);
818 	SEQ_PUT_DEC(" kB\nSwapPss:        ",
819 					mss->swap_pss >> PSS_SHIFT);
820 	SEQ_PUT_DEC(" kB\nLocked:         ",
821 					mss->pss_locked >> PSS_SHIFT);
822 	seq_puts(m, " kB\n");
823 }
824 
825 static int show_smap(struct seq_file *m, void *v)
826 {
827 	struct vm_area_struct *vma = v;
828 	struct mem_size_stats mss;
829 
830 	memset(&mss, 0, sizeof(mss));
831 
832 	smap_gather_stats(vma, &mss);
833 
834 	show_map_vma(m, vma);
835 
836 	SEQ_PUT_DEC("Size:           ", vma->vm_end - vma->vm_start);
837 	SEQ_PUT_DEC(" kB\nKernelPageSize: ", vma_kernel_pagesize(vma));
838 	SEQ_PUT_DEC(" kB\nMMUPageSize:    ", vma_mmu_pagesize(vma));
839 	seq_puts(m, " kB\n");
840 
841 	__show_smap(m, &mss, false);
842 
843 	seq_printf(m, "THPeligible:		%d\n",
844 		   transparent_hugepage_enabled(vma));
845 
846 	if (arch_pkeys_enabled())
847 		seq_printf(m, "ProtectionKey:  %8u\n", vma_pkey(vma));
848 	show_smap_vma_flags(m, vma);
849 
850 	m_cache_vma(m, vma);
851 
852 	return 0;
853 }
854 
855 static int show_smaps_rollup(struct seq_file *m, void *v)
856 {
857 	struct proc_maps_private *priv = m->private;
858 	struct mem_size_stats mss;
859 	struct mm_struct *mm;
860 	struct vm_area_struct *vma;
861 	unsigned long last_vma_end = 0;
862 	int ret = 0;
863 
864 	priv->task = get_proc_task(priv->inode);
865 	if (!priv->task)
866 		return -ESRCH;
867 
868 	mm = priv->mm;
869 	if (!mm || !mmget_not_zero(mm)) {
870 		ret = -ESRCH;
871 		goto out_put_task;
872 	}
873 
874 	memset(&mss, 0, sizeof(mss));
875 
876 	ret = down_read_killable(&mm->mmap_sem);
877 	if (ret)
878 		goto out_put_mm;
879 
880 	hold_task_mempolicy(priv);
881 
882 	for (vma = priv->mm->mmap; vma; vma = vma->vm_next) {
883 		smap_gather_stats(vma, &mss);
884 		last_vma_end = vma->vm_end;
885 	}
886 
887 	show_vma_header_prefix(m, priv->mm->mmap->vm_start,
888 			       last_vma_end, 0, 0, 0, 0);
889 	seq_pad(m, ' ');
890 	seq_puts(m, "[rollup]\n");
891 
892 	__show_smap(m, &mss, true);
893 
894 	release_task_mempolicy(priv);
895 	up_read(&mm->mmap_sem);
896 
897 out_put_mm:
898 	mmput(mm);
899 out_put_task:
900 	put_task_struct(priv->task);
901 	priv->task = NULL;
902 
903 	return ret;
904 }
905 #undef SEQ_PUT_DEC
906 
907 static const struct seq_operations proc_pid_smaps_op = {
908 	.start	= m_start,
909 	.next	= m_next,
910 	.stop	= m_stop,
911 	.show	= show_smap
912 };
913 
914 static int pid_smaps_open(struct inode *inode, struct file *file)
915 {
916 	return do_maps_open(inode, file, &proc_pid_smaps_op);
917 }
918 
919 static int smaps_rollup_open(struct inode *inode, struct file *file)
920 {
921 	int ret;
922 	struct proc_maps_private *priv;
923 
924 	priv = kzalloc(sizeof(*priv), GFP_KERNEL_ACCOUNT);
925 	if (!priv)
926 		return -ENOMEM;
927 
928 	ret = single_open(file, show_smaps_rollup, priv);
929 	if (ret)
930 		goto out_free;
931 
932 	priv->inode = inode;
933 	priv->mm = proc_mem_open(inode, PTRACE_MODE_READ);
934 	if (IS_ERR(priv->mm)) {
935 		ret = PTR_ERR(priv->mm);
936 
937 		single_release(inode, file);
938 		goto out_free;
939 	}
940 
941 	return 0;
942 
943 out_free:
944 	kfree(priv);
945 	return ret;
946 }
947 
948 static int smaps_rollup_release(struct inode *inode, struct file *file)
949 {
950 	struct seq_file *seq = file->private_data;
951 	struct proc_maps_private *priv = seq->private;
952 
953 	if (priv->mm)
954 		mmdrop(priv->mm);
955 
956 	kfree(priv);
957 	return single_release(inode, file);
958 }
959 
960 const struct file_operations proc_pid_smaps_operations = {
961 	.open		= pid_smaps_open,
962 	.read		= seq_read,
963 	.llseek		= seq_lseek,
964 	.release	= proc_map_release,
965 };
966 
967 const struct file_operations proc_pid_smaps_rollup_operations = {
968 	.open		= smaps_rollup_open,
969 	.read		= seq_read,
970 	.llseek		= seq_lseek,
971 	.release	= smaps_rollup_release,
972 };
973 
974 enum clear_refs_types {
975 	CLEAR_REFS_ALL = 1,
976 	CLEAR_REFS_ANON,
977 	CLEAR_REFS_MAPPED,
978 	CLEAR_REFS_SOFT_DIRTY,
979 	CLEAR_REFS_MM_HIWATER_RSS,
980 	CLEAR_REFS_LAST,
981 };
982 
983 struct clear_refs_private {
984 	enum clear_refs_types type;
985 };
986 
987 #ifdef CONFIG_MEM_SOFT_DIRTY
988 static inline void clear_soft_dirty(struct vm_area_struct *vma,
989 		unsigned long addr, pte_t *pte)
990 {
991 	/*
992 	 * The soft-dirty tracker uses #PF-s to catch writes
993 	 * to pages, so write-protect the pte as well. See the
994 	 * Documentation/admin-guide/mm/soft-dirty.rst for full description
995 	 * of how soft-dirty works.
996 	 */
997 	pte_t ptent = *pte;
998 
999 	if (pte_present(ptent)) {
1000 		pte_t old_pte;
1001 
1002 		old_pte = ptep_modify_prot_start(vma, addr, pte);
1003 		ptent = pte_wrprotect(old_pte);
1004 		ptent = pte_clear_soft_dirty(ptent);
1005 		ptep_modify_prot_commit(vma, addr, pte, old_pte, ptent);
1006 	} else if (is_swap_pte(ptent)) {
1007 		ptent = pte_swp_clear_soft_dirty(ptent);
1008 		set_pte_at(vma->vm_mm, addr, pte, ptent);
1009 	}
1010 }
1011 #else
1012 static inline void clear_soft_dirty(struct vm_area_struct *vma,
1013 		unsigned long addr, pte_t *pte)
1014 {
1015 }
1016 #endif
1017 
1018 #if defined(CONFIG_MEM_SOFT_DIRTY) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
1019 static inline void clear_soft_dirty_pmd(struct vm_area_struct *vma,
1020 		unsigned long addr, pmd_t *pmdp)
1021 {
1022 	pmd_t old, pmd = *pmdp;
1023 
1024 	if (pmd_present(pmd)) {
1025 		/* See comment in change_huge_pmd() */
1026 		old = pmdp_invalidate(vma, addr, pmdp);
1027 		if (pmd_dirty(old))
1028 			pmd = pmd_mkdirty(pmd);
1029 		if (pmd_young(old))
1030 			pmd = pmd_mkyoung(pmd);
1031 
1032 		pmd = pmd_wrprotect(pmd);
1033 		pmd = pmd_clear_soft_dirty(pmd);
1034 
1035 		set_pmd_at(vma->vm_mm, addr, pmdp, pmd);
1036 	} else if (is_migration_entry(pmd_to_swp_entry(pmd))) {
1037 		pmd = pmd_swp_clear_soft_dirty(pmd);
1038 		set_pmd_at(vma->vm_mm, addr, pmdp, pmd);
1039 	}
1040 }
1041 #else
1042 static inline void clear_soft_dirty_pmd(struct vm_area_struct *vma,
1043 		unsigned long addr, pmd_t *pmdp)
1044 {
1045 }
1046 #endif
1047 
1048 static int clear_refs_pte_range(pmd_t *pmd, unsigned long addr,
1049 				unsigned long end, struct mm_walk *walk)
1050 {
1051 	struct clear_refs_private *cp = walk->private;
1052 	struct vm_area_struct *vma = walk->vma;
1053 	pte_t *pte, ptent;
1054 	spinlock_t *ptl;
1055 	struct page *page;
1056 
1057 	ptl = pmd_trans_huge_lock(pmd, vma);
1058 	if (ptl) {
1059 		if (cp->type == CLEAR_REFS_SOFT_DIRTY) {
1060 			clear_soft_dirty_pmd(vma, addr, pmd);
1061 			goto out;
1062 		}
1063 
1064 		if (!pmd_present(*pmd))
1065 			goto out;
1066 
1067 		page = pmd_page(*pmd);
1068 
1069 		/* Clear accessed and referenced bits. */
1070 		pmdp_test_and_clear_young(vma, addr, pmd);
1071 		test_and_clear_page_young(page);
1072 		ClearPageReferenced(page);
1073 out:
1074 		spin_unlock(ptl);
1075 		return 0;
1076 	}
1077 
1078 	if (pmd_trans_unstable(pmd))
1079 		return 0;
1080 
1081 	pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
1082 	for (; addr != end; pte++, addr += PAGE_SIZE) {
1083 		ptent = *pte;
1084 
1085 		if (cp->type == CLEAR_REFS_SOFT_DIRTY) {
1086 			clear_soft_dirty(vma, addr, pte);
1087 			continue;
1088 		}
1089 
1090 		if (!pte_present(ptent))
1091 			continue;
1092 
1093 		page = vm_normal_page(vma, addr, ptent);
1094 		if (!page)
1095 			continue;
1096 
1097 		/* Clear accessed and referenced bits. */
1098 		ptep_test_and_clear_young(vma, addr, pte);
1099 		test_and_clear_page_young(page);
1100 		ClearPageReferenced(page);
1101 	}
1102 	pte_unmap_unlock(pte - 1, ptl);
1103 	cond_resched();
1104 	return 0;
1105 }
1106 
1107 static int clear_refs_test_walk(unsigned long start, unsigned long end,
1108 				struct mm_walk *walk)
1109 {
1110 	struct clear_refs_private *cp = walk->private;
1111 	struct vm_area_struct *vma = walk->vma;
1112 
1113 	if (vma->vm_flags & VM_PFNMAP)
1114 		return 1;
1115 
1116 	/*
1117 	 * Writing 1 to /proc/pid/clear_refs affects all pages.
1118 	 * Writing 2 to /proc/pid/clear_refs only affects anonymous pages.
1119 	 * Writing 3 to /proc/pid/clear_refs only affects file mapped pages.
1120 	 * Writing 4 to /proc/pid/clear_refs affects all pages.
1121 	 */
1122 	if (cp->type == CLEAR_REFS_ANON && vma->vm_file)
1123 		return 1;
1124 	if (cp->type == CLEAR_REFS_MAPPED && !vma->vm_file)
1125 		return 1;
1126 	return 0;
1127 }
1128 
1129 static const struct mm_walk_ops clear_refs_walk_ops = {
1130 	.pmd_entry		= clear_refs_pte_range,
1131 	.test_walk		= clear_refs_test_walk,
1132 };
1133 
1134 static ssize_t clear_refs_write(struct file *file, const char __user *buf,
1135 				size_t count, loff_t *ppos)
1136 {
1137 	struct task_struct *task;
1138 	char buffer[PROC_NUMBUF];
1139 	struct mm_struct *mm;
1140 	struct vm_area_struct *vma;
1141 	enum clear_refs_types type;
1142 	struct mmu_gather tlb;
1143 	int itype;
1144 	int rv;
1145 
1146 	memset(buffer, 0, sizeof(buffer));
1147 	if (count > sizeof(buffer) - 1)
1148 		count = sizeof(buffer) - 1;
1149 	if (copy_from_user(buffer, buf, count))
1150 		return -EFAULT;
1151 	rv = kstrtoint(strstrip(buffer), 10, &itype);
1152 	if (rv < 0)
1153 		return rv;
1154 	type = (enum clear_refs_types)itype;
1155 	if (type < CLEAR_REFS_ALL || type >= CLEAR_REFS_LAST)
1156 		return -EINVAL;
1157 
1158 	task = get_proc_task(file_inode(file));
1159 	if (!task)
1160 		return -ESRCH;
1161 	mm = get_task_mm(task);
1162 	if (mm) {
1163 		struct mmu_notifier_range range;
1164 		struct clear_refs_private cp = {
1165 			.type = type,
1166 		};
1167 
1168 		if (type == CLEAR_REFS_MM_HIWATER_RSS) {
1169 			if (down_write_killable(&mm->mmap_sem)) {
1170 				count = -EINTR;
1171 				goto out_mm;
1172 			}
1173 
1174 			/*
1175 			 * Writing 5 to /proc/pid/clear_refs resets the peak
1176 			 * resident set size to this mm's current rss value.
1177 			 */
1178 			reset_mm_hiwater_rss(mm);
1179 			up_write(&mm->mmap_sem);
1180 			goto out_mm;
1181 		}
1182 
1183 		if (down_read_killable(&mm->mmap_sem)) {
1184 			count = -EINTR;
1185 			goto out_mm;
1186 		}
1187 		tlb_gather_mmu(&tlb, mm, 0, -1);
1188 		if (type == CLEAR_REFS_SOFT_DIRTY) {
1189 			for (vma = mm->mmap; vma; vma = vma->vm_next) {
1190 				if (!(vma->vm_flags & VM_SOFTDIRTY))
1191 					continue;
1192 				up_read(&mm->mmap_sem);
1193 				if (down_write_killable(&mm->mmap_sem)) {
1194 					count = -EINTR;
1195 					goto out_mm;
1196 				}
1197 				/*
1198 				 * Avoid to modify vma->vm_flags
1199 				 * without locked ops while the
1200 				 * coredump reads the vm_flags.
1201 				 */
1202 				if (!mmget_still_valid(mm)) {
1203 					/*
1204 					 * Silently return "count"
1205 					 * like if get_task_mm()
1206 					 * failed. FIXME: should this
1207 					 * function have returned
1208 					 * -ESRCH if get_task_mm()
1209 					 * failed like if
1210 					 * get_proc_task() fails?
1211 					 */
1212 					up_write(&mm->mmap_sem);
1213 					goto out_mm;
1214 				}
1215 				for (vma = mm->mmap; vma; vma = vma->vm_next) {
1216 					vma->vm_flags &= ~VM_SOFTDIRTY;
1217 					vma_set_page_prot(vma);
1218 				}
1219 				downgrade_write(&mm->mmap_sem);
1220 				break;
1221 			}
1222 
1223 			mmu_notifier_range_init(&range, MMU_NOTIFY_SOFT_DIRTY,
1224 						0, NULL, mm, 0, -1UL);
1225 			mmu_notifier_invalidate_range_start(&range);
1226 		}
1227 		walk_page_range(mm, 0, mm->highest_vm_end, &clear_refs_walk_ops,
1228 				&cp);
1229 		if (type == CLEAR_REFS_SOFT_DIRTY)
1230 			mmu_notifier_invalidate_range_end(&range);
1231 		tlb_finish_mmu(&tlb, 0, -1);
1232 		up_read(&mm->mmap_sem);
1233 out_mm:
1234 		mmput(mm);
1235 	}
1236 	put_task_struct(task);
1237 
1238 	return count;
1239 }
1240 
1241 const struct file_operations proc_clear_refs_operations = {
1242 	.write		= clear_refs_write,
1243 	.llseek		= noop_llseek,
1244 };
1245 
1246 typedef struct {
1247 	u64 pme;
1248 } pagemap_entry_t;
1249 
1250 struct pagemapread {
1251 	int pos, len;		/* units: PM_ENTRY_BYTES, not bytes */
1252 	pagemap_entry_t *buffer;
1253 	bool show_pfn;
1254 };
1255 
1256 #define PAGEMAP_WALK_SIZE	(PMD_SIZE)
1257 #define PAGEMAP_WALK_MASK	(PMD_MASK)
1258 
1259 #define PM_ENTRY_BYTES		sizeof(pagemap_entry_t)
1260 #define PM_PFRAME_BITS		55
1261 #define PM_PFRAME_MASK		GENMASK_ULL(PM_PFRAME_BITS - 1, 0)
1262 #define PM_SOFT_DIRTY		BIT_ULL(55)
1263 #define PM_MMAP_EXCLUSIVE	BIT_ULL(56)
1264 #define PM_FILE			BIT_ULL(61)
1265 #define PM_SWAP			BIT_ULL(62)
1266 #define PM_PRESENT		BIT_ULL(63)
1267 
1268 #define PM_END_OF_BUFFER    1
1269 
1270 static inline pagemap_entry_t make_pme(u64 frame, u64 flags)
1271 {
1272 	return (pagemap_entry_t) { .pme = (frame & PM_PFRAME_MASK) | flags };
1273 }
1274 
1275 static int add_to_pagemap(unsigned long addr, pagemap_entry_t *pme,
1276 			  struct pagemapread *pm)
1277 {
1278 	pm->buffer[pm->pos++] = *pme;
1279 	if (pm->pos >= pm->len)
1280 		return PM_END_OF_BUFFER;
1281 	return 0;
1282 }
1283 
1284 static int pagemap_pte_hole(unsigned long start, unsigned long end,
1285 				struct mm_walk *walk)
1286 {
1287 	struct pagemapread *pm = walk->private;
1288 	unsigned long addr = start;
1289 	int err = 0;
1290 
1291 	while (addr < end) {
1292 		struct vm_area_struct *vma = find_vma(walk->mm, addr);
1293 		pagemap_entry_t pme = make_pme(0, 0);
1294 		/* End of address space hole, which we mark as non-present. */
1295 		unsigned long hole_end;
1296 
1297 		if (vma)
1298 			hole_end = min(end, vma->vm_start);
1299 		else
1300 			hole_end = end;
1301 
1302 		for (; addr < hole_end; addr += PAGE_SIZE) {
1303 			err = add_to_pagemap(addr, &pme, pm);
1304 			if (err)
1305 				goto out;
1306 		}
1307 
1308 		if (!vma)
1309 			break;
1310 
1311 		/* Addresses in the VMA. */
1312 		if (vma->vm_flags & VM_SOFTDIRTY)
1313 			pme = make_pme(0, PM_SOFT_DIRTY);
1314 		for (; addr < min(end, vma->vm_end); addr += PAGE_SIZE) {
1315 			err = add_to_pagemap(addr, &pme, pm);
1316 			if (err)
1317 				goto out;
1318 		}
1319 	}
1320 out:
1321 	return err;
1322 }
1323 
1324 static pagemap_entry_t pte_to_pagemap_entry(struct pagemapread *pm,
1325 		struct vm_area_struct *vma, unsigned long addr, pte_t pte)
1326 {
1327 	u64 frame = 0, flags = 0;
1328 	struct page *page = NULL;
1329 
1330 	if (pte_present(pte)) {
1331 		if (pm->show_pfn)
1332 			frame = pte_pfn(pte);
1333 		flags |= PM_PRESENT;
1334 		page = vm_normal_page(vma, addr, pte);
1335 		if (pte_soft_dirty(pte))
1336 			flags |= PM_SOFT_DIRTY;
1337 	} else if (is_swap_pte(pte)) {
1338 		swp_entry_t entry;
1339 		if (pte_swp_soft_dirty(pte))
1340 			flags |= PM_SOFT_DIRTY;
1341 		entry = pte_to_swp_entry(pte);
1342 		if (pm->show_pfn)
1343 			frame = swp_type(entry) |
1344 				(swp_offset(entry) << MAX_SWAPFILES_SHIFT);
1345 		flags |= PM_SWAP;
1346 		if (is_migration_entry(entry))
1347 			page = migration_entry_to_page(entry);
1348 
1349 		if (is_device_private_entry(entry))
1350 			page = device_private_entry_to_page(entry);
1351 	}
1352 
1353 	if (page && !PageAnon(page))
1354 		flags |= PM_FILE;
1355 	if (page && page_mapcount(page) == 1)
1356 		flags |= PM_MMAP_EXCLUSIVE;
1357 	if (vma->vm_flags & VM_SOFTDIRTY)
1358 		flags |= PM_SOFT_DIRTY;
1359 
1360 	return make_pme(frame, flags);
1361 }
1362 
1363 static int pagemap_pmd_range(pmd_t *pmdp, unsigned long addr, unsigned long end,
1364 			     struct mm_walk *walk)
1365 {
1366 	struct vm_area_struct *vma = walk->vma;
1367 	struct pagemapread *pm = walk->private;
1368 	spinlock_t *ptl;
1369 	pte_t *pte, *orig_pte;
1370 	int err = 0;
1371 
1372 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1373 	ptl = pmd_trans_huge_lock(pmdp, vma);
1374 	if (ptl) {
1375 		u64 flags = 0, frame = 0;
1376 		pmd_t pmd = *pmdp;
1377 		struct page *page = NULL;
1378 
1379 		if (vma->vm_flags & VM_SOFTDIRTY)
1380 			flags |= PM_SOFT_DIRTY;
1381 
1382 		if (pmd_present(pmd)) {
1383 			page = pmd_page(pmd);
1384 
1385 			flags |= PM_PRESENT;
1386 			if (pmd_soft_dirty(pmd))
1387 				flags |= PM_SOFT_DIRTY;
1388 			if (pm->show_pfn)
1389 				frame = pmd_pfn(pmd) +
1390 					((addr & ~PMD_MASK) >> PAGE_SHIFT);
1391 		}
1392 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
1393 		else if (is_swap_pmd(pmd)) {
1394 			swp_entry_t entry = pmd_to_swp_entry(pmd);
1395 			unsigned long offset;
1396 
1397 			if (pm->show_pfn) {
1398 				offset = swp_offset(entry) +
1399 					((addr & ~PMD_MASK) >> PAGE_SHIFT);
1400 				frame = swp_type(entry) |
1401 					(offset << MAX_SWAPFILES_SHIFT);
1402 			}
1403 			flags |= PM_SWAP;
1404 			if (pmd_swp_soft_dirty(pmd))
1405 				flags |= PM_SOFT_DIRTY;
1406 			VM_BUG_ON(!is_pmd_migration_entry(pmd));
1407 			page = migration_entry_to_page(entry);
1408 		}
1409 #endif
1410 
1411 		if (page && page_mapcount(page) == 1)
1412 			flags |= PM_MMAP_EXCLUSIVE;
1413 
1414 		for (; addr != end; addr += PAGE_SIZE) {
1415 			pagemap_entry_t pme = make_pme(frame, flags);
1416 
1417 			err = add_to_pagemap(addr, &pme, pm);
1418 			if (err)
1419 				break;
1420 			if (pm->show_pfn) {
1421 				if (flags & PM_PRESENT)
1422 					frame++;
1423 				else if (flags & PM_SWAP)
1424 					frame += (1 << MAX_SWAPFILES_SHIFT);
1425 			}
1426 		}
1427 		spin_unlock(ptl);
1428 		return err;
1429 	}
1430 
1431 	if (pmd_trans_unstable(pmdp))
1432 		return 0;
1433 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
1434 
1435 	/*
1436 	 * We can assume that @vma always points to a valid one and @end never
1437 	 * goes beyond vma->vm_end.
1438 	 */
1439 	orig_pte = pte = pte_offset_map_lock(walk->mm, pmdp, addr, &ptl);
1440 	for (; addr < end; pte++, addr += PAGE_SIZE) {
1441 		pagemap_entry_t pme;
1442 
1443 		pme = pte_to_pagemap_entry(pm, vma, addr, *pte);
1444 		err = add_to_pagemap(addr, &pme, pm);
1445 		if (err)
1446 			break;
1447 	}
1448 	pte_unmap_unlock(orig_pte, ptl);
1449 
1450 	cond_resched();
1451 
1452 	return err;
1453 }
1454 
1455 #ifdef CONFIG_HUGETLB_PAGE
1456 /* This function walks within one hugetlb entry in the single call */
1457 static int pagemap_hugetlb_range(pte_t *ptep, unsigned long hmask,
1458 				 unsigned long addr, unsigned long end,
1459 				 struct mm_walk *walk)
1460 {
1461 	struct pagemapread *pm = walk->private;
1462 	struct vm_area_struct *vma = walk->vma;
1463 	u64 flags = 0, frame = 0;
1464 	int err = 0;
1465 	pte_t pte;
1466 
1467 	if (vma->vm_flags & VM_SOFTDIRTY)
1468 		flags |= PM_SOFT_DIRTY;
1469 
1470 	pte = huge_ptep_get(ptep);
1471 	if (pte_present(pte)) {
1472 		struct page *page = pte_page(pte);
1473 
1474 		if (!PageAnon(page))
1475 			flags |= PM_FILE;
1476 
1477 		if (page_mapcount(page) == 1)
1478 			flags |= PM_MMAP_EXCLUSIVE;
1479 
1480 		flags |= PM_PRESENT;
1481 		if (pm->show_pfn)
1482 			frame = pte_pfn(pte) +
1483 				((addr & ~hmask) >> PAGE_SHIFT);
1484 	}
1485 
1486 	for (; addr != end; addr += PAGE_SIZE) {
1487 		pagemap_entry_t pme = make_pme(frame, flags);
1488 
1489 		err = add_to_pagemap(addr, &pme, pm);
1490 		if (err)
1491 			return err;
1492 		if (pm->show_pfn && (flags & PM_PRESENT))
1493 			frame++;
1494 	}
1495 
1496 	cond_resched();
1497 
1498 	return err;
1499 }
1500 #else
1501 #define pagemap_hugetlb_range	NULL
1502 #endif /* HUGETLB_PAGE */
1503 
1504 static const struct mm_walk_ops pagemap_ops = {
1505 	.pmd_entry	= pagemap_pmd_range,
1506 	.pte_hole	= pagemap_pte_hole,
1507 	.hugetlb_entry	= pagemap_hugetlb_range,
1508 };
1509 
1510 /*
1511  * /proc/pid/pagemap - an array mapping virtual pages to pfns
1512  *
1513  * For each page in the address space, this file contains one 64-bit entry
1514  * consisting of the following:
1515  *
1516  * Bits 0-54  page frame number (PFN) if present
1517  * Bits 0-4   swap type if swapped
1518  * Bits 5-54  swap offset if swapped
1519  * Bit  55    pte is soft-dirty (see Documentation/admin-guide/mm/soft-dirty.rst)
1520  * Bit  56    page exclusively mapped
1521  * Bits 57-60 zero
1522  * Bit  61    page is file-page or shared-anon
1523  * Bit  62    page swapped
1524  * Bit  63    page present
1525  *
1526  * If the page is not present but in swap, then the PFN contains an
1527  * encoding of the swap file number and the page's offset into the
1528  * swap. Unmapped pages return a null PFN. This allows determining
1529  * precisely which pages are mapped (or in swap) and comparing mapped
1530  * pages between processes.
1531  *
1532  * Efficient users of this interface will use /proc/pid/maps to
1533  * determine which areas of memory are actually mapped and llseek to
1534  * skip over unmapped regions.
1535  */
1536 static ssize_t pagemap_read(struct file *file, char __user *buf,
1537 			    size_t count, loff_t *ppos)
1538 {
1539 	struct mm_struct *mm = file->private_data;
1540 	struct pagemapread pm;
1541 	unsigned long src;
1542 	unsigned long svpfn;
1543 	unsigned long start_vaddr;
1544 	unsigned long end_vaddr;
1545 	int ret = 0, copied = 0;
1546 
1547 	if (!mm || !mmget_not_zero(mm))
1548 		goto out;
1549 
1550 	ret = -EINVAL;
1551 	/* file position must be aligned */
1552 	if ((*ppos % PM_ENTRY_BYTES) || (count % PM_ENTRY_BYTES))
1553 		goto out_mm;
1554 
1555 	ret = 0;
1556 	if (!count)
1557 		goto out_mm;
1558 
1559 	/* do not disclose physical addresses: attack vector */
1560 	pm.show_pfn = file_ns_capable(file, &init_user_ns, CAP_SYS_ADMIN);
1561 
1562 	pm.len = (PAGEMAP_WALK_SIZE >> PAGE_SHIFT);
1563 	pm.buffer = kmalloc_array(pm.len, PM_ENTRY_BYTES, GFP_KERNEL);
1564 	ret = -ENOMEM;
1565 	if (!pm.buffer)
1566 		goto out_mm;
1567 
1568 	src = *ppos;
1569 	svpfn = src / PM_ENTRY_BYTES;
1570 	start_vaddr = svpfn << PAGE_SHIFT;
1571 	end_vaddr = mm->task_size;
1572 
1573 	/* watch out for wraparound */
1574 	if (svpfn > mm->task_size >> PAGE_SHIFT)
1575 		start_vaddr = end_vaddr;
1576 
1577 	/*
1578 	 * The odds are that this will stop walking way
1579 	 * before end_vaddr, because the length of the
1580 	 * user buffer is tracked in "pm", and the walk
1581 	 * will stop when we hit the end of the buffer.
1582 	 */
1583 	ret = 0;
1584 	while (count && (start_vaddr < end_vaddr)) {
1585 		int len;
1586 		unsigned long end;
1587 
1588 		pm.pos = 0;
1589 		end = (start_vaddr + PAGEMAP_WALK_SIZE) & PAGEMAP_WALK_MASK;
1590 		/* overflow ? */
1591 		if (end < start_vaddr || end > end_vaddr)
1592 			end = end_vaddr;
1593 		ret = down_read_killable(&mm->mmap_sem);
1594 		if (ret)
1595 			goto out_free;
1596 		ret = walk_page_range(mm, start_vaddr, end, &pagemap_ops, &pm);
1597 		up_read(&mm->mmap_sem);
1598 		start_vaddr = end;
1599 
1600 		len = min(count, PM_ENTRY_BYTES * pm.pos);
1601 		if (copy_to_user(buf, pm.buffer, len)) {
1602 			ret = -EFAULT;
1603 			goto out_free;
1604 		}
1605 		copied += len;
1606 		buf += len;
1607 		count -= len;
1608 	}
1609 	*ppos += copied;
1610 	if (!ret || ret == PM_END_OF_BUFFER)
1611 		ret = copied;
1612 
1613 out_free:
1614 	kfree(pm.buffer);
1615 out_mm:
1616 	mmput(mm);
1617 out:
1618 	return ret;
1619 }
1620 
1621 static int pagemap_open(struct inode *inode, struct file *file)
1622 {
1623 	struct mm_struct *mm;
1624 
1625 	mm = proc_mem_open(inode, PTRACE_MODE_READ);
1626 	if (IS_ERR(mm))
1627 		return PTR_ERR(mm);
1628 	file->private_data = mm;
1629 	return 0;
1630 }
1631 
1632 static int pagemap_release(struct inode *inode, struct file *file)
1633 {
1634 	struct mm_struct *mm = file->private_data;
1635 
1636 	if (mm)
1637 		mmdrop(mm);
1638 	return 0;
1639 }
1640 
1641 const struct file_operations proc_pagemap_operations = {
1642 	.llseek		= mem_lseek, /* borrow this */
1643 	.read		= pagemap_read,
1644 	.open		= pagemap_open,
1645 	.release	= pagemap_release,
1646 };
1647 #endif /* CONFIG_PROC_PAGE_MONITOR */
1648 
1649 #ifdef CONFIG_NUMA
1650 
1651 struct numa_maps {
1652 	unsigned long pages;
1653 	unsigned long anon;
1654 	unsigned long active;
1655 	unsigned long writeback;
1656 	unsigned long mapcount_max;
1657 	unsigned long dirty;
1658 	unsigned long swapcache;
1659 	unsigned long node[MAX_NUMNODES];
1660 };
1661 
1662 struct numa_maps_private {
1663 	struct proc_maps_private proc_maps;
1664 	struct numa_maps md;
1665 };
1666 
1667 static void gather_stats(struct page *page, struct numa_maps *md, int pte_dirty,
1668 			unsigned long nr_pages)
1669 {
1670 	int count = page_mapcount(page);
1671 
1672 	md->pages += nr_pages;
1673 	if (pte_dirty || PageDirty(page))
1674 		md->dirty += nr_pages;
1675 
1676 	if (PageSwapCache(page))
1677 		md->swapcache += nr_pages;
1678 
1679 	if (PageActive(page) || PageUnevictable(page))
1680 		md->active += nr_pages;
1681 
1682 	if (PageWriteback(page))
1683 		md->writeback += nr_pages;
1684 
1685 	if (PageAnon(page))
1686 		md->anon += nr_pages;
1687 
1688 	if (count > md->mapcount_max)
1689 		md->mapcount_max = count;
1690 
1691 	md->node[page_to_nid(page)] += nr_pages;
1692 }
1693 
1694 static struct page *can_gather_numa_stats(pte_t pte, struct vm_area_struct *vma,
1695 		unsigned long addr)
1696 {
1697 	struct page *page;
1698 	int nid;
1699 
1700 	if (!pte_present(pte))
1701 		return NULL;
1702 
1703 	page = vm_normal_page(vma, addr, pte);
1704 	if (!page)
1705 		return NULL;
1706 
1707 	if (PageReserved(page))
1708 		return NULL;
1709 
1710 	nid = page_to_nid(page);
1711 	if (!node_isset(nid, node_states[N_MEMORY]))
1712 		return NULL;
1713 
1714 	return page;
1715 }
1716 
1717 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1718 static struct page *can_gather_numa_stats_pmd(pmd_t pmd,
1719 					      struct vm_area_struct *vma,
1720 					      unsigned long addr)
1721 {
1722 	struct page *page;
1723 	int nid;
1724 
1725 	if (!pmd_present(pmd))
1726 		return NULL;
1727 
1728 	page = vm_normal_page_pmd(vma, addr, pmd);
1729 	if (!page)
1730 		return NULL;
1731 
1732 	if (PageReserved(page))
1733 		return NULL;
1734 
1735 	nid = page_to_nid(page);
1736 	if (!node_isset(nid, node_states[N_MEMORY]))
1737 		return NULL;
1738 
1739 	return page;
1740 }
1741 #endif
1742 
1743 static int gather_pte_stats(pmd_t *pmd, unsigned long addr,
1744 		unsigned long end, struct mm_walk *walk)
1745 {
1746 	struct numa_maps *md = walk->private;
1747 	struct vm_area_struct *vma = walk->vma;
1748 	spinlock_t *ptl;
1749 	pte_t *orig_pte;
1750 	pte_t *pte;
1751 
1752 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1753 	ptl = pmd_trans_huge_lock(pmd, vma);
1754 	if (ptl) {
1755 		struct page *page;
1756 
1757 		page = can_gather_numa_stats_pmd(*pmd, vma, addr);
1758 		if (page)
1759 			gather_stats(page, md, pmd_dirty(*pmd),
1760 				     HPAGE_PMD_SIZE/PAGE_SIZE);
1761 		spin_unlock(ptl);
1762 		return 0;
1763 	}
1764 
1765 	if (pmd_trans_unstable(pmd))
1766 		return 0;
1767 #endif
1768 	orig_pte = pte = pte_offset_map_lock(walk->mm, pmd, addr, &ptl);
1769 	do {
1770 		struct page *page = can_gather_numa_stats(*pte, vma, addr);
1771 		if (!page)
1772 			continue;
1773 		gather_stats(page, md, pte_dirty(*pte), 1);
1774 
1775 	} while (pte++, addr += PAGE_SIZE, addr != end);
1776 	pte_unmap_unlock(orig_pte, ptl);
1777 	cond_resched();
1778 	return 0;
1779 }
1780 #ifdef CONFIG_HUGETLB_PAGE
1781 static int gather_hugetlb_stats(pte_t *pte, unsigned long hmask,
1782 		unsigned long addr, unsigned long end, struct mm_walk *walk)
1783 {
1784 	pte_t huge_pte = huge_ptep_get(pte);
1785 	struct numa_maps *md;
1786 	struct page *page;
1787 
1788 	if (!pte_present(huge_pte))
1789 		return 0;
1790 
1791 	page = pte_page(huge_pte);
1792 	if (!page)
1793 		return 0;
1794 
1795 	md = walk->private;
1796 	gather_stats(page, md, pte_dirty(huge_pte), 1);
1797 	return 0;
1798 }
1799 
1800 #else
1801 static int gather_hugetlb_stats(pte_t *pte, unsigned long hmask,
1802 		unsigned long addr, unsigned long end, struct mm_walk *walk)
1803 {
1804 	return 0;
1805 }
1806 #endif
1807 
1808 static const struct mm_walk_ops show_numa_ops = {
1809 	.hugetlb_entry = gather_hugetlb_stats,
1810 	.pmd_entry = gather_pte_stats,
1811 };
1812 
1813 /*
1814  * Display pages allocated per node and memory policy via /proc.
1815  */
1816 static int show_numa_map(struct seq_file *m, void *v)
1817 {
1818 	struct numa_maps_private *numa_priv = m->private;
1819 	struct proc_maps_private *proc_priv = &numa_priv->proc_maps;
1820 	struct vm_area_struct *vma = v;
1821 	struct numa_maps *md = &numa_priv->md;
1822 	struct file *file = vma->vm_file;
1823 	struct mm_struct *mm = vma->vm_mm;
1824 	struct mempolicy *pol;
1825 	char buffer[64];
1826 	int nid;
1827 
1828 	if (!mm)
1829 		return 0;
1830 
1831 	/* Ensure we start with an empty set of numa_maps statistics. */
1832 	memset(md, 0, sizeof(*md));
1833 
1834 	pol = __get_vma_policy(vma, vma->vm_start);
1835 	if (pol) {
1836 		mpol_to_str(buffer, sizeof(buffer), pol);
1837 		mpol_cond_put(pol);
1838 	} else {
1839 		mpol_to_str(buffer, sizeof(buffer), proc_priv->task_mempolicy);
1840 	}
1841 
1842 	seq_printf(m, "%08lx %s", vma->vm_start, buffer);
1843 
1844 	if (file) {
1845 		seq_puts(m, " file=");
1846 		seq_file_path(m, file, "\n\t= ");
1847 	} else if (vma->vm_start <= mm->brk && vma->vm_end >= mm->start_brk) {
1848 		seq_puts(m, " heap");
1849 	} else if (is_stack(vma)) {
1850 		seq_puts(m, " stack");
1851 	}
1852 
1853 	if (is_vm_hugetlb_page(vma))
1854 		seq_puts(m, " huge");
1855 
1856 	/* mmap_sem is held by m_start */
1857 	walk_page_vma(vma, &show_numa_ops, md);
1858 
1859 	if (!md->pages)
1860 		goto out;
1861 
1862 	if (md->anon)
1863 		seq_printf(m, " anon=%lu", md->anon);
1864 
1865 	if (md->dirty)
1866 		seq_printf(m, " dirty=%lu", md->dirty);
1867 
1868 	if (md->pages != md->anon && md->pages != md->dirty)
1869 		seq_printf(m, " mapped=%lu", md->pages);
1870 
1871 	if (md->mapcount_max > 1)
1872 		seq_printf(m, " mapmax=%lu", md->mapcount_max);
1873 
1874 	if (md->swapcache)
1875 		seq_printf(m, " swapcache=%lu", md->swapcache);
1876 
1877 	if (md->active < md->pages && !is_vm_hugetlb_page(vma))
1878 		seq_printf(m, " active=%lu", md->active);
1879 
1880 	if (md->writeback)
1881 		seq_printf(m, " writeback=%lu", md->writeback);
1882 
1883 	for_each_node_state(nid, N_MEMORY)
1884 		if (md->node[nid])
1885 			seq_printf(m, " N%d=%lu", nid, md->node[nid]);
1886 
1887 	seq_printf(m, " kernelpagesize_kB=%lu", vma_kernel_pagesize(vma) >> 10);
1888 out:
1889 	seq_putc(m, '\n');
1890 	m_cache_vma(m, vma);
1891 	return 0;
1892 }
1893 
1894 static const struct seq_operations proc_pid_numa_maps_op = {
1895 	.start  = m_start,
1896 	.next   = m_next,
1897 	.stop   = m_stop,
1898 	.show   = show_numa_map,
1899 };
1900 
1901 static int pid_numa_maps_open(struct inode *inode, struct file *file)
1902 {
1903 	return proc_maps_open(inode, file, &proc_pid_numa_maps_op,
1904 				sizeof(struct numa_maps_private));
1905 }
1906 
1907 const struct file_operations proc_pid_numa_maps_operations = {
1908 	.open		= pid_numa_maps_open,
1909 	.read		= seq_read,
1910 	.llseek		= seq_lseek,
1911 	.release	= proc_map_release,
1912 };
1913 
1914 #endif /* CONFIG_NUMA */
1915