xref: /openbmc/linux/fs/notify/fanotify/fanotify.c (revision 78c5335b)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/fanotify.h>
3 #include <linux/fdtable.h>
4 #include <linux/fsnotify_backend.h>
5 #include <linux/init.h>
6 #include <linux/jiffies.h>
7 #include <linux/kernel.h> /* UINT_MAX */
8 #include <linux/mount.h>
9 #include <linux/sched.h>
10 #include <linux/sched/user.h>
11 #include <linux/sched/signal.h>
12 #include <linux/types.h>
13 #include <linux/wait.h>
14 #include <linux/audit.h>
15 #include <linux/sched/mm.h>
16 #include <linux/statfs.h>
17 #include <linux/stringhash.h>
18 
19 #include "fanotify.h"
20 
21 static bool fanotify_path_equal(struct path *p1, struct path *p2)
22 {
23 	return p1->mnt == p2->mnt && p1->dentry == p2->dentry;
24 }
25 
26 static unsigned int fanotify_hash_path(const struct path *path)
27 {
28 	return hash_ptr(path->dentry, FANOTIFY_EVENT_HASH_BITS) ^
29 		hash_ptr(path->mnt, FANOTIFY_EVENT_HASH_BITS);
30 }
31 
32 static inline bool fanotify_fsid_equal(__kernel_fsid_t *fsid1,
33 				       __kernel_fsid_t *fsid2)
34 {
35 	return fsid1->val[0] == fsid2->val[0] && fsid1->val[1] == fsid2->val[1];
36 }
37 
38 static unsigned int fanotify_hash_fsid(__kernel_fsid_t *fsid)
39 {
40 	return hash_32(fsid->val[0], FANOTIFY_EVENT_HASH_BITS) ^
41 		hash_32(fsid->val[1], FANOTIFY_EVENT_HASH_BITS);
42 }
43 
44 static bool fanotify_fh_equal(struct fanotify_fh *fh1,
45 			      struct fanotify_fh *fh2)
46 {
47 	if (fh1->type != fh2->type || fh1->len != fh2->len)
48 		return false;
49 
50 	return !fh1->len ||
51 		!memcmp(fanotify_fh_buf(fh1), fanotify_fh_buf(fh2), fh1->len);
52 }
53 
54 static unsigned int fanotify_hash_fh(struct fanotify_fh *fh)
55 {
56 	long salt = (long)fh->type | (long)fh->len << 8;
57 
58 	/*
59 	 * full_name_hash() works long by long, so it handles fh buf optimally.
60 	 */
61 	return full_name_hash((void *)salt, fanotify_fh_buf(fh), fh->len);
62 }
63 
64 static bool fanotify_fid_event_equal(struct fanotify_fid_event *ffe1,
65 				     struct fanotify_fid_event *ffe2)
66 {
67 	/* Do not merge fid events without object fh */
68 	if (!ffe1->object_fh.len)
69 		return false;
70 
71 	return fanotify_fsid_equal(&ffe1->fsid, &ffe2->fsid) &&
72 		fanotify_fh_equal(&ffe1->object_fh, &ffe2->object_fh);
73 }
74 
75 static bool fanotify_info_equal(struct fanotify_info *info1,
76 				struct fanotify_info *info2)
77 {
78 	if (info1->dir_fh_totlen != info2->dir_fh_totlen ||
79 	    info1->file_fh_totlen != info2->file_fh_totlen ||
80 	    info1->name_len != info2->name_len)
81 		return false;
82 
83 	if (info1->dir_fh_totlen &&
84 	    !fanotify_fh_equal(fanotify_info_dir_fh(info1),
85 			       fanotify_info_dir_fh(info2)))
86 		return false;
87 
88 	if (info1->file_fh_totlen &&
89 	    !fanotify_fh_equal(fanotify_info_file_fh(info1),
90 			       fanotify_info_file_fh(info2)))
91 		return false;
92 
93 	return !info1->name_len ||
94 		!memcmp(fanotify_info_name(info1), fanotify_info_name(info2),
95 			info1->name_len);
96 }
97 
98 static bool fanotify_name_event_equal(struct fanotify_name_event *fne1,
99 				      struct fanotify_name_event *fne2)
100 {
101 	struct fanotify_info *info1 = &fne1->info;
102 	struct fanotify_info *info2 = &fne2->info;
103 
104 	/* Do not merge name events without dir fh */
105 	if (!info1->dir_fh_totlen)
106 		return false;
107 
108 	if (!fanotify_fsid_equal(&fne1->fsid, &fne2->fsid))
109 		return false;
110 
111 	return fanotify_info_equal(info1, info2);
112 }
113 
114 static bool fanotify_error_event_equal(struct fanotify_error_event *fee1,
115 				       struct fanotify_error_event *fee2)
116 {
117 	/* Error events against the same file system are always merged. */
118 	if (!fanotify_fsid_equal(&fee1->fsid, &fee2->fsid))
119 		return false;
120 
121 	return true;
122 }
123 
124 static bool fanotify_should_merge(struct fanotify_event *old,
125 				  struct fanotify_event *new)
126 {
127 	pr_debug("%s: old=%p new=%p\n", __func__, old, new);
128 
129 	if (old->hash != new->hash ||
130 	    old->type != new->type || old->pid != new->pid)
131 		return false;
132 
133 	/*
134 	 * We want to merge many dirent events in the same dir (i.e.
135 	 * creates/unlinks/renames), but we do not want to merge dirent
136 	 * events referring to subdirs with dirent events referring to
137 	 * non subdirs, otherwise, user won't be able to tell from a
138 	 * mask FAN_CREATE|FAN_DELETE|FAN_ONDIR if it describes mkdir+
139 	 * unlink pair or rmdir+create pair of events.
140 	 */
141 	if ((old->mask & FS_ISDIR) != (new->mask & FS_ISDIR))
142 		return false;
143 
144 	switch (old->type) {
145 	case FANOTIFY_EVENT_TYPE_PATH:
146 		return fanotify_path_equal(fanotify_event_path(old),
147 					   fanotify_event_path(new));
148 	case FANOTIFY_EVENT_TYPE_FID:
149 		return fanotify_fid_event_equal(FANOTIFY_FE(old),
150 						FANOTIFY_FE(new));
151 	case FANOTIFY_EVENT_TYPE_FID_NAME:
152 		return fanotify_name_event_equal(FANOTIFY_NE(old),
153 						 FANOTIFY_NE(new));
154 	case FANOTIFY_EVENT_TYPE_FS_ERROR:
155 		return fanotify_error_event_equal(FANOTIFY_EE(old),
156 						  FANOTIFY_EE(new));
157 	default:
158 		WARN_ON_ONCE(1);
159 	}
160 
161 	return false;
162 }
163 
164 /* Limit event merges to limit CPU overhead per event */
165 #define FANOTIFY_MAX_MERGE_EVENTS 128
166 
167 /* and the list better be locked by something too! */
168 static int fanotify_merge(struct fsnotify_group *group,
169 			  struct fsnotify_event *event)
170 {
171 	struct fanotify_event *old, *new = FANOTIFY_E(event);
172 	unsigned int bucket = fanotify_event_hash_bucket(group, new);
173 	struct hlist_head *hlist = &group->fanotify_data.merge_hash[bucket];
174 	int i = 0;
175 
176 	pr_debug("%s: group=%p event=%p bucket=%u\n", __func__,
177 		 group, event, bucket);
178 
179 	/*
180 	 * Don't merge a permission event with any other event so that we know
181 	 * the event structure we have created in fanotify_handle_event() is the
182 	 * one we should check for permission response.
183 	 */
184 	if (fanotify_is_perm_event(new->mask))
185 		return 0;
186 
187 	hlist_for_each_entry(old, hlist, merge_list) {
188 		if (++i > FANOTIFY_MAX_MERGE_EVENTS)
189 			break;
190 		if (fanotify_should_merge(old, new)) {
191 			old->mask |= new->mask;
192 
193 			if (fanotify_is_error_event(old->mask))
194 				FANOTIFY_EE(old)->err_count++;
195 
196 			return 1;
197 		}
198 	}
199 
200 	return 0;
201 }
202 
203 /*
204  * Wait for response to permission event. The function also takes care of
205  * freeing the permission event (or offloads that in case the wait is canceled
206  * by a signal). The function returns 0 in case access got allowed by userspace,
207  * -EPERM in case userspace disallowed the access, and -ERESTARTSYS in case
208  * the wait got interrupted by a signal.
209  */
210 static int fanotify_get_response(struct fsnotify_group *group,
211 				 struct fanotify_perm_event *event,
212 				 struct fsnotify_iter_info *iter_info)
213 {
214 	int ret;
215 
216 	pr_debug("%s: group=%p event=%p\n", __func__, group, event);
217 
218 	ret = wait_event_killable(group->fanotify_data.access_waitq,
219 				  event->state == FAN_EVENT_ANSWERED);
220 	/* Signal pending? */
221 	if (ret < 0) {
222 		spin_lock(&group->notification_lock);
223 		/* Event reported to userspace and no answer yet? */
224 		if (event->state == FAN_EVENT_REPORTED) {
225 			/* Event will get freed once userspace answers to it */
226 			event->state = FAN_EVENT_CANCELED;
227 			spin_unlock(&group->notification_lock);
228 			return ret;
229 		}
230 		/* Event not yet reported? Just remove it. */
231 		if (event->state == FAN_EVENT_INIT) {
232 			fsnotify_remove_queued_event(group, &event->fae.fse);
233 			/* Permission events are not supposed to be hashed */
234 			WARN_ON_ONCE(!hlist_unhashed(&event->fae.merge_list));
235 		}
236 		/*
237 		 * Event may be also answered in case signal delivery raced
238 		 * with wakeup. In that case we have nothing to do besides
239 		 * freeing the event and reporting error.
240 		 */
241 		spin_unlock(&group->notification_lock);
242 		goto out;
243 	}
244 
245 	/* userspace responded, convert to something usable */
246 	switch (event->response & ~FAN_AUDIT) {
247 	case FAN_ALLOW:
248 		ret = 0;
249 		break;
250 	case FAN_DENY:
251 	default:
252 		ret = -EPERM;
253 	}
254 
255 	/* Check if the response should be audited */
256 	if (event->response & FAN_AUDIT)
257 		audit_fanotify(event->response & ~FAN_AUDIT);
258 
259 	pr_debug("%s: group=%p event=%p about to return ret=%d\n", __func__,
260 		 group, event, ret);
261 out:
262 	fsnotify_destroy_event(group, &event->fae.fse);
263 
264 	return ret;
265 }
266 
267 /*
268  * This function returns a mask for an event that only contains the flags
269  * that have been specifically requested by the user. Flags that may have
270  * been included within the event mask, but have not been explicitly
271  * requested by the user, will not be present in the returned mask.
272  */
273 static u32 fanotify_group_event_mask(struct fsnotify_group *group,
274 				     struct fsnotify_iter_info *iter_info,
275 				     u32 event_mask, const void *data,
276 				     int data_type, struct inode *dir)
277 {
278 	__u32 marks_mask = 0, marks_ignored_mask = 0;
279 	__u32 test_mask, user_mask = FANOTIFY_OUTGOING_EVENTS |
280 				     FANOTIFY_EVENT_FLAGS;
281 	const struct path *path = fsnotify_data_path(data, data_type);
282 	unsigned int fid_mode = FAN_GROUP_FLAG(group, FANOTIFY_FID_BITS);
283 	struct fsnotify_mark *mark;
284 	int type;
285 
286 	pr_debug("%s: report_mask=%x mask=%x data=%p data_type=%d\n",
287 		 __func__, iter_info->report_mask, event_mask, data, data_type);
288 
289 	if (!fid_mode) {
290 		/* Do we have path to open a file descriptor? */
291 		if (!path)
292 			return 0;
293 		/* Path type events are only relevant for files and dirs */
294 		if (!d_is_reg(path->dentry) && !d_can_lookup(path->dentry))
295 			return 0;
296 	} else if (!(fid_mode & FAN_REPORT_FID)) {
297 		/* Do we have a directory inode to report? */
298 		if (!dir && !(event_mask & FS_ISDIR))
299 			return 0;
300 	}
301 
302 	fsnotify_foreach_obj_type(type) {
303 		if (!fsnotify_iter_should_report_type(iter_info, type))
304 			continue;
305 		mark = iter_info->marks[type];
306 
307 		/* Apply ignore mask regardless of ISDIR and ON_CHILD flags */
308 		marks_ignored_mask |= mark->ignored_mask;
309 
310 		/*
311 		 * If the event is on dir and this mark doesn't care about
312 		 * events on dir, don't send it!
313 		 */
314 		if (event_mask & FS_ISDIR && !(mark->mask & FS_ISDIR))
315 			continue;
316 
317 		/*
318 		 * If the event is on a child and this mark is on a parent not
319 		 * watching children, don't send it!
320 		 */
321 		if (type == FSNOTIFY_OBJ_TYPE_PARENT &&
322 		    !(mark->mask & FS_EVENT_ON_CHILD))
323 			continue;
324 
325 		marks_mask |= mark->mask;
326 	}
327 
328 	test_mask = event_mask & marks_mask & ~marks_ignored_mask;
329 
330 	/*
331 	 * For dirent modification events (create/delete/move) that do not carry
332 	 * the child entry name information, we report FAN_ONDIR for mkdir/rmdir
333 	 * so user can differentiate them from creat/unlink.
334 	 *
335 	 * For backward compatibility and consistency, do not report FAN_ONDIR
336 	 * to user in legacy fanotify mode (reporting fd) and report FAN_ONDIR
337 	 * to user in fid mode for all event types.
338 	 *
339 	 * We never report FAN_EVENT_ON_CHILD to user, but we do pass it in to
340 	 * fanotify_alloc_event() when group is reporting fid as indication
341 	 * that event happened on child.
342 	 */
343 	if (fid_mode) {
344 		/* Do not report event flags without any event */
345 		if (!(test_mask & ~FANOTIFY_EVENT_FLAGS))
346 			return 0;
347 	} else {
348 		user_mask &= ~FANOTIFY_EVENT_FLAGS;
349 	}
350 
351 	return test_mask & user_mask;
352 }
353 
354 /*
355  * Check size needed to encode fanotify_fh.
356  *
357  * Return size of encoded fh without fanotify_fh header.
358  * Return 0 on failure to encode.
359  */
360 static int fanotify_encode_fh_len(struct inode *inode)
361 {
362 	int dwords = 0;
363 	int fh_len;
364 
365 	if (!inode)
366 		return 0;
367 
368 	exportfs_encode_inode_fh(inode, NULL, &dwords, NULL);
369 	fh_len = dwords << 2;
370 
371 	/*
372 	 * struct fanotify_error_event might be preallocated and is
373 	 * limited to MAX_HANDLE_SZ.  This should never happen, but
374 	 * safeguard by forcing an invalid file handle.
375 	 */
376 	if (WARN_ON_ONCE(fh_len > MAX_HANDLE_SZ))
377 		return 0;
378 
379 	return fh_len;
380 }
381 
382 /*
383  * Encode fanotify_fh.
384  *
385  * Return total size of encoded fh including fanotify_fh header.
386  * Return 0 on failure to encode.
387  */
388 static int fanotify_encode_fh(struct fanotify_fh *fh, struct inode *inode,
389 			      unsigned int fh_len, unsigned int *hash,
390 			      gfp_t gfp)
391 {
392 	int dwords, type = 0;
393 	char *ext_buf = NULL;
394 	void *buf = fh->buf;
395 	int err;
396 
397 	fh->type = FILEID_ROOT;
398 	fh->len = 0;
399 	fh->flags = 0;
400 
401 	/*
402 	 * Invalid FHs are used by FAN_FS_ERROR for errors not
403 	 * linked to any inode. The f_handle won't be reported
404 	 * back to userspace.
405 	 */
406 	if (!inode)
407 		goto out;
408 
409 	/*
410 	 * !gpf means preallocated variable size fh, but fh_len could
411 	 * be zero in that case if encoding fh len failed.
412 	 */
413 	err = -ENOENT;
414 	if (fh_len < 4 || WARN_ON_ONCE(fh_len % 4))
415 		goto out_err;
416 
417 	/* No external buffer in a variable size allocated fh */
418 	if (gfp && fh_len > FANOTIFY_INLINE_FH_LEN) {
419 		/* Treat failure to allocate fh as failure to encode fh */
420 		err = -ENOMEM;
421 		ext_buf = kmalloc(fh_len, gfp);
422 		if (!ext_buf)
423 			goto out_err;
424 
425 		*fanotify_fh_ext_buf_ptr(fh) = ext_buf;
426 		buf = ext_buf;
427 		fh->flags |= FANOTIFY_FH_FLAG_EXT_BUF;
428 	}
429 
430 	dwords = fh_len >> 2;
431 	type = exportfs_encode_inode_fh(inode, buf, &dwords, NULL);
432 	err = -EINVAL;
433 	if (!type || type == FILEID_INVALID || fh_len != dwords << 2)
434 		goto out_err;
435 
436 	fh->type = type;
437 	fh->len = fh_len;
438 
439 out:
440 	/*
441 	 * Mix fh into event merge key.  Hash might be NULL in case of
442 	 * unhashed FID events (i.e. FAN_FS_ERROR).
443 	 */
444 	if (hash)
445 		*hash ^= fanotify_hash_fh(fh);
446 
447 	return FANOTIFY_FH_HDR_LEN + fh_len;
448 
449 out_err:
450 	pr_warn_ratelimited("fanotify: failed to encode fid (type=%d, len=%d, err=%i)\n",
451 			    type, fh_len, err);
452 	kfree(ext_buf);
453 	*fanotify_fh_ext_buf_ptr(fh) = NULL;
454 	/* Report the event without a file identifier on encode error */
455 	fh->type = FILEID_INVALID;
456 	fh->len = 0;
457 	return 0;
458 }
459 
460 /*
461  * The inode to use as identifier when reporting fid depends on the event.
462  * Report the modified directory inode on dirent modification events.
463  * Report the "victim" inode otherwise.
464  * For example:
465  * FS_ATTRIB reports the child inode even if reported on a watched parent.
466  * FS_CREATE reports the modified dir inode and not the created inode.
467  */
468 static struct inode *fanotify_fid_inode(u32 event_mask, const void *data,
469 					int data_type, struct inode *dir)
470 {
471 	if (event_mask & ALL_FSNOTIFY_DIRENT_EVENTS)
472 		return dir;
473 
474 	return fsnotify_data_inode(data, data_type);
475 }
476 
477 /*
478  * The inode to use as identifier when reporting dir fid depends on the event.
479  * Report the modified directory inode on dirent modification events.
480  * Report the "victim" inode if "victim" is a directory.
481  * Report the parent inode if "victim" is not a directory and event is
482  * reported to parent.
483  * Otherwise, do not report dir fid.
484  */
485 static struct inode *fanotify_dfid_inode(u32 event_mask, const void *data,
486 					 int data_type, struct inode *dir)
487 {
488 	struct inode *inode = fsnotify_data_inode(data, data_type);
489 
490 	if (event_mask & ALL_FSNOTIFY_DIRENT_EVENTS)
491 		return dir;
492 
493 	if (inode && S_ISDIR(inode->i_mode))
494 		return inode;
495 
496 	return dir;
497 }
498 
499 static struct fanotify_event *fanotify_alloc_path_event(const struct path *path,
500 							unsigned int *hash,
501 							gfp_t gfp)
502 {
503 	struct fanotify_path_event *pevent;
504 
505 	pevent = kmem_cache_alloc(fanotify_path_event_cachep, gfp);
506 	if (!pevent)
507 		return NULL;
508 
509 	pevent->fae.type = FANOTIFY_EVENT_TYPE_PATH;
510 	pevent->path = *path;
511 	*hash ^= fanotify_hash_path(path);
512 	path_get(path);
513 
514 	return &pevent->fae;
515 }
516 
517 static struct fanotify_event *fanotify_alloc_perm_event(const struct path *path,
518 							gfp_t gfp)
519 {
520 	struct fanotify_perm_event *pevent;
521 
522 	pevent = kmem_cache_alloc(fanotify_perm_event_cachep, gfp);
523 	if (!pevent)
524 		return NULL;
525 
526 	pevent->fae.type = FANOTIFY_EVENT_TYPE_PATH_PERM;
527 	pevent->response = 0;
528 	pevent->state = FAN_EVENT_INIT;
529 	pevent->path = *path;
530 	path_get(path);
531 
532 	return &pevent->fae;
533 }
534 
535 static struct fanotify_event *fanotify_alloc_fid_event(struct inode *id,
536 						       __kernel_fsid_t *fsid,
537 						       unsigned int *hash,
538 						       gfp_t gfp)
539 {
540 	struct fanotify_fid_event *ffe;
541 
542 	ffe = kmem_cache_alloc(fanotify_fid_event_cachep, gfp);
543 	if (!ffe)
544 		return NULL;
545 
546 	ffe->fae.type = FANOTIFY_EVENT_TYPE_FID;
547 	ffe->fsid = *fsid;
548 	*hash ^= fanotify_hash_fsid(fsid);
549 	fanotify_encode_fh(&ffe->object_fh, id, fanotify_encode_fh_len(id),
550 			   hash, gfp);
551 
552 	return &ffe->fae;
553 }
554 
555 static struct fanotify_event *fanotify_alloc_name_event(struct inode *id,
556 							__kernel_fsid_t *fsid,
557 							const struct qstr *name,
558 							struct inode *child,
559 							unsigned int *hash,
560 							gfp_t gfp)
561 {
562 	struct fanotify_name_event *fne;
563 	struct fanotify_info *info;
564 	struct fanotify_fh *dfh, *ffh;
565 	unsigned int dir_fh_len = fanotify_encode_fh_len(id);
566 	unsigned int child_fh_len = fanotify_encode_fh_len(child);
567 	unsigned int size;
568 
569 	size = sizeof(*fne) + FANOTIFY_FH_HDR_LEN + dir_fh_len;
570 	if (child_fh_len)
571 		size += FANOTIFY_FH_HDR_LEN + child_fh_len;
572 	if (name)
573 		size += name->len + 1;
574 	fne = kmalloc(size, gfp);
575 	if (!fne)
576 		return NULL;
577 
578 	fne->fae.type = FANOTIFY_EVENT_TYPE_FID_NAME;
579 	fne->fsid = *fsid;
580 	*hash ^= fanotify_hash_fsid(fsid);
581 	info = &fne->info;
582 	fanotify_info_init(info);
583 	dfh = fanotify_info_dir_fh(info);
584 	info->dir_fh_totlen = fanotify_encode_fh(dfh, id, dir_fh_len, hash, 0);
585 	if (child_fh_len) {
586 		ffh = fanotify_info_file_fh(info);
587 		info->file_fh_totlen = fanotify_encode_fh(ffh, child,
588 							child_fh_len, hash, 0);
589 	}
590 	if (name) {
591 		long salt = name->len;
592 
593 		fanotify_info_copy_name(info, name);
594 		*hash ^= full_name_hash((void *)salt, name->name, name->len);
595 	}
596 
597 	pr_debug("%s: ino=%lu size=%u dir_fh_len=%u child_fh_len=%u name_len=%u name='%.*s'\n",
598 		 __func__, id->i_ino, size, dir_fh_len, child_fh_len,
599 		 info->name_len, info->name_len, fanotify_info_name(info));
600 
601 	return &fne->fae;
602 }
603 
604 static struct fanotify_event *fanotify_alloc_error_event(
605 						struct fsnotify_group *group,
606 						__kernel_fsid_t *fsid,
607 						const void *data, int data_type,
608 						unsigned int *hash)
609 {
610 	struct fs_error_report *report =
611 			fsnotify_data_error_report(data, data_type);
612 	struct inode *inode;
613 	struct fanotify_error_event *fee;
614 	int fh_len;
615 
616 	if (WARN_ON_ONCE(!report))
617 		return NULL;
618 
619 	fee = mempool_alloc(&group->fanotify_data.error_events_pool, GFP_NOFS);
620 	if (!fee)
621 		return NULL;
622 
623 	fee->fae.type = FANOTIFY_EVENT_TYPE_FS_ERROR;
624 	fee->error = report->error;
625 	fee->err_count = 1;
626 	fee->fsid = *fsid;
627 
628 	inode = report->inode;
629 	fh_len = fanotify_encode_fh_len(inode);
630 
631 	/* Bad fh_len. Fallback to using an invalid fh. Should never happen. */
632 	if (!fh_len && inode)
633 		inode = NULL;
634 
635 	fanotify_encode_fh(&fee->object_fh, inode, fh_len, NULL, 0);
636 
637 	*hash ^= fanotify_hash_fsid(fsid);
638 
639 	return &fee->fae;
640 }
641 
642 static struct fanotify_event *fanotify_alloc_event(struct fsnotify_group *group,
643 						   u32 mask, const void *data,
644 						   int data_type, struct inode *dir,
645 						   const struct qstr *file_name,
646 						   __kernel_fsid_t *fsid)
647 {
648 	struct fanotify_event *event = NULL;
649 	gfp_t gfp = GFP_KERNEL_ACCOUNT;
650 	struct inode *id = fanotify_fid_inode(mask, data, data_type, dir);
651 	struct inode *dirid = fanotify_dfid_inode(mask, data, data_type, dir);
652 	const struct path *path = fsnotify_data_path(data, data_type);
653 	unsigned int fid_mode = FAN_GROUP_FLAG(group, FANOTIFY_FID_BITS);
654 	struct mem_cgroup *old_memcg;
655 	struct inode *child = NULL;
656 	bool name_event = false;
657 	unsigned int hash = 0;
658 	bool ondir = mask & FAN_ONDIR;
659 	struct pid *pid;
660 
661 	if ((fid_mode & FAN_REPORT_DIR_FID) && dirid) {
662 		/*
663 		 * With both flags FAN_REPORT_DIR_FID and FAN_REPORT_FID, we
664 		 * report the child fid for events reported on a non-dir child
665 		 * in addition to reporting the parent fid and maybe child name.
666 		 */
667 		if ((fid_mode & FAN_REPORT_FID) && id != dirid && !ondir)
668 			child = id;
669 
670 		id = dirid;
671 
672 		/*
673 		 * We record file name only in a group with FAN_REPORT_NAME
674 		 * and when we have a directory inode to report.
675 		 *
676 		 * For directory entry modification event, we record the fid of
677 		 * the directory and the name of the modified entry.
678 		 *
679 		 * For event on non-directory that is reported to parent, we
680 		 * record the fid of the parent and the name of the child.
681 		 *
682 		 * Even if not reporting name, we need a variable length
683 		 * fanotify_name_event if reporting both parent and child fids.
684 		 */
685 		if (!(fid_mode & FAN_REPORT_NAME)) {
686 			name_event = !!child;
687 			file_name = NULL;
688 		} else if ((mask & ALL_FSNOTIFY_DIRENT_EVENTS) || !ondir) {
689 			name_event = true;
690 		}
691 	}
692 
693 	/*
694 	 * For queues with unlimited length lost events are not expected and
695 	 * can possibly have security implications. Avoid losing events when
696 	 * memory is short. For the limited size queues, avoid OOM killer in the
697 	 * target monitoring memcg as it may have security repercussion.
698 	 */
699 	if (group->max_events == UINT_MAX)
700 		gfp |= __GFP_NOFAIL;
701 	else
702 		gfp |= __GFP_RETRY_MAYFAIL;
703 
704 	/* Whoever is interested in the event, pays for the allocation. */
705 	old_memcg = set_active_memcg(group->memcg);
706 
707 	if (fanotify_is_perm_event(mask)) {
708 		event = fanotify_alloc_perm_event(path, gfp);
709 	} else if (fanotify_is_error_event(mask)) {
710 		event = fanotify_alloc_error_event(group, fsid, data,
711 						   data_type, &hash);
712 	} else if (name_event && (file_name || child)) {
713 		event = fanotify_alloc_name_event(id, fsid, file_name, child,
714 						  &hash, gfp);
715 	} else if (fid_mode) {
716 		event = fanotify_alloc_fid_event(id, fsid, &hash, gfp);
717 	} else {
718 		event = fanotify_alloc_path_event(path, &hash, gfp);
719 	}
720 
721 	if (!event)
722 		goto out;
723 
724 	if (FAN_GROUP_FLAG(group, FAN_REPORT_TID))
725 		pid = get_pid(task_pid(current));
726 	else
727 		pid = get_pid(task_tgid(current));
728 
729 	/* Mix event info, FAN_ONDIR flag and pid into event merge key */
730 	hash ^= hash_long((unsigned long)pid | ondir, FANOTIFY_EVENT_HASH_BITS);
731 	fanotify_init_event(event, hash, mask);
732 	event->pid = pid;
733 
734 out:
735 	set_active_memcg(old_memcg);
736 	return event;
737 }
738 
739 /*
740  * Get cached fsid of the filesystem containing the object from any connector.
741  * All connectors are supposed to have the same fsid, but we do not verify that
742  * here.
743  */
744 static __kernel_fsid_t fanotify_get_fsid(struct fsnotify_iter_info *iter_info)
745 {
746 	int type;
747 	__kernel_fsid_t fsid = {};
748 
749 	fsnotify_foreach_obj_type(type) {
750 		struct fsnotify_mark_connector *conn;
751 
752 		if (!fsnotify_iter_should_report_type(iter_info, type))
753 			continue;
754 
755 		conn = READ_ONCE(iter_info->marks[type]->connector);
756 		/* Mark is just getting destroyed or created? */
757 		if (!conn)
758 			continue;
759 		if (!(conn->flags & FSNOTIFY_CONN_FLAG_HAS_FSID))
760 			continue;
761 		/* Pairs with smp_wmb() in fsnotify_add_mark_list() */
762 		smp_rmb();
763 		fsid = conn->fsid;
764 		if (WARN_ON_ONCE(!fsid.val[0] && !fsid.val[1]))
765 			continue;
766 		return fsid;
767 	}
768 
769 	return fsid;
770 }
771 
772 /*
773  * Add an event to hash table for faster merge.
774  */
775 static void fanotify_insert_event(struct fsnotify_group *group,
776 				  struct fsnotify_event *fsn_event)
777 {
778 	struct fanotify_event *event = FANOTIFY_E(fsn_event);
779 	unsigned int bucket = fanotify_event_hash_bucket(group, event);
780 	struct hlist_head *hlist = &group->fanotify_data.merge_hash[bucket];
781 
782 	assert_spin_locked(&group->notification_lock);
783 
784 	if (!fanotify_is_hashed_event(event->mask))
785 		return;
786 
787 	pr_debug("%s: group=%p event=%p bucket=%u\n", __func__,
788 		 group, event, bucket);
789 
790 	hlist_add_head(&event->merge_list, hlist);
791 }
792 
793 static int fanotify_handle_event(struct fsnotify_group *group, u32 mask,
794 				 const void *data, int data_type,
795 				 struct inode *dir,
796 				 const struct qstr *file_name, u32 cookie,
797 				 struct fsnotify_iter_info *iter_info)
798 {
799 	int ret = 0;
800 	struct fanotify_event *event;
801 	struct fsnotify_event *fsn_event;
802 	__kernel_fsid_t fsid = {};
803 
804 	BUILD_BUG_ON(FAN_ACCESS != FS_ACCESS);
805 	BUILD_BUG_ON(FAN_MODIFY != FS_MODIFY);
806 	BUILD_BUG_ON(FAN_ATTRIB != FS_ATTRIB);
807 	BUILD_BUG_ON(FAN_CLOSE_NOWRITE != FS_CLOSE_NOWRITE);
808 	BUILD_BUG_ON(FAN_CLOSE_WRITE != FS_CLOSE_WRITE);
809 	BUILD_BUG_ON(FAN_OPEN != FS_OPEN);
810 	BUILD_BUG_ON(FAN_MOVED_TO != FS_MOVED_TO);
811 	BUILD_BUG_ON(FAN_MOVED_FROM != FS_MOVED_FROM);
812 	BUILD_BUG_ON(FAN_CREATE != FS_CREATE);
813 	BUILD_BUG_ON(FAN_DELETE != FS_DELETE);
814 	BUILD_BUG_ON(FAN_DELETE_SELF != FS_DELETE_SELF);
815 	BUILD_BUG_ON(FAN_MOVE_SELF != FS_MOVE_SELF);
816 	BUILD_BUG_ON(FAN_EVENT_ON_CHILD != FS_EVENT_ON_CHILD);
817 	BUILD_BUG_ON(FAN_Q_OVERFLOW != FS_Q_OVERFLOW);
818 	BUILD_BUG_ON(FAN_OPEN_PERM != FS_OPEN_PERM);
819 	BUILD_BUG_ON(FAN_ACCESS_PERM != FS_ACCESS_PERM);
820 	BUILD_BUG_ON(FAN_ONDIR != FS_ISDIR);
821 	BUILD_BUG_ON(FAN_OPEN_EXEC != FS_OPEN_EXEC);
822 	BUILD_BUG_ON(FAN_OPEN_EXEC_PERM != FS_OPEN_EXEC_PERM);
823 	BUILD_BUG_ON(FAN_FS_ERROR != FS_ERROR);
824 
825 	BUILD_BUG_ON(HWEIGHT32(ALL_FANOTIFY_EVENT_BITS) != 20);
826 
827 	mask = fanotify_group_event_mask(group, iter_info, mask, data,
828 					 data_type, dir);
829 	if (!mask)
830 		return 0;
831 
832 	pr_debug("%s: group=%p mask=%x\n", __func__, group, mask);
833 
834 	if (fanotify_is_perm_event(mask)) {
835 		/*
836 		 * fsnotify_prepare_user_wait() fails if we race with mark
837 		 * deletion.  Just let the operation pass in that case.
838 		 */
839 		if (!fsnotify_prepare_user_wait(iter_info))
840 			return 0;
841 	}
842 
843 	if (FAN_GROUP_FLAG(group, FANOTIFY_FID_BITS)) {
844 		fsid = fanotify_get_fsid(iter_info);
845 		/* Racing with mark destruction or creation? */
846 		if (!fsid.val[0] && !fsid.val[1])
847 			return 0;
848 	}
849 
850 	event = fanotify_alloc_event(group, mask, data, data_type, dir,
851 				     file_name, &fsid);
852 	ret = -ENOMEM;
853 	if (unlikely(!event)) {
854 		/*
855 		 * We don't queue overflow events for permission events as
856 		 * there the access is denied and so no event is in fact lost.
857 		 */
858 		if (!fanotify_is_perm_event(mask))
859 			fsnotify_queue_overflow(group);
860 		goto finish;
861 	}
862 
863 	fsn_event = &event->fse;
864 	ret = fsnotify_insert_event(group, fsn_event, fanotify_merge,
865 				    fanotify_insert_event);
866 	if (ret) {
867 		/* Permission events shouldn't be merged */
868 		BUG_ON(ret == 1 && mask & FANOTIFY_PERM_EVENTS);
869 		/* Our event wasn't used in the end. Free it. */
870 		fsnotify_destroy_event(group, fsn_event);
871 
872 		ret = 0;
873 	} else if (fanotify_is_perm_event(mask)) {
874 		ret = fanotify_get_response(group, FANOTIFY_PERM(event),
875 					    iter_info);
876 	}
877 finish:
878 	if (fanotify_is_perm_event(mask))
879 		fsnotify_finish_user_wait(iter_info);
880 
881 	return ret;
882 }
883 
884 static void fanotify_free_group_priv(struct fsnotify_group *group)
885 {
886 	kfree(group->fanotify_data.merge_hash);
887 	if (group->fanotify_data.ucounts)
888 		dec_ucount(group->fanotify_data.ucounts,
889 			   UCOUNT_FANOTIFY_GROUPS);
890 
891 	if (mempool_initialized(&group->fanotify_data.error_events_pool))
892 		mempool_exit(&group->fanotify_data.error_events_pool);
893 }
894 
895 static void fanotify_free_path_event(struct fanotify_event *event)
896 {
897 	path_put(fanotify_event_path(event));
898 	kmem_cache_free(fanotify_path_event_cachep, FANOTIFY_PE(event));
899 }
900 
901 static void fanotify_free_perm_event(struct fanotify_event *event)
902 {
903 	path_put(fanotify_event_path(event));
904 	kmem_cache_free(fanotify_perm_event_cachep, FANOTIFY_PERM(event));
905 }
906 
907 static void fanotify_free_fid_event(struct fanotify_event *event)
908 {
909 	struct fanotify_fid_event *ffe = FANOTIFY_FE(event);
910 
911 	if (fanotify_fh_has_ext_buf(&ffe->object_fh))
912 		kfree(fanotify_fh_ext_buf(&ffe->object_fh));
913 	kmem_cache_free(fanotify_fid_event_cachep, ffe);
914 }
915 
916 static void fanotify_free_name_event(struct fanotify_event *event)
917 {
918 	kfree(FANOTIFY_NE(event));
919 }
920 
921 static void fanotify_free_error_event(struct fsnotify_group *group,
922 				      struct fanotify_event *event)
923 {
924 	struct fanotify_error_event *fee = FANOTIFY_EE(event);
925 
926 	mempool_free(fee, &group->fanotify_data.error_events_pool);
927 }
928 
929 static void fanotify_free_event(struct fsnotify_group *group,
930 				struct fsnotify_event *fsn_event)
931 {
932 	struct fanotify_event *event;
933 
934 	event = FANOTIFY_E(fsn_event);
935 	put_pid(event->pid);
936 	switch (event->type) {
937 	case FANOTIFY_EVENT_TYPE_PATH:
938 		fanotify_free_path_event(event);
939 		break;
940 	case FANOTIFY_EVENT_TYPE_PATH_PERM:
941 		fanotify_free_perm_event(event);
942 		break;
943 	case FANOTIFY_EVENT_TYPE_FID:
944 		fanotify_free_fid_event(event);
945 		break;
946 	case FANOTIFY_EVENT_TYPE_FID_NAME:
947 		fanotify_free_name_event(event);
948 		break;
949 	case FANOTIFY_EVENT_TYPE_OVERFLOW:
950 		kfree(event);
951 		break;
952 	case FANOTIFY_EVENT_TYPE_FS_ERROR:
953 		fanotify_free_error_event(group, event);
954 		break;
955 	default:
956 		WARN_ON_ONCE(1);
957 	}
958 }
959 
960 static void fanotify_freeing_mark(struct fsnotify_mark *mark,
961 				  struct fsnotify_group *group)
962 {
963 	if (!FAN_GROUP_FLAG(group, FAN_UNLIMITED_MARKS))
964 		dec_ucount(group->fanotify_data.ucounts, UCOUNT_FANOTIFY_MARKS);
965 }
966 
967 static void fanotify_free_mark(struct fsnotify_mark *fsn_mark)
968 {
969 	kmem_cache_free(fanotify_mark_cache, fsn_mark);
970 }
971 
972 const struct fsnotify_ops fanotify_fsnotify_ops = {
973 	.handle_event = fanotify_handle_event,
974 	.free_group_priv = fanotify_free_group_priv,
975 	.free_event = fanotify_free_event,
976 	.freeing_mark = fanotify_freeing_mark,
977 	.free_mark = fanotify_free_mark,
978 };
979