xref: /linux/mm/mmu_notifier.c (revision ee8287e068a3995b0f8001dd6931e221dfb7c530)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  linux/mm/mmu_notifier.c
4  *
5  *  Copyright (C) 2008  Qumranet, Inc.
6  *  Copyright (C) 2008  SGI
7  *             Christoph Lameter <cl@linux.com>
8  */
9 
10 #include <linux/rculist.h>
11 #include <linux/mmu_notifier.h>
12 #include <linux/export.h>
13 #include <linux/mm.h>
14 #include <linux/err.h>
15 #include <linux/interval_tree.h>
16 #include <linux/srcu.h>
17 #include <linux/rcupdate.h>
18 #include <linux/sched.h>
19 #include <linux/sched/mm.h>
20 #include <linux/slab.h>
21 
22 /* global SRCU for all MMs */
23 DEFINE_STATIC_SRCU(srcu);
24 
25 #ifdef CONFIG_LOCKDEP
26 struct lockdep_map __mmu_notifier_invalidate_range_start_map = {
27 	.name = "mmu_notifier_invalidate_range_start"
28 };
29 #endif
30 
31 /*
32  * The mmu_notifier_subscriptions structure is allocated and installed in
33  * mm->notifier_subscriptions inside the mm_take_all_locks() protected
34  * critical section and it's released only when mm_count reaches zero
35  * in mmdrop().
36  */
37 struct mmu_notifier_subscriptions {
38 	/* all mmu notifiers registered in this mm are queued in this list */
39 	struct hlist_head list;
40 	bool has_itree;
41 	/* to serialize the list modifications and hlist_unhashed */
42 	spinlock_t lock;
43 	unsigned long invalidate_seq;
44 	unsigned long active_invalidate_ranges;
45 	struct rb_root_cached itree;
46 	wait_queue_head_t wq;
47 	struct hlist_head deferred_list;
48 };
49 
50 /*
51  * This is a collision-retry read-side/write-side 'lock', a lot like a
52  * seqcount, however this allows multiple write-sides to hold it at
53  * once. Conceptually the write side is protecting the values of the PTEs in
54  * this mm, such that PTES cannot be read into SPTEs (shadow PTEs) while any
55  * writer exists.
56  *
57  * Note that the core mm creates nested invalidate_range_start()/end() regions
58  * within the same thread, and runs invalidate_range_start()/end() in parallel
59  * on multiple CPUs. This is designed to not reduce concurrency or block
60  * progress on the mm side.
61  *
62  * As a secondary function, holding the full write side also serves to prevent
63  * writers for the itree, this is an optimization to avoid extra locking
64  * during invalidate_range_start/end notifiers.
65  *
66  * The write side has two states, fully excluded:
67  *  - mm->active_invalidate_ranges != 0
68  *  - subscriptions->invalidate_seq & 1 == True (odd)
69  *  - some range on the mm_struct is being invalidated
70  *  - the itree is not allowed to change
71  *
72  * And partially excluded:
73  *  - mm->active_invalidate_ranges != 0
74  *  - subscriptions->invalidate_seq & 1 == False (even)
75  *  - some range on the mm_struct is being invalidated
76  *  - the itree is allowed to change
77  *
78  * Operations on notifier_subscriptions->invalidate_seq (under spinlock):
79  *    seq |= 1  # Begin writing
80  *    seq++     # Release the writing state
81  *    seq & 1   # True if a writer exists
82  *
83  * The later state avoids some expensive work on inv_end in the common case of
84  * no mmu_interval_notifier monitoring the VA.
85  */
86 static bool
87 mn_itree_is_invalidating(struct mmu_notifier_subscriptions *subscriptions)
88 {
89 	lockdep_assert_held(&subscriptions->lock);
90 	return subscriptions->invalidate_seq & 1;
91 }
92 
93 static struct mmu_interval_notifier *
94 mn_itree_inv_start_range(struct mmu_notifier_subscriptions *subscriptions,
95 			 const struct mmu_notifier_range *range,
96 			 unsigned long *seq)
97 {
98 	struct interval_tree_node *node;
99 	struct mmu_interval_notifier *res = NULL;
100 
101 	spin_lock(&subscriptions->lock);
102 	subscriptions->active_invalidate_ranges++;
103 	node = interval_tree_iter_first(&subscriptions->itree, range->start,
104 					range->end - 1);
105 	if (node) {
106 		subscriptions->invalidate_seq |= 1;
107 		res = container_of(node, struct mmu_interval_notifier,
108 				   interval_tree);
109 	}
110 
111 	*seq = subscriptions->invalidate_seq;
112 	spin_unlock(&subscriptions->lock);
113 	return res;
114 }
115 
116 static struct mmu_interval_notifier *
117 mn_itree_inv_next(struct mmu_interval_notifier *interval_sub,
118 		  const struct mmu_notifier_range *range)
119 {
120 	struct interval_tree_node *node;
121 
122 	node = interval_tree_iter_next(&interval_sub->interval_tree,
123 				       range->start, range->end - 1);
124 	if (!node)
125 		return NULL;
126 	return container_of(node, struct mmu_interval_notifier, interval_tree);
127 }
128 
129 static void mn_itree_inv_end(struct mmu_notifier_subscriptions *subscriptions)
130 {
131 	struct mmu_interval_notifier *interval_sub;
132 	struct hlist_node *next;
133 
134 	spin_lock(&subscriptions->lock);
135 	if (--subscriptions->active_invalidate_ranges ||
136 	    !mn_itree_is_invalidating(subscriptions)) {
137 		spin_unlock(&subscriptions->lock);
138 		return;
139 	}
140 
141 	/* Make invalidate_seq even */
142 	subscriptions->invalidate_seq++;
143 
144 	/*
145 	 * The inv_end incorporates a deferred mechanism like rtnl_unlock().
146 	 * Adds and removes are queued until the final inv_end happens then
147 	 * they are progressed. This arrangement for tree updates is used to
148 	 * avoid using a blocking lock during invalidate_range_start.
149 	 */
150 	hlist_for_each_entry_safe(interval_sub, next,
151 				  &subscriptions->deferred_list,
152 				  deferred_item) {
153 		if (RB_EMPTY_NODE(&interval_sub->interval_tree.rb))
154 			interval_tree_insert(&interval_sub->interval_tree,
155 					     &subscriptions->itree);
156 		else
157 			interval_tree_remove(&interval_sub->interval_tree,
158 					     &subscriptions->itree);
159 		hlist_del(&interval_sub->deferred_item);
160 	}
161 	spin_unlock(&subscriptions->lock);
162 
163 	wake_up_all(&subscriptions->wq);
164 }
165 
166 /**
167  * mmu_interval_read_begin - Begin a read side critical section against a VA
168  *                           range
169  * @interval_sub: The interval subscription
170  *
171  * mmu_iterval_read_begin()/mmu_iterval_read_retry() implement a
172  * collision-retry scheme similar to seqcount for the VA range under
173  * subscription. If the mm invokes invalidation during the critical section
174  * then mmu_interval_read_retry() will return true.
175  *
176  * This is useful to obtain shadow PTEs where teardown or setup of the SPTEs
177  * require a blocking context.  The critical region formed by this can sleep,
178  * and the required 'user_lock' can also be a sleeping lock.
179  *
180  * The caller is required to provide a 'user_lock' to serialize both teardown
181  * and setup.
182  *
183  * The return value should be passed to mmu_interval_read_retry().
184  */
185 unsigned long
186 mmu_interval_read_begin(struct mmu_interval_notifier *interval_sub)
187 {
188 	struct mmu_notifier_subscriptions *subscriptions =
189 		interval_sub->mm->notifier_subscriptions;
190 	unsigned long seq;
191 	bool is_invalidating;
192 
193 	/*
194 	 * If the subscription has a different seq value under the user_lock
195 	 * than we started with then it has collided.
196 	 *
197 	 * If the subscription currently has the same seq value as the
198 	 * subscriptions seq, then it is currently between
199 	 * invalidate_start/end and is colliding.
200 	 *
201 	 * The locking looks broadly like this:
202 	 *   mn_itree_inv_start():                 mmu_interval_read_begin():
203 	 *                                         spin_lock
204 	 *                                          seq = READ_ONCE(interval_sub->invalidate_seq);
205 	 *                                          seq == subs->invalidate_seq
206 	 *                                         spin_unlock
207 	 *    spin_lock
208 	 *     seq = ++subscriptions->invalidate_seq
209 	 *    spin_unlock
210 	 *     op->invalidate():
211 	 *       user_lock
212 	 *        mmu_interval_set_seq()
213 	 *         interval_sub->invalidate_seq = seq
214 	 *       user_unlock
215 	 *
216 	 *                          [Required: mmu_interval_read_retry() == true]
217 	 *
218 	 *   mn_itree_inv_end():
219 	 *    spin_lock
220 	 *     seq = ++subscriptions->invalidate_seq
221 	 *    spin_unlock
222 	 *
223 	 *                                        user_lock
224 	 *                                         mmu_interval_read_retry():
225 	 *                                          interval_sub->invalidate_seq != seq
226 	 *                                        user_unlock
227 	 *
228 	 * Barriers are not needed here as any races here are closed by an
229 	 * eventual mmu_interval_read_retry(), which provides a barrier via the
230 	 * user_lock.
231 	 */
232 	spin_lock(&subscriptions->lock);
233 	/* Pairs with the WRITE_ONCE in mmu_interval_set_seq() */
234 	seq = READ_ONCE(interval_sub->invalidate_seq);
235 	is_invalidating = seq == subscriptions->invalidate_seq;
236 	spin_unlock(&subscriptions->lock);
237 
238 	/*
239 	 * interval_sub->invalidate_seq must always be set to an odd value via
240 	 * mmu_interval_set_seq() using the provided cur_seq from
241 	 * mn_itree_inv_start_range(). This ensures that if seq does wrap we
242 	 * will always clear the below sleep in some reasonable time as
243 	 * subscriptions->invalidate_seq is even in the idle state.
244 	 */
245 	lock_map_acquire(&__mmu_notifier_invalidate_range_start_map);
246 	lock_map_release(&__mmu_notifier_invalidate_range_start_map);
247 	if (is_invalidating)
248 		wait_event(subscriptions->wq,
249 			   READ_ONCE(subscriptions->invalidate_seq) != seq);
250 
251 	/*
252 	 * Notice that mmu_interval_read_retry() can already be true at this
253 	 * point, avoiding loops here allows the caller to provide a global
254 	 * time bound.
255 	 */
256 
257 	return seq;
258 }
259 EXPORT_SYMBOL_GPL(mmu_interval_read_begin);
260 
261 static void mn_itree_release(struct mmu_notifier_subscriptions *subscriptions,
262 			     struct mm_struct *mm)
263 {
264 	struct mmu_notifier_range range = {
265 		.flags = MMU_NOTIFIER_RANGE_BLOCKABLE,
266 		.event = MMU_NOTIFY_RELEASE,
267 		.mm = mm,
268 		.start = 0,
269 		.end = ULONG_MAX,
270 	};
271 	struct mmu_interval_notifier *interval_sub;
272 	unsigned long cur_seq;
273 	bool ret;
274 
275 	for (interval_sub =
276 		     mn_itree_inv_start_range(subscriptions, &range, &cur_seq);
277 	     interval_sub;
278 	     interval_sub = mn_itree_inv_next(interval_sub, &range)) {
279 		ret = interval_sub->ops->invalidate(interval_sub, &range,
280 						    cur_seq);
281 		WARN_ON(!ret);
282 	}
283 
284 	mn_itree_inv_end(subscriptions);
285 }
286 
287 /*
288  * This function can't run concurrently against mmu_notifier_register
289  * because mm->mm_users > 0 during mmu_notifier_register and exit_mmap
290  * runs with mm_users == 0. Other tasks may still invoke mmu notifiers
291  * in parallel despite there being no task using this mm any more,
292  * through the vmas outside of the exit_mmap context, such as with
293  * vmtruncate. This serializes against mmu_notifier_unregister with
294  * the notifier_subscriptions->lock in addition to SRCU and it serializes
295  * against the other mmu notifiers with SRCU. struct mmu_notifier_subscriptions
296  * can't go away from under us as exit_mmap holds an mm_count pin
297  * itself.
298  */
299 static void mn_hlist_release(struct mmu_notifier_subscriptions *subscriptions,
300 			     struct mm_struct *mm)
301 {
302 	struct mmu_notifier *subscription;
303 	int id;
304 
305 	/*
306 	 * SRCU here will block mmu_notifier_unregister until
307 	 * ->release returns.
308 	 */
309 	id = srcu_read_lock(&srcu);
310 	hlist_for_each_entry_rcu(subscription, &subscriptions->list, hlist,
311 				 srcu_read_lock_held(&srcu))
312 		/*
313 		 * If ->release runs before mmu_notifier_unregister it must be
314 		 * handled, as it's the only way for the driver to flush all
315 		 * existing sptes and stop the driver from establishing any more
316 		 * sptes before all the pages in the mm are freed.
317 		 */
318 		if (subscription->ops->release)
319 			subscription->ops->release(subscription, mm);
320 
321 	spin_lock(&subscriptions->lock);
322 	while (unlikely(!hlist_empty(&subscriptions->list))) {
323 		subscription = hlist_entry(subscriptions->list.first,
324 					   struct mmu_notifier, hlist);
325 		/*
326 		 * We arrived before mmu_notifier_unregister so
327 		 * mmu_notifier_unregister will do nothing other than to wait
328 		 * for ->release to finish and for mmu_notifier_unregister to
329 		 * return.
330 		 */
331 		hlist_del_init_rcu(&subscription->hlist);
332 	}
333 	spin_unlock(&subscriptions->lock);
334 	srcu_read_unlock(&srcu, id);
335 
336 	/*
337 	 * synchronize_srcu here prevents mmu_notifier_release from returning to
338 	 * exit_mmap (which would proceed with freeing all pages in the mm)
339 	 * until the ->release method returns, if it was invoked by
340 	 * mmu_notifier_unregister.
341 	 *
342 	 * The notifier_subscriptions can't go away from under us because
343 	 * one mm_count is held by exit_mmap.
344 	 */
345 	synchronize_srcu(&srcu);
346 }
347 
348 void __mmu_notifier_release(struct mm_struct *mm)
349 {
350 	struct mmu_notifier_subscriptions *subscriptions =
351 		mm->notifier_subscriptions;
352 
353 	if (subscriptions->has_itree)
354 		mn_itree_release(subscriptions, mm);
355 
356 	if (!hlist_empty(&subscriptions->list))
357 		mn_hlist_release(subscriptions, mm);
358 }
359 
360 /*
361  * If no young bitflag is supported by the hardware, ->clear_flush_young can
362  * unmap the address and return 1 or 0 depending if the mapping previously
363  * existed or not.
364  */
365 int __mmu_notifier_clear_flush_young(struct mm_struct *mm,
366 					unsigned long start,
367 					unsigned long end)
368 {
369 	struct mmu_notifier *subscription;
370 	int young = 0, id;
371 
372 	id = srcu_read_lock(&srcu);
373 	hlist_for_each_entry_rcu(subscription,
374 				 &mm->notifier_subscriptions->list, hlist,
375 				 srcu_read_lock_held(&srcu)) {
376 		if (subscription->ops->clear_flush_young)
377 			young |= subscription->ops->clear_flush_young(
378 				subscription, mm, start, end);
379 	}
380 	srcu_read_unlock(&srcu, id);
381 
382 	return young;
383 }
384 
385 int __mmu_notifier_clear_young(struct mm_struct *mm,
386 			       unsigned long start,
387 			       unsigned long end)
388 {
389 	struct mmu_notifier *subscription;
390 	int young = 0, id;
391 
392 	id = srcu_read_lock(&srcu);
393 	hlist_for_each_entry_rcu(subscription,
394 				 &mm->notifier_subscriptions->list, hlist,
395 				 srcu_read_lock_held(&srcu)) {
396 		if (subscription->ops->clear_young)
397 			young |= subscription->ops->clear_young(subscription,
398 								mm, start, end);
399 	}
400 	srcu_read_unlock(&srcu, id);
401 
402 	return young;
403 }
404 
405 int __mmu_notifier_test_young(struct mm_struct *mm,
406 			      unsigned long address)
407 {
408 	struct mmu_notifier *subscription;
409 	int young = 0, id;
410 
411 	id = srcu_read_lock(&srcu);
412 	hlist_for_each_entry_rcu(subscription,
413 				 &mm->notifier_subscriptions->list, hlist,
414 				 srcu_read_lock_held(&srcu)) {
415 		if (subscription->ops->test_young) {
416 			young = subscription->ops->test_young(subscription, mm,
417 							      address);
418 			if (young)
419 				break;
420 		}
421 	}
422 	srcu_read_unlock(&srcu, id);
423 
424 	return young;
425 }
426 
427 static int mn_itree_invalidate(struct mmu_notifier_subscriptions *subscriptions,
428 			       const struct mmu_notifier_range *range)
429 {
430 	struct mmu_interval_notifier *interval_sub;
431 	unsigned long cur_seq;
432 
433 	for (interval_sub =
434 		     mn_itree_inv_start_range(subscriptions, range, &cur_seq);
435 	     interval_sub;
436 	     interval_sub = mn_itree_inv_next(interval_sub, range)) {
437 		bool ret;
438 
439 		ret = interval_sub->ops->invalidate(interval_sub, range,
440 						    cur_seq);
441 		if (!ret) {
442 			if (WARN_ON(mmu_notifier_range_blockable(range)))
443 				continue;
444 			goto out_would_block;
445 		}
446 	}
447 	return 0;
448 
449 out_would_block:
450 	/*
451 	 * On -EAGAIN the non-blocking caller is not allowed to call
452 	 * invalidate_range_end()
453 	 */
454 	mn_itree_inv_end(subscriptions);
455 	return -EAGAIN;
456 }
457 
458 static int mn_hlist_invalidate_range_start(
459 	struct mmu_notifier_subscriptions *subscriptions,
460 	struct mmu_notifier_range *range)
461 {
462 	struct mmu_notifier *subscription;
463 	int ret = 0;
464 	int id;
465 
466 	id = srcu_read_lock(&srcu);
467 	hlist_for_each_entry_rcu(subscription, &subscriptions->list, hlist,
468 				 srcu_read_lock_held(&srcu)) {
469 		const struct mmu_notifier_ops *ops = subscription->ops;
470 
471 		if (ops->invalidate_range_start) {
472 			int _ret;
473 
474 			if (!mmu_notifier_range_blockable(range))
475 				non_block_start();
476 			_ret = ops->invalidate_range_start(subscription, range);
477 			if (!mmu_notifier_range_blockable(range))
478 				non_block_end();
479 			if (_ret) {
480 				pr_info("%pS callback failed with %d in %sblockable context.\n",
481 					ops->invalidate_range_start, _ret,
482 					!mmu_notifier_range_blockable(range) ?
483 						"non-" :
484 						"");
485 				WARN_ON(mmu_notifier_range_blockable(range) ||
486 					_ret != -EAGAIN);
487 				/*
488 				 * We call all the notifiers on any EAGAIN,
489 				 * there is no way for a notifier to know if
490 				 * its start method failed, thus a start that
491 				 * does EAGAIN can't also do end.
492 				 */
493 				WARN_ON(ops->invalidate_range_end);
494 				ret = _ret;
495 			}
496 		}
497 	}
498 
499 	if (ret) {
500 		/*
501 		 * Must be non-blocking to get here.  If there are multiple
502 		 * notifiers and one or more failed start, any that succeeded
503 		 * start are expecting their end to be called.  Do so now.
504 		 */
505 		hlist_for_each_entry_rcu(subscription, &subscriptions->list,
506 					 hlist, srcu_read_lock_held(&srcu)) {
507 			if (!subscription->ops->invalidate_range_end)
508 				continue;
509 
510 			subscription->ops->invalidate_range_end(subscription,
511 								range);
512 		}
513 	}
514 	srcu_read_unlock(&srcu, id);
515 
516 	return ret;
517 }
518 
519 int __mmu_notifier_invalidate_range_start(struct mmu_notifier_range *range)
520 {
521 	struct mmu_notifier_subscriptions *subscriptions =
522 		range->mm->notifier_subscriptions;
523 	int ret;
524 
525 	if (subscriptions->has_itree) {
526 		ret = mn_itree_invalidate(subscriptions, range);
527 		if (ret)
528 			return ret;
529 	}
530 	if (!hlist_empty(&subscriptions->list))
531 		return mn_hlist_invalidate_range_start(subscriptions, range);
532 	return 0;
533 }
534 
535 static void
536 mn_hlist_invalidate_end(struct mmu_notifier_subscriptions *subscriptions,
537 			struct mmu_notifier_range *range)
538 {
539 	struct mmu_notifier *subscription;
540 	int id;
541 
542 	id = srcu_read_lock(&srcu);
543 	hlist_for_each_entry_rcu(subscription, &subscriptions->list, hlist,
544 				 srcu_read_lock_held(&srcu)) {
545 		if (subscription->ops->invalidate_range_end) {
546 			if (!mmu_notifier_range_blockable(range))
547 				non_block_start();
548 			subscription->ops->invalidate_range_end(subscription,
549 								range);
550 			if (!mmu_notifier_range_blockable(range))
551 				non_block_end();
552 		}
553 	}
554 	srcu_read_unlock(&srcu, id);
555 }
556 
557 void __mmu_notifier_invalidate_range_end(struct mmu_notifier_range *range)
558 {
559 	struct mmu_notifier_subscriptions *subscriptions =
560 		range->mm->notifier_subscriptions;
561 
562 	lock_map_acquire(&__mmu_notifier_invalidate_range_start_map);
563 	if (subscriptions->has_itree)
564 		mn_itree_inv_end(subscriptions);
565 
566 	if (!hlist_empty(&subscriptions->list))
567 		mn_hlist_invalidate_end(subscriptions, range);
568 	lock_map_release(&__mmu_notifier_invalidate_range_start_map);
569 }
570 
571 void __mmu_notifier_arch_invalidate_secondary_tlbs(struct mm_struct *mm,
572 					unsigned long start, unsigned long end)
573 {
574 	struct mmu_notifier *subscription;
575 	int id;
576 
577 	id = srcu_read_lock(&srcu);
578 	hlist_for_each_entry_rcu(subscription,
579 				 &mm->notifier_subscriptions->list, hlist,
580 				 srcu_read_lock_held(&srcu)) {
581 		if (subscription->ops->arch_invalidate_secondary_tlbs)
582 			subscription->ops->arch_invalidate_secondary_tlbs(
583 				subscription, mm,
584 				start, end);
585 	}
586 	srcu_read_unlock(&srcu, id);
587 }
588 
589 /*
590  * Same as mmu_notifier_register but here the caller must hold the mmap_lock in
591  * write mode. A NULL mn signals the notifier is being registered for itree
592  * mode.
593  */
594 int __mmu_notifier_register(struct mmu_notifier *subscription,
595 			    struct mm_struct *mm)
596 {
597 	struct mmu_notifier_subscriptions *subscriptions = NULL;
598 	int ret;
599 
600 	mmap_assert_write_locked(mm);
601 	BUG_ON(atomic_read(&mm->mm_users) <= 0);
602 
603 	/*
604 	 * Subsystems should only register for invalidate_secondary_tlbs() or
605 	 * invalidate_range_start()/end() callbacks, not both.
606 	 */
607 	if (WARN_ON_ONCE(subscription &&
608 			 (subscription->ops->arch_invalidate_secondary_tlbs &&
609 			 (subscription->ops->invalidate_range_start ||
610 			  subscription->ops->invalidate_range_end))))
611 		return -EINVAL;
612 
613 	if (!mm->notifier_subscriptions) {
614 		/*
615 		 * kmalloc cannot be called under mm_take_all_locks(), but we
616 		 * know that mm->notifier_subscriptions can't change while we
617 		 * hold the write side of the mmap_lock.
618 		 */
619 		subscriptions = kzalloc(
620 			sizeof(struct mmu_notifier_subscriptions), GFP_KERNEL);
621 		if (!subscriptions)
622 			return -ENOMEM;
623 
624 		INIT_HLIST_HEAD(&subscriptions->list);
625 		spin_lock_init(&subscriptions->lock);
626 		subscriptions->invalidate_seq = 2;
627 		subscriptions->itree = RB_ROOT_CACHED;
628 		init_waitqueue_head(&subscriptions->wq);
629 		INIT_HLIST_HEAD(&subscriptions->deferred_list);
630 	}
631 
632 	ret = mm_take_all_locks(mm);
633 	if (unlikely(ret))
634 		goto out_clean;
635 
636 	/*
637 	 * Serialize the update against mmu_notifier_unregister. A
638 	 * side note: mmu_notifier_release can't run concurrently with
639 	 * us because we hold the mm_users pin (either implicitly as
640 	 * current->mm or explicitly with get_task_mm() or similar).
641 	 * We can't race against any other mmu notifier method either
642 	 * thanks to mm_take_all_locks().
643 	 *
644 	 * release semantics on the initialization of the
645 	 * mmu_notifier_subscriptions's contents are provided for unlocked
646 	 * readers.  acquire can only be used while holding the mmgrab or
647 	 * mmget, and is safe because once created the
648 	 * mmu_notifier_subscriptions is not freed until the mm is destroyed.
649 	 * As above, users holding the mmap_lock or one of the
650 	 * mm_take_all_locks() do not need to use acquire semantics.
651 	 */
652 	if (subscriptions)
653 		smp_store_release(&mm->notifier_subscriptions, subscriptions);
654 
655 	if (subscription) {
656 		/* Pairs with the mmdrop in mmu_notifier_unregister_* */
657 		mmgrab(mm);
658 		subscription->mm = mm;
659 		subscription->users = 1;
660 
661 		spin_lock(&mm->notifier_subscriptions->lock);
662 		hlist_add_head_rcu(&subscription->hlist,
663 				   &mm->notifier_subscriptions->list);
664 		spin_unlock(&mm->notifier_subscriptions->lock);
665 	} else
666 		mm->notifier_subscriptions->has_itree = true;
667 
668 	mm_drop_all_locks(mm);
669 	BUG_ON(atomic_read(&mm->mm_users) <= 0);
670 	return 0;
671 
672 out_clean:
673 	kfree(subscriptions);
674 	return ret;
675 }
676 EXPORT_SYMBOL_GPL(__mmu_notifier_register);
677 
678 /**
679  * mmu_notifier_register - Register a notifier on a mm
680  * @subscription: The notifier to attach
681  * @mm: The mm to attach the notifier to
682  *
683  * Must not hold mmap_lock nor any other VM related lock when calling
684  * this registration function. Must also ensure mm_users can't go down
685  * to zero while this runs to avoid races with mmu_notifier_release,
686  * so mm has to be current->mm or the mm should be pinned safely such
687  * as with get_task_mm(). If the mm is not current->mm, the mm_users
688  * pin should be released by calling mmput after mmu_notifier_register
689  * returns.
690  *
691  * mmu_notifier_unregister() or mmu_notifier_put() must be always called to
692  * unregister the notifier.
693  *
694  * While the caller has a mmu_notifier get the subscription->mm pointer will remain
695  * valid, and can be converted to an active mm pointer via mmget_not_zero().
696  */
697 int mmu_notifier_register(struct mmu_notifier *subscription,
698 			  struct mm_struct *mm)
699 {
700 	int ret;
701 
702 	mmap_write_lock(mm);
703 	ret = __mmu_notifier_register(subscription, mm);
704 	mmap_write_unlock(mm);
705 	return ret;
706 }
707 EXPORT_SYMBOL_GPL(mmu_notifier_register);
708 
709 static struct mmu_notifier *
710 find_get_mmu_notifier(struct mm_struct *mm, const struct mmu_notifier_ops *ops)
711 {
712 	struct mmu_notifier *subscription;
713 
714 	spin_lock(&mm->notifier_subscriptions->lock);
715 	hlist_for_each_entry_rcu(subscription,
716 				 &mm->notifier_subscriptions->list, hlist,
717 				 lockdep_is_held(&mm->notifier_subscriptions->lock)) {
718 		if (subscription->ops != ops)
719 			continue;
720 
721 		if (likely(subscription->users != UINT_MAX))
722 			subscription->users++;
723 		else
724 			subscription = ERR_PTR(-EOVERFLOW);
725 		spin_unlock(&mm->notifier_subscriptions->lock);
726 		return subscription;
727 	}
728 	spin_unlock(&mm->notifier_subscriptions->lock);
729 	return NULL;
730 }
731 
732 /**
733  * mmu_notifier_get_locked - Return the single struct mmu_notifier for
734  *                           the mm & ops
735  * @ops: The operations struct being subscribe with
736  * @mm : The mm to attach notifiers too
737  *
738  * This function either allocates a new mmu_notifier via
739  * ops->alloc_notifier(), or returns an already existing notifier on the
740  * list. The value of the ops pointer is used to determine when two notifiers
741  * are the same.
742  *
743  * Each call to mmu_notifier_get() must be paired with a call to
744  * mmu_notifier_put(). The caller must hold the write side of mm->mmap_lock.
745  *
746  * While the caller has a mmu_notifier get the mm pointer will remain valid,
747  * and can be converted to an active mm pointer via mmget_not_zero().
748  */
749 struct mmu_notifier *mmu_notifier_get_locked(const struct mmu_notifier_ops *ops,
750 					     struct mm_struct *mm)
751 {
752 	struct mmu_notifier *subscription;
753 	int ret;
754 
755 	mmap_assert_write_locked(mm);
756 
757 	if (mm->notifier_subscriptions) {
758 		subscription = find_get_mmu_notifier(mm, ops);
759 		if (subscription)
760 			return subscription;
761 	}
762 
763 	subscription = ops->alloc_notifier(mm);
764 	if (IS_ERR(subscription))
765 		return subscription;
766 	subscription->ops = ops;
767 	ret = __mmu_notifier_register(subscription, mm);
768 	if (ret)
769 		goto out_free;
770 	return subscription;
771 out_free:
772 	subscription->ops->free_notifier(subscription);
773 	return ERR_PTR(ret);
774 }
775 EXPORT_SYMBOL_GPL(mmu_notifier_get_locked);
776 
777 /* this is called after the last mmu_notifier_unregister() returned */
778 void __mmu_notifier_subscriptions_destroy(struct mm_struct *mm)
779 {
780 	BUG_ON(!hlist_empty(&mm->notifier_subscriptions->list));
781 	kfree(mm->notifier_subscriptions);
782 	mm->notifier_subscriptions = LIST_POISON1; /* debug */
783 }
784 
785 /*
786  * This releases the mm_count pin automatically and frees the mm
787  * structure if it was the last user of it. It serializes against
788  * running mmu notifiers with SRCU and against mmu_notifier_unregister
789  * with the unregister lock + SRCU. All sptes must be dropped before
790  * calling mmu_notifier_unregister. ->release or any other notifier
791  * method may be invoked concurrently with mmu_notifier_unregister,
792  * and only after mmu_notifier_unregister returned we're guaranteed
793  * that ->release or any other method can't run anymore.
794  */
795 void mmu_notifier_unregister(struct mmu_notifier *subscription,
796 			     struct mm_struct *mm)
797 {
798 	BUG_ON(atomic_read(&mm->mm_count) <= 0);
799 
800 	if (!hlist_unhashed(&subscription->hlist)) {
801 		/*
802 		 * SRCU here will force exit_mmap to wait for ->release to
803 		 * finish before freeing the pages.
804 		 */
805 		int id;
806 
807 		id = srcu_read_lock(&srcu);
808 		/*
809 		 * exit_mmap will block in mmu_notifier_release to guarantee
810 		 * that ->release is called before freeing the pages.
811 		 */
812 		if (subscription->ops->release)
813 			subscription->ops->release(subscription, mm);
814 		srcu_read_unlock(&srcu, id);
815 
816 		spin_lock(&mm->notifier_subscriptions->lock);
817 		/*
818 		 * Can not use list_del_rcu() since __mmu_notifier_release
819 		 * can delete it before we hold the lock.
820 		 */
821 		hlist_del_init_rcu(&subscription->hlist);
822 		spin_unlock(&mm->notifier_subscriptions->lock);
823 	}
824 
825 	/*
826 	 * Wait for any running method to finish, of course including
827 	 * ->release if it was run by mmu_notifier_release instead of us.
828 	 */
829 	synchronize_srcu(&srcu);
830 
831 	BUG_ON(atomic_read(&mm->mm_count) <= 0);
832 
833 	mmdrop(mm);
834 }
835 EXPORT_SYMBOL_GPL(mmu_notifier_unregister);
836 
837 static void mmu_notifier_free_rcu(struct rcu_head *rcu)
838 {
839 	struct mmu_notifier *subscription =
840 		container_of(rcu, struct mmu_notifier, rcu);
841 	struct mm_struct *mm = subscription->mm;
842 
843 	subscription->ops->free_notifier(subscription);
844 	/* Pairs with the get in __mmu_notifier_register() */
845 	mmdrop(mm);
846 }
847 
848 /**
849  * mmu_notifier_put - Release the reference on the notifier
850  * @subscription: The notifier to act on
851  *
852  * This function must be paired with each mmu_notifier_get(), it releases the
853  * reference obtained by the get. If this is the last reference then process
854  * to free the notifier will be run asynchronously.
855  *
856  * Unlike mmu_notifier_unregister() the get/put flow only calls ops->release
857  * when the mm_struct is destroyed. Instead free_notifier is always called to
858  * release any resources held by the user.
859  *
860  * As ops->release is not guaranteed to be called, the user must ensure that
861  * all sptes are dropped, and no new sptes can be established before
862  * mmu_notifier_put() is called.
863  *
864  * This function can be called from the ops->release callback, however the
865  * caller must still ensure it is called pairwise with mmu_notifier_get().
866  *
867  * Modules calling this function must call mmu_notifier_synchronize() in
868  * their __exit functions to ensure the async work is completed.
869  */
870 void mmu_notifier_put(struct mmu_notifier *subscription)
871 {
872 	struct mm_struct *mm = subscription->mm;
873 
874 	spin_lock(&mm->notifier_subscriptions->lock);
875 	if (WARN_ON(!subscription->users) || --subscription->users)
876 		goto out_unlock;
877 	hlist_del_init_rcu(&subscription->hlist);
878 	spin_unlock(&mm->notifier_subscriptions->lock);
879 
880 	call_srcu(&srcu, &subscription->rcu, mmu_notifier_free_rcu);
881 	return;
882 
883 out_unlock:
884 	spin_unlock(&mm->notifier_subscriptions->lock);
885 }
886 EXPORT_SYMBOL_GPL(mmu_notifier_put);
887 
888 static int __mmu_interval_notifier_insert(
889 	struct mmu_interval_notifier *interval_sub, struct mm_struct *mm,
890 	struct mmu_notifier_subscriptions *subscriptions, unsigned long start,
891 	unsigned long length, const struct mmu_interval_notifier_ops *ops)
892 {
893 	interval_sub->mm = mm;
894 	interval_sub->ops = ops;
895 	RB_CLEAR_NODE(&interval_sub->interval_tree.rb);
896 	interval_sub->interval_tree.start = start;
897 	/*
898 	 * Note that the representation of the intervals in the interval tree
899 	 * considers the ending point as contained in the interval.
900 	 */
901 	if (length == 0 ||
902 	    check_add_overflow(start, length - 1,
903 			       &interval_sub->interval_tree.last))
904 		return -EOVERFLOW;
905 
906 	/* Must call with a mmget() held */
907 	if (WARN_ON(atomic_read(&mm->mm_users) <= 0))
908 		return -EINVAL;
909 
910 	/* pairs with mmdrop in mmu_interval_notifier_remove() */
911 	mmgrab(mm);
912 
913 	/*
914 	 * If some invalidate_range_start/end region is going on in parallel
915 	 * we don't know what VA ranges are affected, so we must assume this
916 	 * new range is included.
917 	 *
918 	 * If the itree is invalidating then we are not allowed to change
919 	 * it. Retrying until invalidation is done is tricky due to the
920 	 * possibility for live lock, instead defer the add to
921 	 * mn_itree_inv_end() so this algorithm is deterministic.
922 	 *
923 	 * In all cases the value for the interval_sub->invalidate_seq should be
924 	 * odd, see mmu_interval_read_begin()
925 	 */
926 	spin_lock(&subscriptions->lock);
927 	if (subscriptions->active_invalidate_ranges) {
928 		if (mn_itree_is_invalidating(subscriptions))
929 			hlist_add_head(&interval_sub->deferred_item,
930 				       &subscriptions->deferred_list);
931 		else {
932 			subscriptions->invalidate_seq |= 1;
933 			interval_tree_insert(&interval_sub->interval_tree,
934 					     &subscriptions->itree);
935 		}
936 		interval_sub->invalidate_seq = subscriptions->invalidate_seq;
937 	} else {
938 		WARN_ON(mn_itree_is_invalidating(subscriptions));
939 		/*
940 		 * The starting seq for a subscription not under invalidation
941 		 * should be odd, not equal to the current invalidate_seq and
942 		 * invalidate_seq should not 'wrap' to the new seq any time
943 		 * soon.
944 		 */
945 		interval_sub->invalidate_seq =
946 			subscriptions->invalidate_seq - 1;
947 		interval_tree_insert(&interval_sub->interval_tree,
948 				     &subscriptions->itree);
949 	}
950 	spin_unlock(&subscriptions->lock);
951 	return 0;
952 }
953 
954 /**
955  * mmu_interval_notifier_insert - Insert an interval notifier
956  * @interval_sub: Interval subscription to register
957  * @start: Starting virtual address to monitor
958  * @length: Length of the range to monitor
959  * @mm: mm_struct to attach to
960  * @ops: Interval notifier operations to be called on matching events
961  *
962  * This function subscribes the interval notifier for notifications from the
963  * mm.  Upon return the ops related to mmu_interval_notifier will be called
964  * whenever an event that intersects with the given range occurs.
965  *
966  * Upon return the range_notifier may not be present in the interval tree yet.
967  * The caller must use the normal interval notifier read flow via
968  * mmu_interval_read_begin() to establish SPTEs for this range.
969  */
970 int mmu_interval_notifier_insert(struct mmu_interval_notifier *interval_sub,
971 				 struct mm_struct *mm, unsigned long start,
972 				 unsigned long length,
973 				 const struct mmu_interval_notifier_ops *ops)
974 {
975 	struct mmu_notifier_subscriptions *subscriptions;
976 	int ret;
977 
978 	might_lock(&mm->mmap_lock);
979 
980 	subscriptions = smp_load_acquire(&mm->notifier_subscriptions);
981 	if (!subscriptions || !subscriptions->has_itree) {
982 		ret = mmu_notifier_register(NULL, mm);
983 		if (ret)
984 			return ret;
985 		subscriptions = mm->notifier_subscriptions;
986 	}
987 	return __mmu_interval_notifier_insert(interval_sub, mm, subscriptions,
988 					      start, length, ops);
989 }
990 EXPORT_SYMBOL_GPL(mmu_interval_notifier_insert);
991 
992 int mmu_interval_notifier_insert_locked(
993 	struct mmu_interval_notifier *interval_sub, struct mm_struct *mm,
994 	unsigned long start, unsigned long length,
995 	const struct mmu_interval_notifier_ops *ops)
996 {
997 	struct mmu_notifier_subscriptions *subscriptions =
998 		mm->notifier_subscriptions;
999 	int ret;
1000 
1001 	mmap_assert_write_locked(mm);
1002 
1003 	if (!subscriptions || !subscriptions->has_itree) {
1004 		ret = __mmu_notifier_register(NULL, mm);
1005 		if (ret)
1006 			return ret;
1007 		subscriptions = mm->notifier_subscriptions;
1008 	}
1009 	return __mmu_interval_notifier_insert(interval_sub, mm, subscriptions,
1010 					      start, length, ops);
1011 }
1012 EXPORT_SYMBOL_GPL(mmu_interval_notifier_insert_locked);
1013 
1014 static bool
1015 mmu_interval_seq_released(struct mmu_notifier_subscriptions *subscriptions,
1016 			  unsigned long seq)
1017 {
1018 	bool ret;
1019 
1020 	spin_lock(&subscriptions->lock);
1021 	ret = subscriptions->invalidate_seq != seq;
1022 	spin_unlock(&subscriptions->lock);
1023 	return ret;
1024 }
1025 
1026 /**
1027  * mmu_interval_notifier_remove - Remove a interval notifier
1028  * @interval_sub: Interval subscription to unregister
1029  *
1030  * This function must be paired with mmu_interval_notifier_insert(). It cannot
1031  * be called from any ops callback.
1032  *
1033  * Once this returns ops callbacks are no longer running on other CPUs and
1034  * will not be called in future.
1035  */
1036 void mmu_interval_notifier_remove(struct mmu_interval_notifier *interval_sub)
1037 {
1038 	struct mm_struct *mm = interval_sub->mm;
1039 	struct mmu_notifier_subscriptions *subscriptions =
1040 		mm->notifier_subscriptions;
1041 	unsigned long seq = 0;
1042 
1043 	might_sleep();
1044 
1045 	spin_lock(&subscriptions->lock);
1046 	if (mn_itree_is_invalidating(subscriptions)) {
1047 		/*
1048 		 * remove is being called after insert put this on the
1049 		 * deferred list, but before the deferred list was processed.
1050 		 */
1051 		if (RB_EMPTY_NODE(&interval_sub->interval_tree.rb)) {
1052 			hlist_del(&interval_sub->deferred_item);
1053 		} else {
1054 			hlist_add_head(&interval_sub->deferred_item,
1055 				       &subscriptions->deferred_list);
1056 			seq = subscriptions->invalidate_seq;
1057 		}
1058 	} else {
1059 		WARN_ON(RB_EMPTY_NODE(&interval_sub->interval_tree.rb));
1060 		interval_tree_remove(&interval_sub->interval_tree,
1061 				     &subscriptions->itree);
1062 	}
1063 	spin_unlock(&subscriptions->lock);
1064 
1065 	/*
1066 	 * The possible sleep on progress in the invalidation requires the
1067 	 * caller not hold any locks held by invalidation callbacks.
1068 	 */
1069 	lock_map_acquire(&__mmu_notifier_invalidate_range_start_map);
1070 	lock_map_release(&__mmu_notifier_invalidate_range_start_map);
1071 	if (seq)
1072 		wait_event(subscriptions->wq,
1073 			   mmu_interval_seq_released(subscriptions, seq));
1074 
1075 	/* pairs with mmgrab in mmu_interval_notifier_insert() */
1076 	mmdrop(mm);
1077 }
1078 EXPORT_SYMBOL_GPL(mmu_interval_notifier_remove);
1079 
1080 /**
1081  * mmu_notifier_synchronize - Ensure all mmu_notifiers are freed
1082  *
1083  * This function ensures that all outstanding async SRU work from
1084  * mmu_notifier_put() is completed. After it returns any mmu_notifier_ops
1085  * associated with an unused mmu_notifier will no longer be called.
1086  *
1087  * Before using the caller must ensure that all of its mmu_notifiers have been
1088  * fully released via mmu_notifier_put().
1089  *
1090  * Modules using the mmu_notifier_put() API should call this in their __exit
1091  * function to avoid module unloading races.
1092  */
1093 void mmu_notifier_synchronize(void)
1094 {
1095 	synchronize_srcu(&srcu);
1096 }
1097 EXPORT_SYMBOL_GPL(mmu_notifier_synchronize);
1098