xref: /linux/fs/notify/mark.c (revision 7f71507851fc7764b36a3221839607d3a45c2025)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  Copyright (C) 2008 Red Hat, Inc., Eric Paris <eparis@redhat.com>
4  */
5 
6 /*
7  * fsnotify inode mark locking/lifetime/and refcnting
8  *
9  * REFCNT:
10  * The group->recnt and mark->refcnt tell how many "things" in the kernel
11  * currently are referencing the objects. Both kind of objects typically will
12  * live inside the kernel with a refcnt of 2, one for its creation and one for
13  * the reference a group and a mark hold to each other.
14  * If you are holding the appropriate locks, you can take a reference and the
15  * object itself is guaranteed to survive until the reference is dropped.
16  *
17  * LOCKING:
18  * There are 3 locks involved with fsnotify inode marks and they MUST be taken
19  * in order as follows:
20  *
21  * group->mark_mutex
22  * mark->lock
23  * mark->connector->lock
24  *
25  * group->mark_mutex protects the marks_list anchored inside a given group and
26  * each mark is hooked via the g_list.  It also protects the groups private
27  * data (i.e group limits).
28 
29  * mark->lock protects the marks attributes like its masks and flags.
30  * Furthermore it protects the access to a reference of the group that the mark
31  * is assigned to as well as the access to a reference of the inode/vfsmount
32  * that is being watched by the mark.
33  *
34  * mark->connector->lock protects the list of marks anchored inside an
35  * inode / vfsmount and each mark is hooked via the i_list.
36  *
37  * A list of notification marks relating to inode / mnt is contained in
38  * fsnotify_mark_connector. That structure is alive as long as there are any
39  * marks in the list and is also protected by fsnotify_mark_srcu. A mark gets
40  * detached from fsnotify_mark_connector when last reference to the mark is
41  * dropped.  Thus having mark reference is enough to protect mark->connector
42  * pointer and to make sure fsnotify_mark_connector cannot disappear. Also
43  * because we remove mark from g_list before dropping mark reference associated
44  * with that, any mark found through g_list is guaranteed to have
45  * mark->connector set until we drop group->mark_mutex.
46  *
47  * LIFETIME:
48  * Inode marks survive between when they are added to an inode and when their
49  * refcnt==0. Marks are also protected by fsnotify_mark_srcu.
50  *
51  * The inode mark can be cleared for a number of different reasons including:
52  * - The inode is unlinked for the last time.  (fsnotify_inode_remove)
53  * - The inode is being evicted from cache. (fsnotify_inode_delete)
54  * - The fs the inode is on is unmounted.  (fsnotify_inode_delete/fsnotify_unmount_inodes)
55  * - Something explicitly requests that it be removed.  (fsnotify_destroy_mark)
56  * - The fsnotify_group associated with the mark is going away and all such marks
57  *   need to be cleaned up. (fsnotify_clear_marks_by_group)
58  *
59  * This has the very interesting property of being able to run concurrently with
60  * any (or all) other directions.
61  */
62 
63 #include <linux/fs.h>
64 #include <linux/init.h>
65 #include <linux/kernel.h>
66 #include <linux/kthread.h>
67 #include <linux/module.h>
68 #include <linux/mutex.h>
69 #include <linux/slab.h>
70 #include <linux/spinlock.h>
71 #include <linux/srcu.h>
72 #include <linux/ratelimit.h>
73 
74 #include <linux/atomic.h>
75 
76 #include <linux/fsnotify_backend.h>
77 #include "fsnotify.h"
78 
79 #define FSNOTIFY_REAPER_DELAY	(1)	/* 1 jiffy */
80 
81 struct srcu_struct fsnotify_mark_srcu;
82 struct kmem_cache *fsnotify_mark_connector_cachep;
83 
84 static DEFINE_SPINLOCK(destroy_lock);
85 static LIST_HEAD(destroy_list);
86 static struct fsnotify_mark_connector *connector_destroy_list;
87 
88 static void fsnotify_mark_destroy_workfn(struct work_struct *work);
89 static DECLARE_DELAYED_WORK(reaper_work, fsnotify_mark_destroy_workfn);
90 
91 static void fsnotify_connector_destroy_workfn(struct work_struct *work);
92 static DECLARE_WORK(connector_reaper_work, fsnotify_connector_destroy_workfn);
93 
94 void fsnotify_get_mark(struct fsnotify_mark *mark)
95 {
96 	WARN_ON_ONCE(!refcount_read(&mark->refcnt));
97 	refcount_inc(&mark->refcnt);
98 }
99 
100 static fsnotify_connp_t *fsnotify_object_connp(void *obj,
101 				enum fsnotify_obj_type obj_type)
102 {
103 	switch (obj_type) {
104 	case FSNOTIFY_OBJ_TYPE_INODE:
105 		return &((struct inode *)obj)->i_fsnotify_marks;
106 	case FSNOTIFY_OBJ_TYPE_VFSMOUNT:
107 		return &real_mount(obj)->mnt_fsnotify_marks;
108 	case FSNOTIFY_OBJ_TYPE_SB:
109 		return fsnotify_sb_marks(obj);
110 	default:
111 		return NULL;
112 	}
113 }
114 
115 static __u32 *fsnotify_conn_mask_p(struct fsnotify_mark_connector *conn)
116 {
117 	if (conn->type == FSNOTIFY_OBJ_TYPE_INODE)
118 		return &fsnotify_conn_inode(conn)->i_fsnotify_mask;
119 	else if (conn->type == FSNOTIFY_OBJ_TYPE_VFSMOUNT)
120 		return &fsnotify_conn_mount(conn)->mnt_fsnotify_mask;
121 	else if (conn->type == FSNOTIFY_OBJ_TYPE_SB)
122 		return &fsnotify_conn_sb(conn)->s_fsnotify_mask;
123 	return NULL;
124 }
125 
126 __u32 fsnotify_conn_mask(struct fsnotify_mark_connector *conn)
127 {
128 	if (WARN_ON(!fsnotify_valid_obj_type(conn->type)))
129 		return 0;
130 
131 	return READ_ONCE(*fsnotify_conn_mask_p(conn));
132 }
133 
134 static void fsnotify_get_sb_watched_objects(struct super_block *sb)
135 {
136 	atomic_long_inc(fsnotify_sb_watched_objects(sb));
137 }
138 
139 static void fsnotify_put_sb_watched_objects(struct super_block *sb)
140 {
141 	atomic_long_t *watched_objects = fsnotify_sb_watched_objects(sb);
142 
143 	/* the superblock can go away after this decrement */
144 	if (atomic_long_dec_and_test(watched_objects))
145 		wake_up_var(watched_objects);
146 }
147 
148 static void fsnotify_get_inode_ref(struct inode *inode)
149 {
150 	ihold(inode);
151 	fsnotify_get_sb_watched_objects(inode->i_sb);
152 }
153 
154 static void fsnotify_put_inode_ref(struct inode *inode)
155 {
156 	/* read ->i_sb before the inode can go away */
157 	struct super_block *sb = inode->i_sb;
158 
159 	iput(inode);
160 	fsnotify_put_sb_watched_objects(sb);
161 }
162 
163 /*
164  * Grab or drop watched objects reference depending on whether the connector
165  * is attached and has any marks attached.
166  */
167 static void fsnotify_update_sb_watchers(struct super_block *sb,
168 					struct fsnotify_mark_connector *conn)
169 {
170 	struct fsnotify_sb_info *sbinfo = fsnotify_sb_info(sb);
171 	bool is_watched = conn->flags & FSNOTIFY_CONN_FLAG_IS_WATCHED;
172 	struct fsnotify_mark *first_mark = NULL;
173 	unsigned int highest_prio = 0;
174 
175 	if (conn->obj)
176 		first_mark = hlist_entry_safe(conn->list.first,
177 					      struct fsnotify_mark, obj_list);
178 	if (first_mark)
179 		highest_prio = first_mark->group->priority;
180 	if (WARN_ON(highest_prio >= __FSNOTIFY_PRIO_NUM))
181 		highest_prio = 0;
182 
183 	/*
184 	 * If the highest priority of group watching this object is prio,
185 	 * then watched object has a reference on counters [0..prio].
186 	 * Update priority >= 1 watched objects counters.
187 	 */
188 	for (unsigned int p = conn->prio + 1; p <= highest_prio; p++)
189 		atomic_long_inc(&sbinfo->watched_objects[p]);
190 	for (unsigned int p = conn->prio; p > highest_prio; p--)
191 		atomic_long_dec(&sbinfo->watched_objects[p]);
192 	conn->prio = highest_prio;
193 
194 	/* Update priority >= 0 (a.k.a total) watched objects counter */
195 	BUILD_BUG_ON(FSNOTIFY_PRIO_NORMAL != 0);
196 	if (first_mark && !is_watched) {
197 		conn->flags |= FSNOTIFY_CONN_FLAG_IS_WATCHED;
198 		fsnotify_get_sb_watched_objects(sb);
199 	} else if (!first_mark && is_watched) {
200 		conn->flags &= ~FSNOTIFY_CONN_FLAG_IS_WATCHED;
201 		fsnotify_put_sb_watched_objects(sb);
202 	}
203 }
204 
205 /*
206  * Grab or drop inode reference for the connector if needed.
207  *
208  * When it's time to drop the reference, we only clear the HAS_IREF flag and
209  * return the inode object. fsnotify_drop_object() will be resonsible for doing
210  * iput() outside of spinlocks. This happens when last mark that wanted iref is
211  * detached.
212  */
213 static struct inode *fsnotify_update_iref(struct fsnotify_mark_connector *conn,
214 					  bool want_iref)
215 {
216 	bool has_iref = conn->flags & FSNOTIFY_CONN_FLAG_HAS_IREF;
217 	struct inode *inode = NULL;
218 
219 	if (conn->type != FSNOTIFY_OBJ_TYPE_INODE ||
220 	    want_iref == has_iref)
221 		return NULL;
222 
223 	if (want_iref) {
224 		/* Pin inode if any mark wants inode refcount held */
225 		fsnotify_get_inode_ref(fsnotify_conn_inode(conn));
226 		conn->flags |= FSNOTIFY_CONN_FLAG_HAS_IREF;
227 	} else {
228 		/* Unpin inode after detach of last mark that wanted iref */
229 		inode = fsnotify_conn_inode(conn);
230 		conn->flags &= ~FSNOTIFY_CONN_FLAG_HAS_IREF;
231 	}
232 
233 	return inode;
234 }
235 
236 static void *__fsnotify_recalc_mask(struct fsnotify_mark_connector *conn)
237 {
238 	u32 new_mask = 0;
239 	bool want_iref = false;
240 	struct fsnotify_mark *mark;
241 
242 	assert_spin_locked(&conn->lock);
243 	/* We can get detached connector here when inode is getting unlinked. */
244 	if (!fsnotify_valid_obj_type(conn->type))
245 		return NULL;
246 	hlist_for_each_entry(mark, &conn->list, obj_list) {
247 		if (!(mark->flags & FSNOTIFY_MARK_FLAG_ATTACHED))
248 			continue;
249 		new_mask |= fsnotify_calc_mask(mark);
250 		if (conn->type == FSNOTIFY_OBJ_TYPE_INODE &&
251 		    !(mark->flags & FSNOTIFY_MARK_FLAG_NO_IREF))
252 			want_iref = true;
253 	}
254 	/*
255 	 * We use WRITE_ONCE() to prevent silly compiler optimizations from
256 	 * confusing readers not holding conn->lock with partial updates.
257 	 */
258 	WRITE_ONCE(*fsnotify_conn_mask_p(conn), new_mask);
259 
260 	return fsnotify_update_iref(conn, want_iref);
261 }
262 
263 static bool fsnotify_conn_watches_children(
264 					struct fsnotify_mark_connector *conn)
265 {
266 	if (conn->type != FSNOTIFY_OBJ_TYPE_INODE)
267 		return false;
268 
269 	return fsnotify_inode_watches_children(fsnotify_conn_inode(conn));
270 }
271 
272 static void fsnotify_conn_set_children_dentry_flags(
273 					struct fsnotify_mark_connector *conn)
274 {
275 	if (conn->type != FSNOTIFY_OBJ_TYPE_INODE)
276 		return;
277 
278 	fsnotify_set_children_dentry_flags(fsnotify_conn_inode(conn));
279 }
280 
281 /*
282  * Calculate mask of events for a list of marks. The caller must make sure
283  * connector and connector->obj cannot disappear under us.  Callers achieve
284  * this by holding a mark->lock or mark->group->mark_mutex for a mark on this
285  * list.
286  */
287 void fsnotify_recalc_mask(struct fsnotify_mark_connector *conn)
288 {
289 	bool update_children;
290 
291 	if (!conn)
292 		return;
293 
294 	spin_lock(&conn->lock);
295 	update_children = !fsnotify_conn_watches_children(conn);
296 	__fsnotify_recalc_mask(conn);
297 	update_children &= fsnotify_conn_watches_children(conn);
298 	spin_unlock(&conn->lock);
299 	/*
300 	 * Set children's PARENT_WATCHED flags only if parent started watching.
301 	 * When parent stops watching, we clear false positive PARENT_WATCHED
302 	 * flags lazily in __fsnotify_parent().
303 	 */
304 	if (update_children)
305 		fsnotify_conn_set_children_dentry_flags(conn);
306 }
307 
308 /* Free all connectors queued for freeing once SRCU period ends */
309 static void fsnotify_connector_destroy_workfn(struct work_struct *work)
310 {
311 	struct fsnotify_mark_connector *conn, *free;
312 
313 	spin_lock(&destroy_lock);
314 	conn = connector_destroy_list;
315 	connector_destroy_list = NULL;
316 	spin_unlock(&destroy_lock);
317 
318 	synchronize_srcu(&fsnotify_mark_srcu);
319 	while (conn) {
320 		free = conn;
321 		conn = conn->destroy_next;
322 		kmem_cache_free(fsnotify_mark_connector_cachep, free);
323 	}
324 }
325 
326 static void *fsnotify_detach_connector_from_object(
327 					struct fsnotify_mark_connector *conn,
328 					unsigned int *type)
329 {
330 	fsnotify_connp_t *connp = fsnotify_object_connp(conn->obj, conn->type);
331 	struct super_block *sb = fsnotify_connector_sb(conn);
332 	struct inode *inode = NULL;
333 
334 	*type = conn->type;
335 	if (conn->type == FSNOTIFY_OBJ_TYPE_DETACHED)
336 		return NULL;
337 
338 	if (conn->type == FSNOTIFY_OBJ_TYPE_INODE) {
339 		inode = fsnotify_conn_inode(conn);
340 		inode->i_fsnotify_mask = 0;
341 
342 		/* Unpin inode when detaching from connector */
343 		if (!(conn->flags & FSNOTIFY_CONN_FLAG_HAS_IREF))
344 			inode = NULL;
345 	} else if (conn->type == FSNOTIFY_OBJ_TYPE_VFSMOUNT) {
346 		fsnotify_conn_mount(conn)->mnt_fsnotify_mask = 0;
347 	} else if (conn->type == FSNOTIFY_OBJ_TYPE_SB) {
348 		fsnotify_conn_sb(conn)->s_fsnotify_mask = 0;
349 	}
350 
351 	rcu_assign_pointer(*connp, NULL);
352 	conn->obj = NULL;
353 	conn->type = FSNOTIFY_OBJ_TYPE_DETACHED;
354 	fsnotify_update_sb_watchers(sb, conn);
355 
356 	return inode;
357 }
358 
359 static void fsnotify_final_mark_destroy(struct fsnotify_mark *mark)
360 {
361 	struct fsnotify_group *group = mark->group;
362 
363 	if (WARN_ON_ONCE(!group))
364 		return;
365 	group->ops->free_mark(mark);
366 	fsnotify_put_group(group);
367 }
368 
369 /* Drop object reference originally held by a connector */
370 static void fsnotify_drop_object(unsigned int type, void *objp)
371 {
372 	if (!objp)
373 		return;
374 	/* Currently only inode references are passed to be dropped */
375 	if (WARN_ON_ONCE(type != FSNOTIFY_OBJ_TYPE_INODE))
376 		return;
377 	fsnotify_put_inode_ref(objp);
378 }
379 
380 void fsnotify_put_mark(struct fsnotify_mark *mark)
381 {
382 	struct fsnotify_mark_connector *conn = READ_ONCE(mark->connector);
383 	void *objp = NULL;
384 	unsigned int type = FSNOTIFY_OBJ_TYPE_DETACHED;
385 	bool free_conn = false;
386 
387 	/* Catch marks that were actually never attached to object */
388 	if (!conn) {
389 		if (refcount_dec_and_test(&mark->refcnt))
390 			fsnotify_final_mark_destroy(mark);
391 		return;
392 	}
393 
394 	/*
395 	 * We have to be careful so that traversals of obj_list under lock can
396 	 * safely grab mark reference.
397 	 */
398 	if (!refcount_dec_and_lock(&mark->refcnt, &conn->lock))
399 		return;
400 
401 	hlist_del_init_rcu(&mark->obj_list);
402 	if (hlist_empty(&conn->list)) {
403 		objp = fsnotify_detach_connector_from_object(conn, &type);
404 		free_conn = true;
405 	} else {
406 		struct super_block *sb = fsnotify_connector_sb(conn);
407 
408 		/* Update watched objects after detaching mark */
409 		if (sb)
410 			fsnotify_update_sb_watchers(sb, conn);
411 		objp = __fsnotify_recalc_mask(conn);
412 		type = conn->type;
413 	}
414 	WRITE_ONCE(mark->connector, NULL);
415 	spin_unlock(&conn->lock);
416 
417 	fsnotify_drop_object(type, objp);
418 
419 	if (free_conn) {
420 		spin_lock(&destroy_lock);
421 		conn->destroy_next = connector_destroy_list;
422 		connector_destroy_list = conn;
423 		spin_unlock(&destroy_lock);
424 		queue_work(system_unbound_wq, &connector_reaper_work);
425 	}
426 	/*
427 	 * Note that we didn't update flags telling whether inode cares about
428 	 * what's happening with children. We update these flags from
429 	 * __fsnotify_parent() lazily when next event happens on one of our
430 	 * children.
431 	 */
432 	spin_lock(&destroy_lock);
433 	list_add(&mark->g_list, &destroy_list);
434 	spin_unlock(&destroy_lock);
435 	queue_delayed_work(system_unbound_wq, &reaper_work,
436 			   FSNOTIFY_REAPER_DELAY);
437 }
438 EXPORT_SYMBOL_GPL(fsnotify_put_mark);
439 
440 /*
441  * Get mark reference when we found the mark via lockless traversal of object
442  * list. Mark can be already removed from the list by now and on its way to be
443  * destroyed once SRCU period ends.
444  *
445  * Also pin the group so it doesn't disappear under us.
446  */
447 static bool fsnotify_get_mark_safe(struct fsnotify_mark *mark)
448 {
449 	if (!mark)
450 		return true;
451 
452 	if (refcount_inc_not_zero(&mark->refcnt)) {
453 		spin_lock(&mark->lock);
454 		if (mark->flags & FSNOTIFY_MARK_FLAG_ATTACHED) {
455 			/* mark is attached, group is still alive then */
456 			atomic_inc(&mark->group->user_waits);
457 			spin_unlock(&mark->lock);
458 			return true;
459 		}
460 		spin_unlock(&mark->lock);
461 		fsnotify_put_mark(mark);
462 	}
463 	return false;
464 }
465 
466 /*
467  * Puts marks and wakes up group destruction if necessary.
468  *
469  * Pairs with fsnotify_get_mark_safe()
470  */
471 static void fsnotify_put_mark_wake(struct fsnotify_mark *mark)
472 {
473 	if (mark) {
474 		struct fsnotify_group *group = mark->group;
475 
476 		fsnotify_put_mark(mark);
477 		/*
478 		 * We abuse notification_waitq on group shutdown for waiting for
479 		 * all marks pinned when waiting for userspace.
480 		 */
481 		if (atomic_dec_and_test(&group->user_waits) && group->shutdown)
482 			wake_up(&group->notification_waitq);
483 	}
484 }
485 
486 bool fsnotify_prepare_user_wait(struct fsnotify_iter_info *iter_info)
487 	__releases(&fsnotify_mark_srcu)
488 {
489 	int type;
490 
491 	fsnotify_foreach_iter_type(type) {
492 		/* This can fail if mark is being removed */
493 		if (!fsnotify_get_mark_safe(iter_info->marks[type])) {
494 			__release(&fsnotify_mark_srcu);
495 			goto fail;
496 		}
497 	}
498 
499 	/*
500 	 * Now that both marks are pinned by refcount in the inode / vfsmount
501 	 * lists, we can drop SRCU lock, and safely resume the list iteration
502 	 * once userspace returns.
503 	 */
504 	srcu_read_unlock(&fsnotify_mark_srcu, iter_info->srcu_idx);
505 
506 	return true;
507 
508 fail:
509 	for (type--; type >= 0; type--)
510 		fsnotify_put_mark_wake(iter_info->marks[type]);
511 	return false;
512 }
513 
514 void fsnotify_finish_user_wait(struct fsnotify_iter_info *iter_info)
515 	__acquires(&fsnotify_mark_srcu)
516 {
517 	int type;
518 
519 	iter_info->srcu_idx = srcu_read_lock(&fsnotify_mark_srcu);
520 	fsnotify_foreach_iter_type(type)
521 		fsnotify_put_mark_wake(iter_info->marks[type]);
522 }
523 
524 /*
525  * Mark mark as detached, remove it from group list. Mark still stays in object
526  * list until its last reference is dropped. Note that we rely on mark being
527  * removed from group list before corresponding reference to it is dropped. In
528  * particular we rely on mark->connector being valid while we hold
529  * group->mark_mutex if we found the mark through g_list.
530  *
531  * Must be called with group->mark_mutex held. The caller must either hold
532  * reference to the mark or be protected by fsnotify_mark_srcu.
533  */
534 void fsnotify_detach_mark(struct fsnotify_mark *mark)
535 {
536 	fsnotify_group_assert_locked(mark->group);
537 	WARN_ON_ONCE(!srcu_read_lock_held(&fsnotify_mark_srcu) &&
538 		     refcount_read(&mark->refcnt) < 1 +
539 			!!(mark->flags & FSNOTIFY_MARK_FLAG_ATTACHED));
540 
541 	spin_lock(&mark->lock);
542 	/* something else already called this function on this mark */
543 	if (!(mark->flags & FSNOTIFY_MARK_FLAG_ATTACHED)) {
544 		spin_unlock(&mark->lock);
545 		return;
546 	}
547 	mark->flags &= ~FSNOTIFY_MARK_FLAG_ATTACHED;
548 	list_del_init(&mark->g_list);
549 	spin_unlock(&mark->lock);
550 
551 	/* Drop mark reference acquired in fsnotify_add_mark_locked() */
552 	fsnotify_put_mark(mark);
553 }
554 
555 /*
556  * Free fsnotify mark. The mark is actually only marked as being freed.  The
557  * freeing is actually happening only once last reference to the mark is
558  * dropped from a workqueue which first waits for srcu period end.
559  *
560  * Caller must have a reference to the mark or be protected by
561  * fsnotify_mark_srcu.
562  */
563 void fsnotify_free_mark(struct fsnotify_mark *mark)
564 {
565 	struct fsnotify_group *group = mark->group;
566 
567 	spin_lock(&mark->lock);
568 	/* something else already called this function on this mark */
569 	if (!(mark->flags & FSNOTIFY_MARK_FLAG_ALIVE)) {
570 		spin_unlock(&mark->lock);
571 		return;
572 	}
573 	mark->flags &= ~FSNOTIFY_MARK_FLAG_ALIVE;
574 	spin_unlock(&mark->lock);
575 
576 	/*
577 	 * Some groups like to know that marks are being freed.  This is a
578 	 * callback to the group function to let it know that this mark
579 	 * is being freed.
580 	 */
581 	if (group->ops->freeing_mark)
582 		group->ops->freeing_mark(mark, group);
583 }
584 
585 void fsnotify_destroy_mark(struct fsnotify_mark *mark,
586 			   struct fsnotify_group *group)
587 {
588 	fsnotify_group_lock(group);
589 	fsnotify_detach_mark(mark);
590 	fsnotify_group_unlock(group);
591 	fsnotify_free_mark(mark);
592 }
593 EXPORT_SYMBOL_GPL(fsnotify_destroy_mark);
594 
595 /*
596  * Sorting function for lists of fsnotify marks.
597  *
598  * Fanotify supports different notification classes (reflected as priority of
599  * notification group). Events shall be passed to notification groups in
600  * decreasing priority order. To achieve this marks in notification lists for
601  * inodes and vfsmounts are sorted so that priorities of corresponding groups
602  * are descending.
603  *
604  * Furthermore correct handling of the ignore mask requires processing inode
605  * and vfsmount marks of each group together. Using the group address as
606  * further sort criterion provides a unique sorting order and thus we can
607  * merge inode and vfsmount lists of marks in linear time and find groups
608  * present in both lists.
609  *
610  * A return value of 1 signifies that b has priority over a.
611  * A return value of 0 signifies that the two marks have to be handled together.
612  * A return value of -1 signifies that a has priority over b.
613  */
614 int fsnotify_compare_groups(struct fsnotify_group *a, struct fsnotify_group *b)
615 {
616 	if (a == b)
617 		return 0;
618 	if (!a)
619 		return 1;
620 	if (!b)
621 		return -1;
622 	if (a->priority < b->priority)
623 		return 1;
624 	if (a->priority > b->priority)
625 		return -1;
626 	if (a < b)
627 		return 1;
628 	return -1;
629 }
630 
631 static int fsnotify_attach_info_to_sb(struct super_block *sb)
632 {
633 	struct fsnotify_sb_info *sbinfo;
634 
635 	/* sb info is freed on fsnotify_sb_delete() */
636 	sbinfo = kzalloc(sizeof(*sbinfo), GFP_KERNEL);
637 	if (!sbinfo)
638 		return -ENOMEM;
639 
640 	/*
641 	 * cmpxchg() provides the barrier so that callers of fsnotify_sb_info()
642 	 * will observe an initialized structure
643 	 */
644 	if (cmpxchg(&sb->s_fsnotify_info, NULL, sbinfo)) {
645 		/* Someone else created sbinfo for us */
646 		kfree(sbinfo);
647 	}
648 	return 0;
649 }
650 
651 static int fsnotify_attach_connector_to_object(fsnotify_connp_t *connp,
652 					       void *obj, unsigned int obj_type)
653 {
654 	struct fsnotify_mark_connector *conn;
655 
656 	conn = kmem_cache_alloc(fsnotify_mark_connector_cachep, GFP_KERNEL);
657 	if (!conn)
658 		return -ENOMEM;
659 	spin_lock_init(&conn->lock);
660 	INIT_HLIST_HEAD(&conn->list);
661 	conn->flags = 0;
662 	conn->prio = 0;
663 	conn->type = obj_type;
664 	conn->obj = obj;
665 
666 	/*
667 	 * cmpxchg() provides the barrier so that readers of *connp can see
668 	 * only initialized structure
669 	 */
670 	if (cmpxchg(connp, NULL, conn)) {
671 		/* Someone else created list structure for us */
672 		kmem_cache_free(fsnotify_mark_connector_cachep, conn);
673 	}
674 	return 0;
675 }
676 
677 /*
678  * Get mark connector, make sure it is alive and return with its lock held.
679  * This is for users that get connector pointer from inode or mount. Users that
680  * hold reference to a mark on the list may directly lock connector->lock as
681  * they are sure list cannot go away under them.
682  */
683 static struct fsnotify_mark_connector *fsnotify_grab_connector(
684 						fsnotify_connp_t *connp)
685 {
686 	struct fsnotify_mark_connector *conn;
687 	int idx;
688 
689 	idx = srcu_read_lock(&fsnotify_mark_srcu);
690 	conn = srcu_dereference(*connp, &fsnotify_mark_srcu);
691 	if (!conn)
692 		goto out;
693 	spin_lock(&conn->lock);
694 	if (conn->type == FSNOTIFY_OBJ_TYPE_DETACHED) {
695 		spin_unlock(&conn->lock);
696 		srcu_read_unlock(&fsnotify_mark_srcu, idx);
697 		return NULL;
698 	}
699 out:
700 	srcu_read_unlock(&fsnotify_mark_srcu, idx);
701 	return conn;
702 }
703 
704 /*
705  * Add mark into proper place in given list of marks. These marks may be used
706  * for the fsnotify backend to determine which event types should be delivered
707  * to which group and for which inodes. These marks are ordered according to
708  * priority, highest number first, and then by the group's location in memory.
709  */
710 static int fsnotify_add_mark_list(struct fsnotify_mark *mark, void *obj,
711 				  unsigned int obj_type, int add_flags)
712 {
713 	struct super_block *sb = fsnotify_object_sb(obj, obj_type);
714 	struct fsnotify_mark *lmark, *last = NULL;
715 	struct fsnotify_mark_connector *conn;
716 	fsnotify_connp_t *connp;
717 	int cmp;
718 	int err = 0;
719 
720 	if (WARN_ON(!fsnotify_valid_obj_type(obj_type)))
721 		return -EINVAL;
722 
723 	/*
724 	 * Attach the sb info before attaching a connector to any object on sb.
725 	 * The sb info will remain attached as long as sb lives.
726 	 */
727 	if (!fsnotify_sb_info(sb)) {
728 		err = fsnotify_attach_info_to_sb(sb);
729 		if (err)
730 			return err;
731 	}
732 
733 	connp = fsnotify_object_connp(obj, obj_type);
734 restart:
735 	spin_lock(&mark->lock);
736 	conn = fsnotify_grab_connector(connp);
737 	if (!conn) {
738 		spin_unlock(&mark->lock);
739 		err = fsnotify_attach_connector_to_object(connp, obj, obj_type);
740 		if (err)
741 			return err;
742 		goto restart;
743 	}
744 
745 	/* is mark the first mark? */
746 	if (hlist_empty(&conn->list)) {
747 		hlist_add_head_rcu(&mark->obj_list, &conn->list);
748 		goto added;
749 	}
750 
751 	/* should mark be in the middle of the current list? */
752 	hlist_for_each_entry(lmark, &conn->list, obj_list) {
753 		last = lmark;
754 
755 		if ((lmark->group == mark->group) &&
756 		    (lmark->flags & FSNOTIFY_MARK_FLAG_ATTACHED) &&
757 		    !(mark->group->flags & FSNOTIFY_GROUP_DUPS)) {
758 			err = -EEXIST;
759 			goto out_err;
760 		}
761 
762 		cmp = fsnotify_compare_groups(lmark->group, mark->group);
763 		if (cmp >= 0) {
764 			hlist_add_before_rcu(&mark->obj_list, &lmark->obj_list);
765 			goto added;
766 		}
767 	}
768 
769 	BUG_ON(last == NULL);
770 	/* mark should be the last entry.  last is the current last entry */
771 	hlist_add_behind_rcu(&mark->obj_list, &last->obj_list);
772 added:
773 	fsnotify_update_sb_watchers(sb, conn);
774 	/*
775 	 * Since connector is attached to object using cmpxchg() we are
776 	 * guaranteed that connector initialization is fully visible by anyone
777 	 * seeing mark->connector set.
778 	 */
779 	WRITE_ONCE(mark->connector, conn);
780 out_err:
781 	spin_unlock(&conn->lock);
782 	spin_unlock(&mark->lock);
783 	return err;
784 }
785 
786 /*
787  * Attach an initialized mark to a given group and fs object.
788  * These marks may be used for the fsnotify backend to determine which
789  * event types should be delivered to which group.
790  */
791 int fsnotify_add_mark_locked(struct fsnotify_mark *mark,
792 			     void *obj, unsigned int obj_type,
793 			     int add_flags)
794 {
795 	struct fsnotify_group *group = mark->group;
796 	int ret = 0;
797 
798 	fsnotify_group_assert_locked(group);
799 
800 	/*
801 	 * LOCKING ORDER!!!!
802 	 * group->mark_mutex
803 	 * mark->lock
804 	 * mark->connector->lock
805 	 */
806 	spin_lock(&mark->lock);
807 	mark->flags |= FSNOTIFY_MARK_FLAG_ALIVE | FSNOTIFY_MARK_FLAG_ATTACHED;
808 
809 	list_add(&mark->g_list, &group->marks_list);
810 	fsnotify_get_mark(mark); /* for g_list */
811 	spin_unlock(&mark->lock);
812 
813 	ret = fsnotify_add_mark_list(mark, obj, obj_type, add_flags);
814 	if (ret)
815 		goto err;
816 
817 	fsnotify_recalc_mask(mark->connector);
818 
819 	return ret;
820 err:
821 	spin_lock(&mark->lock);
822 	mark->flags &= ~(FSNOTIFY_MARK_FLAG_ALIVE |
823 			 FSNOTIFY_MARK_FLAG_ATTACHED);
824 	list_del_init(&mark->g_list);
825 	spin_unlock(&mark->lock);
826 
827 	fsnotify_put_mark(mark);
828 	return ret;
829 }
830 
831 int fsnotify_add_mark(struct fsnotify_mark *mark, void *obj,
832 		      unsigned int obj_type, int add_flags)
833 {
834 	int ret;
835 	struct fsnotify_group *group = mark->group;
836 
837 	fsnotify_group_lock(group);
838 	ret = fsnotify_add_mark_locked(mark, obj, obj_type, add_flags);
839 	fsnotify_group_unlock(group);
840 	return ret;
841 }
842 EXPORT_SYMBOL_GPL(fsnotify_add_mark);
843 
844 /*
845  * Given a list of marks, find the mark associated with given group. If found
846  * take a reference to that mark and return it, else return NULL.
847  */
848 struct fsnotify_mark *fsnotify_find_mark(void *obj, unsigned int obj_type,
849 					 struct fsnotify_group *group)
850 {
851 	fsnotify_connp_t *connp = fsnotify_object_connp(obj, obj_type);
852 	struct fsnotify_mark_connector *conn;
853 	struct fsnotify_mark *mark;
854 
855 	if (!connp)
856 		return NULL;
857 
858 	conn = fsnotify_grab_connector(connp);
859 	if (!conn)
860 		return NULL;
861 
862 	hlist_for_each_entry(mark, &conn->list, obj_list) {
863 		if (mark->group == group &&
864 		    (mark->flags & FSNOTIFY_MARK_FLAG_ATTACHED)) {
865 			fsnotify_get_mark(mark);
866 			spin_unlock(&conn->lock);
867 			return mark;
868 		}
869 	}
870 	spin_unlock(&conn->lock);
871 	return NULL;
872 }
873 EXPORT_SYMBOL_GPL(fsnotify_find_mark);
874 
875 /* Clear any marks in a group with given type mask */
876 void fsnotify_clear_marks_by_group(struct fsnotify_group *group,
877 				   unsigned int obj_type)
878 {
879 	struct fsnotify_mark *lmark, *mark;
880 	LIST_HEAD(to_free);
881 	struct list_head *head = &to_free;
882 
883 	/* Skip selection step if we want to clear all marks. */
884 	if (obj_type == FSNOTIFY_OBJ_TYPE_ANY) {
885 		head = &group->marks_list;
886 		goto clear;
887 	}
888 	/*
889 	 * We have to be really careful here. Anytime we drop mark_mutex, e.g.
890 	 * fsnotify_clear_marks_by_inode() can come and free marks. Even in our
891 	 * to_free list so we have to use mark_mutex even when accessing that
892 	 * list. And freeing mark requires us to drop mark_mutex. So we can
893 	 * reliably free only the first mark in the list. That's why we first
894 	 * move marks to free to to_free list in one go and then free marks in
895 	 * to_free list one by one.
896 	 */
897 	fsnotify_group_lock(group);
898 	list_for_each_entry_safe(mark, lmark, &group->marks_list, g_list) {
899 		if (mark->connector->type == obj_type)
900 			list_move(&mark->g_list, &to_free);
901 	}
902 	fsnotify_group_unlock(group);
903 
904 clear:
905 	while (1) {
906 		fsnotify_group_lock(group);
907 		if (list_empty(head)) {
908 			fsnotify_group_unlock(group);
909 			break;
910 		}
911 		mark = list_first_entry(head, struct fsnotify_mark, g_list);
912 		fsnotify_get_mark(mark);
913 		fsnotify_detach_mark(mark);
914 		fsnotify_group_unlock(group);
915 		fsnotify_free_mark(mark);
916 		fsnotify_put_mark(mark);
917 	}
918 }
919 
920 /* Destroy all marks attached to an object via connector */
921 void fsnotify_destroy_marks(fsnotify_connp_t *connp)
922 {
923 	struct fsnotify_mark_connector *conn;
924 	struct fsnotify_mark *mark, *old_mark = NULL;
925 	void *objp;
926 	unsigned int type;
927 
928 	conn = fsnotify_grab_connector(connp);
929 	if (!conn)
930 		return;
931 	/*
932 	 * We have to be careful since we can race with e.g.
933 	 * fsnotify_clear_marks_by_group() and once we drop the conn->lock, the
934 	 * list can get modified. However we are holding mark reference and
935 	 * thus our mark cannot be removed from obj_list so we can continue
936 	 * iteration after regaining conn->lock.
937 	 */
938 	hlist_for_each_entry(mark, &conn->list, obj_list) {
939 		fsnotify_get_mark(mark);
940 		spin_unlock(&conn->lock);
941 		if (old_mark)
942 			fsnotify_put_mark(old_mark);
943 		old_mark = mark;
944 		fsnotify_destroy_mark(mark, mark->group);
945 		spin_lock(&conn->lock);
946 	}
947 	/*
948 	 * Detach list from object now so that we don't pin inode until all
949 	 * mark references get dropped. It would lead to strange results such
950 	 * as delaying inode deletion or blocking unmount.
951 	 */
952 	objp = fsnotify_detach_connector_from_object(conn, &type);
953 	spin_unlock(&conn->lock);
954 	if (old_mark)
955 		fsnotify_put_mark(old_mark);
956 	fsnotify_drop_object(type, objp);
957 }
958 
959 /*
960  * Nothing fancy, just initialize lists and locks and counters.
961  */
962 void fsnotify_init_mark(struct fsnotify_mark *mark,
963 			struct fsnotify_group *group)
964 {
965 	memset(mark, 0, sizeof(*mark));
966 	spin_lock_init(&mark->lock);
967 	refcount_set(&mark->refcnt, 1);
968 	fsnotify_get_group(group);
969 	mark->group = group;
970 	WRITE_ONCE(mark->connector, NULL);
971 }
972 EXPORT_SYMBOL_GPL(fsnotify_init_mark);
973 
974 /*
975  * Destroy all marks in destroy_list, waits for SRCU period to finish before
976  * actually freeing marks.
977  */
978 static void fsnotify_mark_destroy_workfn(struct work_struct *work)
979 {
980 	struct fsnotify_mark *mark, *next;
981 	struct list_head private_destroy_list;
982 
983 	spin_lock(&destroy_lock);
984 	/* exchange the list head */
985 	list_replace_init(&destroy_list, &private_destroy_list);
986 	spin_unlock(&destroy_lock);
987 
988 	synchronize_srcu(&fsnotify_mark_srcu);
989 
990 	list_for_each_entry_safe(mark, next, &private_destroy_list, g_list) {
991 		list_del_init(&mark->g_list);
992 		fsnotify_final_mark_destroy(mark);
993 	}
994 }
995 
996 /* Wait for all marks queued for destruction to be actually destroyed */
997 void fsnotify_wait_marks_destroyed(void)
998 {
999 	flush_delayed_work(&reaper_work);
1000 }
1001 EXPORT_SYMBOL_GPL(fsnotify_wait_marks_destroyed);
1002