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