1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/fanotify.h>
3 #include <linux/fcntl.h>
4 #include <linux/fdtable.h>
5 #include <linux/file.h>
6 #include <linux/fs.h>
7 #include <linux/anon_inodes.h>
8 #include <linux/fsnotify_backend.h>
9 #include <linux/init.h>
10 #include <linux/mount.h>
11 #include <linux/namei.h>
12 #include <linux/poll.h>
13 #include <linux/security.h>
14 #include <linux/syscalls.h>
15 #include <linux/slab.h>
16 #include <linux/types.h>
17 #include <linux/uaccess.h>
18 #include <linux/compat.h>
19 #include <linux/sched/signal.h>
20 #include <linux/memcontrol.h>
21 #include <linux/statfs.h>
22 #include <linux/exportfs.h>
23 
24 #include <asm/ioctls.h>
25 
26 #include "../../mount.h"
27 #include "../fdinfo.h"
28 #include "fanotify.h"
29 
30 #define FANOTIFY_DEFAULT_MAX_EVENTS	16384
31 #define FANOTIFY_OLD_DEFAULT_MAX_MARKS	8192
32 #define FANOTIFY_DEFAULT_MAX_GROUPS	128
33 #define FANOTIFY_DEFAULT_FEE_POOL_SIZE	32
34 
35 /*
36  * Legacy fanotify marks limits (8192) is per group and we introduced a tunable
37  * limit of marks per user, similar to inotify.  Effectively, the legacy limit
38  * of fanotify marks per user is <max marks per group> * <max groups per user>.
39  * This default limit (1M) also happens to match the increased limit of inotify
40  * max_user_watches since v5.10.
41  */
42 #define FANOTIFY_DEFAULT_MAX_USER_MARKS	\
43 	(FANOTIFY_OLD_DEFAULT_MAX_MARKS * FANOTIFY_DEFAULT_MAX_GROUPS)
44 
45 /*
46  * Most of the memory cost of adding an inode mark is pinning the marked inode.
47  * The size of the filesystem inode struct is not uniform across filesystems,
48  * so double the size of a VFS inode is used as a conservative approximation.
49  */
50 #define INODE_MARK_COST	(2 * sizeof(struct inode))
51 
52 /* configurable via /proc/sys/fs/fanotify/ */
53 static int fanotify_max_queued_events __read_mostly;
54 
55 #ifdef CONFIG_SYSCTL
56 
57 #include <linux/sysctl.h>
58 
59 static long ft_zero = 0;
60 static long ft_int_max = INT_MAX;
61 
62 static struct ctl_table fanotify_table[] = {
63 	{
64 		.procname	= "max_user_groups",
65 		.data	= &init_user_ns.ucount_max[UCOUNT_FANOTIFY_GROUPS],
66 		.maxlen		= sizeof(long),
67 		.mode		= 0644,
68 		.proc_handler	= proc_doulongvec_minmax,
69 		.extra1		= &ft_zero,
70 		.extra2		= &ft_int_max,
71 	},
72 	{
73 		.procname	= "max_user_marks",
74 		.data	= &init_user_ns.ucount_max[UCOUNT_FANOTIFY_MARKS],
75 		.maxlen		= sizeof(long),
76 		.mode		= 0644,
77 		.proc_handler	= proc_doulongvec_minmax,
78 		.extra1		= &ft_zero,
79 		.extra2		= &ft_int_max,
80 	},
81 	{
82 		.procname	= "max_queued_events",
83 		.data		= &fanotify_max_queued_events,
84 		.maxlen		= sizeof(int),
85 		.mode		= 0644,
86 		.proc_handler	= proc_dointvec_minmax,
87 		.extra1		= SYSCTL_ZERO
88 	},
89 	{ }
90 };
91 
92 static void __init fanotify_sysctls_init(void)
93 {
94 	register_sysctl("fs/fanotify", fanotify_table);
95 }
96 #else
97 #define fanotify_sysctls_init() do { } while (0)
98 #endif /* CONFIG_SYSCTL */
99 
100 /*
101  * All flags that may be specified in parameter event_f_flags of fanotify_init.
102  *
103  * Internal and external open flags are stored together in field f_flags of
104  * struct file. Only external open flags shall be allowed in event_f_flags.
105  * Internal flags like FMODE_NONOTIFY, FMODE_EXEC, FMODE_NOCMTIME shall be
106  * excluded.
107  */
108 #define	FANOTIFY_INIT_ALL_EVENT_F_BITS				( \
109 		O_ACCMODE	| O_APPEND	| O_NONBLOCK	| \
110 		__O_SYNC	| O_DSYNC	| O_CLOEXEC     | \
111 		O_LARGEFILE	| O_NOATIME	)
112 
113 extern const struct fsnotify_ops fanotify_fsnotify_ops;
114 
115 struct kmem_cache *fanotify_mark_cache __read_mostly;
116 struct kmem_cache *fanotify_fid_event_cachep __read_mostly;
117 struct kmem_cache *fanotify_path_event_cachep __read_mostly;
118 struct kmem_cache *fanotify_perm_event_cachep __read_mostly;
119 
120 #define FANOTIFY_EVENT_ALIGN 4
121 #define FANOTIFY_FID_INFO_HDR_LEN \
122 	(sizeof(struct fanotify_event_info_fid) + sizeof(struct file_handle))
123 #define FANOTIFY_PIDFD_INFO_HDR_LEN \
124 	sizeof(struct fanotify_event_info_pidfd)
125 #define FANOTIFY_ERROR_INFO_LEN \
126 	(sizeof(struct fanotify_event_info_error))
127 
128 static int fanotify_fid_info_len(int fh_len, int name_len)
129 {
130 	int info_len = fh_len;
131 
132 	if (name_len)
133 		info_len += name_len + 1;
134 
135 	return roundup(FANOTIFY_FID_INFO_HDR_LEN + info_len,
136 		       FANOTIFY_EVENT_ALIGN);
137 }
138 
139 /* FAN_RENAME may have one or two dir+name info records */
140 static int fanotify_dir_name_info_len(struct fanotify_event *event)
141 {
142 	struct fanotify_info *info = fanotify_event_info(event);
143 	int dir_fh_len = fanotify_event_dir_fh_len(event);
144 	int dir2_fh_len = fanotify_event_dir2_fh_len(event);
145 	int info_len = 0;
146 
147 	if (dir_fh_len)
148 		info_len += fanotify_fid_info_len(dir_fh_len,
149 						  info->name_len);
150 	if (dir2_fh_len)
151 		info_len += fanotify_fid_info_len(dir2_fh_len,
152 						  info->name2_len);
153 
154 	return info_len;
155 }
156 
157 static size_t fanotify_event_len(unsigned int info_mode,
158 				 struct fanotify_event *event)
159 {
160 	size_t event_len = FAN_EVENT_METADATA_LEN;
161 	int fh_len;
162 	int dot_len = 0;
163 
164 	if (!info_mode)
165 		return event_len;
166 
167 	if (fanotify_is_error_event(event->mask))
168 		event_len += FANOTIFY_ERROR_INFO_LEN;
169 
170 	if (fanotify_event_has_any_dir_fh(event)) {
171 		event_len += fanotify_dir_name_info_len(event);
172 	} else if ((info_mode & FAN_REPORT_NAME) &&
173 		   (event->mask & FAN_ONDIR)) {
174 		/*
175 		 * With group flag FAN_REPORT_NAME, if name was not recorded in
176 		 * event on a directory, we will report the name ".".
177 		 */
178 		dot_len = 1;
179 	}
180 
181 	if (info_mode & FAN_REPORT_PIDFD)
182 		event_len += FANOTIFY_PIDFD_INFO_HDR_LEN;
183 
184 	if (fanotify_event_has_object_fh(event)) {
185 		fh_len = fanotify_event_object_fh_len(event);
186 		event_len += fanotify_fid_info_len(fh_len, dot_len);
187 	}
188 
189 	return event_len;
190 }
191 
192 /*
193  * Remove an hashed event from merge hash table.
194  */
195 static void fanotify_unhash_event(struct fsnotify_group *group,
196 				  struct fanotify_event *event)
197 {
198 	assert_spin_locked(&group->notification_lock);
199 
200 	pr_debug("%s: group=%p event=%p bucket=%u\n", __func__,
201 		 group, event, fanotify_event_hash_bucket(group, event));
202 
203 	if (WARN_ON_ONCE(hlist_unhashed(&event->merge_list)))
204 		return;
205 
206 	hlist_del_init(&event->merge_list);
207 }
208 
209 /*
210  * Get an fanotify notification event if one exists and is small
211  * enough to fit in "count". Return an error pointer if the count
212  * is not large enough. When permission event is dequeued, its state is
213  * updated accordingly.
214  */
215 static struct fanotify_event *get_one_event(struct fsnotify_group *group,
216 					    size_t count)
217 {
218 	size_t event_size;
219 	struct fanotify_event *event = NULL;
220 	struct fsnotify_event *fsn_event;
221 	unsigned int info_mode = FAN_GROUP_FLAG(group, FANOTIFY_INFO_MODES);
222 
223 	pr_debug("%s: group=%p count=%zd\n", __func__, group, count);
224 
225 	spin_lock(&group->notification_lock);
226 	fsn_event = fsnotify_peek_first_event(group);
227 	if (!fsn_event)
228 		goto out;
229 
230 	event = FANOTIFY_E(fsn_event);
231 	event_size = fanotify_event_len(info_mode, event);
232 
233 	if (event_size > count) {
234 		event = ERR_PTR(-EINVAL);
235 		goto out;
236 	}
237 
238 	/*
239 	 * Held the notification_lock the whole time, so this is the
240 	 * same event we peeked above.
241 	 */
242 	fsnotify_remove_first_event(group);
243 	if (fanotify_is_perm_event(event->mask))
244 		FANOTIFY_PERM(event)->state = FAN_EVENT_REPORTED;
245 	if (fanotify_is_hashed_event(event->mask))
246 		fanotify_unhash_event(group, event);
247 out:
248 	spin_unlock(&group->notification_lock);
249 	return event;
250 }
251 
252 static int create_fd(struct fsnotify_group *group, struct path *path,
253 		     struct file **file)
254 {
255 	int client_fd;
256 	struct file *new_file;
257 
258 	client_fd = get_unused_fd_flags(group->fanotify_data.f_flags);
259 	if (client_fd < 0)
260 		return client_fd;
261 
262 	/*
263 	 * we need a new file handle for the userspace program so it can read even if it was
264 	 * originally opened O_WRONLY.
265 	 */
266 	new_file = dentry_open(path,
267 			       group->fanotify_data.f_flags | FMODE_NONOTIFY,
268 			       current_cred());
269 	if (IS_ERR(new_file)) {
270 		/*
271 		 * we still send an event even if we can't open the file.  this
272 		 * can happen when say tasks are gone and we try to open their
273 		 * /proc files or we try to open a WRONLY file like in sysfs
274 		 * we just send the errno to userspace since there isn't much
275 		 * else we can do.
276 		 */
277 		put_unused_fd(client_fd);
278 		client_fd = PTR_ERR(new_file);
279 	} else {
280 		*file = new_file;
281 	}
282 
283 	return client_fd;
284 }
285 
286 /*
287  * Finish processing of permission event by setting it to ANSWERED state and
288  * drop group->notification_lock.
289  */
290 static void finish_permission_event(struct fsnotify_group *group,
291 				    struct fanotify_perm_event *event,
292 				    unsigned int response)
293 				    __releases(&group->notification_lock)
294 {
295 	bool destroy = false;
296 
297 	assert_spin_locked(&group->notification_lock);
298 	event->response = response;
299 	if (event->state == FAN_EVENT_CANCELED)
300 		destroy = true;
301 	else
302 		event->state = FAN_EVENT_ANSWERED;
303 	spin_unlock(&group->notification_lock);
304 	if (destroy)
305 		fsnotify_destroy_event(group, &event->fae.fse);
306 }
307 
308 static int process_access_response(struct fsnotify_group *group,
309 				   struct fanotify_response *response_struct)
310 {
311 	struct fanotify_perm_event *event;
312 	int fd = response_struct->fd;
313 	int response = response_struct->response;
314 
315 	pr_debug("%s: group=%p fd=%d response=%d\n", __func__, group,
316 		 fd, response);
317 	/*
318 	 * make sure the response is valid, if invalid we do nothing and either
319 	 * userspace can send a valid response or we will clean it up after the
320 	 * timeout
321 	 */
322 	switch (response & ~FAN_AUDIT) {
323 	case FAN_ALLOW:
324 	case FAN_DENY:
325 		break;
326 	default:
327 		return -EINVAL;
328 	}
329 
330 	if (fd < 0)
331 		return -EINVAL;
332 
333 	if ((response & FAN_AUDIT) && !FAN_GROUP_FLAG(group, FAN_ENABLE_AUDIT))
334 		return -EINVAL;
335 
336 	spin_lock(&group->notification_lock);
337 	list_for_each_entry(event, &group->fanotify_data.access_list,
338 			    fae.fse.list) {
339 		if (event->fd != fd)
340 			continue;
341 
342 		list_del_init(&event->fae.fse.list);
343 		finish_permission_event(group, event, response);
344 		wake_up(&group->fanotify_data.access_waitq);
345 		return 0;
346 	}
347 	spin_unlock(&group->notification_lock);
348 
349 	return -ENOENT;
350 }
351 
352 static size_t copy_error_info_to_user(struct fanotify_event *event,
353 				      char __user *buf, int count)
354 {
355 	struct fanotify_event_info_error info = { };
356 	struct fanotify_error_event *fee = FANOTIFY_EE(event);
357 
358 	info.hdr.info_type = FAN_EVENT_INFO_TYPE_ERROR;
359 	info.hdr.len = FANOTIFY_ERROR_INFO_LEN;
360 
361 	if (WARN_ON(count < info.hdr.len))
362 		return -EFAULT;
363 
364 	info.error = fee->error;
365 	info.error_count = fee->err_count;
366 
367 	if (copy_to_user(buf, &info, sizeof(info)))
368 		return -EFAULT;
369 
370 	return info.hdr.len;
371 }
372 
373 static int copy_fid_info_to_user(__kernel_fsid_t *fsid, struct fanotify_fh *fh,
374 				 int info_type, const char *name,
375 				 size_t name_len,
376 				 char __user *buf, size_t count)
377 {
378 	struct fanotify_event_info_fid info = { };
379 	struct file_handle handle = { };
380 	unsigned char bounce[FANOTIFY_INLINE_FH_LEN], *fh_buf;
381 	size_t fh_len = fh ? fh->len : 0;
382 	size_t info_len = fanotify_fid_info_len(fh_len, name_len);
383 	size_t len = info_len;
384 
385 	pr_debug("%s: fh_len=%zu name_len=%zu, info_len=%zu, count=%zu\n",
386 		 __func__, fh_len, name_len, info_len, count);
387 
388 	if (WARN_ON_ONCE(len < sizeof(info) || len > count))
389 		return -EFAULT;
390 
391 	/*
392 	 * Copy event info fid header followed by variable sized file handle
393 	 * and optionally followed by variable sized filename.
394 	 */
395 	switch (info_type) {
396 	case FAN_EVENT_INFO_TYPE_FID:
397 	case FAN_EVENT_INFO_TYPE_DFID:
398 		if (WARN_ON_ONCE(name_len))
399 			return -EFAULT;
400 		break;
401 	case FAN_EVENT_INFO_TYPE_DFID_NAME:
402 	case FAN_EVENT_INFO_TYPE_OLD_DFID_NAME:
403 	case FAN_EVENT_INFO_TYPE_NEW_DFID_NAME:
404 		if (WARN_ON_ONCE(!name || !name_len))
405 			return -EFAULT;
406 		break;
407 	default:
408 		return -EFAULT;
409 	}
410 
411 	info.hdr.info_type = info_type;
412 	info.hdr.len = len;
413 	info.fsid = *fsid;
414 	if (copy_to_user(buf, &info, sizeof(info)))
415 		return -EFAULT;
416 
417 	buf += sizeof(info);
418 	len -= sizeof(info);
419 	if (WARN_ON_ONCE(len < sizeof(handle)))
420 		return -EFAULT;
421 
422 	handle.handle_type = fh->type;
423 	handle.handle_bytes = fh_len;
424 
425 	/* Mangle handle_type for bad file_handle */
426 	if (!fh_len)
427 		handle.handle_type = FILEID_INVALID;
428 
429 	if (copy_to_user(buf, &handle, sizeof(handle)))
430 		return -EFAULT;
431 
432 	buf += sizeof(handle);
433 	len -= sizeof(handle);
434 	if (WARN_ON_ONCE(len < fh_len))
435 		return -EFAULT;
436 
437 	/*
438 	 * For an inline fh and inline file name, copy through stack to exclude
439 	 * the copy from usercopy hardening protections.
440 	 */
441 	fh_buf = fanotify_fh_buf(fh);
442 	if (fh_len <= FANOTIFY_INLINE_FH_LEN) {
443 		memcpy(bounce, fh_buf, fh_len);
444 		fh_buf = bounce;
445 	}
446 	if (copy_to_user(buf, fh_buf, fh_len))
447 		return -EFAULT;
448 
449 	buf += fh_len;
450 	len -= fh_len;
451 
452 	if (name_len) {
453 		/* Copy the filename with terminating null */
454 		name_len++;
455 		if (WARN_ON_ONCE(len < name_len))
456 			return -EFAULT;
457 
458 		if (copy_to_user(buf, name, name_len))
459 			return -EFAULT;
460 
461 		buf += name_len;
462 		len -= name_len;
463 	}
464 
465 	/* Pad with 0's */
466 	WARN_ON_ONCE(len < 0 || len >= FANOTIFY_EVENT_ALIGN);
467 	if (len > 0 && clear_user(buf, len))
468 		return -EFAULT;
469 
470 	return info_len;
471 }
472 
473 static int copy_pidfd_info_to_user(int pidfd,
474 				   char __user *buf,
475 				   size_t count)
476 {
477 	struct fanotify_event_info_pidfd info = { };
478 	size_t info_len = FANOTIFY_PIDFD_INFO_HDR_LEN;
479 
480 	if (WARN_ON_ONCE(info_len > count))
481 		return -EFAULT;
482 
483 	info.hdr.info_type = FAN_EVENT_INFO_TYPE_PIDFD;
484 	info.hdr.len = info_len;
485 	info.pidfd = pidfd;
486 
487 	if (copy_to_user(buf, &info, info_len))
488 		return -EFAULT;
489 
490 	return info_len;
491 }
492 
493 static int copy_info_records_to_user(struct fanotify_event *event,
494 				     struct fanotify_info *info,
495 				     unsigned int info_mode, int pidfd,
496 				     char __user *buf, size_t count)
497 {
498 	int ret, total_bytes = 0, info_type = 0;
499 	unsigned int fid_mode = info_mode & FANOTIFY_FID_BITS;
500 	unsigned int pidfd_mode = info_mode & FAN_REPORT_PIDFD;
501 
502 	/*
503 	 * Event info records order is as follows:
504 	 * 1. dir fid + name
505 	 * 2. (optional) new dir fid + new name
506 	 * 3. (optional) child fid
507 	 */
508 	if (fanotify_event_has_dir_fh(event)) {
509 		info_type = info->name_len ? FAN_EVENT_INFO_TYPE_DFID_NAME :
510 					     FAN_EVENT_INFO_TYPE_DFID;
511 
512 		/* FAN_RENAME uses special info types */
513 		if (event->mask & FAN_RENAME)
514 			info_type = FAN_EVENT_INFO_TYPE_OLD_DFID_NAME;
515 
516 		ret = copy_fid_info_to_user(fanotify_event_fsid(event),
517 					    fanotify_info_dir_fh(info),
518 					    info_type,
519 					    fanotify_info_name(info),
520 					    info->name_len, buf, count);
521 		if (ret < 0)
522 			return ret;
523 
524 		buf += ret;
525 		count -= ret;
526 		total_bytes += ret;
527 	}
528 
529 	/* New dir fid+name may be reported in addition to old dir fid+name */
530 	if (fanotify_event_has_dir2_fh(event)) {
531 		info_type = FAN_EVENT_INFO_TYPE_NEW_DFID_NAME;
532 		ret = copy_fid_info_to_user(fanotify_event_fsid(event),
533 					    fanotify_info_dir2_fh(info),
534 					    info_type,
535 					    fanotify_info_name2(info),
536 					    info->name2_len, buf, count);
537 		if (ret < 0)
538 			return ret;
539 
540 		buf += ret;
541 		count -= ret;
542 		total_bytes += ret;
543 	}
544 
545 	if (fanotify_event_has_object_fh(event)) {
546 		const char *dot = NULL;
547 		int dot_len = 0;
548 
549 		if (fid_mode == FAN_REPORT_FID || info_type) {
550 			/*
551 			 * With only group flag FAN_REPORT_FID only type FID is
552 			 * reported. Second info record type is always FID.
553 			 */
554 			info_type = FAN_EVENT_INFO_TYPE_FID;
555 		} else if ((fid_mode & FAN_REPORT_NAME) &&
556 			   (event->mask & FAN_ONDIR)) {
557 			/*
558 			 * With group flag FAN_REPORT_NAME, if name was not
559 			 * recorded in an event on a directory, report the name
560 			 * "." with info type DFID_NAME.
561 			 */
562 			info_type = FAN_EVENT_INFO_TYPE_DFID_NAME;
563 			dot = ".";
564 			dot_len = 1;
565 		} else if ((event->mask & ALL_FSNOTIFY_DIRENT_EVENTS) ||
566 			   (event->mask & FAN_ONDIR)) {
567 			/*
568 			 * With group flag FAN_REPORT_DIR_FID, a single info
569 			 * record has type DFID for directory entry modification
570 			 * event and for event on a directory.
571 			 */
572 			info_type = FAN_EVENT_INFO_TYPE_DFID;
573 		} else {
574 			/*
575 			 * With group flags FAN_REPORT_DIR_FID|FAN_REPORT_FID,
576 			 * a single info record has type FID for event on a
577 			 * non-directory, when there is no directory to report.
578 			 * For example, on FAN_DELETE_SELF event.
579 			 */
580 			info_type = FAN_EVENT_INFO_TYPE_FID;
581 		}
582 
583 		ret = copy_fid_info_to_user(fanotify_event_fsid(event),
584 					    fanotify_event_object_fh(event),
585 					    info_type, dot, dot_len,
586 					    buf, count);
587 		if (ret < 0)
588 			return ret;
589 
590 		buf += ret;
591 		count -= ret;
592 		total_bytes += ret;
593 	}
594 
595 	if (pidfd_mode) {
596 		ret = copy_pidfd_info_to_user(pidfd, buf, count);
597 		if (ret < 0)
598 			return ret;
599 
600 		buf += ret;
601 		count -= ret;
602 		total_bytes += ret;
603 	}
604 
605 	if (fanotify_is_error_event(event->mask)) {
606 		ret = copy_error_info_to_user(event, buf, count);
607 		if (ret < 0)
608 			return ret;
609 		buf += ret;
610 		count -= ret;
611 		total_bytes += ret;
612 	}
613 
614 	return total_bytes;
615 }
616 
617 static ssize_t copy_event_to_user(struct fsnotify_group *group,
618 				  struct fanotify_event *event,
619 				  char __user *buf, size_t count)
620 {
621 	struct fanotify_event_metadata metadata;
622 	struct path *path = fanotify_event_path(event);
623 	struct fanotify_info *info = fanotify_event_info(event);
624 	unsigned int info_mode = FAN_GROUP_FLAG(group, FANOTIFY_INFO_MODES);
625 	unsigned int pidfd_mode = info_mode & FAN_REPORT_PIDFD;
626 	struct file *f = NULL;
627 	int ret, pidfd = FAN_NOPIDFD, fd = FAN_NOFD;
628 
629 	pr_debug("%s: group=%p event=%p\n", __func__, group, event);
630 
631 	metadata.event_len = fanotify_event_len(info_mode, event);
632 	metadata.metadata_len = FAN_EVENT_METADATA_LEN;
633 	metadata.vers = FANOTIFY_METADATA_VERSION;
634 	metadata.reserved = 0;
635 	metadata.mask = event->mask & FANOTIFY_OUTGOING_EVENTS;
636 	metadata.pid = pid_vnr(event->pid);
637 	/*
638 	 * For an unprivileged listener, event->pid can be used to identify the
639 	 * events generated by the listener process itself, without disclosing
640 	 * the pids of other processes.
641 	 */
642 	if (FAN_GROUP_FLAG(group, FANOTIFY_UNPRIV) &&
643 	    task_tgid(current) != event->pid)
644 		metadata.pid = 0;
645 
646 	/*
647 	 * For now, fid mode is required for an unprivileged listener and
648 	 * fid mode does not report fd in events.  Keep this check anyway
649 	 * for safety in case fid mode requirement is relaxed in the future
650 	 * to allow unprivileged listener to get events with no fd and no fid.
651 	 */
652 	if (!FAN_GROUP_FLAG(group, FANOTIFY_UNPRIV) &&
653 	    path && path->mnt && path->dentry) {
654 		fd = create_fd(group, path, &f);
655 		if (fd < 0)
656 			return fd;
657 	}
658 	metadata.fd = fd;
659 
660 	if (pidfd_mode) {
661 		/*
662 		 * Complain if the FAN_REPORT_PIDFD and FAN_REPORT_TID mutual
663 		 * exclusion is ever lifted. At the time of incoporating pidfd
664 		 * support within fanotify, the pidfd API only supported the
665 		 * creation of pidfds for thread-group leaders.
666 		 */
667 		WARN_ON_ONCE(FAN_GROUP_FLAG(group, FAN_REPORT_TID));
668 
669 		/*
670 		 * The PIDTYPE_TGID check for an event->pid is performed
671 		 * preemptively in an attempt to catch out cases where the event
672 		 * listener reads events after the event generating process has
673 		 * already terminated. Report FAN_NOPIDFD to the event listener
674 		 * in those cases, with all other pidfd creation errors being
675 		 * reported as FAN_EPIDFD.
676 		 */
677 		if (metadata.pid == 0 ||
678 		    !pid_has_task(event->pid, PIDTYPE_TGID)) {
679 			pidfd = FAN_NOPIDFD;
680 		} else {
681 			pidfd = pidfd_create(event->pid, 0);
682 			if (pidfd < 0)
683 				pidfd = FAN_EPIDFD;
684 		}
685 	}
686 
687 	ret = -EFAULT;
688 	/*
689 	 * Sanity check copy size in case get_one_event() and
690 	 * event_len sizes ever get out of sync.
691 	 */
692 	if (WARN_ON_ONCE(metadata.event_len > count))
693 		goto out_close_fd;
694 
695 	if (copy_to_user(buf, &metadata, FAN_EVENT_METADATA_LEN))
696 		goto out_close_fd;
697 
698 	buf += FAN_EVENT_METADATA_LEN;
699 	count -= FAN_EVENT_METADATA_LEN;
700 
701 	if (fanotify_is_perm_event(event->mask))
702 		FANOTIFY_PERM(event)->fd = fd;
703 
704 	if (info_mode) {
705 		ret = copy_info_records_to_user(event, info, info_mode, pidfd,
706 						buf, count);
707 		if (ret < 0)
708 			goto out_close_fd;
709 	}
710 
711 	if (f)
712 		fd_install(fd, f);
713 
714 	return metadata.event_len;
715 
716 out_close_fd:
717 	if (fd != FAN_NOFD) {
718 		put_unused_fd(fd);
719 		fput(f);
720 	}
721 
722 	if (pidfd >= 0)
723 		close_fd(pidfd);
724 
725 	return ret;
726 }
727 
728 /* intofiy userspace file descriptor functions */
729 static __poll_t fanotify_poll(struct file *file, poll_table *wait)
730 {
731 	struct fsnotify_group *group = file->private_data;
732 	__poll_t ret = 0;
733 
734 	poll_wait(file, &group->notification_waitq, wait);
735 	spin_lock(&group->notification_lock);
736 	if (!fsnotify_notify_queue_is_empty(group))
737 		ret = EPOLLIN | EPOLLRDNORM;
738 	spin_unlock(&group->notification_lock);
739 
740 	return ret;
741 }
742 
743 static ssize_t fanotify_read(struct file *file, char __user *buf,
744 			     size_t count, loff_t *pos)
745 {
746 	struct fsnotify_group *group;
747 	struct fanotify_event *event;
748 	char __user *start;
749 	int ret;
750 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
751 
752 	start = buf;
753 	group = file->private_data;
754 
755 	pr_debug("%s: group=%p\n", __func__, group);
756 
757 	add_wait_queue(&group->notification_waitq, &wait);
758 	while (1) {
759 		/*
760 		 * User can supply arbitrarily large buffer. Avoid softlockups
761 		 * in case there are lots of available events.
762 		 */
763 		cond_resched();
764 		event = get_one_event(group, count);
765 		if (IS_ERR(event)) {
766 			ret = PTR_ERR(event);
767 			break;
768 		}
769 
770 		if (!event) {
771 			ret = -EAGAIN;
772 			if (file->f_flags & O_NONBLOCK)
773 				break;
774 
775 			ret = -ERESTARTSYS;
776 			if (signal_pending(current))
777 				break;
778 
779 			if (start != buf)
780 				break;
781 
782 			wait_woken(&wait, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
783 			continue;
784 		}
785 
786 		ret = copy_event_to_user(group, event, buf, count);
787 		if (unlikely(ret == -EOPENSTALE)) {
788 			/*
789 			 * We cannot report events with stale fd so drop it.
790 			 * Setting ret to 0 will continue the event loop and
791 			 * do the right thing if there are no more events to
792 			 * read (i.e. return bytes read, -EAGAIN or wait).
793 			 */
794 			ret = 0;
795 		}
796 
797 		/*
798 		 * Permission events get queued to wait for response.  Other
799 		 * events can be destroyed now.
800 		 */
801 		if (!fanotify_is_perm_event(event->mask)) {
802 			fsnotify_destroy_event(group, &event->fse);
803 		} else {
804 			if (ret <= 0) {
805 				spin_lock(&group->notification_lock);
806 				finish_permission_event(group,
807 					FANOTIFY_PERM(event), FAN_DENY);
808 				wake_up(&group->fanotify_data.access_waitq);
809 			} else {
810 				spin_lock(&group->notification_lock);
811 				list_add_tail(&event->fse.list,
812 					&group->fanotify_data.access_list);
813 				spin_unlock(&group->notification_lock);
814 			}
815 		}
816 		if (ret < 0)
817 			break;
818 		buf += ret;
819 		count -= ret;
820 	}
821 	remove_wait_queue(&group->notification_waitq, &wait);
822 
823 	if (start != buf && ret != -EFAULT)
824 		ret = buf - start;
825 	return ret;
826 }
827 
828 static ssize_t fanotify_write(struct file *file, const char __user *buf, size_t count, loff_t *pos)
829 {
830 	struct fanotify_response response = { .fd = -1, .response = -1 };
831 	struct fsnotify_group *group;
832 	int ret;
833 
834 	if (!IS_ENABLED(CONFIG_FANOTIFY_ACCESS_PERMISSIONS))
835 		return -EINVAL;
836 
837 	group = file->private_data;
838 
839 	if (count < sizeof(response))
840 		return -EINVAL;
841 
842 	count = sizeof(response);
843 
844 	pr_debug("%s: group=%p count=%zu\n", __func__, group, count);
845 
846 	if (copy_from_user(&response, buf, count))
847 		return -EFAULT;
848 
849 	ret = process_access_response(group, &response);
850 	if (ret < 0)
851 		count = ret;
852 
853 	return count;
854 }
855 
856 static int fanotify_release(struct inode *ignored, struct file *file)
857 {
858 	struct fsnotify_group *group = file->private_data;
859 	struct fsnotify_event *fsn_event;
860 
861 	/*
862 	 * Stop new events from arriving in the notification queue. since
863 	 * userspace cannot use fanotify fd anymore, no event can enter or
864 	 * leave access_list by now either.
865 	 */
866 	fsnotify_group_stop_queueing(group);
867 
868 	/*
869 	 * Process all permission events on access_list and notification queue
870 	 * and simulate reply from userspace.
871 	 */
872 	spin_lock(&group->notification_lock);
873 	while (!list_empty(&group->fanotify_data.access_list)) {
874 		struct fanotify_perm_event *event;
875 
876 		event = list_first_entry(&group->fanotify_data.access_list,
877 				struct fanotify_perm_event, fae.fse.list);
878 		list_del_init(&event->fae.fse.list);
879 		finish_permission_event(group, event, FAN_ALLOW);
880 		spin_lock(&group->notification_lock);
881 	}
882 
883 	/*
884 	 * Destroy all non-permission events. For permission events just
885 	 * dequeue them and set the response. They will be freed once the
886 	 * response is consumed and fanotify_get_response() returns.
887 	 */
888 	while ((fsn_event = fsnotify_remove_first_event(group))) {
889 		struct fanotify_event *event = FANOTIFY_E(fsn_event);
890 
891 		if (!(event->mask & FANOTIFY_PERM_EVENTS)) {
892 			spin_unlock(&group->notification_lock);
893 			fsnotify_destroy_event(group, fsn_event);
894 		} else {
895 			finish_permission_event(group, FANOTIFY_PERM(event),
896 						FAN_ALLOW);
897 		}
898 		spin_lock(&group->notification_lock);
899 	}
900 	spin_unlock(&group->notification_lock);
901 
902 	/* Response for all permission events it set, wakeup waiters */
903 	wake_up(&group->fanotify_data.access_waitq);
904 
905 	/* matches the fanotify_init->fsnotify_alloc_group */
906 	fsnotify_destroy_group(group);
907 
908 	return 0;
909 }
910 
911 static long fanotify_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
912 {
913 	struct fsnotify_group *group;
914 	struct fsnotify_event *fsn_event;
915 	void __user *p;
916 	int ret = -ENOTTY;
917 	size_t send_len = 0;
918 
919 	group = file->private_data;
920 
921 	p = (void __user *) arg;
922 
923 	switch (cmd) {
924 	case FIONREAD:
925 		spin_lock(&group->notification_lock);
926 		list_for_each_entry(fsn_event, &group->notification_list, list)
927 			send_len += FAN_EVENT_METADATA_LEN;
928 		spin_unlock(&group->notification_lock);
929 		ret = put_user(send_len, (int __user *) p);
930 		break;
931 	}
932 
933 	return ret;
934 }
935 
936 static const struct file_operations fanotify_fops = {
937 	.show_fdinfo	= fanotify_show_fdinfo,
938 	.poll		= fanotify_poll,
939 	.read		= fanotify_read,
940 	.write		= fanotify_write,
941 	.fasync		= NULL,
942 	.release	= fanotify_release,
943 	.unlocked_ioctl	= fanotify_ioctl,
944 	.compat_ioctl	= compat_ptr_ioctl,
945 	.llseek		= noop_llseek,
946 };
947 
948 static int fanotify_find_path(int dfd, const char __user *filename,
949 			      struct path *path, unsigned int flags, __u64 mask,
950 			      unsigned int obj_type)
951 {
952 	int ret;
953 
954 	pr_debug("%s: dfd=%d filename=%p flags=%x\n", __func__,
955 		 dfd, filename, flags);
956 
957 	if (filename == NULL) {
958 		struct fd f = fdget(dfd);
959 
960 		ret = -EBADF;
961 		if (!f.file)
962 			goto out;
963 
964 		ret = -ENOTDIR;
965 		if ((flags & FAN_MARK_ONLYDIR) &&
966 		    !(S_ISDIR(file_inode(f.file)->i_mode))) {
967 			fdput(f);
968 			goto out;
969 		}
970 
971 		*path = f.file->f_path;
972 		path_get(path);
973 		fdput(f);
974 	} else {
975 		unsigned int lookup_flags = 0;
976 
977 		if (!(flags & FAN_MARK_DONT_FOLLOW))
978 			lookup_flags |= LOOKUP_FOLLOW;
979 		if (flags & FAN_MARK_ONLYDIR)
980 			lookup_flags |= LOOKUP_DIRECTORY;
981 
982 		ret = user_path_at(dfd, filename, lookup_flags, path);
983 		if (ret)
984 			goto out;
985 	}
986 
987 	/* you can only watch an inode if you have read permissions on it */
988 	ret = path_permission(path, MAY_READ);
989 	if (ret) {
990 		path_put(path);
991 		goto out;
992 	}
993 
994 	ret = security_path_notify(path, mask, obj_type);
995 	if (ret)
996 		path_put(path);
997 
998 out:
999 	return ret;
1000 }
1001 
1002 static __u32 fanotify_mark_remove_from_mask(struct fsnotify_mark *fsn_mark,
1003 					    __u32 mask, unsigned int flags,
1004 					    __u32 umask, int *destroy)
1005 {
1006 	__u32 oldmask, newmask;
1007 
1008 	/* umask bits cannot be removed by user */
1009 	mask &= ~umask;
1010 	spin_lock(&fsn_mark->lock);
1011 	oldmask = fsnotify_calc_mask(fsn_mark);
1012 	if (!(flags & FAN_MARK_IGNORED_MASK)) {
1013 		fsn_mark->mask &= ~mask;
1014 	} else {
1015 		fsn_mark->ignored_mask &= ~mask;
1016 	}
1017 	newmask = fsnotify_calc_mask(fsn_mark);
1018 	/*
1019 	 * We need to keep the mark around even if remaining mask cannot
1020 	 * result in any events (e.g. mask == FAN_ONDIR) to support incremenal
1021 	 * changes to the mask.
1022 	 * Destroy mark when only umask bits remain.
1023 	 */
1024 	*destroy = !((fsn_mark->mask | fsn_mark->ignored_mask) & ~umask);
1025 	spin_unlock(&fsn_mark->lock);
1026 
1027 	return oldmask & ~newmask;
1028 }
1029 
1030 static int fanotify_remove_mark(struct fsnotify_group *group,
1031 				fsnotify_connp_t *connp, __u32 mask,
1032 				unsigned int flags, __u32 umask)
1033 {
1034 	struct fsnotify_mark *fsn_mark = NULL;
1035 	__u32 removed;
1036 	int destroy_mark;
1037 
1038 	mutex_lock(&group->mark_mutex);
1039 	fsn_mark = fsnotify_find_mark(connp, group);
1040 	if (!fsn_mark) {
1041 		mutex_unlock(&group->mark_mutex);
1042 		return -ENOENT;
1043 	}
1044 
1045 	removed = fanotify_mark_remove_from_mask(fsn_mark, mask, flags,
1046 						 umask, &destroy_mark);
1047 	if (removed & fsnotify_conn_mask(fsn_mark->connector))
1048 		fsnotify_recalc_mask(fsn_mark->connector);
1049 	if (destroy_mark)
1050 		fsnotify_detach_mark(fsn_mark);
1051 	mutex_unlock(&group->mark_mutex);
1052 	if (destroy_mark)
1053 		fsnotify_free_mark(fsn_mark);
1054 
1055 	/* matches the fsnotify_find_mark() */
1056 	fsnotify_put_mark(fsn_mark);
1057 	return 0;
1058 }
1059 
1060 static int fanotify_remove_vfsmount_mark(struct fsnotify_group *group,
1061 					 struct vfsmount *mnt, __u32 mask,
1062 					 unsigned int flags, __u32 umask)
1063 {
1064 	return fanotify_remove_mark(group, &real_mount(mnt)->mnt_fsnotify_marks,
1065 				    mask, flags, umask);
1066 }
1067 
1068 static int fanotify_remove_sb_mark(struct fsnotify_group *group,
1069 				   struct super_block *sb, __u32 mask,
1070 				   unsigned int flags, __u32 umask)
1071 {
1072 	return fanotify_remove_mark(group, &sb->s_fsnotify_marks, mask,
1073 				    flags, umask);
1074 }
1075 
1076 static int fanotify_remove_inode_mark(struct fsnotify_group *group,
1077 				      struct inode *inode, __u32 mask,
1078 				      unsigned int flags, __u32 umask)
1079 {
1080 	return fanotify_remove_mark(group, &inode->i_fsnotify_marks, mask,
1081 				    flags, umask);
1082 }
1083 
1084 static void fanotify_mark_add_ignored_mask(struct fsnotify_mark *fsn_mark,
1085 					   __u32 mask, unsigned int flags,
1086 					   __u32 *removed)
1087 {
1088 	fsn_mark->ignored_mask |= mask;
1089 
1090 	/*
1091 	 * Setting FAN_MARK_IGNORED_SURV_MODIFY for the first time may lead to
1092 	 * the removal of the FS_MODIFY bit in calculated mask if it was set
1093 	 * because of an ignored mask that is now going to survive FS_MODIFY.
1094 	 */
1095 	if ((flags & FAN_MARK_IGNORED_SURV_MODIFY) &&
1096 	    !(fsn_mark->flags & FSNOTIFY_MARK_FLAG_IGNORED_SURV_MODIFY)) {
1097 		fsn_mark->flags |= FSNOTIFY_MARK_FLAG_IGNORED_SURV_MODIFY;
1098 		if (!(fsn_mark->mask & FS_MODIFY))
1099 			*removed = FS_MODIFY;
1100 	}
1101 }
1102 
1103 static __u32 fanotify_mark_add_to_mask(struct fsnotify_mark *fsn_mark,
1104 				       __u32 mask, unsigned int flags,
1105 				       __u32 *removed)
1106 {
1107 	__u32 oldmask, newmask;
1108 
1109 	spin_lock(&fsn_mark->lock);
1110 	oldmask = fsnotify_calc_mask(fsn_mark);
1111 	if (!(flags & FAN_MARK_IGNORED_MASK)) {
1112 		fsn_mark->mask |= mask;
1113 	} else {
1114 		fanotify_mark_add_ignored_mask(fsn_mark, mask, flags, removed);
1115 	}
1116 	newmask = fsnotify_calc_mask(fsn_mark);
1117 	spin_unlock(&fsn_mark->lock);
1118 
1119 	return newmask & ~oldmask;
1120 }
1121 
1122 static struct fsnotify_mark *fanotify_add_new_mark(struct fsnotify_group *group,
1123 						   fsnotify_connp_t *connp,
1124 						   unsigned int obj_type,
1125 						   __kernel_fsid_t *fsid)
1126 {
1127 	struct ucounts *ucounts = group->fanotify_data.ucounts;
1128 	struct fsnotify_mark *mark;
1129 	int ret;
1130 
1131 	/*
1132 	 * Enforce per user marks limits per user in all containing user ns.
1133 	 * A group with FAN_UNLIMITED_MARKS does not contribute to mark count
1134 	 * in the limited groups account.
1135 	 */
1136 	if (!FAN_GROUP_FLAG(group, FAN_UNLIMITED_MARKS) &&
1137 	    !inc_ucount(ucounts->ns, ucounts->uid, UCOUNT_FANOTIFY_MARKS))
1138 		return ERR_PTR(-ENOSPC);
1139 
1140 	mark = kmem_cache_alloc(fanotify_mark_cache, GFP_KERNEL);
1141 	if (!mark) {
1142 		ret = -ENOMEM;
1143 		goto out_dec_ucounts;
1144 	}
1145 
1146 	fsnotify_init_mark(mark, group);
1147 	ret = fsnotify_add_mark_locked(mark, connp, obj_type, 0, fsid);
1148 	if (ret) {
1149 		fsnotify_put_mark(mark);
1150 		goto out_dec_ucounts;
1151 	}
1152 
1153 	return mark;
1154 
1155 out_dec_ucounts:
1156 	if (!FAN_GROUP_FLAG(group, FAN_UNLIMITED_MARKS))
1157 		dec_ucount(ucounts, UCOUNT_FANOTIFY_MARKS);
1158 	return ERR_PTR(ret);
1159 }
1160 
1161 static int fanotify_group_init_error_pool(struct fsnotify_group *group)
1162 {
1163 	if (mempool_initialized(&group->fanotify_data.error_events_pool))
1164 		return 0;
1165 
1166 	return mempool_init_kmalloc_pool(&group->fanotify_data.error_events_pool,
1167 					 FANOTIFY_DEFAULT_FEE_POOL_SIZE,
1168 					 sizeof(struct fanotify_error_event));
1169 }
1170 
1171 static int fanotify_add_mark(struct fsnotify_group *group,
1172 			     fsnotify_connp_t *connp, unsigned int obj_type,
1173 			     __u32 mask, unsigned int flags,
1174 			     __kernel_fsid_t *fsid)
1175 {
1176 	struct fsnotify_mark *fsn_mark;
1177 	__u32 added, removed = 0;
1178 	int ret = 0;
1179 
1180 	mutex_lock(&group->mark_mutex);
1181 	fsn_mark = fsnotify_find_mark(connp, group);
1182 	if (!fsn_mark) {
1183 		fsn_mark = fanotify_add_new_mark(group, connp, obj_type, fsid);
1184 		if (IS_ERR(fsn_mark)) {
1185 			mutex_unlock(&group->mark_mutex);
1186 			return PTR_ERR(fsn_mark);
1187 		}
1188 	}
1189 
1190 	/*
1191 	 * Error events are pre-allocated per group, only if strictly
1192 	 * needed (i.e. FAN_FS_ERROR was requested).
1193 	 */
1194 	if (!(flags & FAN_MARK_IGNORED_MASK) && (mask & FAN_FS_ERROR)) {
1195 		ret = fanotify_group_init_error_pool(group);
1196 		if (ret)
1197 			goto out;
1198 	}
1199 
1200 	added = fanotify_mark_add_to_mask(fsn_mark, mask, flags, &removed);
1201 	if (removed || (added & ~fsnotify_conn_mask(fsn_mark->connector)))
1202 		fsnotify_recalc_mask(fsn_mark->connector);
1203 
1204 out:
1205 	mutex_unlock(&group->mark_mutex);
1206 
1207 	fsnotify_put_mark(fsn_mark);
1208 	return ret;
1209 }
1210 
1211 static int fanotify_add_vfsmount_mark(struct fsnotify_group *group,
1212 				      struct vfsmount *mnt, __u32 mask,
1213 				      unsigned int flags, __kernel_fsid_t *fsid)
1214 {
1215 	return fanotify_add_mark(group, &real_mount(mnt)->mnt_fsnotify_marks,
1216 				 FSNOTIFY_OBJ_TYPE_VFSMOUNT, mask, flags, fsid);
1217 }
1218 
1219 static int fanotify_add_sb_mark(struct fsnotify_group *group,
1220 				struct super_block *sb, __u32 mask,
1221 				unsigned int flags, __kernel_fsid_t *fsid)
1222 {
1223 	return fanotify_add_mark(group, &sb->s_fsnotify_marks,
1224 				 FSNOTIFY_OBJ_TYPE_SB, mask, flags, fsid);
1225 }
1226 
1227 static int fanotify_add_inode_mark(struct fsnotify_group *group,
1228 				   struct inode *inode, __u32 mask,
1229 				   unsigned int flags, __kernel_fsid_t *fsid)
1230 {
1231 	pr_debug("%s: group=%p inode=%p\n", __func__, group, inode);
1232 
1233 	/*
1234 	 * If some other task has this inode open for write we should not add
1235 	 * an ignored mark, unless that ignored mark is supposed to survive
1236 	 * modification changes anyway.
1237 	 */
1238 	if ((flags & FAN_MARK_IGNORED_MASK) &&
1239 	    !(flags & FAN_MARK_IGNORED_SURV_MODIFY) &&
1240 	    inode_is_open_for_write(inode))
1241 		return 0;
1242 
1243 	return fanotify_add_mark(group, &inode->i_fsnotify_marks,
1244 				 FSNOTIFY_OBJ_TYPE_INODE, mask, flags, fsid);
1245 }
1246 
1247 static struct fsnotify_event *fanotify_alloc_overflow_event(void)
1248 {
1249 	struct fanotify_event *oevent;
1250 
1251 	oevent = kmalloc(sizeof(*oevent), GFP_KERNEL_ACCOUNT);
1252 	if (!oevent)
1253 		return NULL;
1254 
1255 	fanotify_init_event(oevent, 0, FS_Q_OVERFLOW);
1256 	oevent->type = FANOTIFY_EVENT_TYPE_OVERFLOW;
1257 
1258 	return &oevent->fse;
1259 }
1260 
1261 static struct hlist_head *fanotify_alloc_merge_hash(void)
1262 {
1263 	struct hlist_head *hash;
1264 
1265 	hash = kmalloc(sizeof(struct hlist_head) << FANOTIFY_HTABLE_BITS,
1266 		       GFP_KERNEL_ACCOUNT);
1267 	if (!hash)
1268 		return NULL;
1269 
1270 	__hash_init(hash, FANOTIFY_HTABLE_SIZE);
1271 
1272 	return hash;
1273 }
1274 
1275 /* fanotify syscalls */
1276 SYSCALL_DEFINE2(fanotify_init, unsigned int, flags, unsigned int, event_f_flags)
1277 {
1278 	struct fsnotify_group *group;
1279 	int f_flags, fd;
1280 	unsigned int fid_mode = flags & FANOTIFY_FID_BITS;
1281 	unsigned int class = flags & FANOTIFY_CLASS_BITS;
1282 	unsigned int internal_flags = 0;
1283 
1284 	pr_debug("%s: flags=%x event_f_flags=%x\n",
1285 		 __func__, flags, event_f_flags);
1286 
1287 	if (!capable(CAP_SYS_ADMIN)) {
1288 		/*
1289 		 * An unprivileged user can setup an fanotify group with
1290 		 * limited functionality - an unprivileged group is limited to
1291 		 * notification events with file handles and it cannot use
1292 		 * unlimited queue/marks.
1293 		 */
1294 		if ((flags & FANOTIFY_ADMIN_INIT_FLAGS) || !fid_mode)
1295 			return -EPERM;
1296 
1297 		/*
1298 		 * Setting the internal flag FANOTIFY_UNPRIV on the group
1299 		 * prevents setting mount/filesystem marks on this group and
1300 		 * prevents reporting pid and open fd in events.
1301 		 */
1302 		internal_flags |= FANOTIFY_UNPRIV;
1303 	}
1304 
1305 #ifdef CONFIG_AUDITSYSCALL
1306 	if (flags & ~(FANOTIFY_INIT_FLAGS | FAN_ENABLE_AUDIT))
1307 #else
1308 	if (flags & ~FANOTIFY_INIT_FLAGS)
1309 #endif
1310 		return -EINVAL;
1311 
1312 	/*
1313 	 * A pidfd can only be returned for a thread-group leader; thus
1314 	 * FAN_REPORT_PIDFD and FAN_REPORT_TID need to remain mutually
1315 	 * exclusive.
1316 	 */
1317 	if ((flags & FAN_REPORT_PIDFD) && (flags & FAN_REPORT_TID))
1318 		return -EINVAL;
1319 
1320 	if (event_f_flags & ~FANOTIFY_INIT_ALL_EVENT_F_BITS)
1321 		return -EINVAL;
1322 
1323 	switch (event_f_flags & O_ACCMODE) {
1324 	case O_RDONLY:
1325 	case O_RDWR:
1326 	case O_WRONLY:
1327 		break;
1328 	default:
1329 		return -EINVAL;
1330 	}
1331 
1332 	if (fid_mode && class != FAN_CLASS_NOTIF)
1333 		return -EINVAL;
1334 
1335 	/*
1336 	 * Child name is reported with parent fid so requires dir fid.
1337 	 * We can report both child fid and dir fid with or without name.
1338 	 */
1339 	if ((fid_mode & FAN_REPORT_NAME) && !(fid_mode & FAN_REPORT_DIR_FID))
1340 		return -EINVAL;
1341 
1342 	/*
1343 	 * FAN_REPORT_TARGET_FID requires FAN_REPORT_NAME and FAN_REPORT_FID
1344 	 * and is used as an indication to report both dir and child fid on all
1345 	 * dirent events.
1346 	 */
1347 	if ((fid_mode & FAN_REPORT_TARGET_FID) &&
1348 	    (!(fid_mode & FAN_REPORT_NAME) || !(fid_mode & FAN_REPORT_FID)))
1349 		return -EINVAL;
1350 
1351 	f_flags = O_RDWR | FMODE_NONOTIFY;
1352 	if (flags & FAN_CLOEXEC)
1353 		f_flags |= O_CLOEXEC;
1354 	if (flags & FAN_NONBLOCK)
1355 		f_flags |= O_NONBLOCK;
1356 
1357 	/* fsnotify_alloc_group takes a ref.  Dropped in fanotify_release */
1358 	group = fsnotify_alloc_user_group(&fanotify_fsnotify_ops);
1359 	if (IS_ERR(group)) {
1360 		return PTR_ERR(group);
1361 	}
1362 
1363 	/* Enforce groups limits per user in all containing user ns */
1364 	group->fanotify_data.ucounts = inc_ucount(current_user_ns(),
1365 						  current_euid(),
1366 						  UCOUNT_FANOTIFY_GROUPS);
1367 	if (!group->fanotify_data.ucounts) {
1368 		fd = -EMFILE;
1369 		goto out_destroy_group;
1370 	}
1371 
1372 	group->fanotify_data.flags = flags | internal_flags;
1373 	group->memcg = get_mem_cgroup_from_mm(current->mm);
1374 
1375 	group->fanotify_data.merge_hash = fanotify_alloc_merge_hash();
1376 	if (!group->fanotify_data.merge_hash) {
1377 		fd = -ENOMEM;
1378 		goto out_destroy_group;
1379 	}
1380 
1381 	group->overflow_event = fanotify_alloc_overflow_event();
1382 	if (unlikely(!group->overflow_event)) {
1383 		fd = -ENOMEM;
1384 		goto out_destroy_group;
1385 	}
1386 
1387 	if (force_o_largefile())
1388 		event_f_flags |= O_LARGEFILE;
1389 	group->fanotify_data.f_flags = event_f_flags;
1390 	init_waitqueue_head(&group->fanotify_data.access_waitq);
1391 	INIT_LIST_HEAD(&group->fanotify_data.access_list);
1392 	switch (class) {
1393 	case FAN_CLASS_NOTIF:
1394 		group->priority = FS_PRIO_0;
1395 		break;
1396 	case FAN_CLASS_CONTENT:
1397 		group->priority = FS_PRIO_1;
1398 		break;
1399 	case FAN_CLASS_PRE_CONTENT:
1400 		group->priority = FS_PRIO_2;
1401 		break;
1402 	default:
1403 		fd = -EINVAL;
1404 		goto out_destroy_group;
1405 	}
1406 
1407 	if (flags & FAN_UNLIMITED_QUEUE) {
1408 		fd = -EPERM;
1409 		if (!capable(CAP_SYS_ADMIN))
1410 			goto out_destroy_group;
1411 		group->max_events = UINT_MAX;
1412 	} else {
1413 		group->max_events = fanotify_max_queued_events;
1414 	}
1415 
1416 	if (flags & FAN_UNLIMITED_MARKS) {
1417 		fd = -EPERM;
1418 		if (!capable(CAP_SYS_ADMIN))
1419 			goto out_destroy_group;
1420 	}
1421 
1422 	if (flags & FAN_ENABLE_AUDIT) {
1423 		fd = -EPERM;
1424 		if (!capable(CAP_AUDIT_WRITE))
1425 			goto out_destroy_group;
1426 	}
1427 
1428 	fd = anon_inode_getfd("[fanotify]", &fanotify_fops, group, f_flags);
1429 	if (fd < 0)
1430 		goto out_destroy_group;
1431 
1432 	return fd;
1433 
1434 out_destroy_group:
1435 	fsnotify_destroy_group(group);
1436 	return fd;
1437 }
1438 
1439 static int fanotify_test_fsid(struct dentry *dentry, __kernel_fsid_t *fsid)
1440 {
1441 	__kernel_fsid_t root_fsid;
1442 	int err;
1443 
1444 	/*
1445 	 * Make sure dentry is not of a filesystem with zero fsid (e.g. fuse).
1446 	 */
1447 	err = vfs_get_fsid(dentry, fsid);
1448 	if (err)
1449 		return err;
1450 
1451 	if (!fsid->val[0] && !fsid->val[1])
1452 		return -ENODEV;
1453 
1454 	/*
1455 	 * Make sure dentry is not of a filesystem subvolume (e.g. btrfs)
1456 	 * which uses a different fsid than sb root.
1457 	 */
1458 	err = vfs_get_fsid(dentry->d_sb->s_root, &root_fsid);
1459 	if (err)
1460 		return err;
1461 
1462 	if (root_fsid.val[0] != fsid->val[0] ||
1463 	    root_fsid.val[1] != fsid->val[1])
1464 		return -EXDEV;
1465 
1466 	return 0;
1467 }
1468 
1469 /* Check if filesystem can encode a unique fid */
1470 static int fanotify_test_fid(struct dentry *dentry)
1471 {
1472 	/*
1473 	 * We need to make sure that the file system supports at least
1474 	 * encoding a file handle so user can use name_to_handle_at() to
1475 	 * compare fid returned with event to the file handle of watched
1476 	 * objects. However, name_to_handle_at() requires that the
1477 	 * filesystem also supports decoding file handles.
1478 	 */
1479 	if (!dentry->d_sb->s_export_op ||
1480 	    !dentry->d_sb->s_export_op->fh_to_dentry)
1481 		return -EOPNOTSUPP;
1482 
1483 	return 0;
1484 }
1485 
1486 static int fanotify_events_supported(struct path *path, __u64 mask)
1487 {
1488 	/*
1489 	 * Some filesystems such as 'proc' acquire unusual locks when opening
1490 	 * files. For them fanotify permission events have high chances of
1491 	 * deadlocking the system - open done when reporting fanotify event
1492 	 * blocks on this "unusual" lock while another process holding the lock
1493 	 * waits for fanotify permission event to be answered. Just disallow
1494 	 * permission events for such filesystems.
1495 	 */
1496 	if (mask & FANOTIFY_PERM_EVENTS &&
1497 	    path->mnt->mnt_sb->s_type->fs_flags & FS_DISALLOW_NOTIFY_PERM)
1498 		return -EINVAL;
1499 	return 0;
1500 }
1501 
1502 static int do_fanotify_mark(int fanotify_fd, unsigned int flags, __u64 mask,
1503 			    int dfd, const char  __user *pathname)
1504 {
1505 	struct inode *inode = NULL;
1506 	struct vfsmount *mnt = NULL;
1507 	struct fsnotify_group *group;
1508 	struct fd f;
1509 	struct path path;
1510 	__kernel_fsid_t __fsid, *fsid = NULL;
1511 	u32 valid_mask = FANOTIFY_EVENTS | FANOTIFY_EVENT_FLAGS;
1512 	unsigned int mark_type = flags & FANOTIFY_MARK_TYPE_BITS;
1513 	bool ignored = flags & FAN_MARK_IGNORED_MASK;
1514 	unsigned int obj_type, fid_mode;
1515 	u32 umask = 0;
1516 	int ret;
1517 
1518 	pr_debug("%s: fanotify_fd=%d flags=%x dfd=%d pathname=%p mask=%llx\n",
1519 		 __func__, fanotify_fd, flags, dfd, pathname, mask);
1520 
1521 	/* we only use the lower 32 bits as of right now. */
1522 	if (upper_32_bits(mask))
1523 		return -EINVAL;
1524 
1525 	if (flags & ~FANOTIFY_MARK_FLAGS)
1526 		return -EINVAL;
1527 
1528 	switch (mark_type) {
1529 	case FAN_MARK_INODE:
1530 		obj_type = FSNOTIFY_OBJ_TYPE_INODE;
1531 		break;
1532 	case FAN_MARK_MOUNT:
1533 		obj_type = FSNOTIFY_OBJ_TYPE_VFSMOUNT;
1534 		break;
1535 	case FAN_MARK_FILESYSTEM:
1536 		obj_type = FSNOTIFY_OBJ_TYPE_SB;
1537 		break;
1538 	default:
1539 		return -EINVAL;
1540 	}
1541 
1542 	switch (flags & (FAN_MARK_ADD | FAN_MARK_REMOVE | FAN_MARK_FLUSH)) {
1543 	case FAN_MARK_ADD:
1544 	case FAN_MARK_REMOVE:
1545 		if (!mask)
1546 			return -EINVAL;
1547 		break;
1548 	case FAN_MARK_FLUSH:
1549 		if (flags & ~(FANOTIFY_MARK_TYPE_BITS | FAN_MARK_FLUSH))
1550 			return -EINVAL;
1551 		break;
1552 	default:
1553 		return -EINVAL;
1554 	}
1555 
1556 	if (IS_ENABLED(CONFIG_FANOTIFY_ACCESS_PERMISSIONS))
1557 		valid_mask |= FANOTIFY_PERM_EVENTS;
1558 
1559 	if (mask & ~valid_mask)
1560 		return -EINVAL;
1561 
1562 	/* Event flags (ONDIR, ON_CHILD) are meaningless in ignored mask */
1563 	if (ignored)
1564 		mask &= ~FANOTIFY_EVENT_FLAGS;
1565 
1566 	f = fdget(fanotify_fd);
1567 	if (unlikely(!f.file))
1568 		return -EBADF;
1569 
1570 	/* verify that this is indeed an fanotify instance */
1571 	ret = -EINVAL;
1572 	if (unlikely(f.file->f_op != &fanotify_fops))
1573 		goto fput_and_out;
1574 	group = f.file->private_data;
1575 
1576 	/*
1577 	 * An unprivileged user is not allowed to setup mount nor filesystem
1578 	 * marks.  This also includes setting up such marks by a group that
1579 	 * was initialized by an unprivileged user.
1580 	 */
1581 	ret = -EPERM;
1582 	if ((!capable(CAP_SYS_ADMIN) ||
1583 	     FAN_GROUP_FLAG(group, FANOTIFY_UNPRIV)) &&
1584 	    mark_type != FAN_MARK_INODE)
1585 		goto fput_and_out;
1586 
1587 	/*
1588 	 * group->priority == FS_PRIO_0 == FAN_CLASS_NOTIF.  These are not
1589 	 * allowed to set permissions events.
1590 	 */
1591 	ret = -EINVAL;
1592 	if (mask & FANOTIFY_PERM_EVENTS &&
1593 	    group->priority == FS_PRIO_0)
1594 		goto fput_and_out;
1595 
1596 	if (mask & FAN_FS_ERROR &&
1597 	    mark_type != FAN_MARK_FILESYSTEM)
1598 		goto fput_and_out;
1599 
1600 	/*
1601 	 * Events that do not carry enough information to report
1602 	 * event->fd require a group that supports reporting fid.  Those
1603 	 * events are not supported on a mount mark, because they do not
1604 	 * carry enough information (i.e. path) to be filtered by mount
1605 	 * point.
1606 	 */
1607 	fid_mode = FAN_GROUP_FLAG(group, FANOTIFY_FID_BITS);
1608 	if (mask & ~(FANOTIFY_FD_EVENTS|FANOTIFY_EVENT_FLAGS) &&
1609 	    (!fid_mode || mark_type == FAN_MARK_MOUNT))
1610 		goto fput_and_out;
1611 
1612 	/*
1613 	 * FAN_RENAME uses special info type records to report the old and
1614 	 * new parent+name.  Reporting only old and new parent id is less
1615 	 * useful and was not implemented.
1616 	 */
1617 	if (mask & FAN_RENAME && !(fid_mode & FAN_REPORT_NAME))
1618 		goto fput_and_out;
1619 
1620 	if (flags & FAN_MARK_FLUSH) {
1621 		ret = 0;
1622 		if (mark_type == FAN_MARK_MOUNT)
1623 			fsnotify_clear_vfsmount_marks_by_group(group);
1624 		else if (mark_type == FAN_MARK_FILESYSTEM)
1625 			fsnotify_clear_sb_marks_by_group(group);
1626 		else
1627 			fsnotify_clear_inode_marks_by_group(group);
1628 		goto fput_and_out;
1629 	}
1630 
1631 	ret = fanotify_find_path(dfd, pathname, &path, flags,
1632 			(mask & ALL_FSNOTIFY_EVENTS), obj_type);
1633 	if (ret)
1634 		goto fput_and_out;
1635 
1636 	if (flags & FAN_MARK_ADD) {
1637 		ret = fanotify_events_supported(&path, mask);
1638 		if (ret)
1639 			goto path_put_and_out;
1640 	}
1641 
1642 	if (fid_mode) {
1643 		ret = fanotify_test_fsid(path.dentry, &__fsid);
1644 		if (ret)
1645 			goto path_put_and_out;
1646 
1647 		ret = fanotify_test_fid(path.dentry);
1648 		if (ret)
1649 			goto path_put_and_out;
1650 
1651 		fsid = &__fsid;
1652 	}
1653 
1654 	/* inode held in place by reference to path; group by fget on fd */
1655 	if (mark_type == FAN_MARK_INODE)
1656 		inode = path.dentry->d_inode;
1657 	else
1658 		mnt = path.mnt;
1659 
1660 	/* Mask out FAN_EVENT_ON_CHILD flag for sb/mount/non-dir marks */
1661 	if (mnt || !S_ISDIR(inode->i_mode)) {
1662 		mask &= ~FAN_EVENT_ON_CHILD;
1663 		umask = FAN_EVENT_ON_CHILD;
1664 		/*
1665 		 * If group needs to report parent fid, register for getting
1666 		 * events with parent/name info for non-directory.
1667 		 */
1668 		if ((fid_mode & FAN_REPORT_DIR_FID) &&
1669 		    (flags & FAN_MARK_ADD) && !ignored)
1670 			mask |= FAN_EVENT_ON_CHILD;
1671 	}
1672 
1673 	/* create/update an inode mark */
1674 	switch (flags & (FAN_MARK_ADD | FAN_MARK_REMOVE)) {
1675 	case FAN_MARK_ADD:
1676 		if (mark_type == FAN_MARK_MOUNT)
1677 			ret = fanotify_add_vfsmount_mark(group, mnt, mask,
1678 							 flags, fsid);
1679 		else if (mark_type == FAN_MARK_FILESYSTEM)
1680 			ret = fanotify_add_sb_mark(group, mnt->mnt_sb, mask,
1681 						   flags, fsid);
1682 		else
1683 			ret = fanotify_add_inode_mark(group, inode, mask,
1684 						      flags, fsid);
1685 		break;
1686 	case FAN_MARK_REMOVE:
1687 		if (mark_type == FAN_MARK_MOUNT)
1688 			ret = fanotify_remove_vfsmount_mark(group, mnt, mask,
1689 							    flags, umask);
1690 		else if (mark_type == FAN_MARK_FILESYSTEM)
1691 			ret = fanotify_remove_sb_mark(group, mnt->mnt_sb, mask,
1692 						      flags, umask);
1693 		else
1694 			ret = fanotify_remove_inode_mark(group, inode, mask,
1695 							 flags, umask);
1696 		break;
1697 	default:
1698 		ret = -EINVAL;
1699 	}
1700 
1701 path_put_and_out:
1702 	path_put(&path);
1703 fput_and_out:
1704 	fdput(f);
1705 	return ret;
1706 }
1707 
1708 #ifndef CONFIG_ARCH_SPLIT_ARG64
1709 SYSCALL_DEFINE5(fanotify_mark, int, fanotify_fd, unsigned int, flags,
1710 			      __u64, mask, int, dfd,
1711 			      const char  __user *, pathname)
1712 {
1713 	return do_fanotify_mark(fanotify_fd, flags, mask, dfd, pathname);
1714 }
1715 #endif
1716 
1717 #if defined(CONFIG_ARCH_SPLIT_ARG64) || defined(CONFIG_COMPAT)
1718 SYSCALL32_DEFINE6(fanotify_mark,
1719 				int, fanotify_fd, unsigned int, flags,
1720 				SC_ARG64(mask), int, dfd,
1721 				const char  __user *, pathname)
1722 {
1723 	return do_fanotify_mark(fanotify_fd, flags, SC_VAL64(__u64, mask),
1724 				dfd, pathname);
1725 }
1726 #endif
1727 
1728 /*
1729  * fanotify_user_setup - Our initialization function.  Note that we cannot return
1730  * error because we have compiled-in VFS hooks.  So an (unlikely) failure here
1731  * must result in panic().
1732  */
1733 static int __init fanotify_user_setup(void)
1734 {
1735 	struct sysinfo si;
1736 	int max_marks;
1737 
1738 	si_meminfo(&si);
1739 	/*
1740 	 * Allow up to 1% of addressable memory to be accounted for per user
1741 	 * marks limited to the range [8192, 1048576]. mount and sb marks are
1742 	 * a lot cheaper than inode marks, but there is no reason for a user
1743 	 * to have many of those, so calculate by the cost of inode marks.
1744 	 */
1745 	max_marks = (((si.totalram - si.totalhigh) / 100) << PAGE_SHIFT) /
1746 		    INODE_MARK_COST;
1747 	max_marks = clamp(max_marks, FANOTIFY_OLD_DEFAULT_MAX_MARKS,
1748 				     FANOTIFY_DEFAULT_MAX_USER_MARKS);
1749 
1750 	BUILD_BUG_ON(FANOTIFY_INIT_FLAGS & FANOTIFY_INTERNAL_GROUP_FLAGS);
1751 	BUILD_BUG_ON(HWEIGHT32(FANOTIFY_INIT_FLAGS) != 12);
1752 	BUILD_BUG_ON(HWEIGHT32(FANOTIFY_MARK_FLAGS) != 9);
1753 
1754 	fanotify_mark_cache = KMEM_CACHE(fsnotify_mark,
1755 					 SLAB_PANIC|SLAB_ACCOUNT);
1756 	fanotify_fid_event_cachep = KMEM_CACHE(fanotify_fid_event,
1757 					       SLAB_PANIC);
1758 	fanotify_path_event_cachep = KMEM_CACHE(fanotify_path_event,
1759 						SLAB_PANIC);
1760 	if (IS_ENABLED(CONFIG_FANOTIFY_ACCESS_PERMISSIONS)) {
1761 		fanotify_perm_event_cachep =
1762 			KMEM_CACHE(fanotify_perm_event, SLAB_PANIC);
1763 	}
1764 
1765 	fanotify_max_queued_events = FANOTIFY_DEFAULT_MAX_EVENTS;
1766 	init_user_ns.ucount_max[UCOUNT_FANOTIFY_GROUPS] =
1767 					FANOTIFY_DEFAULT_MAX_GROUPS;
1768 	init_user_ns.ucount_max[UCOUNT_FANOTIFY_MARKS] = max_marks;
1769 	fanotify_sysctls_init();
1770 
1771 	return 0;
1772 }
1773 device_initcall(fanotify_user_setup);
1774