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