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