1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * fs/kernfs/file.c - kernfs file implementation
4 *
5 * Copyright (c) 2001-3 Patrick Mochel
6 * Copyright (c) 2007 SUSE Linux Products GmbH
7 * Copyright (c) 2007, 2013 Tejun Heo <tj@kernel.org>
8 */
9
10 #include <linux/fs.h>
11 #include <linux/seq_file.h>
12 #include <linux/slab.h>
13 #include <linux/poll.h>
14 #include <linux/pagemap.h>
15 #include <linux/sched/mm.h>
16 #include <linux/fsnotify.h>
17 #include <linux/uio.h>
18
19 #include "kernfs-internal.h"
20
21 struct kernfs_open_node {
22 struct rcu_head rcu_head;
23 atomic_t event;
24 wait_queue_head_t poll;
25 struct list_head files; /* goes through kernfs_open_file.list */
26 unsigned int nr_mmapped;
27 unsigned int nr_to_release;
28 };
29
30 /*
31 * kernfs_notify() may be called from any context and bounces notifications
32 * through a work item. To minimize space overhead in kernfs_node, the
33 * pending queue is implemented as a singly linked list of kernfs_nodes.
34 * The list is terminated with the self pointer so that whether a
35 * kernfs_node is on the list or not can be determined by testing the next
36 * pointer for NULL.
37 */
38 #define KERNFS_NOTIFY_EOL ((void *)&kernfs_notify_list)
39
40 static DEFINE_SPINLOCK(kernfs_notify_lock);
41 static struct kernfs_node *kernfs_notify_list = KERNFS_NOTIFY_EOL;
42
kernfs_open_file_mutex_ptr(struct kernfs_node * kn)43 static inline struct mutex *kernfs_open_file_mutex_ptr(struct kernfs_node *kn)
44 {
45 int idx = hash_ptr(kn, NR_KERNFS_LOCK_BITS);
46
47 return &kernfs_locks->open_file_mutex[idx];
48 }
49
kernfs_open_file_mutex_lock(struct kernfs_node * kn)50 static inline struct mutex *kernfs_open_file_mutex_lock(struct kernfs_node *kn)
51 {
52 struct mutex *lock;
53
54 lock = kernfs_open_file_mutex_ptr(kn);
55
56 mutex_lock(lock);
57
58 return lock;
59 }
60
61 /**
62 * of_on - Return the kernfs_open_node of the specified kernfs_open_file
63 * @of: taret kernfs_open_file
64 */
of_on(struct kernfs_open_file * of)65 static struct kernfs_open_node *of_on(struct kernfs_open_file *of)
66 {
67 return rcu_dereference_protected(of->kn->attr.open,
68 !list_empty(&of->list));
69 }
70
71 /**
72 * kernfs_deref_open_node_locked - Get kernfs_open_node corresponding to @kn
73 *
74 * @kn: target kernfs_node.
75 *
76 * Fetch and return ->attr.open of @kn when caller holds the
77 * kernfs_open_file_mutex_ptr(kn).
78 *
79 * Update of ->attr.open happens under kernfs_open_file_mutex_ptr(kn). So when
80 * the caller guarantees that this mutex is being held, other updaters can't
81 * change ->attr.open and this means that we can safely deref ->attr.open
82 * outside RCU read-side critical section.
83 *
84 * The caller needs to make sure that kernfs_open_file_mutex is held.
85 */
86 static struct kernfs_open_node *
kernfs_deref_open_node_locked(struct kernfs_node * kn)87 kernfs_deref_open_node_locked(struct kernfs_node *kn)
88 {
89 return rcu_dereference_protected(kn->attr.open,
90 lockdep_is_held(kernfs_open_file_mutex_ptr(kn)));
91 }
92
kernfs_of(struct file * file)93 static struct kernfs_open_file *kernfs_of(struct file *file)
94 {
95 return ((struct seq_file *)file->private_data)->private;
96 }
97
98 /*
99 * Determine the kernfs_ops for the given kernfs_node. This function must
100 * be called while holding an active reference.
101 */
kernfs_ops(struct kernfs_node * kn)102 static const struct kernfs_ops *kernfs_ops(struct kernfs_node *kn)
103 {
104 if (kn->flags & KERNFS_LOCKDEP)
105 lockdep_assert_held(kn);
106 return kn->attr.ops;
107 }
108
109 /*
110 * As kernfs_seq_stop() is also called after kernfs_seq_start() or
111 * kernfs_seq_next() failure, it needs to distinguish whether it's stopping
112 * a seq_file iteration which is fully initialized with an active reference
113 * or an aborted kernfs_seq_start() due to get_active failure. The
114 * position pointer is the only context for each seq_file iteration and
115 * thus the stop condition should be encoded in it. As the return value is
116 * directly visible to userland, ERR_PTR(-ENODEV) is the only acceptable
117 * choice to indicate get_active failure.
118 *
119 * Unfortunately, this is complicated due to the optional custom seq_file
120 * operations which may return ERR_PTR(-ENODEV) too. kernfs_seq_stop()
121 * can't distinguish whether ERR_PTR(-ENODEV) is from get_active failure or
122 * custom seq_file operations and thus can't decide whether put_active
123 * should be performed or not only on ERR_PTR(-ENODEV).
124 *
125 * This is worked around by factoring out the custom seq_stop() and
126 * put_active part into kernfs_seq_stop_active(), skipping it from
127 * kernfs_seq_stop() if ERR_PTR(-ENODEV) while invoking it directly after
128 * custom seq_file operations fail with ERR_PTR(-ENODEV) - this ensures
129 * that kernfs_seq_stop_active() is skipped only after get_active failure.
130 */
kernfs_seq_stop_active(struct seq_file * sf,void * v)131 static void kernfs_seq_stop_active(struct seq_file *sf, void *v)
132 {
133 struct kernfs_open_file *of = sf->private;
134 const struct kernfs_ops *ops = kernfs_ops(of->kn);
135
136 if (ops->seq_stop)
137 ops->seq_stop(sf, v);
138 kernfs_put_active(of->kn);
139 }
140
kernfs_seq_start(struct seq_file * sf,loff_t * ppos)141 static void *kernfs_seq_start(struct seq_file *sf, loff_t *ppos)
142 {
143 struct kernfs_open_file *of = sf->private;
144 const struct kernfs_ops *ops;
145
146 /*
147 * @of->mutex nests outside active ref and is primarily to ensure that
148 * the ops aren't called concurrently for the same open file.
149 */
150 mutex_lock(&of->mutex);
151 if (!kernfs_get_active(of->kn))
152 return ERR_PTR(-ENODEV);
153
154 ops = kernfs_ops(of->kn);
155 if (ops->seq_start) {
156 void *next = ops->seq_start(sf, ppos);
157 /* see the comment above kernfs_seq_stop_active() */
158 if (next == ERR_PTR(-ENODEV))
159 kernfs_seq_stop_active(sf, next);
160 return next;
161 }
162 return single_start(sf, ppos);
163 }
164
kernfs_seq_next(struct seq_file * sf,void * v,loff_t * ppos)165 static void *kernfs_seq_next(struct seq_file *sf, void *v, loff_t *ppos)
166 {
167 struct kernfs_open_file *of = sf->private;
168 const struct kernfs_ops *ops = kernfs_ops(of->kn);
169
170 if (ops->seq_next) {
171 void *next = ops->seq_next(sf, v, ppos);
172 /* see the comment above kernfs_seq_stop_active() */
173 if (next == ERR_PTR(-ENODEV))
174 kernfs_seq_stop_active(sf, next);
175 return next;
176 } else {
177 /*
178 * The same behavior and code as single_open(), always
179 * terminate after the initial read.
180 */
181 ++*ppos;
182 return NULL;
183 }
184 }
185
kernfs_seq_stop(struct seq_file * sf,void * v)186 static void kernfs_seq_stop(struct seq_file *sf, void *v)
187 {
188 struct kernfs_open_file *of = sf->private;
189
190 if (v != ERR_PTR(-ENODEV))
191 kernfs_seq_stop_active(sf, v);
192 mutex_unlock(&of->mutex);
193 }
194
kernfs_seq_show(struct seq_file * sf,void * v)195 static int kernfs_seq_show(struct seq_file *sf, void *v)
196 {
197 struct kernfs_open_file *of = sf->private;
198
199 of->event = atomic_read(&of_on(of)->event);
200
201 return of->kn->attr.ops->seq_show(sf, v);
202 }
203
204 static const struct seq_operations kernfs_seq_ops = {
205 .start = kernfs_seq_start,
206 .next = kernfs_seq_next,
207 .stop = kernfs_seq_stop,
208 .show = kernfs_seq_show,
209 };
210
211 /*
212 * As reading a bin file can have side-effects, the exact offset and bytes
213 * specified in read(2) call should be passed to the read callback making
214 * it difficult to use seq_file. Implement simplistic custom buffering for
215 * bin files.
216 */
kernfs_file_read_iter(struct kiocb * iocb,struct iov_iter * iter)217 static ssize_t kernfs_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
218 {
219 struct kernfs_open_file *of = kernfs_of(iocb->ki_filp);
220 ssize_t len = min_t(size_t, iov_iter_count(iter), PAGE_SIZE);
221 const struct kernfs_ops *ops;
222 char *buf;
223
224 buf = of->prealloc_buf;
225 if (buf)
226 mutex_lock(&of->prealloc_mutex);
227 else
228 buf = kmalloc(len, GFP_KERNEL);
229 if (!buf)
230 return -ENOMEM;
231
232 /*
233 * @of->mutex nests outside active ref and is used both to ensure that
234 * the ops aren't called concurrently for the same open file.
235 */
236 mutex_lock(&of->mutex);
237 if (!kernfs_get_active(of->kn)) {
238 len = -ENODEV;
239 mutex_unlock(&of->mutex);
240 goto out_free;
241 }
242
243 of->event = atomic_read(&of_on(of)->event);
244
245 ops = kernfs_ops(of->kn);
246 if (ops->read)
247 len = ops->read(of, buf, len, iocb->ki_pos);
248 else
249 len = -EINVAL;
250
251 kernfs_put_active(of->kn);
252 mutex_unlock(&of->mutex);
253
254 if (len < 0)
255 goto out_free;
256
257 if (copy_to_iter(buf, len, iter) != len) {
258 len = -EFAULT;
259 goto out_free;
260 }
261
262 iocb->ki_pos += len;
263
264 out_free:
265 if (buf == of->prealloc_buf)
266 mutex_unlock(&of->prealloc_mutex);
267 else
268 kfree(buf);
269 return len;
270 }
271
kernfs_fop_read_iter(struct kiocb * iocb,struct iov_iter * iter)272 static ssize_t kernfs_fop_read_iter(struct kiocb *iocb, struct iov_iter *iter)
273 {
274 if (kernfs_of(iocb->ki_filp)->kn->flags & KERNFS_HAS_SEQ_SHOW)
275 return seq_read_iter(iocb, iter);
276 return kernfs_file_read_iter(iocb, iter);
277 }
278
279 /*
280 * Copy data in from userland and pass it to the matching kernfs write
281 * operation.
282 *
283 * There is no easy way for us to know if userspace is only doing a partial
284 * write, so we don't support them. We expect the entire buffer to come on
285 * the first write. Hint: if you're writing a value, first read the file,
286 * modify only the value you're changing, then write entire buffer
287 * back.
288 */
kernfs_fop_write_iter(struct kiocb * iocb,struct iov_iter * iter)289 static ssize_t kernfs_fop_write_iter(struct kiocb *iocb, struct iov_iter *iter)
290 {
291 struct kernfs_open_file *of = kernfs_of(iocb->ki_filp);
292 ssize_t len = iov_iter_count(iter);
293 const struct kernfs_ops *ops;
294 char *buf;
295
296 if (of->atomic_write_len) {
297 if (len > of->atomic_write_len)
298 return -E2BIG;
299 } else {
300 len = min_t(size_t, len, PAGE_SIZE);
301 }
302
303 buf = of->prealloc_buf;
304 if (buf)
305 mutex_lock(&of->prealloc_mutex);
306 else
307 buf = kmalloc(len + 1, GFP_KERNEL);
308 if (!buf)
309 return -ENOMEM;
310
311 if (copy_from_iter(buf, len, iter) != len) {
312 len = -EFAULT;
313 goto out_free;
314 }
315 buf[len] = '\0'; /* guarantee string termination */
316
317 /*
318 * @of->mutex nests outside active ref and is used both to ensure that
319 * the ops aren't called concurrently for the same open file.
320 */
321 mutex_lock(&of->mutex);
322 if (!kernfs_get_active(of->kn)) {
323 mutex_unlock(&of->mutex);
324 len = -ENODEV;
325 goto out_free;
326 }
327
328 ops = kernfs_ops(of->kn);
329 if (ops->write)
330 len = ops->write(of, buf, len, iocb->ki_pos);
331 else
332 len = -EINVAL;
333
334 kernfs_put_active(of->kn);
335 mutex_unlock(&of->mutex);
336
337 if (len > 0)
338 iocb->ki_pos += len;
339
340 out_free:
341 if (buf == of->prealloc_buf)
342 mutex_unlock(&of->prealloc_mutex);
343 else
344 kfree(buf);
345 return len;
346 }
347
kernfs_vma_open(struct vm_area_struct * vma)348 static void kernfs_vma_open(struct vm_area_struct *vma)
349 {
350 struct file *file = vma->vm_file;
351 struct kernfs_open_file *of = kernfs_of(file);
352
353 if (!of->vm_ops)
354 return;
355
356 if (!kernfs_get_active(of->kn))
357 return;
358
359 if (of->vm_ops->open)
360 of->vm_ops->open(vma);
361
362 kernfs_put_active(of->kn);
363 }
364
kernfs_vma_fault(struct vm_fault * vmf)365 static vm_fault_t kernfs_vma_fault(struct vm_fault *vmf)
366 {
367 struct file *file = vmf->vma->vm_file;
368 struct kernfs_open_file *of = kernfs_of(file);
369 vm_fault_t ret;
370
371 if (!of->vm_ops)
372 return VM_FAULT_SIGBUS;
373
374 if (!kernfs_get_active(of->kn))
375 return VM_FAULT_SIGBUS;
376
377 ret = VM_FAULT_SIGBUS;
378 if (of->vm_ops->fault)
379 ret = of->vm_ops->fault(vmf);
380
381 kernfs_put_active(of->kn);
382 return ret;
383 }
384
kernfs_vma_page_mkwrite(struct vm_fault * vmf)385 static vm_fault_t kernfs_vma_page_mkwrite(struct vm_fault *vmf)
386 {
387 struct file *file = vmf->vma->vm_file;
388 struct kernfs_open_file *of = kernfs_of(file);
389 vm_fault_t ret;
390
391 if (!of->vm_ops)
392 return VM_FAULT_SIGBUS;
393
394 if (!kernfs_get_active(of->kn))
395 return VM_FAULT_SIGBUS;
396
397 ret = 0;
398 if (of->vm_ops->page_mkwrite)
399 ret = of->vm_ops->page_mkwrite(vmf);
400 else
401 file_update_time(file);
402
403 kernfs_put_active(of->kn);
404 return ret;
405 }
406
kernfs_vma_access(struct vm_area_struct * vma,unsigned long addr,void * buf,int len,int write)407 static int kernfs_vma_access(struct vm_area_struct *vma, unsigned long addr,
408 void *buf, int len, int write)
409 {
410 struct file *file = vma->vm_file;
411 struct kernfs_open_file *of = kernfs_of(file);
412 int ret;
413
414 if (!of->vm_ops)
415 return -EINVAL;
416
417 if (!kernfs_get_active(of->kn))
418 return -EINVAL;
419
420 ret = -EINVAL;
421 if (of->vm_ops->access)
422 ret = of->vm_ops->access(vma, addr, buf, len, write);
423
424 kernfs_put_active(of->kn);
425 return ret;
426 }
427
428 #ifdef CONFIG_NUMA
kernfs_vma_set_policy(struct vm_area_struct * vma,struct mempolicy * new)429 static int kernfs_vma_set_policy(struct vm_area_struct *vma,
430 struct mempolicy *new)
431 {
432 struct file *file = vma->vm_file;
433 struct kernfs_open_file *of = kernfs_of(file);
434 int ret;
435
436 if (!of->vm_ops)
437 return 0;
438
439 if (!kernfs_get_active(of->kn))
440 return -EINVAL;
441
442 ret = 0;
443 if (of->vm_ops->set_policy)
444 ret = of->vm_ops->set_policy(vma, new);
445
446 kernfs_put_active(of->kn);
447 return ret;
448 }
449
kernfs_vma_get_policy(struct vm_area_struct * vma,unsigned long addr)450 static struct mempolicy *kernfs_vma_get_policy(struct vm_area_struct *vma,
451 unsigned long addr)
452 {
453 struct file *file = vma->vm_file;
454 struct kernfs_open_file *of = kernfs_of(file);
455 struct mempolicy *pol;
456
457 if (!of->vm_ops)
458 return vma->vm_policy;
459
460 if (!kernfs_get_active(of->kn))
461 return vma->vm_policy;
462
463 pol = vma->vm_policy;
464 if (of->vm_ops->get_policy)
465 pol = of->vm_ops->get_policy(vma, addr);
466
467 kernfs_put_active(of->kn);
468 return pol;
469 }
470
471 #endif
472
473 static const struct vm_operations_struct kernfs_vm_ops = {
474 .open = kernfs_vma_open,
475 .fault = kernfs_vma_fault,
476 .page_mkwrite = kernfs_vma_page_mkwrite,
477 .access = kernfs_vma_access,
478 #ifdef CONFIG_NUMA
479 .set_policy = kernfs_vma_set_policy,
480 .get_policy = kernfs_vma_get_policy,
481 #endif
482 };
483
kernfs_fop_mmap(struct file * file,struct vm_area_struct * vma)484 static int kernfs_fop_mmap(struct file *file, struct vm_area_struct *vma)
485 {
486 struct kernfs_open_file *of = kernfs_of(file);
487 const struct kernfs_ops *ops;
488 int rc;
489
490 /*
491 * mmap path and of->mutex are prone to triggering spurious lockdep
492 * warnings and we don't want to add spurious locking dependency
493 * between the two. Check whether mmap is actually implemented
494 * without grabbing @of->mutex by testing HAS_MMAP flag. See the
495 * comment in kernfs_file_open() for more details.
496 */
497 if (!(of->kn->flags & KERNFS_HAS_MMAP))
498 return -ENODEV;
499
500 mutex_lock(&of->mutex);
501
502 rc = -ENODEV;
503 if (!kernfs_get_active(of->kn))
504 goto out_unlock;
505
506 ops = kernfs_ops(of->kn);
507 rc = ops->mmap(of, vma);
508 if (rc)
509 goto out_put;
510
511 /*
512 * PowerPC's pci_mmap of legacy_mem uses shmem_zero_setup()
513 * to satisfy versions of X which crash if the mmap fails: that
514 * substitutes a new vm_file, and we don't then want bin_vm_ops.
515 */
516 if (vma->vm_file != file)
517 goto out_put;
518
519 rc = -EINVAL;
520 if (of->mmapped && of->vm_ops != vma->vm_ops)
521 goto out_put;
522
523 /*
524 * It is not possible to successfully wrap close.
525 * So error if someone is trying to use close.
526 */
527 if (vma->vm_ops && vma->vm_ops->close)
528 goto out_put;
529
530 rc = 0;
531 of->mmapped = true;
532 of_on(of)->nr_mmapped++;
533 of->vm_ops = vma->vm_ops;
534 vma->vm_ops = &kernfs_vm_ops;
535 out_put:
536 kernfs_put_active(of->kn);
537 out_unlock:
538 mutex_unlock(&of->mutex);
539
540 return rc;
541 }
542
543 /**
544 * kernfs_get_open_node - get or create kernfs_open_node
545 * @kn: target kernfs_node
546 * @of: kernfs_open_file for this instance of open
547 *
548 * If @kn->attr.open exists, increment its reference count; otherwise,
549 * create one. @of is chained to the files list.
550 *
551 * LOCKING:
552 * Kernel thread context (may sleep).
553 *
554 * RETURNS:
555 * 0 on success, -errno on failure.
556 */
kernfs_get_open_node(struct kernfs_node * kn,struct kernfs_open_file * of)557 static int kernfs_get_open_node(struct kernfs_node *kn,
558 struct kernfs_open_file *of)
559 {
560 struct kernfs_open_node *on;
561 struct mutex *mutex;
562
563 mutex = kernfs_open_file_mutex_lock(kn);
564 on = kernfs_deref_open_node_locked(kn);
565
566 if (!on) {
567 /* not there, initialize a new one */
568 on = kzalloc(sizeof(*on), GFP_KERNEL);
569 if (!on) {
570 mutex_unlock(mutex);
571 return -ENOMEM;
572 }
573 atomic_set(&on->event, 1);
574 init_waitqueue_head(&on->poll);
575 INIT_LIST_HEAD(&on->files);
576 rcu_assign_pointer(kn->attr.open, on);
577 }
578
579 list_add_tail(&of->list, &on->files);
580 if (kn->flags & KERNFS_HAS_RELEASE)
581 on->nr_to_release++;
582
583 mutex_unlock(mutex);
584 return 0;
585 }
586
587 /**
588 * kernfs_unlink_open_file - Unlink @of from @kn.
589 *
590 * @kn: target kernfs_node
591 * @of: associated kernfs_open_file
592 * @open_failed: ->open() failed, cancel ->release()
593 *
594 * Unlink @of from list of @kn's associated open files. If list of
595 * associated open files becomes empty, disassociate and free
596 * kernfs_open_node.
597 *
598 * LOCKING:
599 * None.
600 */
kernfs_unlink_open_file(struct kernfs_node * kn,struct kernfs_open_file * of,bool open_failed)601 static void kernfs_unlink_open_file(struct kernfs_node *kn,
602 struct kernfs_open_file *of,
603 bool open_failed)
604 {
605 struct kernfs_open_node *on;
606 struct mutex *mutex;
607
608 mutex = kernfs_open_file_mutex_lock(kn);
609
610 on = kernfs_deref_open_node_locked(kn);
611 if (!on) {
612 mutex_unlock(mutex);
613 return;
614 }
615
616 if (of) {
617 if (kn->flags & KERNFS_HAS_RELEASE) {
618 WARN_ON_ONCE(of->released == open_failed);
619 if (open_failed)
620 on->nr_to_release--;
621 }
622 if (of->mmapped)
623 on->nr_mmapped--;
624 list_del(&of->list);
625 }
626
627 if (list_empty(&on->files)) {
628 rcu_assign_pointer(kn->attr.open, NULL);
629 kfree_rcu(on, rcu_head);
630 }
631
632 mutex_unlock(mutex);
633 }
634
kernfs_fop_open(struct inode * inode,struct file * file)635 static int kernfs_fop_open(struct inode *inode, struct file *file)
636 {
637 struct kernfs_node *kn = inode->i_private;
638 struct kernfs_root *root = kernfs_root(kn);
639 const struct kernfs_ops *ops;
640 struct kernfs_open_file *of;
641 bool has_read, has_write, has_mmap;
642 int error = -EACCES;
643
644 if (!kernfs_get_active(kn))
645 return -ENODEV;
646
647 ops = kernfs_ops(kn);
648
649 has_read = ops->seq_show || ops->read || ops->mmap;
650 has_write = ops->write || ops->mmap;
651 has_mmap = ops->mmap;
652
653 /* see the flag definition for details */
654 if (root->flags & KERNFS_ROOT_EXTRA_OPEN_PERM_CHECK) {
655 if ((file->f_mode & FMODE_WRITE) &&
656 (!(inode->i_mode & S_IWUGO) || !has_write))
657 goto err_out;
658
659 if ((file->f_mode & FMODE_READ) &&
660 (!(inode->i_mode & S_IRUGO) || !has_read))
661 goto err_out;
662 }
663
664 /* allocate a kernfs_open_file for the file */
665 error = -ENOMEM;
666 of = kzalloc(sizeof(struct kernfs_open_file), GFP_KERNEL);
667 if (!of)
668 goto err_out;
669
670 /*
671 * The following is done to give a different lockdep key to
672 * @of->mutex for files which implement mmap. This is a rather
673 * crude way to avoid false positive lockdep warning around
674 * mm->mmap_lock - mmap nests @of->mutex under mm->mmap_lock and
675 * reading /sys/block/sda/trace/act_mask grabs sr_mutex, under
676 * which mm->mmap_lock nests, while holding @of->mutex. As each
677 * open file has a separate mutex, it's okay as long as those don't
678 * happen on the same file. At this point, we can't easily give
679 * each file a separate locking class. Let's differentiate on
680 * whether the file has mmap or not for now.
681 *
682 * Both paths of the branch look the same. They're supposed to
683 * look that way and give @of->mutex different static lockdep keys.
684 */
685 if (has_mmap)
686 mutex_init(&of->mutex);
687 else
688 mutex_init(&of->mutex);
689
690 of->kn = kn;
691 of->file = file;
692
693 /*
694 * Write path needs to atomic_write_len outside active reference.
695 * Cache it in open_file. See kernfs_fop_write_iter() for details.
696 */
697 of->atomic_write_len = ops->atomic_write_len;
698
699 error = -EINVAL;
700 /*
701 * ->seq_show is incompatible with ->prealloc,
702 * as seq_read does its own allocation.
703 * ->read must be used instead.
704 */
705 if (ops->prealloc && ops->seq_show)
706 goto err_free;
707 if (ops->prealloc) {
708 int len = of->atomic_write_len ?: PAGE_SIZE;
709 of->prealloc_buf = kmalloc(len + 1, GFP_KERNEL);
710 error = -ENOMEM;
711 if (!of->prealloc_buf)
712 goto err_free;
713 mutex_init(&of->prealloc_mutex);
714 }
715
716 /*
717 * Always instantiate seq_file even if read access doesn't use
718 * seq_file or is not requested. This unifies private data access
719 * and readable regular files are the vast majority anyway.
720 */
721 if (ops->seq_show)
722 error = seq_open(file, &kernfs_seq_ops);
723 else
724 error = seq_open(file, NULL);
725 if (error)
726 goto err_free;
727
728 of->seq_file = file->private_data;
729 of->seq_file->private = of;
730
731 /* seq_file clears PWRITE unconditionally, restore it if WRITE */
732 if (file->f_mode & FMODE_WRITE)
733 file->f_mode |= FMODE_PWRITE;
734
735 /* make sure we have open node struct */
736 error = kernfs_get_open_node(kn, of);
737 if (error)
738 goto err_seq_release;
739
740 if (ops->open) {
741 /* nobody has access to @of yet, skip @of->mutex */
742 error = ops->open(of);
743 if (error)
744 goto err_put_node;
745 }
746
747 /* open succeeded, put active references */
748 kernfs_put_active(kn);
749 return 0;
750
751 err_put_node:
752 kernfs_unlink_open_file(kn, of, true);
753 err_seq_release:
754 seq_release(inode, file);
755 err_free:
756 kfree(of->prealloc_buf);
757 kfree(of);
758 err_out:
759 kernfs_put_active(kn);
760 return error;
761 }
762
763 /* used from release/drain to ensure that ->release() is called exactly once */
kernfs_release_file(struct kernfs_node * kn,struct kernfs_open_file * of)764 static void kernfs_release_file(struct kernfs_node *kn,
765 struct kernfs_open_file *of)
766 {
767 /*
768 * @of is guaranteed to have no other file operations in flight and
769 * we just want to synchronize release and drain paths.
770 * @kernfs_open_file_mutex_ptr(kn) is enough. @of->mutex can't be used
771 * here because drain path may be called from places which can
772 * cause circular dependency.
773 */
774 lockdep_assert_held(kernfs_open_file_mutex_ptr(kn));
775
776 if (!of->released) {
777 /*
778 * A file is never detached without being released and we
779 * need to be able to release files which are deactivated
780 * and being drained. Don't use kernfs_ops().
781 */
782 kn->attr.ops->release(of);
783 of->released = true;
784 of_on(of)->nr_to_release--;
785 }
786 }
787
kernfs_fop_release(struct inode * inode,struct file * filp)788 static int kernfs_fop_release(struct inode *inode, struct file *filp)
789 {
790 struct kernfs_node *kn = inode->i_private;
791 struct kernfs_open_file *of = kernfs_of(filp);
792
793 if (kn->flags & KERNFS_HAS_RELEASE) {
794 struct mutex *mutex;
795
796 mutex = kernfs_open_file_mutex_lock(kn);
797 kernfs_release_file(kn, of);
798 mutex_unlock(mutex);
799 }
800
801 kernfs_unlink_open_file(kn, of, false);
802 seq_release(inode, filp);
803 kfree(of->prealloc_buf);
804 kfree(of);
805
806 return 0;
807 }
808
kernfs_should_drain_open_files(struct kernfs_node * kn)809 bool kernfs_should_drain_open_files(struct kernfs_node *kn)
810 {
811 struct kernfs_open_node *on;
812 bool ret;
813
814 /*
815 * @kn being deactivated guarantees that @kn->attr.open can't change
816 * beneath us making the lockless test below safe.
817 */
818 WARN_ON_ONCE(atomic_read(&kn->active) != KN_DEACTIVATED_BIAS);
819
820 rcu_read_lock();
821 on = rcu_dereference(kn->attr.open);
822 ret = on && (on->nr_mmapped || on->nr_to_release);
823 rcu_read_unlock();
824
825 return ret;
826 }
827
kernfs_drain_open_files(struct kernfs_node * kn)828 void kernfs_drain_open_files(struct kernfs_node *kn)
829 {
830 struct kernfs_open_node *on;
831 struct kernfs_open_file *of;
832 struct mutex *mutex;
833
834 mutex = kernfs_open_file_mutex_lock(kn);
835 on = kernfs_deref_open_node_locked(kn);
836 if (!on) {
837 mutex_unlock(mutex);
838 return;
839 }
840
841 list_for_each_entry(of, &on->files, list) {
842 struct inode *inode = file_inode(of->file);
843
844 if (of->mmapped) {
845 unmap_mapping_range(inode->i_mapping, 0, 0, 1);
846 of->mmapped = false;
847 on->nr_mmapped--;
848 }
849
850 if (kn->flags & KERNFS_HAS_RELEASE)
851 kernfs_release_file(kn, of);
852 }
853
854 WARN_ON_ONCE(on->nr_mmapped || on->nr_to_release);
855 mutex_unlock(mutex);
856 }
857
858 /*
859 * Kernfs attribute files are pollable. The idea is that you read
860 * the content and then you use 'poll' or 'select' to wait for
861 * the content to change. When the content changes (assuming the
862 * manager for the kobject supports notification), poll will
863 * return EPOLLERR|EPOLLPRI, and select will return the fd whether
864 * it is waiting for read, write, or exceptions.
865 * Once poll/select indicates that the value has changed, you
866 * need to close and re-open the file, or seek to 0 and read again.
867 * Reminder: this only works for attributes which actively support
868 * it, and it is not possible to test an attribute from userspace
869 * to see if it supports poll (Neither 'poll' nor 'select' return
870 * an appropriate error code). When in doubt, set a suitable timeout value.
871 */
kernfs_generic_poll(struct kernfs_open_file * of,poll_table * wait)872 __poll_t kernfs_generic_poll(struct kernfs_open_file *of, poll_table *wait)
873 {
874 struct kernfs_open_node *on = of_on(of);
875
876 poll_wait(of->file, &on->poll, wait);
877
878 if (of->event != atomic_read(&on->event))
879 return DEFAULT_POLLMASK|EPOLLERR|EPOLLPRI;
880
881 return DEFAULT_POLLMASK;
882 }
883
kernfs_fop_poll(struct file * filp,poll_table * wait)884 static __poll_t kernfs_fop_poll(struct file *filp, poll_table *wait)
885 {
886 struct kernfs_open_file *of = kernfs_of(filp);
887 struct kernfs_node *kn = kernfs_dentry_node(filp->f_path.dentry);
888 __poll_t ret;
889
890 if (!kernfs_get_active(kn))
891 return DEFAULT_POLLMASK|EPOLLERR|EPOLLPRI;
892
893 if (kn->attr.ops->poll)
894 ret = kn->attr.ops->poll(of, wait);
895 else
896 ret = kernfs_generic_poll(of, wait);
897
898 kernfs_put_active(kn);
899 return ret;
900 }
901
kernfs_notify_workfn(struct work_struct * work)902 static void kernfs_notify_workfn(struct work_struct *work)
903 {
904 struct kernfs_node *kn;
905 struct kernfs_super_info *info;
906 struct kernfs_root *root;
907 repeat:
908 /* pop one off the notify_list */
909 spin_lock_irq(&kernfs_notify_lock);
910 kn = kernfs_notify_list;
911 if (kn == KERNFS_NOTIFY_EOL) {
912 spin_unlock_irq(&kernfs_notify_lock);
913 return;
914 }
915 kernfs_notify_list = kn->attr.notify_next;
916 kn->attr.notify_next = NULL;
917 spin_unlock_irq(&kernfs_notify_lock);
918
919 root = kernfs_root(kn);
920 /* kick fsnotify */
921 down_write(&root->kernfs_rwsem);
922
923 list_for_each_entry(info, &kernfs_root(kn)->supers, node) {
924 struct kernfs_node *parent;
925 struct inode *p_inode = NULL;
926 struct inode *inode;
927 struct qstr name;
928
929 /*
930 * We want fsnotify_modify() on @kn but as the
931 * modifications aren't originating from userland don't
932 * have the matching @file available. Look up the inodes
933 * and generate the events manually.
934 */
935 inode = ilookup(info->sb, kernfs_ino(kn));
936 if (!inode)
937 continue;
938
939 name = (struct qstr)QSTR_INIT(kn->name, strlen(kn->name));
940 parent = kernfs_get_parent(kn);
941 if (parent) {
942 p_inode = ilookup(info->sb, kernfs_ino(parent));
943 if (p_inode) {
944 fsnotify(FS_MODIFY | FS_EVENT_ON_CHILD,
945 inode, FSNOTIFY_EVENT_INODE,
946 p_inode, &name, inode, 0);
947 iput(p_inode);
948 }
949
950 kernfs_put(parent);
951 }
952
953 if (!p_inode)
954 fsnotify_inode(inode, FS_MODIFY);
955
956 iput(inode);
957 }
958
959 up_write(&root->kernfs_rwsem);
960 kernfs_put(kn);
961 goto repeat;
962 }
963
964 /**
965 * kernfs_notify - notify a kernfs file
966 * @kn: file to notify
967 *
968 * Notify @kn such that poll(2) on @kn wakes up. Maybe be called from any
969 * context.
970 */
kernfs_notify(struct kernfs_node * kn)971 void kernfs_notify(struct kernfs_node *kn)
972 {
973 static DECLARE_WORK(kernfs_notify_work, kernfs_notify_workfn);
974 unsigned long flags;
975 struct kernfs_open_node *on;
976
977 if (WARN_ON(kernfs_type(kn) != KERNFS_FILE))
978 return;
979
980 /* kick poll immediately */
981 rcu_read_lock();
982 on = rcu_dereference(kn->attr.open);
983 if (on) {
984 atomic_inc(&on->event);
985 wake_up_interruptible(&on->poll);
986 }
987 rcu_read_unlock();
988
989 /* schedule work to kick fsnotify */
990 spin_lock_irqsave(&kernfs_notify_lock, flags);
991 if (!kn->attr.notify_next) {
992 kernfs_get(kn);
993 kn->attr.notify_next = kernfs_notify_list;
994 kernfs_notify_list = kn;
995 schedule_work(&kernfs_notify_work);
996 }
997 spin_unlock_irqrestore(&kernfs_notify_lock, flags);
998 }
999 EXPORT_SYMBOL_GPL(kernfs_notify);
1000
1001 const struct file_operations kernfs_file_fops = {
1002 .read_iter = kernfs_fop_read_iter,
1003 .write_iter = kernfs_fop_write_iter,
1004 .llseek = generic_file_llseek,
1005 .mmap = kernfs_fop_mmap,
1006 .open = kernfs_fop_open,
1007 .release = kernfs_fop_release,
1008 .poll = kernfs_fop_poll,
1009 .fsync = noop_fsync,
1010 .splice_read = generic_file_splice_read,
1011 .splice_write = iter_file_splice_write,
1012 };
1013
1014 /**
1015 * __kernfs_create_file - kernfs internal function to create a file
1016 * @parent: directory to create the file in
1017 * @name: name of the file
1018 * @mode: mode of the file
1019 * @uid: uid of the file
1020 * @gid: gid of the file
1021 * @size: size of the file
1022 * @ops: kernfs operations for the file
1023 * @priv: private data for the file
1024 * @ns: optional namespace tag of the file
1025 * @key: lockdep key for the file's active_ref, %NULL to disable lockdep
1026 *
1027 * Returns the created node on success, ERR_PTR() value on error.
1028 */
__kernfs_create_file(struct kernfs_node * parent,const char * name,umode_t mode,kuid_t uid,kgid_t gid,loff_t size,const struct kernfs_ops * ops,void * priv,const void * ns,struct lock_class_key * key)1029 struct kernfs_node *__kernfs_create_file(struct kernfs_node *parent,
1030 const char *name,
1031 umode_t mode, kuid_t uid, kgid_t gid,
1032 loff_t size,
1033 const struct kernfs_ops *ops,
1034 void *priv, const void *ns,
1035 struct lock_class_key *key)
1036 {
1037 struct kernfs_node *kn;
1038 unsigned flags;
1039 int rc;
1040
1041 flags = KERNFS_FILE;
1042
1043 kn = kernfs_new_node(parent, name, (mode & S_IALLUGO) | S_IFREG,
1044 uid, gid, flags);
1045 if (!kn)
1046 return ERR_PTR(-ENOMEM);
1047
1048 kn->attr.ops = ops;
1049 kn->attr.size = size;
1050 kn->ns = ns;
1051 kn->priv = priv;
1052
1053 #ifdef CONFIG_DEBUG_LOCK_ALLOC
1054 if (key) {
1055 lockdep_init_map(&kn->dep_map, "kn->active", key, 0);
1056 kn->flags |= KERNFS_LOCKDEP;
1057 }
1058 #endif
1059
1060 /*
1061 * kn->attr.ops is accessible only while holding active ref. We
1062 * need to know whether some ops are implemented outside active
1063 * ref. Cache their existence in flags.
1064 */
1065 if (ops->seq_show)
1066 kn->flags |= KERNFS_HAS_SEQ_SHOW;
1067 if (ops->mmap)
1068 kn->flags |= KERNFS_HAS_MMAP;
1069 if (ops->release)
1070 kn->flags |= KERNFS_HAS_RELEASE;
1071
1072 rc = kernfs_add_one(kn);
1073 if (rc) {
1074 kernfs_put(kn);
1075 return ERR_PTR(rc);
1076 }
1077 return kn;
1078 }
1079