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