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