xref: /linux/fs/proc/task_mmu.c (revision 665db14d0712ac27f6a0081510bd811efb3faa3c)
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 #include <linux/minmax.h>
24 #include <linux/overflow.h>
25 #include <linux/buildid.h>
26 
27 #include <asm/elf.h>
28 #include <asm/tlb.h>
29 #include <asm/tlbflush.h>
30 #include "internal.h"
31 
32 #define SEQ_PUT_DEC(str, val) \
33 		seq_put_decimal_ull_width(m, str, (val) << (PAGE_SHIFT-10), 8)
34 void task_mem(struct seq_file *m, struct mm_struct *mm)
35 {
36 	unsigned long text, lib, swap, anon, file, shmem;
37 	unsigned long hiwater_vm, total_vm, hiwater_rss, total_rss;
38 
39 	anon = get_mm_counter(mm, MM_ANONPAGES);
40 	file = get_mm_counter(mm, MM_FILEPAGES);
41 	shmem = get_mm_counter(mm, MM_SHMEMPAGES);
42 
43 	/*
44 	 * Note: to minimize their overhead, mm maintains hiwater_vm and
45 	 * hiwater_rss only when about to *lower* total_vm or rss.  Any
46 	 * collector of these hiwater stats must therefore get total_vm
47 	 * and rss too, which will usually be the higher.  Barriers? not
48 	 * worth the effort, such snapshots can always be inconsistent.
49 	 */
50 	hiwater_vm = total_vm = mm->total_vm;
51 	if (hiwater_vm < mm->hiwater_vm)
52 		hiwater_vm = mm->hiwater_vm;
53 	hiwater_rss = total_rss = anon + file + shmem;
54 	if (hiwater_rss < mm->hiwater_rss)
55 		hiwater_rss = mm->hiwater_rss;
56 
57 	/* split executable areas between text and lib */
58 	text = PAGE_ALIGN(mm->end_code) - (mm->start_code & PAGE_MASK);
59 	text = min(text, mm->exec_vm << PAGE_SHIFT);
60 	lib = (mm->exec_vm << PAGE_SHIFT) - text;
61 
62 	swap = get_mm_counter(mm, MM_SWAPENTS);
63 	SEQ_PUT_DEC("VmPeak:\t", hiwater_vm);
64 	SEQ_PUT_DEC(" kB\nVmSize:\t", total_vm);
65 	SEQ_PUT_DEC(" kB\nVmLck:\t", mm->locked_vm);
66 	SEQ_PUT_DEC(" kB\nVmPin:\t", atomic64_read(&mm->pinned_vm));
67 	SEQ_PUT_DEC(" kB\nVmHWM:\t", hiwater_rss);
68 	SEQ_PUT_DEC(" kB\nVmRSS:\t", total_rss);
69 	SEQ_PUT_DEC(" kB\nRssAnon:\t", anon);
70 	SEQ_PUT_DEC(" kB\nRssFile:\t", file);
71 	SEQ_PUT_DEC(" kB\nRssShmem:\t", shmem);
72 	SEQ_PUT_DEC(" kB\nVmData:\t", mm->data_vm);
73 	SEQ_PUT_DEC(" kB\nVmStk:\t", mm->stack_vm);
74 	seq_put_decimal_ull_width(m,
75 		    " kB\nVmExe:\t", text >> 10, 8);
76 	seq_put_decimal_ull_width(m,
77 		    " kB\nVmLib:\t", lib >> 10, 8);
78 	seq_put_decimal_ull_width(m,
79 		    " kB\nVmPTE:\t", mm_pgtables_bytes(mm) >> 10, 8);
80 	SEQ_PUT_DEC(" kB\nVmSwap:\t", swap);
81 	seq_puts(m, " kB\n");
82 	hugetlb_report_usage(m, mm);
83 }
84 #undef SEQ_PUT_DEC
85 
86 unsigned long task_vsize(struct mm_struct *mm)
87 {
88 	return PAGE_SIZE * mm->total_vm;
89 }
90 
91 unsigned long task_statm(struct mm_struct *mm,
92 			 unsigned long *shared, unsigned long *text,
93 			 unsigned long *data, unsigned long *resident)
94 {
95 	*shared = get_mm_counter(mm, MM_FILEPAGES) +
96 			get_mm_counter(mm, MM_SHMEMPAGES);
97 	*text = (PAGE_ALIGN(mm->end_code) - (mm->start_code & PAGE_MASK))
98 								>> PAGE_SHIFT;
99 	*data = mm->data_vm + mm->stack_vm;
100 	*resident = *shared + get_mm_counter(mm, MM_ANONPAGES);
101 	return mm->total_vm;
102 }
103 
104 #ifdef CONFIG_NUMA
105 /*
106  * Save get_task_policy() for show_numa_map().
107  */
108 static void hold_task_mempolicy(struct proc_maps_private *priv)
109 {
110 	struct task_struct *task = priv->task;
111 
112 	task_lock(task);
113 	priv->task_mempolicy = get_task_policy(task);
114 	mpol_get(priv->task_mempolicy);
115 	task_unlock(task);
116 }
117 static void release_task_mempolicy(struct proc_maps_private *priv)
118 {
119 	mpol_put(priv->task_mempolicy);
120 }
121 #else
122 static void hold_task_mempolicy(struct proc_maps_private *priv)
123 {
124 }
125 static void release_task_mempolicy(struct proc_maps_private *priv)
126 {
127 }
128 #endif
129 
130 static struct vm_area_struct *proc_get_vma(struct proc_maps_private *priv,
131 						loff_t *ppos)
132 {
133 	struct vm_area_struct *vma = vma_next(&priv->iter);
134 
135 	if (vma) {
136 		*ppos = vma->vm_start;
137 	} else {
138 		*ppos = -2UL;
139 		vma = get_gate_vma(priv->mm);
140 	}
141 
142 	return vma;
143 }
144 
145 static void *m_start(struct seq_file *m, loff_t *ppos)
146 {
147 	struct proc_maps_private *priv = m->private;
148 	unsigned long last_addr = *ppos;
149 	struct mm_struct *mm;
150 
151 	/* See m_next(). Zero at the start or after lseek. */
152 	if (last_addr == -1UL)
153 		return NULL;
154 
155 	priv->task = get_proc_task(priv->inode);
156 	if (!priv->task)
157 		return ERR_PTR(-ESRCH);
158 
159 	mm = priv->mm;
160 	if (!mm || !mmget_not_zero(mm)) {
161 		put_task_struct(priv->task);
162 		priv->task = NULL;
163 		return NULL;
164 	}
165 
166 	if (mmap_read_lock_killable(mm)) {
167 		mmput(mm);
168 		put_task_struct(priv->task);
169 		priv->task = NULL;
170 		return ERR_PTR(-EINTR);
171 	}
172 
173 	vma_iter_init(&priv->iter, mm, last_addr);
174 	hold_task_mempolicy(priv);
175 	if (last_addr == -2UL)
176 		return get_gate_vma(mm);
177 
178 	return proc_get_vma(priv, ppos);
179 }
180 
181 static void *m_next(struct seq_file *m, void *v, loff_t *ppos)
182 {
183 	if (*ppos == -2UL) {
184 		*ppos = -1UL;
185 		return NULL;
186 	}
187 	return proc_get_vma(m->private, ppos);
188 }
189 
190 static void m_stop(struct seq_file *m, void *v)
191 {
192 	struct proc_maps_private *priv = m->private;
193 	struct mm_struct *mm = priv->mm;
194 
195 	if (!priv->task)
196 		return;
197 
198 	release_task_mempolicy(priv);
199 	mmap_read_unlock(mm);
200 	mmput(mm);
201 	put_task_struct(priv->task);
202 	priv->task = NULL;
203 }
204 
205 static int proc_maps_open(struct inode *inode, struct file *file,
206 			const struct seq_operations *ops, int psize)
207 {
208 	struct proc_maps_private *priv = __seq_open_private(file, ops, psize);
209 
210 	if (!priv)
211 		return -ENOMEM;
212 
213 	priv->inode = inode;
214 	priv->mm = proc_mem_open(inode, PTRACE_MODE_READ);
215 	if (IS_ERR(priv->mm)) {
216 		int err = PTR_ERR(priv->mm);
217 
218 		seq_release_private(inode, file);
219 		return err;
220 	}
221 
222 	return 0;
223 }
224 
225 static int proc_map_release(struct inode *inode, struct file *file)
226 {
227 	struct seq_file *seq = file->private_data;
228 	struct proc_maps_private *priv = seq->private;
229 
230 	if (priv->mm)
231 		mmdrop(priv->mm);
232 
233 	return seq_release_private(inode, file);
234 }
235 
236 static int do_maps_open(struct inode *inode, struct file *file,
237 			const struct seq_operations *ops)
238 {
239 	return proc_maps_open(inode, file, ops,
240 				sizeof(struct proc_maps_private));
241 }
242 
243 static void get_vma_name(struct vm_area_struct *vma,
244 			 const struct path **path,
245 			 const char **name,
246 			 const char **name_fmt)
247 {
248 	struct anon_vma_name *anon_name = vma->vm_mm ? anon_vma_name(vma) : NULL;
249 
250 	*name = NULL;
251 	*path = NULL;
252 	*name_fmt = NULL;
253 
254 	/*
255 	 * Print the dentry name for named mappings, and a
256 	 * special [heap] marker for the heap:
257 	 */
258 	if (vma->vm_file) {
259 		/*
260 		 * If user named this anon shared memory via
261 		 * prctl(PR_SET_VMA ..., use the provided name.
262 		 */
263 		if (anon_name) {
264 			*name_fmt = "[anon_shmem:%s]";
265 			*name = anon_name->name;
266 		} else {
267 			*path = file_user_path(vma->vm_file);
268 		}
269 		return;
270 	}
271 
272 	if (vma->vm_ops && vma->vm_ops->name) {
273 		*name = vma->vm_ops->name(vma);
274 		if (*name)
275 			return;
276 	}
277 
278 	*name = arch_vma_name(vma);
279 	if (*name)
280 		return;
281 
282 	if (!vma->vm_mm) {
283 		*name = "[vdso]";
284 		return;
285 	}
286 
287 	if (vma_is_initial_heap(vma)) {
288 		*name = "[heap]";
289 		return;
290 	}
291 
292 	if (vma_is_initial_stack(vma)) {
293 		*name = "[stack]";
294 		return;
295 	}
296 
297 	if (anon_name) {
298 		*name_fmt = "[anon:%s]";
299 		*name = anon_name->name;
300 		return;
301 	}
302 }
303 
304 static void show_vma_header_prefix(struct seq_file *m,
305 				   unsigned long start, unsigned long end,
306 				   vm_flags_t flags, unsigned long long pgoff,
307 				   dev_t dev, unsigned long ino)
308 {
309 	seq_setwidth(m, 25 + sizeof(void *) * 6 - 1);
310 	seq_put_hex_ll(m, NULL, start, 8);
311 	seq_put_hex_ll(m, "-", end, 8);
312 	seq_putc(m, ' ');
313 	seq_putc(m, flags & VM_READ ? 'r' : '-');
314 	seq_putc(m, flags & VM_WRITE ? 'w' : '-');
315 	seq_putc(m, flags & VM_EXEC ? 'x' : '-');
316 	seq_putc(m, flags & VM_MAYSHARE ? 's' : 'p');
317 	seq_put_hex_ll(m, " ", pgoff, 8);
318 	seq_put_hex_ll(m, " ", MAJOR(dev), 2);
319 	seq_put_hex_ll(m, ":", MINOR(dev), 2);
320 	seq_put_decimal_ull(m, " ", ino);
321 	seq_putc(m, ' ');
322 }
323 
324 static void
325 show_map_vma(struct seq_file *m, struct vm_area_struct *vma)
326 {
327 	const struct path *path;
328 	const char *name_fmt, *name;
329 	vm_flags_t flags = vma->vm_flags;
330 	unsigned long ino = 0;
331 	unsigned long long pgoff = 0;
332 	unsigned long start, end;
333 	dev_t dev = 0;
334 
335 	if (vma->vm_file) {
336 		const struct inode *inode = file_user_inode(vma->vm_file);
337 
338 		dev = inode->i_sb->s_dev;
339 		ino = inode->i_ino;
340 		pgoff = ((loff_t)vma->vm_pgoff) << PAGE_SHIFT;
341 	}
342 
343 	start = vma->vm_start;
344 	end = vma->vm_end;
345 	show_vma_header_prefix(m, start, end, flags, pgoff, dev, ino);
346 
347 	get_vma_name(vma, &path, &name, &name_fmt);
348 	if (path) {
349 		seq_pad(m, ' ');
350 		seq_path(m, path, "\n");
351 	} else if (name_fmt) {
352 		seq_pad(m, ' ');
353 		seq_printf(m, name_fmt, name);
354 	} else if (name) {
355 		seq_pad(m, ' ');
356 		seq_puts(m, name);
357 	}
358 	seq_putc(m, '\n');
359 }
360 
361 static int show_map(struct seq_file *m, void *v)
362 {
363 	show_map_vma(m, v);
364 	return 0;
365 }
366 
367 static const struct seq_operations proc_pid_maps_op = {
368 	.start	= m_start,
369 	.next	= m_next,
370 	.stop	= m_stop,
371 	.show	= show_map
372 };
373 
374 static int pid_maps_open(struct inode *inode, struct file *file)
375 {
376 	return do_maps_open(inode, file, &proc_pid_maps_op);
377 }
378 
379 #define PROCMAP_QUERY_VMA_FLAGS (				\
380 		PROCMAP_QUERY_VMA_READABLE |			\
381 		PROCMAP_QUERY_VMA_WRITABLE |			\
382 		PROCMAP_QUERY_VMA_EXECUTABLE |			\
383 		PROCMAP_QUERY_VMA_SHARED			\
384 )
385 
386 #define PROCMAP_QUERY_VALID_FLAGS_MASK (			\
387 		PROCMAP_QUERY_COVERING_OR_NEXT_VMA |		\
388 		PROCMAP_QUERY_FILE_BACKED_VMA |			\
389 		PROCMAP_QUERY_VMA_FLAGS				\
390 )
391 
392 static int query_vma_setup(struct mm_struct *mm)
393 {
394 	return mmap_read_lock_killable(mm);
395 }
396 
397 static void query_vma_teardown(struct mm_struct *mm, struct vm_area_struct *vma)
398 {
399 	mmap_read_unlock(mm);
400 }
401 
402 static struct vm_area_struct *query_vma_find_by_addr(struct mm_struct *mm, unsigned long addr)
403 {
404 	return find_vma(mm, addr);
405 }
406 
407 static struct vm_area_struct *query_matching_vma(struct mm_struct *mm,
408 						 unsigned long addr, u32 flags)
409 {
410 	struct vm_area_struct *vma;
411 
412 next_vma:
413 	vma = query_vma_find_by_addr(mm, addr);
414 	if (!vma)
415 		goto no_vma;
416 
417 	/* user requested only file-backed VMA, keep iterating */
418 	if ((flags & PROCMAP_QUERY_FILE_BACKED_VMA) && !vma->vm_file)
419 		goto skip_vma;
420 
421 	/* VMA permissions should satisfy query flags */
422 	if (flags & PROCMAP_QUERY_VMA_FLAGS) {
423 		u32 perm = 0;
424 
425 		if (flags & PROCMAP_QUERY_VMA_READABLE)
426 			perm |= VM_READ;
427 		if (flags & PROCMAP_QUERY_VMA_WRITABLE)
428 			perm |= VM_WRITE;
429 		if (flags & PROCMAP_QUERY_VMA_EXECUTABLE)
430 			perm |= VM_EXEC;
431 		if (flags & PROCMAP_QUERY_VMA_SHARED)
432 			perm |= VM_MAYSHARE;
433 
434 		if ((vma->vm_flags & perm) != perm)
435 			goto skip_vma;
436 	}
437 
438 	/* found covering VMA or user is OK with the matching next VMA */
439 	if ((flags & PROCMAP_QUERY_COVERING_OR_NEXT_VMA) || vma->vm_start <= addr)
440 		return vma;
441 
442 skip_vma:
443 	/*
444 	 * If the user needs closest matching VMA, keep iterating.
445 	 */
446 	addr = vma->vm_end;
447 	if (flags & PROCMAP_QUERY_COVERING_OR_NEXT_VMA)
448 		goto next_vma;
449 
450 no_vma:
451 	return ERR_PTR(-ENOENT);
452 }
453 
454 static int do_procmap_query(struct proc_maps_private *priv, void __user *uarg)
455 {
456 	struct procmap_query karg;
457 	struct vm_area_struct *vma;
458 	struct mm_struct *mm;
459 	const char *name = NULL;
460 	char build_id_buf[BUILD_ID_SIZE_MAX], *name_buf = NULL;
461 	__u64 usize;
462 	int err;
463 
464 	if (copy_from_user(&usize, (void __user *)uarg, sizeof(usize)))
465 		return -EFAULT;
466 	/* argument struct can never be that large, reject abuse */
467 	if (usize > PAGE_SIZE)
468 		return -E2BIG;
469 	/* argument struct should have at least query_flags and query_addr fields */
470 	if (usize < offsetofend(struct procmap_query, query_addr))
471 		return -EINVAL;
472 	err = copy_struct_from_user(&karg, sizeof(karg), uarg, usize);
473 	if (err)
474 		return err;
475 
476 	/* reject unknown flags */
477 	if (karg.query_flags & ~PROCMAP_QUERY_VALID_FLAGS_MASK)
478 		return -EINVAL;
479 	/* either both buffer address and size are set, or both should be zero */
480 	if (!!karg.vma_name_size != !!karg.vma_name_addr)
481 		return -EINVAL;
482 	if (!!karg.build_id_size != !!karg.build_id_addr)
483 		return -EINVAL;
484 
485 	mm = priv->mm;
486 	if (!mm || !mmget_not_zero(mm))
487 		return -ESRCH;
488 
489 	err = query_vma_setup(mm);
490 	if (err) {
491 		mmput(mm);
492 		return err;
493 	}
494 
495 	vma = query_matching_vma(mm, karg.query_addr, karg.query_flags);
496 	if (IS_ERR(vma)) {
497 		err = PTR_ERR(vma);
498 		vma = NULL;
499 		goto out;
500 	}
501 
502 	karg.vma_start = vma->vm_start;
503 	karg.vma_end = vma->vm_end;
504 
505 	karg.vma_flags = 0;
506 	if (vma->vm_flags & VM_READ)
507 		karg.vma_flags |= PROCMAP_QUERY_VMA_READABLE;
508 	if (vma->vm_flags & VM_WRITE)
509 		karg.vma_flags |= PROCMAP_QUERY_VMA_WRITABLE;
510 	if (vma->vm_flags & VM_EXEC)
511 		karg.vma_flags |= PROCMAP_QUERY_VMA_EXECUTABLE;
512 	if (vma->vm_flags & VM_MAYSHARE)
513 		karg.vma_flags |= PROCMAP_QUERY_VMA_SHARED;
514 
515 	karg.vma_page_size = vma_kernel_pagesize(vma);
516 
517 	if (vma->vm_file) {
518 		const struct inode *inode = file_user_inode(vma->vm_file);
519 
520 		karg.vma_offset = ((__u64)vma->vm_pgoff) << PAGE_SHIFT;
521 		karg.dev_major = MAJOR(inode->i_sb->s_dev);
522 		karg.dev_minor = MINOR(inode->i_sb->s_dev);
523 		karg.inode = inode->i_ino;
524 	} else {
525 		karg.vma_offset = 0;
526 		karg.dev_major = 0;
527 		karg.dev_minor = 0;
528 		karg.inode = 0;
529 	}
530 
531 	if (karg.build_id_size) {
532 		__u32 build_id_sz;
533 
534 		err = build_id_parse(vma, build_id_buf, &build_id_sz);
535 		if (err) {
536 			karg.build_id_size = 0;
537 		} else {
538 			if (karg.build_id_size < build_id_sz) {
539 				err = -ENAMETOOLONG;
540 				goto out;
541 			}
542 			karg.build_id_size = build_id_sz;
543 		}
544 	}
545 
546 	if (karg.build_id_size) {
547 		__u32 build_id_sz;
548 
549 		err = build_id_parse(vma, build_id_buf, &build_id_sz);
550 		if (err) {
551 			karg.build_id_size = 0;
552 		} else {
553 			if (karg.build_id_size < build_id_sz) {
554 				err = -ENAMETOOLONG;
555 				goto out;
556 			}
557 			karg.build_id_size = build_id_sz;
558 		}
559 	}
560 
561 	if (karg.vma_name_size) {
562 		size_t name_buf_sz = min_t(size_t, PATH_MAX, karg.vma_name_size);
563 		const struct path *path;
564 		const char *name_fmt;
565 		size_t name_sz = 0;
566 
567 		get_vma_name(vma, &path, &name, &name_fmt);
568 
569 		if (path || name_fmt || name) {
570 			name_buf = kmalloc(name_buf_sz, GFP_KERNEL);
571 			if (!name_buf) {
572 				err = -ENOMEM;
573 				goto out;
574 			}
575 		}
576 		if (path) {
577 			name = d_path(path, name_buf, name_buf_sz);
578 			if (IS_ERR(name)) {
579 				err = PTR_ERR(name);
580 				goto out;
581 			}
582 			name_sz = name_buf + name_buf_sz - name;
583 		} else if (name || name_fmt) {
584 			name_sz = 1 + snprintf(name_buf, name_buf_sz, name_fmt ?: "%s", name);
585 			name = name_buf;
586 		}
587 		if (name_sz > name_buf_sz) {
588 			err = -ENAMETOOLONG;
589 			goto out;
590 		}
591 		karg.vma_name_size = name_sz;
592 	}
593 
594 	/* unlock vma or mmap_lock, and put mm_struct before copying data to user */
595 	query_vma_teardown(mm, vma);
596 	mmput(mm);
597 
598 	if (karg.vma_name_size && copy_to_user(u64_to_user_ptr(karg.vma_name_addr),
599 					       name, karg.vma_name_size)) {
600 		kfree(name_buf);
601 		return -EFAULT;
602 	}
603 	kfree(name_buf);
604 
605 	if (karg.build_id_size && copy_to_user(u64_to_user_ptr(karg.build_id_addr),
606 					       build_id_buf, karg.build_id_size))
607 		return -EFAULT;
608 
609 	if (copy_to_user(uarg, &karg, min_t(size_t, sizeof(karg), usize)))
610 		return -EFAULT;
611 
612 	return 0;
613 
614 out:
615 	query_vma_teardown(mm, vma);
616 	mmput(mm);
617 	kfree(name_buf);
618 	return err;
619 }
620 
621 static long procfs_procmap_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
622 {
623 	struct seq_file *seq = file->private_data;
624 	struct proc_maps_private *priv = seq->private;
625 
626 	switch (cmd) {
627 	case PROCMAP_QUERY:
628 		return do_procmap_query(priv, (void __user *)arg);
629 	default:
630 		return -ENOIOCTLCMD;
631 	}
632 }
633 
634 const struct file_operations proc_pid_maps_operations = {
635 	.open		= pid_maps_open,
636 	.read		= seq_read,
637 	.llseek		= seq_lseek,
638 	.release	= proc_map_release,
639 	.unlocked_ioctl = procfs_procmap_ioctl,
640 	.compat_ioctl	= compat_ptr_ioctl,
641 };
642 
643 /*
644  * Proportional Set Size(PSS): my share of RSS.
645  *
646  * PSS of a process is the count of pages it has in memory, where each
647  * page is divided by the number of processes sharing it.  So if a
648  * process has 1000 pages all to itself, and 1000 shared with one other
649  * process, its PSS will be 1500.
650  *
651  * To keep (accumulated) division errors low, we adopt a 64bit
652  * fixed-point pss counter to minimize division errors. So (pss >>
653  * PSS_SHIFT) would be the real byte count.
654  *
655  * A shift of 12 before division means (assuming 4K page size):
656  * 	- 1M 3-user-pages add up to 8KB errors;
657  * 	- supports mapcount up to 2^24, or 16M;
658  * 	- supports PSS up to 2^52 bytes, or 4PB.
659  */
660 #define PSS_SHIFT 12
661 
662 #ifdef CONFIG_PROC_PAGE_MONITOR
663 struct mem_size_stats {
664 	unsigned long resident;
665 	unsigned long shared_clean;
666 	unsigned long shared_dirty;
667 	unsigned long private_clean;
668 	unsigned long private_dirty;
669 	unsigned long referenced;
670 	unsigned long anonymous;
671 	unsigned long lazyfree;
672 	unsigned long anonymous_thp;
673 	unsigned long shmem_thp;
674 	unsigned long file_thp;
675 	unsigned long swap;
676 	unsigned long shared_hugetlb;
677 	unsigned long private_hugetlb;
678 	unsigned long ksm;
679 	u64 pss;
680 	u64 pss_anon;
681 	u64 pss_file;
682 	u64 pss_shmem;
683 	u64 pss_dirty;
684 	u64 pss_locked;
685 	u64 swap_pss;
686 };
687 
688 static void smaps_page_accumulate(struct mem_size_stats *mss,
689 		struct folio *folio, unsigned long size, unsigned long pss,
690 		bool dirty, bool locked, bool private)
691 {
692 	mss->pss += pss;
693 
694 	if (folio_test_anon(folio))
695 		mss->pss_anon += pss;
696 	else if (folio_test_swapbacked(folio))
697 		mss->pss_shmem += pss;
698 	else
699 		mss->pss_file += pss;
700 
701 	if (locked)
702 		mss->pss_locked += pss;
703 
704 	if (dirty || folio_test_dirty(folio)) {
705 		mss->pss_dirty += pss;
706 		if (private)
707 			mss->private_dirty += size;
708 		else
709 			mss->shared_dirty += size;
710 	} else {
711 		if (private)
712 			mss->private_clean += size;
713 		else
714 			mss->shared_clean += size;
715 	}
716 }
717 
718 static void smaps_account(struct mem_size_stats *mss, struct page *page,
719 		bool compound, bool young, bool dirty, bool locked,
720 		bool present)
721 {
722 	struct folio *folio = page_folio(page);
723 	int i, nr = compound ? compound_nr(page) : 1;
724 	unsigned long size = nr * PAGE_SIZE;
725 
726 	/*
727 	 * First accumulate quantities that depend only on |size| and the type
728 	 * of the compound page.
729 	 */
730 	if (folio_test_anon(folio)) {
731 		mss->anonymous += size;
732 		if (!folio_test_swapbacked(folio) && !dirty &&
733 		    !folio_test_dirty(folio))
734 			mss->lazyfree += size;
735 	}
736 
737 	if (folio_test_ksm(folio))
738 		mss->ksm += size;
739 
740 	mss->resident += size;
741 	/* Accumulate the size in pages that have been accessed. */
742 	if (young || folio_test_young(folio) || folio_test_referenced(folio))
743 		mss->referenced += size;
744 
745 	/*
746 	 * Then accumulate quantities that may depend on sharing, or that may
747 	 * differ page-by-page.
748 	 *
749 	 * refcount == 1 for present entries guarantees that the folio is mapped
750 	 * exactly once. For large folios this implies that exactly one
751 	 * PTE/PMD/... maps (a part of) this folio.
752 	 *
753 	 * Treat all non-present entries (where relying on the mapcount and
754 	 * refcount doesn't make sense) as "maybe shared, but not sure how
755 	 * often". We treat device private entries as being fake-present.
756 	 *
757 	 * Note that it would not be safe to read the mapcount especially for
758 	 * pages referenced by migration entries, even with the PTL held.
759 	 */
760 	if (folio_ref_count(folio) == 1 || !present) {
761 		smaps_page_accumulate(mss, folio, size, size << PSS_SHIFT,
762 				      dirty, locked, present);
763 		return;
764 	}
765 	/*
766 	 * We obtain a snapshot of the mapcount. Without holding the folio lock
767 	 * this snapshot can be slightly wrong as we cannot always read the
768 	 * mapcount atomically.
769 	 */
770 	for (i = 0; i < nr; i++, page++) {
771 		int mapcount = folio_precise_page_mapcount(folio, page);
772 		unsigned long pss = PAGE_SIZE << PSS_SHIFT;
773 		if (mapcount >= 2)
774 			pss /= mapcount;
775 		smaps_page_accumulate(mss, folio, PAGE_SIZE, pss,
776 				dirty, locked, mapcount < 2);
777 	}
778 }
779 
780 #ifdef CONFIG_SHMEM
781 static int smaps_pte_hole(unsigned long addr, unsigned long end,
782 			  __always_unused int depth, struct mm_walk *walk)
783 {
784 	struct mem_size_stats *mss = walk->private;
785 	struct vm_area_struct *vma = walk->vma;
786 
787 	mss->swap += shmem_partial_swap_usage(walk->vma->vm_file->f_mapping,
788 					      linear_page_index(vma, addr),
789 					      linear_page_index(vma, end));
790 
791 	return 0;
792 }
793 #else
794 #define smaps_pte_hole		NULL
795 #endif /* CONFIG_SHMEM */
796 
797 static void smaps_pte_hole_lookup(unsigned long addr, struct mm_walk *walk)
798 {
799 #ifdef CONFIG_SHMEM
800 	if (walk->ops->pte_hole) {
801 		/* depth is not used */
802 		smaps_pte_hole(addr, addr + PAGE_SIZE, 0, walk);
803 	}
804 #endif
805 }
806 
807 static void smaps_pte_entry(pte_t *pte, unsigned long addr,
808 		struct mm_walk *walk)
809 {
810 	struct mem_size_stats *mss = walk->private;
811 	struct vm_area_struct *vma = walk->vma;
812 	bool locked = !!(vma->vm_flags & VM_LOCKED);
813 	struct page *page = NULL;
814 	bool present = false, young = false, dirty = false;
815 	pte_t ptent = ptep_get(pte);
816 
817 	if (pte_present(ptent)) {
818 		page = vm_normal_page(vma, addr, ptent);
819 		young = pte_young(ptent);
820 		dirty = pte_dirty(ptent);
821 		present = true;
822 	} else if (is_swap_pte(ptent)) {
823 		swp_entry_t swpent = pte_to_swp_entry(ptent);
824 
825 		if (!non_swap_entry(swpent)) {
826 			int mapcount;
827 
828 			mss->swap += PAGE_SIZE;
829 			mapcount = swp_swapcount(swpent);
830 			if (mapcount >= 2) {
831 				u64 pss_delta = (u64)PAGE_SIZE << PSS_SHIFT;
832 
833 				do_div(pss_delta, mapcount);
834 				mss->swap_pss += pss_delta;
835 			} else {
836 				mss->swap_pss += (u64)PAGE_SIZE << PSS_SHIFT;
837 			}
838 		} else if (is_pfn_swap_entry(swpent)) {
839 			if (is_device_private_entry(swpent))
840 				present = true;
841 			page = pfn_swap_entry_to_page(swpent);
842 		}
843 	} else {
844 		smaps_pte_hole_lookup(addr, walk);
845 		return;
846 	}
847 
848 	if (!page)
849 		return;
850 
851 	smaps_account(mss, page, false, young, dirty, locked, present);
852 }
853 
854 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
855 static void smaps_pmd_entry(pmd_t *pmd, unsigned long addr,
856 		struct mm_walk *walk)
857 {
858 	struct mem_size_stats *mss = walk->private;
859 	struct vm_area_struct *vma = walk->vma;
860 	bool locked = !!(vma->vm_flags & VM_LOCKED);
861 	struct page *page = NULL;
862 	bool present = false;
863 	struct folio *folio;
864 
865 	if (pmd_present(*pmd)) {
866 		page = vm_normal_page_pmd(vma, addr, *pmd);
867 		present = true;
868 	} else if (unlikely(thp_migration_supported() && is_swap_pmd(*pmd))) {
869 		swp_entry_t entry = pmd_to_swp_entry(*pmd);
870 
871 		if (is_pfn_swap_entry(entry))
872 			page = pfn_swap_entry_to_page(entry);
873 	}
874 	if (IS_ERR_OR_NULL(page))
875 		return;
876 	folio = page_folio(page);
877 	if (folio_test_anon(folio))
878 		mss->anonymous_thp += HPAGE_PMD_SIZE;
879 	else if (folio_test_swapbacked(folio))
880 		mss->shmem_thp += HPAGE_PMD_SIZE;
881 	else if (folio_is_zone_device(folio))
882 		/* pass */;
883 	else
884 		mss->file_thp += HPAGE_PMD_SIZE;
885 
886 	smaps_account(mss, page, true, pmd_young(*pmd), pmd_dirty(*pmd),
887 		      locked, present);
888 }
889 #else
890 static void smaps_pmd_entry(pmd_t *pmd, unsigned long addr,
891 		struct mm_walk *walk)
892 {
893 }
894 #endif
895 
896 static int smaps_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end,
897 			   struct mm_walk *walk)
898 {
899 	struct vm_area_struct *vma = walk->vma;
900 	pte_t *pte;
901 	spinlock_t *ptl;
902 
903 	ptl = pmd_trans_huge_lock(pmd, vma);
904 	if (ptl) {
905 		smaps_pmd_entry(pmd, addr, walk);
906 		spin_unlock(ptl);
907 		goto out;
908 	}
909 
910 	pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
911 	if (!pte) {
912 		walk->action = ACTION_AGAIN;
913 		return 0;
914 	}
915 	for (; addr != end; pte++, addr += PAGE_SIZE)
916 		smaps_pte_entry(pte, addr, walk);
917 	pte_unmap_unlock(pte - 1, ptl);
918 out:
919 	cond_resched();
920 	return 0;
921 }
922 
923 static void show_smap_vma_flags(struct seq_file *m, struct vm_area_struct *vma)
924 {
925 	/*
926 	 * Don't forget to update Documentation/ on changes.
927 	 */
928 	static const char mnemonics[BITS_PER_LONG][2] = {
929 		/*
930 		 * In case if we meet a flag we don't know about.
931 		 */
932 		[0 ... (BITS_PER_LONG-1)] = "??",
933 
934 		[ilog2(VM_READ)]	= "rd",
935 		[ilog2(VM_WRITE)]	= "wr",
936 		[ilog2(VM_EXEC)]	= "ex",
937 		[ilog2(VM_SHARED)]	= "sh",
938 		[ilog2(VM_MAYREAD)]	= "mr",
939 		[ilog2(VM_MAYWRITE)]	= "mw",
940 		[ilog2(VM_MAYEXEC)]	= "me",
941 		[ilog2(VM_MAYSHARE)]	= "ms",
942 		[ilog2(VM_GROWSDOWN)]	= "gd",
943 		[ilog2(VM_PFNMAP)]	= "pf",
944 		[ilog2(VM_LOCKED)]	= "lo",
945 		[ilog2(VM_IO)]		= "io",
946 		[ilog2(VM_SEQ_READ)]	= "sr",
947 		[ilog2(VM_RAND_READ)]	= "rr",
948 		[ilog2(VM_DONTCOPY)]	= "dc",
949 		[ilog2(VM_DONTEXPAND)]	= "de",
950 		[ilog2(VM_LOCKONFAULT)]	= "lf",
951 		[ilog2(VM_ACCOUNT)]	= "ac",
952 		[ilog2(VM_NORESERVE)]	= "nr",
953 		[ilog2(VM_HUGETLB)]	= "ht",
954 		[ilog2(VM_SYNC)]	= "sf",
955 		[ilog2(VM_ARCH_1)]	= "ar",
956 		[ilog2(VM_WIPEONFORK)]	= "wf",
957 		[ilog2(VM_DONTDUMP)]	= "dd",
958 #ifdef CONFIG_ARM64_BTI
959 		[ilog2(VM_ARM64_BTI)]	= "bt",
960 #endif
961 #ifdef CONFIG_MEM_SOFT_DIRTY
962 		[ilog2(VM_SOFTDIRTY)]	= "sd",
963 #endif
964 		[ilog2(VM_MIXEDMAP)]	= "mm",
965 		[ilog2(VM_HUGEPAGE)]	= "hg",
966 		[ilog2(VM_NOHUGEPAGE)]	= "nh",
967 		[ilog2(VM_MERGEABLE)]	= "mg",
968 		[ilog2(VM_UFFD_MISSING)]= "um",
969 		[ilog2(VM_UFFD_WP)]	= "uw",
970 #ifdef CONFIG_ARM64_MTE
971 		[ilog2(VM_MTE)]		= "mt",
972 		[ilog2(VM_MTE_ALLOWED)]	= "",
973 #endif
974 #ifdef CONFIG_ARCH_HAS_PKEYS
975 		/* These come out via ProtectionKey: */
976 		[ilog2(VM_PKEY_BIT0)]	= "",
977 		[ilog2(VM_PKEY_BIT1)]	= "",
978 		[ilog2(VM_PKEY_BIT2)]	= "",
979 #if VM_PKEY_BIT3
980 		[ilog2(VM_PKEY_BIT3)]	= "",
981 #endif
982 #if VM_PKEY_BIT4
983 		[ilog2(VM_PKEY_BIT4)]	= "",
984 #endif
985 #endif /* CONFIG_ARCH_HAS_PKEYS */
986 #ifdef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
987 		[ilog2(VM_UFFD_MINOR)]	= "ui",
988 #endif /* CONFIG_HAVE_ARCH_USERFAULTFD_MINOR */
989 #ifdef CONFIG_X86_USER_SHADOW_STACK
990 		[ilog2(VM_SHADOW_STACK)] = "ss",
991 #endif
992 #if defined(CONFIG_64BIT) || defined(CONFIG_PPC32)
993 		[ilog2(VM_DROPPABLE)] = "dp",
994 #endif
995 #ifdef CONFIG_64BIT
996 		[ilog2(VM_SEALED)] = "sl",
997 #endif
998 	};
999 	size_t i;
1000 
1001 	seq_puts(m, "VmFlags: ");
1002 	for (i = 0; i < BITS_PER_LONG; i++) {
1003 		if (!mnemonics[i][0])
1004 			continue;
1005 		if (vma->vm_flags & (1UL << i)) {
1006 			seq_putc(m, mnemonics[i][0]);
1007 			seq_putc(m, mnemonics[i][1]);
1008 			seq_putc(m, ' ');
1009 		}
1010 	}
1011 	seq_putc(m, '\n');
1012 }
1013 
1014 #ifdef CONFIG_HUGETLB_PAGE
1015 static int smaps_hugetlb_range(pte_t *pte, unsigned long hmask,
1016 				 unsigned long addr, unsigned long end,
1017 				 struct mm_walk *walk)
1018 {
1019 	struct mem_size_stats *mss = walk->private;
1020 	struct vm_area_struct *vma = walk->vma;
1021 	pte_t ptent = huge_ptep_get(walk->mm, addr, pte);
1022 	struct folio *folio = NULL;
1023 	bool present = false;
1024 
1025 	if (pte_present(ptent)) {
1026 		folio = page_folio(pte_page(ptent));
1027 		present = true;
1028 	} else if (is_swap_pte(ptent)) {
1029 		swp_entry_t swpent = pte_to_swp_entry(ptent);
1030 
1031 		if (is_pfn_swap_entry(swpent))
1032 			folio = pfn_swap_entry_folio(swpent);
1033 	}
1034 
1035 	if (folio) {
1036 		/* We treat non-present entries as "maybe shared". */
1037 		if (!present || folio_likely_mapped_shared(folio) ||
1038 		    hugetlb_pmd_shared(pte))
1039 			mss->shared_hugetlb += huge_page_size(hstate_vma(vma));
1040 		else
1041 			mss->private_hugetlb += huge_page_size(hstate_vma(vma));
1042 	}
1043 	return 0;
1044 }
1045 #else
1046 #define smaps_hugetlb_range	NULL
1047 #endif /* HUGETLB_PAGE */
1048 
1049 static const struct mm_walk_ops smaps_walk_ops = {
1050 	.pmd_entry		= smaps_pte_range,
1051 	.hugetlb_entry		= smaps_hugetlb_range,
1052 	.walk_lock		= PGWALK_RDLOCK,
1053 };
1054 
1055 static const struct mm_walk_ops smaps_shmem_walk_ops = {
1056 	.pmd_entry		= smaps_pte_range,
1057 	.hugetlb_entry		= smaps_hugetlb_range,
1058 	.pte_hole		= smaps_pte_hole,
1059 	.walk_lock		= PGWALK_RDLOCK,
1060 };
1061 
1062 /*
1063  * Gather mem stats from @vma with the indicated beginning
1064  * address @start, and keep them in @mss.
1065  *
1066  * Use vm_start of @vma as the beginning address if @start is 0.
1067  */
1068 static void smap_gather_stats(struct vm_area_struct *vma,
1069 		struct mem_size_stats *mss, unsigned long start)
1070 {
1071 	const struct mm_walk_ops *ops = &smaps_walk_ops;
1072 
1073 	/* Invalid start */
1074 	if (start >= vma->vm_end)
1075 		return;
1076 
1077 	if (vma->vm_file && shmem_mapping(vma->vm_file->f_mapping)) {
1078 		/*
1079 		 * For shared or readonly shmem mappings we know that all
1080 		 * swapped out pages belong to the shmem object, and we can
1081 		 * obtain the swap value much more efficiently. For private
1082 		 * writable mappings, we might have COW pages that are
1083 		 * not affected by the parent swapped out pages of the shmem
1084 		 * object, so we have to distinguish them during the page walk.
1085 		 * Unless we know that the shmem object (or the part mapped by
1086 		 * our VMA) has no swapped out pages at all.
1087 		 */
1088 		unsigned long shmem_swapped = shmem_swap_usage(vma);
1089 
1090 		if (!start && (!shmem_swapped || (vma->vm_flags & VM_SHARED) ||
1091 					!(vma->vm_flags & VM_WRITE))) {
1092 			mss->swap += shmem_swapped;
1093 		} else {
1094 			ops = &smaps_shmem_walk_ops;
1095 		}
1096 	}
1097 
1098 	/* mmap_lock is held in m_start */
1099 	if (!start)
1100 		walk_page_vma(vma, ops, mss);
1101 	else
1102 		walk_page_range(vma->vm_mm, start, vma->vm_end, ops, mss);
1103 }
1104 
1105 #define SEQ_PUT_DEC(str, val) \
1106 		seq_put_decimal_ull_width(m, str, (val) >> 10, 8)
1107 
1108 /* Show the contents common for smaps and smaps_rollup */
1109 static void __show_smap(struct seq_file *m, const struct mem_size_stats *mss,
1110 	bool rollup_mode)
1111 {
1112 	SEQ_PUT_DEC("Rss:            ", mss->resident);
1113 	SEQ_PUT_DEC(" kB\nPss:            ", mss->pss >> PSS_SHIFT);
1114 	SEQ_PUT_DEC(" kB\nPss_Dirty:      ", mss->pss_dirty >> PSS_SHIFT);
1115 	if (rollup_mode) {
1116 		/*
1117 		 * These are meaningful only for smaps_rollup, otherwise two of
1118 		 * them are zero, and the other one is the same as Pss.
1119 		 */
1120 		SEQ_PUT_DEC(" kB\nPss_Anon:       ",
1121 			mss->pss_anon >> PSS_SHIFT);
1122 		SEQ_PUT_DEC(" kB\nPss_File:       ",
1123 			mss->pss_file >> PSS_SHIFT);
1124 		SEQ_PUT_DEC(" kB\nPss_Shmem:      ",
1125 			mss->pss_shmem >> PSS_SHIFT);
1126 	}
1127 	SEQ_PUT_DEC(" kB\nShared_Clean:   ", mss->shared_clean);
1128 	SEQ_PUT_DEC(" kB\nShared_Dirty:   ", mss->shared_dirty);
1129 	SEQ_PUT_DEC(" kB\nPrivate_Clean:  ", mss->private_clean);
1130 	SEQ_PUT_DEC(" kB\nPrivate_Dirty:  ", mss->private_dirty);
1131 	SEQ_PUT_DEC(" kB\nReferenced:     ", mss->referenced);
1132 	SEQ_PUT_DEC(" kB\nAnonymous:      ", mss->anonymous);
1133 	SEQ_PUT_DEC(" kB\nKSM:            ", mss->ksm);
1134 	SEQ_PUT_DEC(" kB\nLazyFree:       ", mss->lazyfree);
1135 	SEQ_PUT_DEC(" kB\nAnonHugePages:  ", mss->anonymous_thp);
1136 	SEQ_PUT_DEC(" kB\nShmemPmdMapped: ", mss->shmem_thp);
1137 	SEQ_PUT_DEC(" kB\nFilePmdMapped:  ", mss->file_thp);
1138 	SEQ_PUT_DEC(" kB\nShared_Hugetlb: ", mss->shared_hugetlb);
1139 	seq_put_decimal_ull_width(m, " kB\nPrivate_Hugetlb: ",
1140 				  mss->private_hugetlb >> 10, 7);
1141 	SEQ_PUT_DEC(" kB\nSwap:           ", mss->swap);
1142 	SEQ_PUT_DEC(" kB\nSwapPss:        ",
1143 					mss->swap_pss >> PSS_SHIFT);
1144 	SEQ_PUT_DEC(" kB\nLocked:         ",
1145 					mss->pss_locked >> PSS_SHIFT);
1146 	seq_puts(m, " kB\n");
1147 }
1148 
1149 static int show_smap(struct seq_file *m, void *v)
1150 {
1151 	struct vm_area_struct *vma = v;
1152 	struct mem_size_stats mss = {};
1153 
1154 	smap_gather_stats(vma, &mss, 0);
1155 
1156 	show_map_vma(m, vma);
1157 
1158 	SEQ_PUT_DEC("Size:           ", vma->vm_end - vma->vm_start);
1159 	SEQ_PUT_DEC(" kB\nKernelPageSize: ", vma_kernel_pagesize(vma));
1160 	SEQ_PUT_DEC(" kB\nMMUPageSize:    ", vma_mmu_pagesize(vma));
1161 	seq_puts(m, " kB\n");
1162 
1163 	__show_smap(m, &mss, false);
1164 
1165 	seq_printf(m, "THPeligible:    %8u\n",
1166 		   !!thp_vma_allowable_orders(vma, vma->vm_flags,
1167 			   TVA_SMAPS | TVA_ENFORCE_SYSFS, THP_ORDERS_ALL));
1168 
1169 	if (arch_pkeys_enabled())
1170 		seq_printf(m, "ProtectionKey:  %8u\n", vma_pkey(vma));
1171 	show_smap_vma_flags(m, vma);
1172 
1173 	return 0;
1174 }
1175 
1176 static int show_smaps_rollup(struct seq_file *m, void *v)
1177 {
1178 	struct proc_maps_private *priv = m->private;
1179 	struct mem_size_stats mss = {};
1180 	struct mm_struct *mm = priv->mm;
1181 	struct vm_area_struct *vma;
1182 	unsigned long vma_start = 0, last_vma_end = 0;
1183 	int ret = 0;
1184 	VMA_ITERATOR(vmi, mm, 0);
1185 
1186 	priv->task = get_proc_task(priv->inode);
1187 	if (!priv->task)
1188 		return -ESRCH;
1189 
1190 	if (!mm || !mmget_not_zero(mm)) {
1191 		ret = -ESRCH;
1192 		goto out_put_task;
1193 	}
1194 
1195 	ret = mmap_read_lock_killable(mm);
1196 	if (ret)
1197 		goto out_put_mm;
1198 
1199 	hold_task_mempolicy(priv);
1200 	vma = vma_next(&vmi);
1201 
1202 	if (unlikely(!vma))
1203 		goto empty_set;
1204 
1205 	vma_start = vma->vm_start;
1206 	do {
1207 		smap_gather_stats(vma, &mss, 0);
1208 		last_vma_end = vma->vm_end;
1209 
1210 		/*
1211 		 * Release mmap_lock temporarily if someone wants to
1212 		 * access it for write request.
1213 		 */
1214 		if (mmap_lock_is_contended(mm)) {
1215 			vma_iter_invalidate(&vmi);
1216 			mmap_read_unlock(mm);
1217 			ret = mmap_read_lock_killable(mm);
1218 			if (ret) {
1219 				release_task_mempolicy(priv);
1220 				goto out_put_mm;
1221 			}
1222 
1223 			/*
1224 			 * After dropping the lock, there are four cases to
1225 			 * consider. See the following example for explanation.
1226 			 *
1227 			 *   +------+------+-----------+
1228 			 *   | VMA1 | VMA2 | VMA3      |
1229 			 *   +------+------+-----------+
1230 			 *   |      |      |           |
1231 			 *  4k     8k     16k         400k
1232 			 *
1233 			 * Suppose we drop the lock after reading VMA2 due to
1234 			 * contention, then we get:
1235 			 *
1236 			 *	last_vma_end = 16k
1237 			 *
1238 			 * 1) VMA2 is freed, but VMA3 exists:
1239 			 *
1240 			 *    vma_next(vmi) will return VMA3.
1241 			 *    In this case, just continue from VMA3.
1242 			 *
1243 			 * 2) VMA2 still exists:
1244 			 *
1245 			 *    vma_next(vmi) will return VMA3.
1246 			 *    In this case, just continue from VMA3.
1247 			 *
1248 			 * 3) No more VMAs can be found:
1249 			 *
1250 			 *    vma_next(vmi) will return NULL.
1251 			 *    No more things to do, just break.
1252 			 *
1253 			 * 4) (last_vma_end - 1) is the middle of a vma (VMA'):
1254 			 *
1255 			 *    vma_next(vmi) will return VMA' whose range
1256 			 *    contains last_vma_end.
1257 			 *    Iterate VMA' from last_vma_end.
1258 			 */
1259 			vma = vma_next(&vmi);
1260 			/* Case 3 above */
1261 			if (!vma)
1262 				break;
1263 
1264 			/* Case 1 and 2 above */
1265 			if (vma->vm_start >= last_vma_end) {
1266 				smap_gather_stats(vma, &mss, 0);
1267 				last_vma_end = vma->vm_end;
1268 				continue;
1269 			}
1270 
1271 			/* Case 4 above */
1272 			if (vma->vm_end > last_vma_end) {
1273 				smap_gather_stats(vma, &mss, last_vma_end);
1274 				last_vma_end = vma->vm_end;
1275 			}
1276 		}
1277 	} for_each_vma(vmi, vma);
1278 
1279 empty_set:
1280 	show_vma_header_prefix(m, vma_start, last_vma_end, 0, 0, 0, 0);
1281 	seq_pad(m, ' ');
1282 	seq_puts(m, "[rollup]\n");
1283 
1284 	__show_smap(m, &mss, true);
1285 
1286 	release_task_mempolicy(priv);
1287 	mmap_read_unlock(mm);
1288 
1289 out_put_mm:
1290 	mmput(mm);
1291 out_put_task:
1292 	put_task_struct(priv->task);
1293 	priv->task = NULL;
1294 
1295 	return ret;
1296 }
1297 #undef SEQ_PUT_DEC
1298 
1299 static const struct seq_operations proc_pid_smaps_op = {
1300 	.start	= m_start,
1301 	.next	= m_next,
1302 	.stop	= m_stop,
1303 	.show	= show_smap
1304 };
1305 
1306 static int pid_smaps_open(struct inode *inode, struct file *file)
1307 {
1308 	return do_maps_open(inode, file, &proc_pid_smaps_op);
1309 }
1310 
1311 static int smaps_rollup_open(struct inode *inode, struct file *file)
1312 {
1313 	int ret;
1314 	struct proc_maps_private *priv;
1315 
1316 	priv = kzalloc(sizeof(*priv), GFP_KERNEL_ACCOUNT);
1317 	if (!priv)
1318 		return -ENOMEM;
1319 
1320 	ret = single_open(file, show_smaps_rollup, priv);
1321 	if (ret)
1322 		goto out_free;
1323 
1324 	priv->inode = inode;
1325 	priv->mm = proc_mem_open(inode, PTRACE_MODE_READ);
1326 	if (IS_ERR(priv->mm)) {
1327 		ret = PTR_ERR(priv->mm);
1328 
1329 		single_release(inode, file);
1330 		goto out_free;
1331 	}
1332 
1333 	return 0;
1334 
1335 out_free:
1336 	kfree(priv);
1337 	return ret;
1338 }
1339 
1340 static int smaps_rollup_release(struct inode *inode, struct file *file)
1341 {
1342 	struct seq_file *seq = file->private_data;
1343 	struct proc_maps_private *priv = seq->private;
1344 
1345 	if (priv->mm)
1346 		mmdrop(priv->mm);
1347 
1348 	kfree(priv);
1349 	return single_release(inode, file);
1350 }
1351 
1352 const struct file_operations proc_pid_smaps_operations = {
1353 	.open		= pid_smaps_open,
1354 	.read		= seq_read,
1355 	.llseek		= seq_lseek,
1356 	.release	= proc_map_release,
1357 };
1358 
1359 const struct file_operations proc_pid_smaps_rollup_operations = {
1360 	.open		= smaps_rollup_open,
1361 	.read		= seq_read,
1362 	.llseek		= seq_lseek,
1363 	.release	= smaps_rollup_release,
1364 };
1365 
1366 enum clear_refs_types {
1367 	CLEAR_REFS_ALL = 1,
1368 	CLEAR_REFS_ANON,
1369 	CLEAR_REFS_MAPPED,
1370 	CLEAR_REFS_SOFT_DIRTY,
1371 	CLEAR_REFS_MM_HIWATER_RSS,
1372 	CLEAR_REFS_LAST,
1373 };
1374 
1375 struct clear_refs_private {
1376 	enum clear_refs_types type;
1377 };
1378 
1379 #ifdef CONFIG_MEM_SOFT_DIRTY
1380 
1381 static inline bool pte_is_pinned(struct vm_area_struct *vma, unsigned long addr, pte_t pte)
1382 {
1383 	struct folio *folio;
1384 
1385 	if (!pte_write(pte))
1386 		return false;
1387 	if (!is_cow_mapping(vma->vm_flags))
1388 		return false;
1389 	if (likely(!test_bit(MMF_HAS_PINNED, &vma->vm_mm->flags)))
1390 		return false;
1391 	folio = vm_normal_folio(vma, addr, pte);
1392 	if (!folio)
1393 		return false;
1394 	return folio_maybe_dma_pinned(folio);
1395 }
1396 
1397 static inline void clear_soft_dirty(struct vm_area_struct *vma,
1398 		unsigned long addr, pte_t *pte)
1399 {
1400 	/*
1401 	 * The soft-dirty tracker uses #PF-s to catch writes
1402 	 * to pages, so write-protect the pte as well. See the
1403 	 * Documentation/admin-guide/mm/soft-dirty.rst for full description
1404 	 * of how soft-dirty works.
1405 	 */
1406 	pte_t ptent = ptep_get(pte);
1407 
1408 	if (pte_present(ptent)) {
1409 		pte_t old_pte;
1410 
1411 		if (pte_is_pinned(vma, addr, ptent))
1412 			return;
1413 		old_pte = ptep_modify_prot_start(vma, addr, pte);
1414 		ptent = pte_wrprotect(old_pte);
1415 		ptent = pte_clear_soft_dirty(ptent);
1416 		ptep_modify_prot_commit(vma, addr, pte, old_pte, ptent);
1417 	} else if (is_swap_pte(ptent)) {
1418 		ptent = pte_swp_clear_soft_dirty(ptent);
1419 		set_pte_at(vma->vm_mm, addr, pte, ptent);
1420 	}
1421 }
1422 #else
1423 static inline void clear_soft_dirty(struct vm_area_struct *vma,
1424 		unsigned long addr, pte_t *pte)
1425 {
1426 }
1427 #endif
1428 
1429 #if defined(CONFIG_MEM_SOFT_DIRTY) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
1430 static inline void clear_soft_dirty_pmd(struct vm_area_struct *vma,
1431 		unsigned long addr, pmd_t *pmdp)
1432 {
1433 	pmd_t old, pmd = *pmdp;
1434 
1435 	if (pmd_present(pmd)) {
1436 		/* See comment in change_huge_pmd() */
1437 		old = pmdp_invalidate(vma, addr, pmdp);
1438 		if (pmd_dirty(old))
1439 			pmd = pmd_mkdirty(pmd);
1440 		if (pmd_young(old))
1441 			pmd = pmd_mkyoung(pmd);
1442 
1443 		pmd = pmd_wrprotect(pmd);
1444 		pmd = pmd_clear_soft_dirty(pmd);
1445 
1446 		set_pmd_at(vma->vm_mm, addr, pmdp, pmd);
1447 	} else if (is_migration_entry(pmd_to_swp_entry(pmd))) {
1448 		pmd = pmd_swp_clear_soft_dirty(pmd);
1449 		set_pmd_at(vma->vm_mm, addr, pmdp, pmd);
1450 	}
1451 }
1452 #else
1453 static inline void clear_soft_dirty_pmd(struct vm_area_struct *vma,
1454 		unsigned long addr, pmd_t *pmdp)
1455 {
1456 }
1457 #endif
1458 
1459 static int clear_refs_pte_range(pmd_t *pmd, unsigned long addr,
1460 				unsigned long end, struct mm_walk *walk)
1461 {
1462 	struct clear_refs_private *cp = walk->private;
1463 	struct vm_area_struct *vma = walk->vma;
1464 	pte_t *pte, ptent;
1465 	spinlock_t *ptl;
1466 	struct folio *folio;
1467 
1468 	ptl = pmd_trans_huge_lock(pmd, vma);
1469 	if (ptl) {
1470 		if (cp->type == CLEAR_REFS_SOFT_DIRTY) {
1471 			clear_soft_dirty_pmd(vma, addr, pmd);
1472 			goto out;
1473 		}
1474 
1475 		if (!pmd_present(*pmd))
1476 			goto out;
1477 
1478 		folio = pmd_folio(*pmd);
1479 
1480 		/* Clear accessed and referenced bits. */
1481 		pmdp_test_and_clear_young(vma, addr, pmd);
1482 		folio_test_clear_young(folio);
1483 		folio_clear_referenced(folio);
1484 out:
1485 		spin_unlock(ptl);
1486 		return 0;
1487 	}
1488 
1489 	pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
1490 	if (!pte) {
1491 		walk->action = ACTION_AGAIN;
1492 		return 0;
1493 	}
1494 	for (; addr != end; pte++, addr += PAGE_SIZE) {
1495 		ptent = ptep_get(pte);
1496 
1497 		if (cp->type == CLEAR_REFS_SOFT_DIRTY) {
1498 			clear_soft_dirty(vma, addr, pte);
1499 			continue;
1500 		}
1501 
1502 		if (!pte_present(ptent))
1503 			continue;
1504 
1505 		folio = vm_normal_folio(vma, addr, ptent);
1506 		if (!folio)
1507 			continue;
1508 
1509 		/* Clear accessed and referenced bits. */
1510 		ptep_test_and_clear_young(vma, addr, pte);
1511 		folio_test_clear_young(folio);
1512 		folio_clear_referenced(folio);
1513 	}
1514 	pte_unmap_unlock(pte - 1, ptl);
1515 	cond_resched();
1516 	return 0;
1517 }
1518 
1519 static int clear_refs_test_walk(unsigned long start, unsigned long end,
1520 				struct mm_walk *walk)
1521 {
1522 	struct clear_refs_private *cp = walk->private;
1523 	struct vm_area_struct *vma = walk->vma;
1524 
1525 	if (vma->vm_flags & VM_PFNMAP)
1526 		return 1;
1527 
1528 	/*
1529 	 * Writing 1 to /proc/pid/clear_refs affects all pages.
1530 	 * Writing 2 to /proc/pid/clear_refs only affects anonymous pages.
1531 	 * Writing 3 to /proc/pid/clear_refs only affects file mapped pages.
1532 	 * Writing 4 to /proc/pid/clear_refs affects all pages.
1533 	 */
1534 	if (cp->type == CLEAR_REFS_ANON && vma->vm_file)
1535 		return 1;
1536 	if (cp->type == CLEAR_REFS_MAPPED && !vma->vm_file)
1537 		return 1;
1538 	return 0;
1539 }
1540 
1541 static const struct mm_walk_ops clear_refs_walk_ops = {
1542 	.pmd_entry		= clear_refs_pte_range,
1543 	.test_walk		= clear_refs_test_walk,
1544 	.walk_lock		= PGWALK_WRLOCK,
1545 };
1546 
1547 static ssize_t clear_refs_write(struct file *file, const char __user *buf,
1548 				size_t count, loff_t *ppos)
1549 {
1550 	struct task_struct *task;
1551 	char buffer[PROC_NUMBUF] = {};
1552 	struct mm_struct *mm;
1553 	struct vm_area_struct *vma;
1554 	enum clear_refs_types type;
1555 	int itype;
1556 	int rv;
1557 
1558 	if (count > sizeof(buffer) - 1)
1559 		count = sizeof(buffer) - 1;
1560 	if (copy_from_user(buffer, buf, count))
1561 		return -EFAULT;
1562 	rv = kstrtoint(strstrip(buffer), 10, &itype);
1563 	if (rv < 0)
1564 		return rv;
1565 	type = (enum clear_refs_types)itype;
1566 	if (type < CLEAR_REFS_ALL || type >= CLEAR_REFS_LAST)
1567 		return -EINVAL;
1568 
1569 	task = get_proc_task(file_inode(file));
1570 	if (!task)
1571 		return -ESRCH;
1572 	mm = get_task_mm(task);
1573 	if (mm) {
1574 		VMA_ITERATOR(vmi, mm, 0);
1575 		struct mmu_notifier_range range;
1576 		struct clear_refs_private cp = {
1577 			.type = type,
1578 		};
1579 
1580 		if (mmap_write_lock_killable(mm)) {
1581 			count = -EINTR;
1582 			goto out_mm;
1583 		}
1584 		if (type == CLEAR_REFS_MM_HIWATER_RSS) {
1585 			/*
1586 			 * Writing 5 to /proc/pid/clear_refs resets the peak
1587 			 * resident set size to this mm's current rss value.
1588 			 */
1589 			reset_mm_hiwater_rss(mm);
1590 			goto out_unlock;
1591 		}
1592 
1593 		if (type == CLEAR_REFS_SOFT_DIRTY) {
1594 			for_each_vma(vmi, vma) {
1595 				if (!(vma->vm_flags & VM_SOFTDIRTY))
1596 					continue;
1597 				vm_flags_clear(vma, VM_SOFTDIRTY);
1598 				vma_set_page_prot(vma);
1599 			}
1600 
1601 			inc_tlb_flush_pending(mm);
1602 			mmu_notifier_range_init(&range, MMU_NOTIFY_SOFT_DIRTY,
1603 						0, mm, 0, -1UL);
1604 			mmu_notifier_invalidate_range_start(&range);
1605 		}
1606 		walk_page_range(mm, 0, -1, &clear_refs_walk_ops, &cp);
1607 		if (type == CLEAR_REFS_SOFT_DIRTY) {
1608 			mmu_notifier_invalidate_range_end(&range);
1609 			flush_tlb_mm(mm);
1610 			dec_tlb_flush_pending(mm);
1611 		}
1612 out_unlock:
1613 		mmap_write_unlock(mm);
1614 out_mm:
1615 		mmput(mm);
1616 	}
1617 	put_task_struct(task);
1618 
1619 	return count;
1620 }
1621 
1622 const struct file_operations proc_clear_refs_operations = {
1623 	.write		= clear_refs_write,
1624 	.llseek		= noop_llseek,
1625 };
1626 
1627 typedef struct {
1628 	u64 pme;
1629 } pagemap_entry_t;
1630 
1631 struct pagemapread {
1632 	int pos, len;		/* units: PM_ENTRY_BYTES, not bytes */
1633 	pagemap_entry_t *buffer;
1634 	bool show_pfn;
1635 };
1636 
1637 #define PAGEMAP_WALK_SIZE	(PMD_SIZE)
1638 #define PAGEMAP_WALK_MASK	(PMD_MASK)
1639 
1640 #define PM_ENTRY_BYTES		sizeof(pagemap_entry_t)
1641 #define PM_PFRAME_BITS		55
1642 #define PM_PFRAME_MASK		GENMASK_ULL(PM_PFRAME_BITS - 1, 0)
1643 #define PM_SOFT_DIRTY		BIT_ULL(55)
1644 #define PM_MMAP_EXCLUSIVE	BIT_ULL(56)
1645 #define PM_UFFD_WP		BIT_ULL(57)
1646 #define PM_FILE			BIT_ULL(61)
1647 #define PM_SWAP			BIT_ULL(62)
1648 #define PM_PRESENT		BIT_ULL(63)
1649 
1650 #define PM_END_OF_BUFFER    1
1651 
1652 static inline pagemap_entry_t make_pme(u64 frame, u64 flags)
1653 {
1654 	return (pagemap_entry_t) { .pme = (frame & PM_PFRAME_MASK) | flags };
1655 }
1656 
1657 static int add_to_pagemap(pagemap_entry_t *pme, struct pagemapread *pm)
1658 {
1659 	pm->buffer[pm->pos++] = *pme;
1660 	if (pm->pos >= pm->len)
1661 		return PM_END_OF_BUFFER;
1662 	return 0;
1663 }
1664 
1665 static int pagemap_pte_hole(unsigned long start, unsigned long end,
1666 			    __always_unused int depth, struct mm_walk *walk)
1667 {
1668 	struct pagemapread *pm = walk->private;
1669 	unsigned long addr = start;
1670 	int err = 0;
1671 
1672 	while (addr < end) {
1673 		struct vm_area_struct *vma = find_vma(walk->mm, addr);
1674 		pagemap_entry_t pme = make_pme(0, 0);
1675 		/* End of address space hole, which we mark as non-present. */
1676 		unsigned long hole_end;
1677 
1678 		if (vma)
1679 			hole_end = min(end, vma->vm_start);
1680 		else
1681 			hole_end = end;
1682 
1683 		for (; addr < hole_end; addr += PAGE_SIZE) {
1684 			err = add_to_pagemap(&pme, pm);
1685 			if (err)
1686 				goto out;
1687 		}
1688 
1689 		if (!vma)
1690 			break;
1691 
1692 		/* Addresses in the VMA. */
1693 		if (vma->vm_flags & VM_SOFTDIRTY)
1694 			pme = make_pme(0, PM_SOFT_DIRTY);
1695 		for (; addr < min(end, vma->vm_end); addr += PAGE_SIZE) {
1696 			err = add_to_pagemap(&pme, pm);
1697 			if (err)
1698 				goto out;
1699 		}
1700 	}
1701 out:
1702 	return err;
1703 }
1704 
1705 static pagemap_entry_t pte_to_pagemap_entry(struct pagemapread *pm,
1706 		struct vm_area_struct *vma, unsigned long addr, pte_t pte)
1707 {
1708 	u64 frame = 0, flags = 0;
1709 	struct page *page = NULL;
1710 	struct folio *folio;
1711 
1712 	if (pte_present(pte)) {
1713 		if (pm->show_pfn)
1714 			frame = pte_pfn(pte);
1715 		flags |= PM_PRESENT;
1716 		page = vm_normal_page(vma, addr, pte);
1717 		if (pte_soft_dirty(pte))
1718 			flags |= PM_SOFT_DIRTY;
1719 		if (pte_uffd_wp(pte))
1720 			flags |= PM_UFFD_WP;
1721 	} else if (is_swap_pte(pte)) {
1722 		swp_entry_t entry;
1723 		if (pte_swp_soft_dirty(pte))
1724 			flags |= PM_SOFT_DIRTY;
1725 		if (pte_swp_uffd_wp(pte))
1726 			flags |= PM_UFFD_WP;
1727 		entry = pte_to_swp_entry(pte);
1728 		if (pm->show_pfn) {
1729 			pgoff_t offset;
1730 			/*
1731 			 * For PFN swap offsets, keeping the offset field
1732 			 * to be PFN only to be compatible with old smaps.
1733 			 */
1734 			if (is_pfn_swap_entry(entry))
1735 				offset = swp_offset_pfn(entry);
1736 			else
1737 				offset = swp_offset(entry);
1738 			frame = swp_type(entry) |
1739 			    (offset << MAX_SWAPFILES_SHIFT);
1740 		}
1741 		flags |= PM_SWAP;
1742 		if (is_pfn_swap_entry(entry))
1743 			page = pfn_swap_entry_to_page(entry);
1744 		if (pte_marker_entry_uffd_wp(entry))
1745 			flags |= PM_UFFD_WP;
1746 	}
1747 
1748 	if (page) {
1749 		folio = page_folio(page);
1750 		if (!folio_test_anon(folio))
1751 			flags |= PM_FILE;
1752 		if ((flags & PM_PRESENT) &&
1753 		    folio_precise_page_mapcount(folio, page) == 1)
1754 			flags |= PM_MMAP_EXCLUSIVE;
1755 	}
1756 	if (vma->vm_flags & VM_SOFTDIRTY)
1757 		flags |= PM_SOFT_DIRTY;
1758 
1759 	return make_pme(frame, flags);
1760 }
1761 
1762 static int pagemap_pmd_range(pmd_t *pmdp, unsigned long addr, unsigned long end,
1763 			     struct mm_walk *walk)
1764 {
1765 	struct vm_area_struct *vma = walk->vma;
1766 	struct pagemapread *pm = walk->private;
1767 	spinlock_t *ptl;
1768 	pte_t *pte, *orig_pte;
1769 	int err = 0;
1770 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1771 
1772 	ptl = pmd_trans_huge_lock(pmdp, vma);
1773 	if (ptl) {
1774 		unsigned int idx = (addr & ~PMD_MASK) >> PAGE_SHIFT;
1775 		u64 flags = 0, frame = 0;
1776 		pmd_t pmd = *pmdp;
1777 		struct page *page = NULL;
1778 		struct folio *folio = NULL;
1779 
1780 		if (vma->vm_flags & VM_SOFTDIRTY)
1781 			flags |= PM_SOFT_DIRTY;
1782 
1783 		if (pmd_present(pmd)) {
1784 			page = pmd_page(pmd);
1785 
1786 			flags |= PM_PRESENT;
1787 			if (pmd_soft_dirty(pmd))
1788 				flags |= PM_SOFT_DIRTY;
1789 			if (pmd_uffd_wp(pmd))
1790 				flags |= PM_UFFD_WP;
1791 			if (pm->show_pfn)
1792 				frame = pmd_pfn(pmd) + idx;
1793 		}
1794 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
1795 		else if (is_swap_pmd(pmd)) {
1796 			swp_entry_t entry = pmd_to_swp_entry(pmd);
1797 			unsigned long offset;
1798 
1799 			if (pm->show_pfn) {
1800 				if (is_pfn_swap_entry(entry))
1801 					offset = swp_offset_pfn(entry) + idx;
1802 				else
1803 					offset = swp_offset(entry) + idx;
1804 				frame = swp_type(entry) |
1805 					(offset << MAX_SWAPFILES_SHIFT);
1806 			}
1807 			flags |= PM_SWAP;
1808 			if (pmd_swp_soft_dirty(pmd))
1809 				flags |= PM_SOFT_DIRTY;
1810 			if (pmd_swp_uffd_wp(pmd))
1811 				flags |= PM_UFFD_WP;
1812 			VM_BUG_ON(!is_pmd_migration_entry(pmd));
1813 			page = pfn_swap_entry_to_page(entry);
1814 		}
1815 #endif
1816 
1817 		if (page) {
1818 			folio = page_folio(page);
1819 			if (!folio_test_anon(folio))
1820 				flags |= PM_FILE;
1821 		}
1822 
1823 		for (; addr != end; addr += PAGE_SIZE, idx++) {
1824 			unsigned long cur_flags = flags;
1825 			pagemap_entry_t pme;
1826 
1827 			if (folio && (flags & PM_PRESENT) &&
1828 			    folio_precise_page_mapcount(folio, page + idx) == 1)
1829 				cur_flags |= PM_MMAP_EXCLUSIVE;
1830 
1831 			pme = make_pme(frame, cur_flags);
1832 			err = add_to_pagemap(&pme, pm);
1833 			if (err)
1834 				break;
1835 			if (pm->show_pfn) {
1836 				if (flags & PM_PRESENT)
1837 					frame++;
1838 				else if (flags & PM_SWAP)
1839 					frame += (1 << MAX_SWAPFILES_SHIFT);
1840 			}
1841 		}
1842 		spin_unlock(ptl);
1843 		return err;
1844 	}
1845 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
1846 
1847 	/*
1848 	 * We can assume that @vma always points to a valid one and @end never
1849 	 * goes beyond vma->vm_end.
1850 	 */
1851 	orig_pte = pte = pte_offset_map_lock(walk->mm, pmdp, addr, &ptl);
1852 	if (!pte) {
1853 		walk->action = ACTION_AGAIN;
1854 		return err;
1855 	}
1856 	for (; addr < end; pte++, addr += PAGE_SIZE) {
1857 		pagemap_entry_t pme;
1858 
1859 		pme = pte_to_pagemap_entry(pm, vma, addr, ptep_get(pte));
1860 		err = add_to_pagemap(&pme, pm);
1861 		if (err)
1862 			break;
1863 	}
1864 	pte_unmap_unlock(orig_pte, ptl);
1865 
1866 	cond_resched();
1867 
1868 	return err;
1869 }
1870 
1871 #ifdef CONFIG_HUGETLB_PAGE
1872 /* This function walks within one hugetlb entry in the single call */
1873 static int pagemap_hugetlb_range(pte_t *ptep, unsigned long hmask,
1874 				 unsigned long addr, unsigned long end,
1875 				 struct mm_walk *walk)
1876 {
1877 	struct pagemapread *pm = walk->private;
1878 	struct vm_area_struct *vma = walk->vma;
1879 	u64 flags = 0, frame = 0;
1880 	int err = 0;
1881 	pte_t pte;
1882 
1883 	if (vma->vm_flags & VM_SOFTDIRTY)
1884 		flags |= PM_SOFT_DIRTY;
1885 
1886 	pte = huge_ptep_get(walk->mm, addr, ptep);
1887 	if (pte_present(pte)) {
1888 		struct folio *folio = page_folio(pte_page(pte));
1889 
1890 		if (!folio_test_anon(folio))
1891 			flags |= PM_FILE;
1892 
1893 		if (!folio_likely_mapped_shared(folio) &&
1894 		    !hugetlb_pmd_shared(ptep))
1895 			flags |= PM_MMAP_EXCLUSIVE;
1896 
1897 		if (huge_pte_uffd_wp(pte))
1898 			flags |= PM_UFFD_WP;
1899 
1900 		flags |= PM_PRESENT;
1901 		if (pm->show_pfn)
1902 			frame = pte_pfn(pte) +
1903 				((addr & ~hmask) >> PAGE_SHIFT);
1904 	} else if (pte_swp_uffd_wp_any(pte)) {
1905 		flags |= PM_UFFD_WP;
1906 	}
1907 
1908 	for (; addr != end; addr += PAGE_SIZE) {
1909 		pagemap_entry_t pme = make_pme(frame, flags);
1910 
1911 		err = add_to_pagemap(&pme, pm);
1912 		if (err)
1913 			return err;
1914 		if (pm->show_pfn && (flags & PM_PRESENT))
1915 			frame++;
1916 	}
1917 
1918 	cond_resched();
1919 
1920 	return err;
1921 }
1922 #else
1923 #define pagemap_hugetlb_range	NULL
1924 #endif /* HUGETLB_PAGE */
1925 
1926 static const struct mm_walk_ops pagemap_ops = {
1927 	.pmd_entry	= pagemap_pmd_range,
1928 	.pte_hole	= pagemap_pte_hole,
1929 	.hugetlb_entry	= pagemap_hugetlb_range,
1930 	.walk_lock	= PGWALK_RDLOCK,
1931 };
1932 
1933 /*
1934  * /proc/pid/pagemap - an array mapping virtual pages to pfns
1935  *
1936  * For each page in the address space, this file contains one 64-bit entry
1937  * consisting of the following:
1938  *
1939  * Bits 0-54  page frame number (PFN) if present
1940  * Bits 0-4   swap type if swapped
1941  * Bits 5-54  swap offset if swapped
1942  * Bit  55    pte is soft-dirty (see Documentation/admin-guide/mm/soft-dirty.rst)
1943  * Bit  56    page exclusively mapped
1944  * Bit  57    pte is uffd-wp write-protected
1945  * Bits 58-60 zero
1946  * Bit  61    page is file-page or shared-anon
1947  * Bit  62    page swapped
1948  * Bit  63    page present
1949  *
1950  * If the page is not present but in swap, then the PFN contains an
1951  * encoding of the swap file number and the page's offset into the
1952  * swap. Unmapped pages return a null PFN. This allows determining
1953  * precisely which pages are mapped (or in swap) and comparing mapped
1954  * pages between processes.
1955  *
1956  * Efficient users of this interface will use /proc/pid/maps to
1957  * determine which areas of memory are actually mapped and llseek to
1958  * skip over unmapped regions.
1959  */
1960 static ssize_t pagemap_read(struct file *file, char __user *buf,
1961 			    size_t count, loff_t *ppos)
1962 {
1963 	struct mm_struct *mm = file->private_data;
1964 	struct pagemapread pm;
1965 	unsigned long src;
1966 	unsigned long svpfn;
1967 	unsigned long start_vaddr;
1968 	unsigned long end_vaddr;
1969 	int ret = 0, copied = 0;
1970 
1971 	if (!mm || !mmget_not_zero(mm))
1972 		goto out;
1973 
1974 	ret = -EINVAL;
1975 	/* file position must be aligned */
1976 	if ((*ppos % PM_ENTRY_BYTES) || (count % PM_ENTRY_BYTES))
1977 		goto out_mm;
1978 
1979 	ret = 0;
1980 	if (!count)
1981 		goto out_mm;
1982 
1983 	/* do not disclose physical addresses: attack vector */
1984 	pm.show_pfn = file_ns_capable(file, &init_user_ns, CAP_SYS_ADMIN);
1985 
1986 	pm.len = (PAGEMAP_WALK_SIZE >> PAGE_SHIFT);
1987 	pm.buffer = kmalloc_array(pm.len, PM_ENTRY_BYTES, GFP_KERNEL);
1988 	ret = -ENOMEM;
1989 	if (!pm.buffer)
1990 		goto out_mm;
1991 
1992 	src = *ppos;
1993 	svpfn = src / PM_ENTRY_BYTES;
1994 	end_vaddr = mm->task_size;
1995 
1996 	/* watch out for wraparound */
1997 	start_vaddr = end_vaddr;
1998 	if (svpfn <= (ULONG_MAX >> PAGE_SHIFT)) {
1999 		unsigned long end;
2000 
2001 		ret = mmap_read_lock_killable(mm);
2002 		if (ret)
2003 			goto out_free;
2004 		start_vaddr = untagged_addr_remote(mm, svpfn << PAGE_SHIFT);
2005 		mmap_read_unlock(mm);
2006 
2007 		end = start_vaddr + ((count / PM_ENTRY_BYTES) << PAGE_SHIFT);
2008 		if (end >= start_vaddr && end < mm->task_size)
2009 			end_vaddr = end;
2010 	}
2011 
2012 	/* Ensure the address is inside the task */
2013 	if (start_vaddr > mm->task_size)
2014 		start_vaddr = end_vaddr;
2015 
2016 	ret = 0;
2017 	while (count && (start_vaddr < end_vaddr)) {
2018 		int len;
2019 		unsigned long end;
2020 
2021 		pm.pos = 0;
2022 		end = (start_vaddr + PAGEMAP_WALK_SIZE) & PAGEMAP_WALK_MASK;
2023 		/* overflow ? */
2024 		if (end < start_vaddr || end > end_vaddr)
2025 			end = end_vaddr;
2026 		ret = mmap_read_lock_killable(mm);
2027 		if (ret)
2028 			goto out_free;
2029 		ret = walk_page_range(mm, start_vaddr, end, &pagemap_ops, &pm);
2030 		mmap_read_unlock(mm);
2031 		start_vaddr = end;
2032 
2033 		len = min(count, PM_ENTRY_BYTES * pm.pos);
2034 		if (copy_to_user(buf, pm.buffer, len)) {
2035 			ret = -EFAULT;
2036 			goto out_free;
2037 		}
2038 		copied += len;
2039 		buf += len;
2040 		count -= len;
2041 	}
2042 	*ppos += copied;
2043 	if (!ret || ret == PM_END_OF_BUFFER)
2044 		ret = copied;
2045 
2046 out_free:
2047 	kfree(pm.buffer);
2048 out_mm:
2049 	mmput(mm);
2050 out:
2051 	return ret;
2052 }
2053 
2054 static int pagemap_open(struct inode *inode, struct file *file)
2055 {
2056 	struct mm_struct *mm;
2057 
2058 	mm = proc_mem_open(inode, PTRACE_MODE_READ);
2059 	if (IS_ERR(mm))
2060 		return PTR_ERR(mm);
2061 	file->private_data = mm;
2062 	return 0;
2063 }
2064 
2065 static int pagemap_release(struct inode *inode, struct file *file)
2066 {
2067 	struct mm_struct *mm = file->private_data;
2068 
2069 	if (mm)
2070 		mmdrop(mm);
2071 	return 0;
2072 }
2073 
2074 #define PM_SCAN_CATEGORIES	(PAGE_IS_WPALLOWED | PAGE_IS_WRITTEN |	\
2075 				 PAGE_IS_FILE |	PAGE_IS_PRESENT |	\
2076 				 PAGE_IS_SWAPPED | PAGE_IS_PFNZERO |	\
2077 				 PAGE_IS_HUGE | PAGE_IS_SOFT_DIRTY)
2078 #define PM_SCAN_FLAGS		(PM_SCAN_WP_MATCHING | PM_SCAN_CHECK_WPASYNC)
2079 
2080 struct pagemap_scan_private {
2081 	struct pm_scan_arg arg;
2082 	unsigned long masks_of_interest, cur_vma_category;
2083 	struct page_region *vec_buf;
2084 	unsigned long vec_buf_len, vec_buf_index, found_pages;
2085 	struct page_region __user *vec_out;
2086 };
2087 
2088 static unsigned long pagemap_page_category(struct pagemap_scan_private *p,
2089 					   struct vm_area_struct *vma,
2090 					   unsigned long addr, pte_t pte)
2091 {
2092 	unsigned long categories = 0;
2093 
2094 	if (pte_present(pte)) {
2095 		struct page *page;
2096 
2097 		categories |= PAGE_IS_PRESENT;
2098 		if (!pte_uffd_wp(pte))
2099 			categories |= PAGE_IS_WRITTEN;
2100 
2101 		if (p->masks_of_interest & PAGE_IS_FILE) {
2102 			page = vm_normal_page(vma, addr, pte);
2103 			if (page && !PageAnon(page))
2104 				categories |= PAGE_IS_FILE;
2105 		}
2106 
2107 		if (is_zero_pfn(pte_pfn(pte)))
2108 			categories |= PAGE_IS_PFNZERO;
2109 		if (pte_soft_dirty(pte))
2110 			categories |= PAGE_IS_SOFT_DIRTY;
2111 	} else if (is_swap_pte(pte)) {
2112 		swp_entry_t swp;
2113 
2114 		categories |= PAGE_IS_SWAPPED;
2115 		if (!pte_swp_uffd_wp_any(pte))
2116 			categories |= PAGE_IS_WRITTEN;
2117 
2118 		if (p->masks_of_interest & PAGE_IS_FILE) {
2119 			swp = pte_to_swp_entry(pte);
2120 			if (is_pfn_swap_entry(swp) &&
2121 			    !folio_test_anon(pfn_swap_entry_folio(swp)))
2122 				categories |= PAGE_IS_FILE;
2123 		}
2124 		if (pte_swp_soft_dirty(pte))
2125 			categories |= PAGE_IS_SOFT_DIRTY;
2126 	}
2127 
2128 	return categories;
2129 }
2130 
2131 static void make_uffd_wp_pte(struct vm_area_struct *vma,
2132 			     unsigned long addr, pte_t *pte, pte_t ptent)
2133 {
2134 	if (pte_present(ptent)) {
2135 		pte_t old_pte;
2136 
2137 		old_pte = ptep_modify_prot_start(vma, addr, pte);
2138 		ptent = pte_mkuffd_wp(old_pte);
2139 		ptep_modify_prot_commit(vma, addr, pte, old_pte, ptent);
2140 	} else if (is_swap_pte(ptent)) {
2141 		ptent = pte_swp_mkuffd_wp(ptent);
2142 		set_pte_at(vma->vm_mm, addr, pte, ptent);
2143 	} else {
2144 		set_pte_at(vma->vm_mm, addr, pte,
2145 			   make_pte_marker(PTE_MARKER_UFFD_WP));
2146 	}
2147 }
2148 
2149 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2150 static unsigned long pagemap_thp_category(struct pagemap_scan_private *p,
2151 					  struct vm_area_struct *vma,
2152 					  unsigned long addr, pmd_t pmd)
2153 {
2154 	unsigned long categories = PAGE_IS_HUGE;
2155 
2156 	if (pmd_present(pmd)) {
2157 		struct page *page;
2158 
2159 		categories |= PAGE_IS_PRESENT;
2160 		if (!pmd_uffd_wp(pmd))
2161 			categories |= PAGE_IS_WRITTEN;
2162 
2163 		if (p->masks_of_interest & PAGE_IS_FILE) {
2164 			page = vm_normal_page_pmd(vma, addr, pmd);
2165 			if (page && !PageAnon(page))
2166 				categories |= PAGE_IS_FILE;
2167 		}
2168 
2169 		if (is_zero_pfn(pmd_pfn(pmd)))
2170 			categories |= PAGE_IS_PFNZERO;
2171 		if (pmd_soft_dirty(pmd))
2172 			categories |= PAGE_IS_SOFT_DIRTY;
2173 	} else if (is_swap_pmd(pmd)) {
2174 		swp_entry_t swp;
2175 
2176 		categories |= PAGE_IS_SWAPPED;
2177 		if (!pmd_swp_uffd_wp(pmd))
2178 			categories |= PAGE_IS_WRITTEN;
2179 		if (pmd_swp_soft_dirty(pmd))
2180 			categories |= PAGE_IS_SOFT_DIRTY;
2181 
2182 		if (p->masks_of_interest & PAGE_IS_FILE) {
2183 			swp = pmd_to_swp_entry(pmd);
2184 			if (is_pfn_swap_entry(swp) &&
2185 			    !folio_test_anon(pfn_swap_entry_folio(swp)))
2186 				categories |= PAGE_IS_FILE;
2187 		}
2188 	}
2189 
2190 	return categories;
2191 }
2192 
2193 static void make_uffd_wp_pmd(struct vm_area_struct *vma,
2194 			     unsigned long addr, pmd_t *pmdp)
2195 {
2196 	pmd_t old, pmd = *pmdp;
2197 
2198 	if (pmd_present(pmd)) {
2199 		old = pmdp_invalidate_ad(vma, addr, pmdp);
2200 		pmd = pmd_mkuffd_wp(old);
2201 		set_pmd_at(vma->vm_mm, addr, pmdp, pmd);
2202 	} else if (is_migration_entry(pmd_to_swp_entry(pmd))) {
2203 		pmd = pmd_swp_mkuffd_wp(pmd);
2204 		set_pmd_at(vma->vm_mm, addr, pmdp, pmd);
2205 	}
2206 }
2207 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
2208 
2209 #ifdef CONFIG_HUGETLB_PAGE
2210 static unsigned long pagemap_hugetlb_category(pte_t pte)
2211 {
2212 	unsigned long categories = PAGE_IS_HUGE;
2213 
2214 	/*
2215 	 * According to pagemap_hugetlb_range(), file-backed HugeTLB
2216 	 * page cannot be swapped. So PAGE_IS_FILE is not checked for
2217 	 * swapped pages.
2218 	 */
2219 	if (pte_present(pte)) {
2220 		categories |= PAGE_IS_PRESENT;
2221 		if (!huge_pte_uffd_wp(pte))
2222 			categories |= PAGE_IS_WRITTEN;
2223 		if (!PageAnon(pte_page(pte)))
2224 			categories |= PAGE_IS_FILE;
2225 		if (is_zero_pfn(pte_pfn(pte)))
2226 			categories |= PAGE_IS_PFNZERO;
2227 		if (pte_soft_dirty(pte))
2228 			categories |= PAGE_IS_SOFT_DIRTY;
2229 	} else if (is_swap_pte(pte)) {
2230 		categories |= PAGE_IS_SWAPPED;
2231 		if (!pte_swp_uffd_wp_any(pte))
2232 			categories |= PAGE_IS_WRITTEN;
2233 		if (pte_swp_soft_dirty(pte))
2234 			categories |= PAGE_IS_SOFT_DIRTY;
2235 	}
2236 
2237 	return categories;
2238 }
2239 
2240 static void make_uffd_wp_huge_pte(struct vm_area_struct *vma,
2241 				  unsigned long addr, pte_t *ptep,
2242 				  pte_t ptent)
2243 {
2244 	unsigned long psize;
2245 
2246 	if (is_hugetlb_entry_hwpoisoned(ptent) || is_pte_marker(ptent))
2247 		return;
2248 
2249 	psize = huge_page_size(hstate_vma(vma));
2250 
2251 	if (is_hugetlb_entry_migration(ptent))
2252 		set_huge_pte_at(vma->vm_mm, addr, ptep,
2253 				pte_swp_mkuffd_wp(ptent), psize);
2254 	else if (!huge_pte_none(ptent))
2255 		huge_ptep_modify_prot_commit(vma, addr, ptep, ptent,
2256 					     huge_pte_mkuffd_wp(ptent));
2257 	else
2258 		set_huge_pte_at(vma->vm_mm, addr, ptep,
2259 				make_pte_marker(PTE_MARKER_UFFD_WP), psize);
2260 }
2261 #endif /* CONFIG_HUGETLB_PAGE */
2262 
2263 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLB_PAGE)
2264 static void pagemap_scan_backout_range(struct pagemap_scan_private *p,
2265 				       unsigned long addr, unsigned long end)
2266 {
2267 	struct page_region *cur_buf = &p->vec_buf[p->vec_buf_index];
2268 
2269 	if (cur_buf->start != addr)
2270 		cur_buf->end = addr;
2271 	else
2272 		cur_buf->start = cur_buf->end = 0;
2273 
2274 	p->found_pages -= (end - addr) / PAGE_SIZE;
2275 }
2276 #endif
2277 
2278 static bool pagemap_scan_is_interesting_page(unsigned long categories,
2279 					     const struct pagemap_scan_private *p)
2280 {
2281 	categories ^= p->arg.category_inverted;
2282 	if ((categories & p->arg.category_mask) != p->arg.category_mask)
2283 		return false;
2284 	if (p->arg.category_anyof_mask && !(categories & p->arg.category_anyof_mask))
2285 		return false;
2286 
2287 	return true;
2288 }
2289 
2290 static bool pagemap_scan_is_interesting_vma(unsigned long categories,
2291 					    const struct pagemap_scan_private *p)
2292 {
2293 	unsigned long required = p->arg.category_mask & PAGE_IS_WPALLOWED;
2294 
2295 	categories ^= p->arg.category_inverted;
2296 	if ((categories & required) != required)
2297 		return false;
2298 
2299 	return true;
2300 }
2301 
2302 static int pagemap_scan_test_walk(unsigned long start, unsigned long end,
2303 				  struct mm_walk *walk)
2304 {
2305 	struct pagemap_scan_private *p = walk->private;
2306 	struct vm_area_struct *vma = walk->vma;
2307 	unsigned long vma_category = 0;
2308 	bool wp_allowed = userfaultfd_wp_async(vma) &&
2309 	    userfaultfd_wp_use_markers(vma);
2310 
2311 	if (!wp_allowed) {
2312 		/* User requested explicit failure over wp-async capability */
2313 		if (p->arg.flags & PM_SCAN_CHECK_WPASYNC)
2314 			return -EPERM;
2315 		/*
2316 		 * User requires wr-protect, and allows silently skipping
2317 		 * unsupported vmas.
2318 		 */
2319 		if (p->arg.flags & PM_SCAN_WP_MATCHING)
2320 			return 1;
2321 		/*
2322 		 * Then the request doesn't involve wr-protects at all,
2323 		 * fall through to the rest checks, and allow vma walk.
2324 		 */
2325 	}
2326 
2327 	if (vma->vm_flags & VM_PFNMAP)
2328 		return 1;
2329 
2330 	if (wp_allowed)
2331 		vma_category |= PAGE_IS_WPALLOWED;
2332 
2333 	if (vma->vm_flags & VM_SOFTDIRTY)
2334 		vma_category |= PAGE_IS_SOFT_DIRTY;
2335 
2336 	if (!pagemap_scan_is_interesting_vma(vma_category, p))
2337 		return 1;
2338 
2339 	p->cur_vma_category = vma_category;
2340 
2341 	return 0;
2342 }
2343 
2344 static bool pagemap_scan_push_range(unsigned long categories,
2345 				    struct pagemap_scan_private *p,
2346 				    unsigned long addr, unsigned long end)
2347 {
2348 	struct page_region *cur_buf = &p->vec_buf[p->vec_buf_index];
2349 
2350 	/*
2351 	 * When there is no output buffer provided at all, the sentinel values
2352 	 * won't match here. There is no other way for `cur_buf->end` to be
2353 	 * non-zero other than it being non-empty.
2354 	 */
2355 	if (addr == cur_buf->end && categories == cur_buf->categories) {
2356 		cur_buf->end = end;
2357 		return true;
2358 	}
2359 
2360 	if (cur_buf->end) {
2361 		if (p->vec_buf_index >= p->vec_buf_len - 1)
2362 			return false;
2363 
2364 		cur_buf = &p->vec_buf[++p->vec_buf_index];
2365 	}
2366 
2367 	cur_buf->start = addr;
2368 	cur_buf->end = end;
2369 	cur_buf->categories = categories;
2370 
2371 	return true;
2372 }
2373 
2374 static int pagemap_scan_output(unsigned long categories,
2375 			       struct pagemap_scan_private *p,
2376 			       unsigned long addr, unsigned long *end)
2377 {
2378 	unsigned long n_pages, total_pages;
2379 	int ret = 0;
2380 
2381 	if (!p->vec_buf)
2382 		return 0;
2383 
2384 	categories &= p->arg.return_mask;
2385 
2386 	n_pages = (*end - addr) / PAGE_SIZE;
2387 	if (check_add_overflow(p->found_pages, n_pages, &total_pages) ||
2388 	    total_pages > p->arg.max_pages) {
2389 		size_t n_too_much = total_pages - p->arg.max_pages;
2390 		*end -= n_too_much * PAGE_SIZE;
2391 		n_pages -= n_too_much;
2392 		ret = -ENOSPC;
2393 	}
2394 
2395 	if (!pagemap_scan_push_range(categories, p, addr, *end)) {
2396 		*end = addr;
2397 		n_pages = 0;
2398 		ret = -ENOSPC;
2399 	}
2400 
2401 	p->found_pages += n_pages;
2402 	if (ret)
2403 		p->arg.walk_end = *end;
2404 
2405 	return ret;
2406 }
2407 
2408 static int pagemap_scan_thp_entry(pmd_t *pmd, unsigned long start,
2409 				  unsigned long end, struct mm_walk *walk)
2410 {
2411 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2412 	struct pagemap_scan_private *p = walk->private;
2413 	struct vm_area_struct *vma = walk->vma;
2414 	unsigned long categories;
2415 	spinlock_t *ptl;
2416 	int ret = 0;
2417 
2418 	ptl = pmd_trans_huge_lock(pmd, vma);
2419 	if (!ptl)
2420 		return -ENOENT;
2421 
2422 	categories = p->cur_vma_category |
2423 		     pagemap_thp_category(p, vma, start, *pmd);
2424 
2425 	if (!pagemap_scan_is_interesting_page(categories, p))
2426 		goto out_unlock;
2427 
2428 	ret = pagemap_scan_output(categories, p, start, &end);
2429 	if (start == end)
2430 		goto out_unlock;
2431 
2432 	if (~p->arg.flags & PM_SCAN_WP_MATCHING)
2433 		goto out_unlock;
2434 	if (~categories & PAGE_IS_WRITTEN)
2435 		goto out_unlock;
2436 
2437 	/*
2438 	 * Break huge page into small pages if the WP operation
2439 	 * needs to be performed on a portion of the huge page.
2440 	 */
2441 	if (end != start + HPAGE_SIZE) {
2442 		spin_unlock(ptl);
2443 		split_huge_pmd(vma, pmd, start);
2444 		pagemap_scan_backout_range(p, start, end);
2445 		/* Report as if there was no THP */
2446 		return -ENOENT;
2447 	}
2448 
2449 	make_uffd_wp_pmd(vma, start, pmd);
2450 	flush_tlb_range(vma, start, end);
2451 out_unlock:
2452 	spin_unlock(ptl);
2453 	return ret;
2454 #else /* !CONFIG_TRANSPARENT_HUGEPAGE */
2455 	return -ENOENT;
2456 #endif
2457 }
2458 
2459 static int pagemap_scan_pmd_entry(pmd_t *pmd, unsigned long start,
2460 				  unsigned long end, struct mm_walk *walk)
2461 {
2462 	struct pagemap_scan_private *p = walk->private;
2463 	struct vm_area_struct *vma = walk->vma;
2464 	unsigned long addr, flush_end = 0;
2465 	pte_t *pte, *start_pte;
2466 	spinlock_t *ptl;
2467 	int ret;
2468 
2469 	arch_enter_lazy_mmu_mode();
2470 
2471 	ret = pagemap_scan_thp_entry(pmd, start, end, walk);
2472 	if (ret != -ENOENT) {
2473 		arch_leave_lazy_mmu_mode();
2474 		return ret;
2475 	}
2476 
2477 	ret = 0;
2478 	start_pte = pte = pte_offset_map_lock(vma->vm_mm, pmd, start, &ptl);
2479 	if (!pte) {
2480 		arch_leave_lazy_mmu_mode();
2481 		walk->action = ACTION_AGAIN;
2482 		return 0;
2483 	}
2484 
2485 	if ((p->arg.flags & PM_SCAN_WP_MATCHING) && !p->vec_out) {
2486 		/* Fast path for performing exclusive WP */
2487 		for (addr = start; addr != end; pte++, addr += PAGE_SIZE) {
2488 			pte_t ptent = ptep_get(pte);
2489 
2490 			if ((pte_present(ptent) && pte_uffd_wp(ptent)) ||
2491 			    pte_swp_uffd_wp_any(ptent))
2492 				continue;
2493 			make_uffd_wp_pte(vma, addr, pte, ptent);
2494 			if (!flush_end)
2495 				start = addr;
2496 			flush_end = addr + PAGE_SIZE;
2497 		}
2498 		goto flush_and_return;
2499 	}
2500 
2501 	if (!p->arg.category_anyof_mask && !p->arg.category_inverted &&
2502 	    p->arg.category_mask == PAGE_IS_WRITTEN &&
2503 	    p->arg.return_mask == PAGE_IS_WRITTEN) {
2504 		for (addr = start; addr < end; pte++, addr += PAGE_SIZE) {
2505 			unsigned long next = addr + PAGE_SIZE;
2506 			pte_t ptent = ptep_get(pte);
2507 
2508 			if ((pte_present(ptent) && pte_uffd_wp(ptent)) ||
2509 			    pte_swp_uffd_wp_any(ptent))
2510 				continue;
2511 			ret = pagemap_scan_output(p->cur_vma_category | PAGE_IS_WRITTEN,
2512 						  p, addr, &next);
2513 			if (next == addr)
2514 				break;
2515 			if (~p->arg.flags & PM_SCAN_WP_MATCHING)
2516 				continue;
2517 			make_uffd_wp_pte(vma, addr, pte, ptent);
2518 			if (!flush_end)
2519 				start = addr;
2520 			flush_end = next;
2521 		}
2522 		goto flush_and_return;
2523 	}
2524 
2525 	for (addr = start; addr != end; pte++, addr += PAGE_SIZE) {
2526 		pte_t ptent = ptep_get(pte);
2527 		unsigned long categories = p->cur_vma_category |
2528 					   pagemap_page_category(p, vma, addr, ptent);
2529 		unsigned long next = addr + PAGE_SIZE;
2530 
2531 		if (!pagemap_scan_is_interesting_page(categories, p))
2532 			continue;
2533 
2534 		ret = pagemap_scan_output(categories, p, addr, &next);
2535 		if (next == addr)
2536 			break;
2537 
2538 		if (~p->arg.flags & PM_SCAN_WP_MATCHING)
2539 			continue;
2540 		if (~categories & PAGE_IS_WRITTEN)
2541 			continue;
2542 
2543 		make_uffd_wp_pte(vma, addr, pte, ptent);
2544 		if (!flush_end)
2545 			start = addr;
2546 		flush_end = next;
2547 	}
2548 
2549 flush_and_return:
2550 	if (flush_end)
2551 		flush_tlb_range(vma, start, addr);
2552 
2553 	pte_unmap_unlock(start_pte, ptl);
2554 	arch_leave_lazy_mmu_mode();
2555 
2556 	cond_resched();
2557 	return ret;
2558 }
2559 
2560 #ifdef CONFIG_HUGETLB_PAGE
2561 static int pagemap_scan_hugetlb_entry(pte_t *ptep, unsigned long hmask,
2562 				      unsigned long start, unsigned long end,
2563 				      struct mm_walk *walk)
2564 {
2565 	struct pagemap_scan_private *p = walk->private;
2566 	struct vm_area_struct *vma = walk->vma;
2567 	unsigned long categories;
2568 	spinlock_t *ptl;
2569 	int ret = 0;
2570 	pte_t pte;
2571 
2572 	if (~p->arg.flags & PM_SCAN_WP_MATCHING) {
2573 		/* Go the short route when not write-protecting pages. */
2574 
2575 		pte = huge_ptep_get(walk->mm, start, ptep);
2576 		categories = p->cur_vma_category | pagemap_hugetlb_category(pte);
2577 
2578 		if (!pagemap_scan_is_interesting_page(categories, p))
2579 			return 0;
2580 
2581 		return pagemap_scan_output(categories, p, start, &end);
2582 	}
2583 
2584 	i_mmap_lock_write(vma->vm_file->f_mapping);
2585 	ptl = huge_pte_lock(hstate_vma(vma), vma->vm_mm, ptep);
2586 
2587 	pte = huge_ptep_get(walk->mm, start, ptep);
2588 	categories = p->cur_vma_category | pagemap_hugetlb_category(pte);
2589 
2590 	if (!pagemap_scan_is_interesting_page(categories, p))
2591 		goto out_unlock;
2592 
2593 	ret = pagemap_scan_output(categories, p, start, &end);
2594 	if (start == end)
2595 		goto out_unlock;
2596 
2597 	if (~categories & PAGE_IS_WRITTEN)
2598 		goto out_unlock;
2599 
2600 	if (end != start + HPAGE_SIZE) {
2601 		/* Partial HugeTLB page WP isn't possible. */
2602 		pagemap_scan_backout_range(p, start, end);
2603 		p->arg.walk_end = start;
2604 		ret = 0;
2605 		goto out_unlock;
2606 	}
2607 
2608 	make_uffd_wp_huge_pte(vma, start, ptep, pte);
2609 	flush_hugetlb_tlb_range(vma, start, end);
2610 
2611 out_unlock:
2612 	spin_unlock(ptl);
2613 	i_mmap_unlock_write(vma->vm_file->f_mapping);
2614 
2615 	return ret;
2616 }
2617 #else
2618 #define pagemap_scan_hugetlb_entry NULL
2619 #endif
2620 
2621 static int pagemap_scan_pte_hole(unsigned long addr, unsigned long end,
2622 				 int depth, struct mm_walk *walk)
2623 {
2624 	struct pagemap_scan_private *p = walk->private;
2625 	struct vm_area_struct *vma = walk->vma;
2626 	int ret, err;
2627 
2628 	if (!vma || !pagemap_scan_is_interesting_page(p->cur_vma_category, p))
2629 		return 0;
2630 
2631 	ret = pagemap_scan_output(p->cur_vma_category, p, addr, &end);
2632 	if (addr == end)
2633 		return ret;
2634 
2635 	if (~p->arg.flags & PM_SCAN_WP_MATCHING)
2636 		return ret;
2637 
2638 	err = uffd_wp_range(vma, addr, end - addr, true);
2639 	if (err < 0)
2640 		ret = err;
2641 
2642 	return ret;
2643 }
2644 
2645 static const struct mm_walk_ops pagemap_scan_ops = {
2646 	.test_walk = pagemap_scan_test_walk,
2647 	.pmd_entry = pagemap_scan_pmd_entry,
2648 	.pte_hole = pagemap_scan_pte_hole,
2649 	.hugetlb_entry = pagemap_scan_hugetlb_entry,
2650 };
2651 
2652 static int pagemap_scan_get_args(struct pm_scan_arg *arg,
2653 				 unsigned long uarg)
2654 {
2655 	if (copy_from_user(arg, (void __user *)uarg, sizeof(*arg)))
2656 		return -EFAULT;
2657 
2658 	if (arg->size != sizeof(struct pm_scan_arg))
2659 		return -EINVAL;
2660 
2661 	/* Validate requested features */
2662 	if (arg->flags & ~PM_SCAN_FLAGS)
2663 		return -EINVAL;
2664 	if ((arg->category_inverted | arg->category_mask |
2665 	     arg->category_anyof_mask | arg->return_mask) & ~PM_SCAN_CATEGORIES)
2666 		return -EINVAL;
2667 
2668 	arg->start = untagged_addr((unsigned long)arg->start);
2669 	arg->end = untagged_addr((unsigned long)arg->end);
2670 	arg->vec = untagged_addr((unsigned long)arg->vec);
2671 
2672 	/* Validate memory pointers */
2673 	if (!IS_ALIGNED(arg->start, PAGE_SIZE))
2674 		return -EINVAL;
2675 	if (!access_ok((void __user *)(long)arg->start, arg->end - arg->start))
2676 		return -EFAULT;
2677 	if (!arg->vec && arg->vec_len)
2678 		return -EINVAL;
2679 	if (arg->vec && !access_ok((void __user *)(long)arg->vec,
2680 			      arg->vec_len * sizeof(struct page_region)))
2681 		return -EFAULT;
2682 
2683 	/* Fixup default values */
2684 	arg->end = ALIGN(arg->end, PAGE_SIZE);
2685 	arg->walk_end = 0;
2686 	if (!arg->max_pages)
2687 		arg->max_pages = ULONG_MAX;
2688 
2689 	return 0;
2690 }
2691 
2692 static int pagemap_scan_writeback_args(struct pm_scan_arg *arg,
2693 				       unsigned long uargl)
2694 {
2695 	struct pm_scan_arg __user *uarg	= (void __user *)uargl;
2696 
2697 	if (copy_to_user(&uarg->walk_end, &arg->walk_end, sizeof(arg->walk_end)))
2698 		return -EFAULT;
2699 
2700 	return 0;
2701 }
2702 
2703 static int pagemap_scan_init_bounce_buffer(struct pagemap_scan_private *p)
2704 {
2705 	if (!p->arg.vec_len)
2706 		return 0;
2707 
2708 	p->vec_buf_len = min_t(size_t, PAGEMAP_WALK_SIZE >> PAGE_SHIFT,
2709 			       p->arg.vec_len);
2710 	p->vec_buf = kmalloc_array(p->vec_buf_len, sizeof(*p->vec_buf),
2711 				   GFP_KERNEL);
2712 	if (!p->vec_buf)
2713 		return -ENOMEM;
2714 
2715 	p->vec_buf->start = p->vec_buf->end = 0;
2716 	p->vec_out = (struct page_region __user *)(long)p->arg.vec;
2717 
2718 	return 0;
2719 }
2720 
2721 static long pagemap_scan_flush_buffer(struct pagemap_scan_private *p)
2722 {
2723 	const struct page_region *buf = p->vec_buf;
2724 	long n = p->vec_buf_index;
2725 
2726 	if (!p->vec_buf)
2727 		return 0;
2728 
2729 	if (buf[n].end != buf[n].start)
2730 		n++;
2731 
2732 	if (!n)
2733 		return 0;
2734 
2735 	if (copy_to_user(p->vec_out, buf, n * sizeof(*buf)))
2736 		return -EFAULT;
2737 
2738 	p->arg.vec_len -= n;
2739 	p->vec_out += n;
2740 
2741 	p->vec_buf_index = 0;
2742 	p->vec_buf_len = min_t(size_t, p->vec_buf_len, p->arg.vec_len);
2743 	p->vec_buf->start = p->vec_buf->end = 0;
2744 
2745 	return n;
2746 }
2747 
2748 static long do_pagemap_scan(struct mm_struct *mm, unsigned long uarg)
2749 {
2750 	struct pagemap_scan_private p = {0};
2751 	unsigned long walk_start;
2752 	size_t n_ranges_out = 0;
2753 	int ret;
2754 
2755 	ret = pagemap_scan_get_args(&p.arg, uarg);
2756 	if (ret)
2757 		return ret;
2758 
2759 	p.masks_of_interest = p.arg.category_mask | p.arg.category_anyof_mask |
2760 			      p.arg.return_mask;
2761 	ret = pagemap_scan_init_bounce_buffer(&p);
2762 	if (ret)
2763 		return ret;
2764 
2765 	for (walk_start = p.arg.start; walk_start < p.arg.end;
2766 			walk_start = p.arg.walk_end) {
2767 		struct mmu_notifier_range range;
2768 		long n_out;
2769 
2770 		if (fatal_signal_pending(current)) {
2771 			ret = -EINTR;
2772 			break;
2773 		}
2774 
2775 		ret = mmap_read_lock_killable(mm);
2776 		if (ret)
2777 			break;
2778 
2779 		/* Protection change for the range is going to happen. */
2780 		if (p.arg.flags & PM_SCAN_WP_MATCHING) {
2781 			mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_VMA, 0,
2782 						mm, walk_start, p.arg.end);
2783 			mmu_notifier_invalidate_range_start(&range);
2784 		}
2785 
2786 		ret = walk_page_range(mm, walk_start, p.arg.end,
2787 				      &pagemap_scan_ops, &p);
2788 
2789 		if (p.arg.flags & PM_SCAN_WP_MATCHING)
2790 			mmu_notifier_invalidate_range_end(&range);
2791 
2792 		mmap_read_unlock(mm);
2793 
2794 		n_out = pagemap_scan_flush_buffer(&p);
2795 		if (n_out < 0)
2796 			ret = n_out;
2797 		else
2798 			n_ranges_out += n_out;
2799 
2800 		if (ret != -ENOSPC)
2801 			break;
2802 
2803 		if (p.arg.vec_len == 0 || p.found_pages == p.arg.max_pages)
2804 			break;
2805 	}
2806 
2807 	/* ENOSPC signifies early stop (buffer full) from the walk. */
2808 	if (!ret || ret == -ENOSPC)
2809 		ret = n_ranges_out;
2810 
2811 	/* The walk_end isn't set when ret is zero */
2812 	if (!p.arg.walk_end)
2813 		p.arg.walk_end = p.arg.end;
2814 	if (pagemap_scan_writeback_args(&p.arg, uarg))
2815 		ret = -EFAULT;
2816 
2817 	kfree(p.vec_buf);
2818 	return ret;
2819 }
2820 
2821 static long do_pagemap_cmd(struct file *file, unsigned int cmd,
2822 			   unsigned long arg)
2823 {
2824 	struct mm_struct *mm = file->private_data;
2825 
2826 	switch (cmd) {
2827 	case PAGEMAP_SCAN:
2828 		return do_pagemap_scan(mm, arg);
2829 
2830 	default:
2831 		return -EINVAL;
2832 	}
2833 }
2834 
2835 const struct file_operations proc_pagemap_operations = {
2836 	.llseek		= mem_lseek, /* borrow this */
2837 	.read		= pagemap_read,
2838 	.open		= pagemap_open,
2839 	.release	= pagemap_release,
2840 	.unlocked_ioctl = do_pagemap_cmd,
2841 	.compat_ioctl	= do_pagemap_cmd,
2842 };
2843 #endif /* CONFIG_PROC_PAGE_MONITOR */
2844 
2845 #ifdef CONFIG_NUMA
2846 
2847 struct numa_maps {
2848 	unsigned long pages;
2849 	unsigned long anon;
2850 	unsigned long active;
2851 	unsigned long writeback;
2852 	unsigned long mapcount_max;
2853 	unsigned long dirty;
2854 	unsigned long swapcache;
2855 	unsigned long node[MAX_NUMNODES];
2856 };
2857 
2858 struct numa_maps_private {
2859 	struct proc_maps_private proc_maps;
2860 	struct numa_maps md;
2861 };
2862 
2863 static void gather_stats(struct page *page, struct numa_maps *md, int pte_dirty,
2864 			unsigned long nr_pages)
2865 {
2866 	struct folio *folio = page_folio(page);
2867 	int count = folio_precise_page_mapcount(folio, page);
2868 
2869 	md->pages += nr_pages;
2870 	if (pte_dirty || folio_test_dirty(folio))
2871 		md->dirty += nr_pages;
2872 
2873 	if (folio_test_swapcache(folio))
2874 		md->swapcache += nr_pages;
2875 
2876 	if (folio_test_active(folio) || folio_test_unevictable(folio))
2877 		md->active += nr_pages;
2878 
2879 	if (folio_test_writeback(folio))
2880 		md->writeback += nr_pages;
2881 
2882 	if (folio_test_anon(folio))
2883 		md->anon += nr_pages;
2884 
2885 	if (count > md->mapcount_max)
2886 		md->mapcount_max = count;
2887 
2888 	md->node[folio_nid(folio)] += nr_pages;
2889 }
2890 
2891 static struct page *can_gather_numa_stats(pte_t pte, struct vm_area_struct *vma,
2892 		unsigned long addr)
2893 {
2894 	struct page *page;
2895 	int nid;
2896 
2897 	if (!pte_present(pte))
2898 		return NULL;
2899 
2900 	page = vm_normal_page(vma, addr, pte);
2901 	if (!page || is_zone_device_page(page))
2902 		return NULL;
2903 
2904 	if (PageReserved(page))
2905 		return NULL;
2906 
2907 	nid = page_to_nid(page);
2908 	if (!node_isset(nid, node_states[N_MEMORY]))
2909 		return NULL;
2910 
2911 	return page;
2912 }
2913 
2914 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2915 static struct page *can_gather_numa_stats_pmd(pmd_t pmd,
2916 					      struct vm_area_struct *vma,
2917 					      unsigned long addr)
2918 {
2919 	struct page *page;
2920 	int nid;
2921 
2922 	if (!pmd_present(pmd))
2923 		return NULL;
2924 
2925 	page = vm_normal_page_pmd(vma, addr, pmd);
2926 	if (!page)
2927 		return NULL;
2928 
2929 	if (PageReserved(page))
2930 		return NULL;
2931 
2932 	nid = page_to_nid(page);
2933 	if (!node_isset(nid, node_states[N_MEMORY]))
2934 		return NULL;
2935 
2936 	return page;
2937 }
2938 #endif
2939 
2940 static int gather_pte_stats(pmd_t *pmd, unsigned long addr,
2941 		unsigned long end, struct mm_walk *walk)
2942 {
2943 	struct numa_maps *md = walk->private;
2944 	struct vm_area_struct *vma = walk->vma;
2945 	spinlock_t *ptl;
2946 	pte_t *orig_pte;
2947 	pte_t *pte;
2948 
2949 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2950 	ptl = pmd_trans_huge_lock(pmd, vma);
2951 	if (ptl) {
2952 		struct page *page;
2953 
2954 		page = can_gather_numa_stats_pmd(*pmd, vma, addr);
2955 		if (page)
2956 			gather_stats(page, md, pmd_dirty(*pmd),
2957 				     HPAGE_PMD_SIZE/PAGE_SIZE);
2958 		spin_unlock(ptl);
2959 		return 0;
2960 	}
2961 #endif
2962 	orig_pte = pte = pte_offset_map_lock(walk->mm, pmd, addr, &ptl);
2963 	if (!pte) {
2964 		walk->action = ACTION_AGAIN;
2965 		return 0;
2966 	}
2967 	do {
2968 		pte_t ptent = ptep_get(pte);
2969 		struct page *page = can_gather_numa_stats(ptent, vma, addr);
2970 		if (!page)
2971 			continue;
2972 		gather_stats(page, md, pte_dirty(ptent), 1);
2973 
2974 	} while (pte++, addr += PAGE_SIZE, addr != end);
2975 	pte_unmap_unlock(orig_pte, ptl);
2976 	cond_resched();
2977 	return 0;
2978 }
2979 #ifdef CONFIG_HUGETLB_PAGE
2980 static int gather_hugetlb_stats(pte_t *pte, unsigned long hmask,
2981 		unsigned long addr, unsigned long end, struct mm_walk *walk)
2982 {
2983 	pte_t huge_pte = huge_ptep_get(walk->mm, addr, pte);
2984 	struct numa_maps *md;
2985 	struct page *page;
2986 
2987 	if (!pte_present(huge_pte))
2988 		return 0;
2989 
2990 	page = pte_page(huge_pte);
2991 
2992 	md = walk->private;
2993 	gather_stats(page, md, pte_dirty(huge_pte), 1);
2994 	return 0;
2995 }
2996 
2997 #else
2998 static int gather_hugetlb_stats(pte_t *pte, unsigned long hmask,
2999 		unsigned long addr, unsigned long end, struct mm_walk *walk)
3000 {
3001 	return 0;
3002 }
3003 #endif
3004 
3005 static const struct mm_walk_ops show_numa_ops = {
3006 	.hugetlb_entry = gather_hugetlb_stats,
3007 	.pmd_entry = gather_pte_stats,
3008 	.walk_lock = PGWALK_RDLOCK,
3009 };
3010 
3011 /*
3012  * Display pages allocated per node and memory policy via /proc.
3013  */
3014 static int show_numa_map(struct seq_file *m, void *v)
3015 {
3016 	struct numa_maps_private *numa_priv = m->private;
3017 	struct proc_maps_private *proc_priv = &numa_priv->proc_maps;
3018 	struct vm_area_struct *vma = v;
3019 	struct numa_maps *md = &numa_priv->md;
3020 	struct file *file = vma->vm_file;
3021 	struct mm_struct *mm = vma->vm_mm;
3022 	char buffer[64];
3023 	struct mempolicy *pol;
3024 	pgoff_t ilx;
3025 	int nid;
3026 
3027 	if (!mm)
3028 		return 0;
3029 
3030 	/* Ensure we start with an empty set of numa_maps statistics. */
3031 	memset(md, 0, sizeof(*md));
3032 
3033 	pol = __get_vma_policy(vma, vma->vm_start, &ilx);
3034 	if (pol) {
3035 		mpol_to_str(buffer, sizeof(buffer), pol);
3036 		mpol_cond_put(pol);
3037 	} else {
3038 		mpol_to_str(buffer, sizeof(buffer), proc_priv->task_mempolicy);
3039 	}
3040 
3041 	seq_printf(m, "%08lx %s", vma->vm_start, buffer);
3042 
3043 	if (file) {
3044 		seq_puts(m, " file=");
3045 		seq_path(m, file_user_path(file), "\n\t= ");
3046 	} else if (vma_is_initial_heap(vma)) {
3047 		seq_puts(m, " heap");
3048 	} else if (vma_is_initial_stack(vma)) {
3049 		seq_puts(m, " stack");
3050 	}
3051 
3052 	if (is_vm_hugetlb_page(vma))
3053 		seq_puts(m, " huge");
3054 
3055 	/* mmap_lock is held by m_start */
3056 	walk_page_vma(vma, &show_numa_ops, md);
3057 
3058 	if (!md->pages)
3059 		goto out;
3060 
3061 	if (md->anon)
3062 		seq_printf(m, " anon=%lu", md->anon);
3063 
3064 	if (md->dirty)
3065 		seq_printf(m, " dirty=%lu", md->dirty);
3066 
3067 	if (md->pages != md->anon && md->pages != md->dirty)
3068 		seq_printf(m, " mapped=%lu", md->pages);
3069 
3070 	if (md->mapcount_max > 1)
3071 		seq_printf(m, " mapmax=%lu", md->mapcount_max);
3072 
3073 	if (md->swapcache)
3074 		seq_printf(m, " swapcache=%lu", md->swapcache);
3075 
3076 	if (md->active < md->pages && !is_vm_hugetlb_page(vma))
3077 		seq_printf(m, " active=%lu", md->active);
3078 
3079 	if (md->writeback)
3080 		seq_printf(m, " writeback=%lu", md->writeback);
3081 
3082 	for_each_node_state(nid, N_MEMORY)
3083 		if (md->node[nid])
3084 			seq_printf(m, " N%d=%lu", nid, md->node[nid]);
3085 
3086 	seq_printf(m, " kernelpagesize_kB=%lu", vma_kernel_pagesize(vma) >> 10);
3087 out:
3088 	seq_putc(m, '\n');
3089 	return 0;
3090 }
3091 
3092 static const struct seq_operations proc_pid_numa_maps_op = {
3093 	.start  = m_start,
3094 	.next   = m_next,
3095 	.stop   = m_stop,
3096 	.show   = show_numa_map,
3097 };
3098 
3099 static int pid_numa_maps_open(struct inode *inode, struct file *file)
3100 {
3101 	return proc_maps_open(inode, file, &proc_pid_numa_maps_op,
3102 				sizeof(struct numa_maps_private));
3103 }
3104 
3105 const struct file_operations proc_pid_numa_maps_operations = {
3106 	.open		= pid_numa_maps_open,
3107 	.read		= seq_read,
3108 	.llseek		= seq_lseek,
3109 	.release	= proc_map_release,
3110 };
3111 
3112 #endif /* CONFIG_NUMA */
3113