xref: /linux/include/linux/mmap_lock.h (revision d96082aa35043cd1856e2213e683db778482a7d8)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _LINUX_MMAP_LOCK_H
3 #define _LINUX_MMAP_LOCK_H
4 
5 /* Avoid a dependency loop by declaring here. */
6 extern int rcuwait_wake_up(struct rcuwait *w);
7 
8 #include <linux/lockdep.h>
9 #include <linux/mm_types.h>
10 #include <linux/mmdebug.h>
11 #include <linux/rwsem.h>
12 #include <linux/tracepoint-defs.h>
13 #include <linux/types.h>
14 #include <linux/cleanup.h>
15 #include <linux/sched/mm.h>
16 
17 #define MMAP_LOCK_INITIALIZER(name) \
18 	.mmap_lock = __RWSEM_INITIALIZER((name).mmap_lock),
19 
20 DECLARE_TRACEPOINT(mmap_lock_start_locking);
21 DECLARE_TRACEPOINT(mmap_lock_acquire_returned);
22 DECLARE_TRACEPOINT(mmap_lock_released);
23 
24 #ifdef CONFIG_TRACING
25 
26 void __mmap_lock_do_trace_start_locking(struct mm_struct *mm, bool write);
27 void __mmap_lock_do_trace_acquire_returned(struct mm_struct *mm, bool write,
28 					   bool success);
29 void __mmap_lock_do_trace_released(struct mm_struct *mm, bool write);
30 
31 static inline void __mmap_lock_trace_start_locking(struct mm_struct *mm,
32 						   bool write)
33 {
34 	if (tracepoint_enabled(mmap_lock_start_locking))
35 		__mmap_lock_do_trace_start_locking(mm, write);
36 }
37 
38 static inline void __mmap_lock_trace_acquire_returned(struct mm_struct *mm,
39 						      bool write, bool success)
40 {
41 	if (tracepoint_enabled(mmap_lock_acquire_returned))
42 		__mmap_lock_do_trace_acquire_returned(mm, write, success);
43 }
44 
45 static inline void __mmap_lock_trace_released(struct mm_struct *mm, bool write)
46 {
47 	if (tracepoint_enabled(mmap_lock_released))
48 		__mmap_lock_do_trace_released(mm, write);
49 }
50 
51 #else /* !CONFIG_TRACING */
52 
53 static inline void __mmap_lock_trace_start_locking(struct mm_struct *mm,
54 						   bool write)
55 {
56 }
57 
58 static inline void __mmap_lock_trace_acquire_returned(struct mm_struct *mm,
59 						      bool write, bool success)
60 {
61 }
62 
63 static inline void __mmap_lock_trace_released(struct mm_struct *mm, bool write)
64 {
65 }
66 
67 #endif /* CONFIG_TRACING */
68 
69 static inline void mmap_assert_locked(const struct mm_struct *mm)
70 {
71 	rwsem_assert_held(&mm->mmap_lock);
72 }
73 
74 static inline void mmap_assert_write_locked(const struct mm_struct *mm)
75 {
76 	rwsem_assert_held_write(&mm->mmap_lock);
77 }
78 
79 #ifdef CONFIG_LOCKDEP
80 #define __vma_lockdep_map(vma) (&vma->vmlock_dep_map)
81 #else
82 #define __vma_lockdep_map(vma) NULL
83 #endif
84 
85 /*
86  * VMA locks do not behave like most ordinary locks found in the kernel, so we
87  * cannot quite have full lockdep tracking in the way we would ideally prefer.
88  *
89  * Read locks act as shared locks which exclude an exclusive lock being
90  * taken. We therefore mark these accordingly on read lock acquire/release.
91  *
92  * Write locks are acquired exclusively per-VMA, but released in a shared
93  * fashion, that is upon vma_end_write_all(), we update the mmap's seqcount such
94  * that write lock is released.
95  *
96  * We therefore cannot track write locks per-VMA, nor do we try. Mitigating this
97  * is the fact that, of course, we do lockdep-track the mmap lock rwsem which
98  * must be held when taking a VMA write lock.
99  *
100  * We do, however, want to indicate that during either acquisition of a VMA
101  * write lock or detachment of a VMA that we require the lock held be exclusive,
102  * so we utilise lockdep to do so.
103  */
104 #define __vma_lockdep_acquire_read(vma) \
105 	lock_acquire_shared(__vma_lockdep_map(vma), 0, 1, NULL, _RET_IP_)
106 #define __vma_lockdep_release_read(vma) \
107 	lock_release(__vma_lockdep_map(vma), _RET_IP_)
108 #define __vma_lockdep_acquire_exclusive(vma) \
109 	lock_acquire_exclusive(__vma_lockdep_map(vma), 0, 0, NULL, _RET_IP_)
110 #define __vma_lockdep_release_exclusive(vma) \
111 	lock_release(__vma_lockdep_map(vma), _RET_IP_)
112 /* Only meaningful if CONFIG_LOCK_STAT is defined. */
113 #define __vma_lockdep_stat_mark_acquired(vma) \
114 	lock_acquired(__vma_lockdep_map(vma), _RET_IP_)
115 
116 static inline void mm_lock_seqcount_init(struct mm_struct *mm)
117 {
118 	seqcount_init(&mm->mm_lock_seq);
119 }
120 
121 static inline void mm_lock_seqcount_begin(struct mm_struct *mm)
122 {
123 	do_raw_write_seqcount_begin(&mm->mm_lock_seq);
124 }
125 
126 static inline void mm_lock_seqcount_end(struct mm_struct *mm)
127 {
128 	ASSERT_EXCLUSIVE_WRITER(mm->mm_lock_seq);
129 	do_raw_write_seqcount_end(&mm->mm_lock_seq);
130 }
131 
132 static inline bool mmap_lock_speculate_try_begin(struct mm_struct *mm, unsigned int *seq)
133 {
134 	/*
135 	 * Since mmap_lock is a sleeping lock, and waiting for it to become
136 	 * unlocked is more or less equivalent with taking it ourselves, don't
137 	 * bother with the speculative path if mmap_lock is already write-locked
138 	 * and take the slow path, which takes the lock.
139 	 */
140 	return raw_seqcount_try_begin(&mm->mm_lock_seq, *seq);
141 }
142 
143 static inline bool mmap_lock_speculate_retry(struct mm_struct *mm, unsigned int seq)
144 {
145 	return read_seqcount_retry(&mm->mm_lock_seq, seq);
146 }
147 
148 static inline void vma_lock_init(struct vm_area_struct *vma, bool reset_refcnt)
149 {
150 #ifdef CONFIG_DEBUG_LOCK_ALLOC
151 	static struct lock_class_key lockdep_key;
152 
153 	lockdep_init_map(__vma_lockdep_map(vma), "vm_lock", &lockdep_key, 0);
154 #endif
155 	if (reset_refcnt)
156 		refcount_set(&vma->vm_refcnt, 0);
157 	vma->vm_lock_seq = UINT_MAX;
158 }
159 
160 /*
161  * This function determines whether the input VMA reference count describes a
162  * VMA which has excluded all VMA read locks.
163  *
164  * In the case of a detached VMA, we may incorrectly indicate that readers are
165  * excluded when one remains, because in that scenario we target a refcount of
166  * VM_REFCNT_EXCLUDE_READERS_FLAG, rather than the attached target of
167  * VM_REFCNT_EXCLUDE_READERS_FLAG + 1.
168  *
169  * However, the race window for that is very small so it is unlikely.
170  *
171  * Returns: true if readers are excluded, false otherwise.
172  */
173 static inline bool __vma_are_readers_excluded(int refcnt)
174 {
175 	/*
176 	 * See the comment describing the vm_area_struct->vm_refcnt field for
177 	 * details of possible refcnt values.
178 	 */
179 	return (refcnt & VM_REFCNT_EXCLUDE_READERS_FLAG) &&
180 		refcnt <= VM_REFCNT_EXCLUDE_READERS_FLAG + 1;
181 }
182 
183 /*
184  * Actually decrement the VMA reference count.
185  *
186  * The function returns the reference count as it was immediately after the
187  * decrement took place. If it returns zero, the VMA is now detached.
188  */
189 static inline __must_check unsigned int
190 __vma_refcount_put_return(struct vm_area_struct *vma)
191 {
192 	int oldcnt;
193 
194 	if (__refcount_dec_and_test(&vma->vm_refcnt, &oldcnt))
195 		return 0;
196 
197 	return oldcnt - 1;
198 }
199 
200 /**
201  * vma_refcount_put() - Drop reference count in VMA vm_refcnt field due to a
202  * read-lock being dropped.
203  * @vma: The VMA whose reference count we wish to decrement.
204  *
205  * If we were the last reader, wake up threads waiting to obtain an exclusive
206  * lock.
207  */
208 static inline void vma_refcount_put(struct vm_area_struct *vma)
209 {
210 	/* Use a copy of vm_mm in case vma is freed after we drop vm_refcnt. */
211 	struct mm_struct *mm = vma->vm_mm;
212 	int newcnt;
213 
214 	__vma_lockdep_release_read(vma);
215 	newcnt = __vma_refcount_put_return(vma);
216 
217 	/*
218 	 * __vma_start_exclude_readers() may be sleeping waiting for readers to
219 	 * drop their reference count, so wake it up if we were the last reader
220 	 * blocking it from being acquired.
221 	 *
222 	 * We may be raced by other readers temporarily incrementing the
223 	 * reference count, though the race window is very small, this might
224 	 * cause spurious wakeups.
225 	 */
226 	if (newcnt && __vma_are_readers_excluded(newcnt))
227 		rcuwait_wake_up(&mm->vma_writer_wait);
228 }
229 
230 /*
231  * Use only while holding mmap read lock which guarantees that vma lock is not
232  * contended (nobody can concurrently write-lock the vma). vma_start_read() should
233  * not be used in such cases because it might fail due to mm_lock_seq overflow.
234  * This functionality is used to obtain vma read lock and drop the mmap read lock.
235  *
236  * VMA can't be detached while we are holding mmap lock, therefore in practice this
237  * function can fail only when there are so many readers that vm_refcnt overflows.
238  * The failure case is very unlikely and is already annotated as such internally.
239  */
240 static inline bool vma_start_read_locked_nested(struct vm_area_struct *vma, int subclass)
241 {
242 	int oldcnt;
243 
244 	mmap_assert_locked(vma->vm_mm);
245 	if (unlikely(!__refcount_inc_not_zero_limited_acquire(&vma->vm_refcnt, &oldcnt,
246 							      VM_REFCNT_LIMIT)))
247 		return false;
248 
249 	__vma_lockdep_acquire_read(vma);
250 	return true;
251 }
252 
253 /*
254  * Use only while holding mmap read lock which guarantees that vma lock is not
255  * contended (nobody can concurrently write-lock the vma). vma_start_read() should
256  * not be used in such cases because it might fail due to mm_lock_seq overflow.
257  * This functionality is used to obtain vma read lock and drop the mmap read lock.
258  *
259  * VMA can't be detached while we are holding mmap lock, therefore in practice this
260  * function can fail only when there are so many readers that vm_refcnt overflows.
261  * The failure case is very unlikely and is already annotated as such internally.
262  */
263 static inline bool vma_start_read_locked(struct vm_area_struct *vma)
264 {
265 	return vma_start_read_locked_nested(vma, 0);
266 }
267 
268 struct vm_area_struct *vma_start_read_unlocked(struct mm_struct *mm,
269 					       unsigned long address);
270 
271 static inline void vma_end_read(struct vm_area_struct *vma)
272 {
273 	vma_refcount_put(vma);
274 }
275 
276 static inline unsigned int __vma_raw_mm_seqnum(struct vm_area_struct *vma)
277 {
278 	const struct mm_struct *mm = vma->vm_mm;
279 
280 	/* We must hold an exclusive write lock for this access to be valid. */
281 	mmap_assert_write_locked(vma->vm_mm);
282 	return mm->mm_lock_seq.sequence;
283 }
284 
285 /*
286  * Determine whether a VMA is write-locked. Must be invoked ONLY if the mmap
287  * write lock is held.
288  *
289  * Returns true if write-locked, otherwise false.
290  */
291 static inline bool __is_vma_write_locked(struct vm_area_struct *vma)
292 {
293 	/*
294 	 * current task is holding mmap_write_lock, both vma->vm_lock_seq and
295 	 * mm->mm_lock_seq can't be concurrently modified.
296 	 */
297 	return vma->vm_lock_seq == __vma_raw_mm_seqnum(vma);
298 }
299 
300 int __vma_start_write(struct vm_area_struct *vma, int state);
301 
302 /*
303  * Begin writing to a VMA.
304  * Exclude concurrent readers under the per-VMA lock until the currently
305  * write-locked mmap_lock is dropped or downgraded.
306  */
307 static inline void vma_start_write(struct vm_area_struct *vma)
308 {
309 	if (!IS_ENABLED(CONFIG_MMU))
310 		return;
311 
312 	if (__is_vma_write_locked(vma))
313 		return;
314 
315 	__vma_start_write(vma, TASK_UNINTERRUPTIBLE);
316 }
317 
318 /**
319  * vma_start_write_killable - Begin writing to a VMA.
320  * @vma: The VMA we are going to modify.
321  *
322  * Exclude concurrent readers under the per-VMA lock until the currently
323  * write-locked mmap_lock is dropped or downgraded.
324  *
325  * Context: May sleep while waiting for readers to drop the vma read lock.
326  * Caller must already hold the mmap_lock for write.
327  *
328  * Return: 0 for a successful acquisition.  -EINTR if a fatal signal was
329  * received.
330  */
331 static inline __must_check
332 int vma_start_write_killable(struct vm_area_struct *vma)
333 {
334 	if (!IS_ENABLED(CONFIG_MMU))
335 		return 0;
336 
337 	if (__is_vma_write_locked(vma))
338 		return 0;
339 
340 	return __vma_start_write(vma, TASK_KILLABLE);
341 }
342 
343 /**
344  * vma_assert_write_locked() - assert that @vma holds a VMA write lock.
345  * @vma: The VMA to assert.
346  */
347 static inline void vma_assert_write_locked(struct vm_area_struct *vma)
348 {
349 	if (!IS_ENABLED(CONFIG_MMU)) {
350 		mmap_assert_write_locked(vma->vm_mm);
351 		return;
352 	}
353 
354 	VM_WARN_ON_ONCE_VMA(!__is_vma_write_locked(vma), vma);
355 }
356 
357 /**
358  * vma_assert_locked() - assert that @vma holds either a VMA read or a VMA write
359  * lock and is not detached.
360  * @vma: The VMA to assert.
361  */
362 static inline void vma_assert_locked(struct vm_area_struct *vma)
363 {
364 	unsigned int refcnt;
365 
366 	if (!IS_ENABLED(CONFIG_MMU)) {
367 		mmap_assert_locked(vma->vm_mm);
368 		return;
369 	}
370 
371 	if (IS_ENABLED(CONFIG_LOCKDEP)) {
372 		if (!lock_is_held(__vma_lockdep_map(vma)))
373 			vma_assert_write_locked(vma);
374 		return;
375 	}
376 
377 	/*
378 	 * See the comment describing the vm_area_struct->vm_refcnt field for
379 	 * details of possible refcnt values.
380 	 */
381 	refcnt = refcount_read(&vma->vm_refcnt);
382 
383 	/*
384 	 * In this case we're either read-locked, write-locked with temporary
385 	 * readers, or in the midst of excluding readers, all of which means
386 	 * we're locked.
387 	 */
388 	if (refcnt > 1)
389 		return;
390 
391 	/* It is a bug for the VMA to be detached here. */
392 	VM_WARN_ON_ONCE_VMA(!refcnt, vma);
393 
394 	/*
395 	 * OK, the VMA has a reference count of 1 which means it is either
396 	 * unlocked and attached or write-locked, so assert that it is
397 	 * write-locked.
398 	 */
399 	vma_assert_write_locked(vma);
400 }
401 
402 /**
403  * vma_assert_stabilised() - assert that this VMA cannot be changed from
404  * underneath us either by having a VMA or mmap lock held.
405  * @vma: The VMA whose stability we wish to assess.
406  *
407  * If lockdep is enabled we can precisely ensure stability via either an mmap
408  * lock owned by us or a specific VMA lock.
409  *
410  * With lockdep disabled we may sometimes race with other threads acquiring the
411  * mmap read lock simultaneous with our VMA read lock.
412  */
413 static inline void vma_assert_stabilised(struct vm_area_struct *vma)
414 {
415 	/*
416 	 * If another thread owns an mmap lock, it may go away at any time, and
417 	 * thus is no guarantee of stability.
418 	 *
419 	 * If lockdep is enabled we can accurately determine if an mmap lock is
420 	 * held and owned by us. Otherwise we must approximate.
421 	 *
422 	 * It doesn't necessarily mean we are not stabilised however, as we may
423 	 * hold a VMA read lock (not a write lock as this would require an owned
424 	 * mmap lock).
425 	 *
426 	 * If (assuming lockdep is not enabled) we were to assert a VMA read
427 	 * lock first we may also run into issues, as other threads can hold VMA
428 	 * read locks simlutaneous to us.
429 	 *
430 	 * Therefore if lockdep is not enabled we risk a false negative (i.e. no
431 	 * assert fired). If accurate checking is required, enable lockdep.
432 	 */
433 	if (IS_ENABLED(CONFIG_LOCKDEP)) {
434 		if (lockdep_is_held(&vma->vm_mm->mmap_lock))
435 			return;
436 	} else {
437 		if (rwsem_is_locked(&vma->vm_mm->mmap_lock))
438 			return;
439 	}
440 
441 	/*
442 	 * We're not stabilised by the mmap lock, so assert that we're
443 	 * stabilised by a VMA lock.
444 	 */
445 	vma_assert_locked(vma);
446 }
447 
448 static inline bool vma_is_attached(struct vm_area_struct *vma)
449 {
450 	return refcount_read(&vma->vm_refcnt);
451 }
452 
453 /*
454  * WARNING: to avoid racing with vma_mark_attached()/vma_mark_detached(), these
455  * assertions should be made either under mmap_write_lock or when the object
456  * has been isolated under mmap_write_lock, ensuring no competing writers.
457  */
458 static inline void vma_assert_attached(struct vm_area_struct *vma)
459 {
460 	if (!IS_ENABLED(CONFIG_MMU))
461 		return;
462 
463 	WARN_ON_ONCE(!vma_is_attached(vma));
464 }
465 
466 static inline void vma_assert_detached(struct vm_area_struct *vma)
467 {
468 	WARN_ON_ONCE(vma_is_attached(vma));
469 }
470 
471 static inline void vma_mark_attached(struct vm_area_struct *vma)
472 {
473 	if (!IS_ENABLED(CONFIG_MMU))
474 		return;
475 
476 	vma_assert_write_locked(vma);
477 	vma_assert_detached(vma);
478 	refcount_set_release(&vma->vm_refcnt, 1);
479 }
480 
481 void __vma_exclude_readers_for_detach(struct vm_area_struct *vma);
482 
483 static inline void vma_mark_detached(struct vm_area_struct *vma)
484 {
485 	if (!IS_ENABLED(CONFIG_MMU))
486 		return;
487 
488 	vma_assert_write_locked(vma);
489 	vma_assert_attached(vma);
490 
491 	/*
492 	 * The VMA still being attached (refcnt > 0) - is unlikely, because the
493 	 * vma has been already write-locked and readers can increment vm_refcnt
494 	 * only temporarily before they check vm_lock_seq, realize the vma is
495 	 * locked and drop back the vm_refcnt. That is a narrow window for
496 	 * observing a raised vm_refcnt.
497 	 *
498 	 * See the comment describing the vm_area_struct->vm_refcnt field for
499 	 * details of possible refcnt values.
500 	 */
501 	if (likely(!__vma_refcount_put_return(vma)))
502 		return;
503 
504 	__vma_exclude_readers_for_detach(vma);
505 }
506 
507 struct vm_area_struct *lock_vma_under_rcu(struct mm_struct *mm,
508 					  unsigned long address);
509 
510 /*
511  * Locks next vma pointed by the iterator. Confirms the locked vma has not
512  * been modified and will retry under mmap_lock protection if modification
513  * was detected. Should be called from read RCU section.
514  * Returns either a valid locked VMA, NULL if no more VMAs or -EINTR if the
515  * process was interrupted.
516  */
517 struct vm_area_struct *lock_next_vma(struct mm_struct *mm,
518 				     struct vma_iterator *iter,
519 				     unsigned long address);
520 
521 static inline void vma_assert_can_modify(struct vm_area_struct *vma)
522 {
523 	if (vma_is_attached(vma))
524 		vma_assert_write_locked(vma);
525 }
526 
527 static inline void mmap_write_lock(struct mm_struct *mm)
528 {
529 	__mmap_lock_trace_start_locking(mm, true);
530 	down_write(&mm->mmap_lock);
531 	mm_lock_seqcount_begin(mm);
532 	__mmap_lock_trace_acquire_returned(mm, true, true);
533 }
534 
535 static inline void mmap_write_lock_nested(struct mm_struct *mm, int subclass)
536 {
537 	__mmap_lock_trace_start_locking(mm, true);
538 	down_write_nested(&mm->mmap_lock, subclass);
539 	mm_lock_seqcount_begin(mm);
540 	__mmap_lock_trace_acquire_returned(mm, true, true);
541 }
542 
543 static inline int __must_check mmap_write_lock_killable(struct mm_struct *mm)
544 {
545 	int ret;
546 
547 	__mmap_lock_trace_start_locking(mm, true);
548 	ret = down_write_killable(&mm->mmap_lock);
549 	if (!ret)
550 		mm_lock_seqcount_begin(mm);
551 	__mmap_lock_trace_acquire_returned(mm, true, ret == 0);
552 	return ret;
553 }
554 
555 /*
556  * Drop all currently-held per-VMA locks.
557  * This is called from the mmap_lock implementation directly before releasing
558  * a write-locked mmap_lock (or downgrading it to read-locked).
559  * This should normally NOT be called manually from other places.
560  * If you want to call this manually anyway, keep in mind that this will release
561  * *all* VMA write locks, including ones from further up the stack.
562  */
563 static inline void vma_end_write_all(struct mm_struct *mm)
564 {
565 	mmap_assert_write_locked(mm);
566 	mm_lock_seqcount_end(mm);
567 }
568 
569 static inline void mmap_write_unlock(struct mm_struct *mm)
570 {
571 	__mmap_lock_trace_released(mm, true);
572 	vma_end_write_all(mm);
573 	up_write(&mm->mmap_lock);
574 }
575 
576 static inline void mmap_write_downgrade(struct mm_struct *mm)
577 {
578 	__mmap_lock_trace_acquire_returned(mm, false, true);
579 	vma_end_write_all(mm);
580 	downgrade_write(&mm->mmap_lock);
581 }
582 
583 static inline void mmap_read_lock(struct mm_struct *mm)
584 {
585 	__mmap_lock_trace_start_locking(mm, false);
586 	down_read(&mm->mmap_lock);
587 	__mmap_lock_trace_acquire_returned(mm, false, true);
588 }
589 
590 static inline int __must_check mmap_read_lock_killable(struct mm_struct *mm)
591 {
592 	int ret;
593 
594 	__mmap_lock_trace_start_locking(mm, false);
595 	ret = down_read_killable(&mm->mmap_lock);
596 	__mmap_lock_trace_acquire_returned(mm, false, ret == 0);
597 	return ret;
598 }
599 
600 static inline bool __must_check mmap_read_trylock(struct mm_struct *mm)
601 {
602 	bool ret;
603 
604 	__mmap_lock_trace_start_locking(mm, false);
605 	ret = down_read_trylock(&mm->mmap_lock) != 0;
606 	__mmap_lock_trace_acquire_returned(mm, false, ret);
607 	return ret;
608 }
609 
610 static inline void mmap_read_unlock(struct mm_struct *mm)
611 {
612 	__mmap_lock_trace_released(mm, false);
613 	up_read(&mm->mmap_lock);
614 }
615 
616 DEFINE_GUARD(mmap_read_lock, struct mm_struct *,
617 	     mmap_read_lock(_T), mmap_read_unlock(_T))
618 DEFINE_GUARD_COND(mmap_read_lock, _try, mmap_read_trylock(_T))
619 DEFINE_GUARD(mmap_write_lock, struct mm_struct *,
620 	     mmap_write_lock(_T), mmap_write_unlock(_T))
621 
622 static inline void mmap_read_unlock_non_owner(struct mm_struct *mm)
623 {
624 	__mmap_lock_trace_released(mm, false);
625 	up_read_non_owner(&mm->mmap_lock);
626 }
627 
628 static inline int mmap_lock_is_contended(struct mm_struct *mm)
629 {
630 	return rwsem_is_contended(&mm->mmap_lock);
631 }
632 
633 #endif /* _LINUX_MMAP_LOCK_H */
634