]> git.karo-electronics.de Git - karo-tx-linux.git/blob - fs/sysfs/file.c
69cca0f4ccf39319d4aec56e5d15fc498069107a
[karo-tx-linux.git] / fs / sysfs / file.c
1 /*
2  * fs/sysfs/file.c - sysfs regular (text) file implementation
3  *
4  * Copyright (c) 2001-3 Patrick Mochel
5  * Copyright (c) 2007 SUSE Linux Products GmbH
6  * Copyright (c) 2007 Tejun Heo <teheo@suse.de>
7  *
8  * This file is released under the GPLv2.
9  *
10  * Please see Documentation/filesystems/sysfs.txt for more information.
11  */
12
13 #include <linux/module.h>
14 #include <linux/kobject.h>
15 #include <linux/kallsyms.h>
16 #include <linux/slab.h>
17 #include <linux/fsnotify.h>
18 #include <linux/namei.h>
19 #include <linux/poll.h>
20 #include <linux/list.h>
21 #include <linux/mutex.h>
22 #include <linux/limits.h>
23 #include <linux/uaccess.h>
24 #include <linux/seq_file.h>
25 #include <linux/mm.h>
26
27 #include "sysfs.h"
28
29 /*
30  * There's one sysfs_open_file for each open file and one sysfs_open_dirent
31  * for each sysfs_dirent with one or more open files.
32  *
33  * sysfs_dirent->s_attr.open points to sysfs_open_dirent.  s_attr.open is
34  * protected by sysfs_open_dirent_lock.
35  *
36  * filp->private_data points to seq_file whose ->private points to
37  * sysfs_open_file.  sysfs_open_files are chained at
38  * sysfs_open_dirent->files, which is protected by sysfs_open_file_mutex.
39  */
40 static DEFINE_SPINLOCK(sysfs_open_dirent_lock);
41 static DEFINE_MUTEX(sysfs_open_file_mutex);
42
43 struct sysfs_open_dirent {
44         atomic_t                refcnt;
45         atomic_t                event;
46         wait_queue_head_t       poll;
47         struct list_head        files; /* goes through sysfs_open_file.list */
48 };
49
50 static struct sysfs_open_file *sysfs_of(struct file *file)
51 {
52         return ((struct seq_file *)file->private_data)->private;
53 }
54
55 /*
56  * Determine the kernfs_ops for the given sysfs_dirent.  This function must
57  * be called while holding an active reference.
58  */
59 static const struct kernfs_ops *kernfs_ops(struct sysfs_dirent *sd)
60 {
61         if (!sysfs_ignore_lockdep(sd))
62                 lockdep_assert_held(sd);
63         return sd->s_attr.ops;
64 }
65
66 /*
67  * Determine ktype->sysfs_ops for the given sysfs_dirent.  This function
68  * must be called while holding an active reference.
69  */
70 static const struct sysfs_ops *sysfs_file_ops(struct sysfs_dirent *sd)
71 {
72         struct kobject *kobj = sd->s_parent->priv;
73
74         if (!sysfs_ignore_lockdep(sd))
75                 lockdep_assert_held(sd);
76         return kobj->ktype ? kobj->ktype->sysfs_ops : NULL;
77 }
78
79 /*
80  * Reads on sysfs are handled through seq_file, which takes care of hairy
81  * details like buffering and seeking.  The following function pipes
82  * sysfs_ops->show() result through seq_file.
83  */
84 static int sysfs_kf_seq_show(struct seq_file *sf, void *v)
85 {
86         struct sysfs_open_file *of = sf->private;
87         struct kobject *kobj = of->sd->s_parent->priv;
88         const struct sysfs_ops *ops = sysfs_file_ops(of->sd);
89         ssize_t count;
90         char *buf;
91
92         /* acquire buffer and ensure that it's >= PAGE_SIZE */
93         count = seq_get_buf(sf, &buf);
94         if (count < PAGE_SIZE) {
95                 seq_commit(sf, -1);
96                 return 0;
97         }
98
99         /*
100          * Invoke show().  Control may reach here via seq file lseek even
101          * if @ops->show() isn't implemented.
102          */
103         if (ops->show) {
104                 count = ops->show(kobj, of->sd->priv, buf);
105                 if (count < 0)
106                         return count;
107         }
108
109         /*
110          * The code works fine with PAGE_SIZE return but it's likely to
111          * indicate truncated result or overflow in normal use cases.
112          */
113         if (count >= (ssize_t)PAGE_SIZE) {
114                 print_symbol("fill_read_buffer: %s returned bad count\n",
115                         (unsigned long)ops->show);
116                 /* Try to struggle along */
117                 count = PAGE_SIZE - 1;
118         }
119         seq_commit(sf, count);
120         return 0;
121 }
122
123 static ssize_t sysfs_kf_bin_read(struct sysfs_open_file *of, char *buf,
124                                  size_t count, loff_t pos)
125 {
126         struct bin_attribute *battr = of->sd->priv;
127         struct kobject *kobj = of->sd->s_parent->priv;
128         loff_t size = file_inode(of->file)->i_size;
129
130         if (!count)
131                 return 0;
132
133         if (size) {
134                 if (pos > size)
135                         return 0;
136                 if (pos + count > size)
137                         count = size - pos;
138         }
139
140         if (!battr->read)
141                 return -EIO;
142
143         return battr->read(of->file, kobj, battr, buf, pos, count);
144 }
145
146 static void *kernfs_seq_start(struct seq_file *sf, loff_t *ppos)
147 {
148         struct sysfs_open_file *of = sf->private;
149
150         /*
151          * @of->mutex nests outside active ref and is just to ensure that
152          * the ops aren't called concurrently for the same open file.
153          */
154         mutex_lock(&of->mutex);
155         if (!sysfs_get_active(of->sd))
156                 return ERR_PTR(-ENODEV);
157
158         /*
159          * The same behavior and code as single_open().  Returns !NULL if
160          * pos is at the beginning; otherwise, NULL.
161          */
162         return NULL + !*ppos;
163 }
164
165 static void *kernfs_seq_next(struct seq_file *sf, void *v, loff_t *ppos)
166 {
167         /*
168          * The same behavior and code as single_open(), always terminate
169          * after the initial read.
170          */
171         ++*ppos;
172         return NULL;
173 }
174
175 static void kernfs_seq_stop(struct seq_file *sf, void *v)
176 {
177         struct sysfs_open_file *of = sf->private;
178
179         sysfs_put_active(of->sd);
180         mutex_unlock(&of->mutex);
181 }
182
183 static int kernfs_seq_show(struct seq_file *sf, void *v)
184 {
185         struct sysfs_open_file *of = sf->private;
186
187         of->event = atomic_read(&of->sd->s_attr.open->event);
188
189         return of->sd->s_attr.ops->seq_show(sf, v);
190 }
191
192 static const struct seq_operations kernfs_seq_ops = {
193         .start = kernfs_seq_start,
194         .next = kernfs_seq_next,
195         .stop = kernfs_seq_stop,
196         .show = kernfs_seq_show,
197 };
198
199 /*
200  * As reading a bin file can have side-effects, the exact offset and bytes
201  * specified in read(2) call should be passed to the read callback making
202  * it difficult to use seq_file.  Implement simplistic custom buffering for
203  * bin files.
204  */
205 static ssize_t kernfs_file_direct_read(struct sysfs_open_file *of,
206                                        char __user *user_buf, size_t count,
207                                        loff_t *ppos)
208 {
209         ssize_t len = min_t(size_t, count, PAGE_SIZE);
210         const struct kernfs_ops *ops;
211         char *buf;
212
213         buf = kmalloc(len, GFP_KERNEL);
214         if (!buf)
215                 return -ENOMEM;
216
217         /*
218          * @of->mutex nests outside active ref and is just to ensure that
219          * the ops aren't called concurrently for the same open file.
220          */
221         mutex_lock(&of->mutex);
222         if (!sysfs_get_active(of->sd)) {
223                 len = -ENODEV;
224                 mutex_unlock(&of->mutex);
225                 goto out_free;
226         }
227
228         ops = kernfs_ops(of->sd);
229         if (ops->read)
230                 len = ops->read(of, buf, len, *ppos);
231         else
232                 len = -EINVAL;
233
234         sysfs_put_active(of->sd);
235         mutex_unlock(&of->mutex);
236
237         if (len < 0)
238                 goto out_free;
239
240         if (copy_to_user(user_buf, buf, len)) {
241                 len = -EFAULT;
242                 goto out_free;
243         }
244
245         *ppos += len;
246
247  out_free:
248         kfree(buf);
249         return len;
250 }
251
252 /**
253  * kernfs_file_read - kernfs vfs read callback
254  * @file: file pointer
255  * @user_buf: data to write
256  * @count: number of bytes
257  * @ppos: starting offset
258  */
259 static ssize_t kernfs_file_read(struct file *file, char __user *user_buf,
260                                 size_t count, loff_t *ppos)
261 {
262         struct sysfs_open_file *of = sysfs_of(file);
263
264         if (of->sd->s_flags & SYSFS_FLAG_HAS_SEQ_SHOW)
265                 return seq_read(file, user_buf, count, ppos);
266         else
267                 return kernfs_file_direct_read(of, user_buf, count, ppos);
268 }
269
270 /* kernfs write callback for regular sysfs files */
271 static ssize_t sysfs_kf_write(struct sysfs_open_file *of, char *buf,
272                               size_t count, loff_t pos)
273 {
274         const struct sysfs_ops *ops = sysfs_file_ops(of->sd);
275         struct kobject *kobj = of->sd->s_parent->priv;
276
277         if (!count)
278                 return 0;
279
280         return ops->store(kobj, of->sd->priv, buf, count);
281 }
282
283 /* kernfs write callback for bin sysfs files */
284 static ssize_t sysfs_kf_bin_write(struct sysfs_open_file *of, char *buf,
285                                   size_t count, loff_t pos)
286 {
287         struct bin_attribute *battr = of->sd->priv;
288         struct kobject *kobj = of->sd->s_parent->priv;
289         loff_t size = file_inode(of->file)->i_size;
290
291         if (size) {
292                 if (size <= pos)
293                         return 0;
294                 count = min_t(ssize_t, count, size - pos);
295         }
296         if (!count)
297                 return 0;
298
299         if (!battr->write)
300                 return -EIO;
301
302         return battr->write(of->file, kobj, battr, buf, pos, count);
303 }
304
305 /**
306  * kernfs_file_write - kernfs vfs write callback
307  * @file: file pointer
308  * @user_buf: data to write
309  * @count: number of bytes
310  * @ppos: starting offset
311  *
312  * Copy data in from userland and pass it to the matching kernfs write
313  * operation.
314  *
315  * There is no easy way for us to know if userspace is only doing a partial
316  * write, so we don't support them. We expect the entire buffer to come on
317  * the first write.  Hint: if you're writing a value, first read the file,
318  * modify only the the value you're changing, then write entire buffer
319  * back.
320  */
321 static ssize_t kernfs_file_write(struct file *file, const char __user *user_buf,
322                                  size_t count, loff_t *ppos)
323 {
324         struct sysfs_open_file *of = sysfs_of(file);
325         ssize_t len = min_t(size_t, count, PAGE_SIZE);
326         const struct kernfs_ops *ops;
327         char *buf;
328
329         buf = kmalloc(len + 1, GFP_KERNEL);
330         if (!buf)
331                 return -ENOMEM;
332
333         if (copy_from_user(buf, user_buf, len)) {
334                 len = -EFAULT;
335                 goto out_free;
336         }
337         buf[len] = '\0';        /* guarantee string termination */
338
339         /*
340          * @of->mutex nests outside active ref and is just to ensure that
341          * the ops aren't called concurrently for the same open file.
342          */
343         mutex_lock(&of->mutex);
344         if (!sysfs_get_active(of->sd)) {
345                 mutex_unlock(&of->mutex);
346                 len = -ENODEV;
347                 goto out_free;
348         }
349
350         ops = kernfs_ops(of->sd);
351         if (ops->write)
352                 len = ops->write(of, buf, len, *ppos);
353         else
354                 len = -EINVAL;
355
356         sysfs_put_active(of->sd);
357         mutex_unlock(&of->mutex);
358
359         if (len > 0)
360                 *ppos += len;
361 out_free:
362         kfree(buf);
363         return len;
364 }
365
366 static int sysfs_kf_bin_mmap(struct sysfs_open_file *of,
367                              struct vm_area_struct *vma)
368 {
369         struct bin_attribute *battr = of->sd->priv;
370         struct kobject *kobj = of->sd->s_parent->priv;
371
372         if (!battr->mmap)
373                 return -ENODEV;
374
375         return battr->mmap(of->file, kobj, battr, vma);
376 }
377
378 static void kernfs_vma_open(struct vm_area_struct *vma)
379 {
380         struct file *file = vma->vm_file;
381         struct sysfs_open_file *of = sysfs_of(file);
382
383         if (!of->vm_ops)
384                 return;
385
386         if (!sysfs_get_active(of->sd))
387                 return;
388
389         if (of->vm_ops->open)
390                 of->vm_ops->open(vma);
391
392         sysfs_put_active(of->sd);
393 }
394
395 static int kernfs_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
396 {
397         struct file *file = vma->vm_file;
398         struct sysfs_open_file *of = sysfs_of(file);
399         int ret;
400
401         if (!of->vm_ops)
402                 return VM_FAULT_SIGBUS;
403
404         if (!sysfs_get_active(of->sd))
405                 return VM_FAULT_SIGBUS;
406
407         ret = VM_FAULT_SIGBUS;
408         if (of->vm_ops->fault)
409                 ret = of->vm_ops->fault(vma, vmf);
410
411         sysfs_put_active(of->sd);
412         return ret;
413 }
414
415 static int kernfs_vma_page_mkwrite(struct vm_area_struct *vma,
416                                    struct vm_fault *vmf)
417 {
418         struct file *file = vma->vm_file;
419         struct sysfs_open_file *of = sysfs_of(file);
420         int ret;
421
422         if (!of->vm_ops)
423                 return VM_FAULT_SIGBUS;
424
425         if (!sysfs_get_active(of->sd))
426                 return VM_FAULT_SIGBUS;
427
428         ret = 0;
429         if (of->vm_ops->page_mkwrite)
430                 ret = of->vm_ops->page_mkwrite(vma, vmf);
431         else
432                 file_update_time(file);
433
434         sysfs_put_active(of->sd);
435         return ret;
436 }
437
438 static int kernfs_vma_access(struct vm_area_struct *vma, unsigned long addr,
439                              void *buf, int len, int write)
440 {
441         struct file *file = vma->vm_file;
442         struct sysfs_open_file *of = sysfs_of(file);
443         int ret;
444
445         if (!of->vm_ops)
446                 return -EINVAL;
447
448         if (!sysfs_get_active(of->sd))
449                 return -EINVAL;
450
451         ret = -EINVAL;
452         if (of->vm_ops->access)
453                 ret = of->vm_ops->access(vma, addr, buf, len, write);
454
455         sysfs_put_active(of->sd);
456         return ret;
457 }
458
459 #ifdef CONFIG_NUMA
460 static int kernfs_vma_set_policy(struct vm_area_struct *vma,
461                                  struct mempolicy *new)
462 {
463         struct file *file = vma->vm_file;
464         struct sysfs_open_file *of = sysfs_of(file);
465         int ret;
466
467         if (!of->vm_ops)
468                 return 0;
469
470         if (!sysfs_get_active(of->sd))
471                 return -EINVAL;
472
473         ret = 0;
474         if (of->vm_ops->set_policy)
475                 ret = of->vm_ops->set_policy(vma, new);
476
477         sysfs_put_active(of->sd);
478         return ret;
479 }
480
481 static struct mempolicy *kernfs_vma_get_policy(struct vm_area_struct *vma,
482                                                unsigned long addr)
483 {
484         struct file *file = vma->vm_file;
485         struct sysfs_open_file *of = sysfs_of(file);
486         struct mempolicy *pol;
487
488         if (!of->vm_ops)
489                 return vma->vm_policy;
490
491         if (!sysfs_get_active(of->sd))
492                 return vma->vm_policy;
493
494         pol = vma->vm_policy;
495         if (of->vm_ops->get_policy)
496                 pol = of->vm_ops->get_policy(vma, addr);
497
498         sysfs_put_active(of->sd);
499         return pol;
500 }
501
502 static int kernfs_vma_migrate(struct vm_area_struct *vma,
503                               const nodemask_t *from, const nodemask_t *to,
504                               unsigned long flags)
505 {
506         struct file *file = vma->vm_file;
507         struct sysfs_open_file *of = sysfs_of(file);
508         int ret;
509
510         if (!of->vm_ops)
511                 return 0;
512
513         if (!sysfs_get_active(of->sd))
514                 return 0;
515
516         ret = 0;
517         if (of->vm_ops->migrate)
518                 ret = of->vm_ops->migrate(vma, from, to, flags);
519
520         sysfs_put_active(of->sd);
521         return ret;
522 }
523 #endif
524
525 static const struct vm_operations_struct kernfs_vm_ops = {
526         .open           = kernfs_vma_open,
527         .fault          = kernfs_vma_fault,
528         .page_mkwrite   = kernfs_vma_page_mkwrite,
529         .access         = kernfs_vma_access,
530 #ifdef CONFIG_NUMA
531         .set_policy     = kernfs_vma_set_policy,
532         .get_policy     = kernfs_vma_get_policy,
533         .migrate        = kernfs_vma_migrate,
534 #endif
535 };
536
537 static int kernfs_file_mmap(struct file *file, struct vm_area_struct *vma)
538 {
539         struct sysfs_open_file *of = sysfs_of(file);
540         const struct kernfs_ops *ops;
541         int rc;
542
543         mutex_lock(&of->mutex);
544
545         rc = -ENODEV;
546         if (!sysfs_get_active(of->sd))
547                 goto out_unlock;
548
549         ops = kernfs_ops(of->sd);
550         if (ops->mmap)
551                 rc = ops->mmap(of, vma);
552         if (rc)
553                 goto out_put;
554
555         /*
556          * PowerPC's pci_mmap of legacy_mem uses shmem_zero_setup()
557          * to satisfy versions of X which crash if the mmap fails: that
558          * substitutes a new vm_file, and we don't then want bin_vm_ops.
559          */
560         if (vma->vm_file != file)
561                 goto out_put;
562
563         rc = -EINVAL;
564         if (of->mmapped && of->vm_ops != vma->vm_ops)
565                 goto out_put;
566
567         /*
568          * It is not possible to successfully wrap close.
569          * So error if someone is trying to use close.
570          */
571         rc = -EINVAL;
572         if (vma->vm_ops && vma->vm_ops->close)
573                 goto out_put;
574
575         rc = 0;
576         of->mmapped = 1;
577         of->vm_ops = vma->vm_ops;
578         vma->vm_ops = &kernfs_vm_ops;
579 out_put:
580         sysfs_put_active(of->sd);
581 out_unlock:
582         mutex_unlock(&of->mutex);
583
584         return rc;
585 }
586
587 /**
588  *      sysfs_get_open_dirent - get or create sysfs_open_dirent
589  *      @sd: target sysfs_dirent
590  *      @of: sysfs_open_file for this instance of open
591  *
592  *      If @sd->s_attr.open exists, increment its reference count;
593  *      otherwise, create one.  @of is chained to the files list.
594  *
595  *      LOCKING:
596  *      Kernel thread context (may sleep).
597  *
598  *      RETURNS:
599  *      0 on success, -errno on failure.
600  */
601 static int sysfs_get_open_dirent(struct sysfs_dirent *sd,
602                                  struct sysfs_open_file *of)
603 {
604         struct sysfs_open_dirent *od, *new_od = NULL;
605
606  retry:
607         mutex_lock(&sysfs_open_file_mutex);
608         spin_lock_irq(&sysfs_open_dirent_lock);
609
610         if (!sd->s_attr.open && new_od) {
611                 sd->s_attr.open = new_od;
612                 new_od = NULL;
613         }
614
615         od = sd->s_attr.open;
616         if (od) {
617                 atomic_inc(&od->refcnt);
618                 list_add_tail(&of->list, &od->files);
619         }
620
621         spin_unlock_irq(&sysfs_open_dirent_lock);
622         mutex_unlock(&sysfs_open_file_mutex);
623
624         if (od) {
625                 kfree(new_od);
626                 return 0;
627         }
628
629         /* not there, initialize a new one and retry */
630         new_od = kmalloc(sizeof(*new_od), GFP_KERNEL);
631         if (!new_od)
632                 return -ENOMEM;
633
634         atomic_set(&new_od->refcnt, 0);
635         atomic_set(&new_od->event, 1);
636         init_waitqueue_head(&new_od->poll);
637         INIT_LIST_HEAD(&new_od->files);
638         goto retry;
639 }
640
641 /**
642  *      sysfs_put_open_dirent - put sysfs_open_dirent
643  *      @sd: target sysfs_dirent
644  *      @of: associated sysfs_open_file
645  *
646  *      Put @sd->s_attr.open and unlink @of from the files list.  If
647  *      reference count reaches zero, disassociate and free it.
648  *
649  *      LOCKING:
650  *      None.
651  */
652 static void sysfs_put_open_dirent(struct sysfs_dirent *sd,
653                                   struct sysfs_open_file *of)
654 {
655         struct sysfs_open_dirent *od = sd->s_attr.open;
656         unsigned long flags;
657
658         mutex_lock(&sysfs_open_file_mutex);
659         spin_lock_irqsave(&sysfs_open_dirent_lock, flags);
660
661         if (of)
662                 list_del(&of->list);
663
664         if (atomic_dec_and_test(&od->refcnt))
665                 sd->s_attr.open = NULL;
666         else
667                 od = NULL;
668
669         spin_unlock_irqrestore(&sysfs_open_dirent_lock, flags);
670         mutex_unlock(&sysfs_open_file_mutex);
671
672         kfree(od);
673 }
674
675 static int kernfs_file_open(struct inode *inode, struct file *file)
676 {
677         struct sysfs_dirent *attr_sd = file->f_path.dentry->d_fsdata;
678         const struct kernfs_ops *ops;
679         struct sysfs_open_file *of;
680         bool has_read, has_write, has_mmap;
681         int error = -EACCES;
682
683         if (!sysfs_get_active(attr_sd))
684                 return -ENODEV;
685
686         ops = kernfs_ops(attr_sd);
687
688         has_read = ops->seq_show || ops->read || ops->mmap;
689         has_write = ops->write || ops->mmap;
690         has_mmap = ops->mmap;
691
692         /* check perms and supported operations */
693         if ((file->f_mode & FMODE_WRITE) &&
694             (!(inode->i_mode & S_IWUGO) || !has_write))
695                 goto err_out;
696
697         if ((file->f_mode & FMODE_READ) &&
698             (!(inode->i_mode & S_IRUGO) || !has_read))
699                 goto err_out;
700
701         /* allocate a sysfs_open_file for the file */
702         error = -ENOMEM;
703         of = kzalloc(sizeof(struct sysfs_open_file), GFP_KERNEL);
704         if (!of)
705                 goto err_out;
706
707         /*
708          * The following is done to give a different lockdep key to
709          * @of->mutex for files which implement mmap.  This is a rather
710          * crude way to avoid false positive lockdep warning around
711          * mm->mmap_sem - mmap nests @of->mutex under mm->mmap_sem and
712          * reading /sys/block/sda/trace/act_mask grabs sr_mutex, under
713          * which mm->mmap_sem nests, while holding @of->mutex.  As each
714          * open file has a separate mutex, it's okay as long as those don't
715          * happen on the same file.  At this point, we can't easily give
716          * each file a separate locking class.  Let's differentiate on
717          * whether the file has mmap or not for now.
718          */
719         if (has_mmap)
720                 mutex_init(&of->mutex);
721         else
722                 mutex_init(&of->mutex);
723
724         of->sd = attr_sd;
725         of->file = file;
726
727         /*
728          * Always instantiate seq_file even if read access doesn't use
729          * seq_file or is not requested.  This unifies private data access
730          * and readable regular files are the vast majority anyway.
731          */
732         if (ops->seq_show)
733                 error = seq_open(file, &kernfs_seq_ops);
734         else
735                 error = seq_open(file, NULL);
736         if (error)
737                 goto err_free;
738
739         ((struct seq_file *)file->private_data)->private = of;
740
741         /* seq_file clears PWRITE unconditionally, restore it if WRITE */
742         if (file->f_mode & FMODE_WRITE)
743                 file->f_mode |= FMODE_PWRITE;
744
745         /* make sure we have open dirent struct */
746         error = sysfs_get_open_dirent(attr_sd, of);
747         if (error)
748                 goto err_close;
749
750         /* open succeeded, put active references */
751         sysfs_put_active(attr_sd);
752         return 0;
753
754 err_close:
755         seq_release(inode, file);
756 err_free:
757         kfree(of);
758 err_out:
759         sysfs_put_active(attr_sd);
760         return error;
761 }
762
763 static int kernfs_file_release(struct inode *inode, struct file *filp)
764 {
765         struct sysfs_dirent *sd = filp->f_path.dentry->d_fsdata;
766         struct sysfs_open_file *of = sysfs_of(filp);
767
768         sysfs_put_open_dirent(sd, of);
769         seq_release(inode, filp);
770         kfree(of);
771
772         return 0;
773 }
774
775 void sysfs_unmap_bin_file(struct sysfs_dirent *sd)
776 {
777         struct sysfs_open_dirent *od;
778         struct sysfs_open_file *of;
779
780         if (!(sd->s_flags & SYSFS_FLAG_HAS_MMAP))
781                 return;
782
783         spin_lock_irq(&sysfs_open_dirent_lock);
784         od = sd->s_attr.open;
785         if (od)
786                 atomic_inc(&od->refcnt);
787         spin_unlock_irq(&sysfs_open_dirent_lock);
788         if (!od)
789                 return;
790
791         mutex_lock(&sysfs_open_file_mutex);
792         list_for_each_entry(of, &od->files, list) {
793                 struct inode *inode = file_inode(of->file);
794                 unmap_mapping_range(inode->i_mapping, 0, 0, 1);
795         }
796         mutex_unlock(&sysfs_open_file_mutex);
797
798         sysfs_put_open_dirent(sd, NULL);
799 }
800
801 /* Sysfs attribute files are pollable.  The idea is that you read
802  * the content and then you use 'poll' or 'select' to wait for
803  * the content to change.  When the content changes (assuming the
804  * manager for the kobject supports notification), poll will
805  * return POLLERR|POLLPRI, and select will return the fd whether
806  * it is waiting for read, write, or exceptions.
807  * Once poll/select indicates that the value has changed, you
808  * need to close and re-open the file, or seek to 0 and read again.
809  * Reminder: this only works for attributes which actively support
810  * it, and it is not possible to test an attribute from userspace
811  * to see if it supports poll (Neither 'poll' nor 'select' return
812  * an appropriate error code).  When in doubt, set a suitable timeout value.
813  */
814 static unsigned int kernfs_file_poll(struct file *filp, poll_table *wait)
815 {
816         struct sysfs_open_file *of = sysfs_of(filp);
817         struct sysfs_dirent *attr_sd = filp->f_path.dentry->d_fsdata;
818         struct sysfs_open_dirent *od = attr_sd->s_attr.open;
819
820         /* need parent for the kobj, grab both */
821         if (!sysfs_get_active(attr_sd))
822                 goto trigger;
823
824         poll_wait(filp, &od->poll, wait);
825
826         sysfs_put_active(attr_sd);
827
828         if (of->event != atomic_read(&od->event))
829                 goto trigger;
830
831         return DEFAULT_POLLMASK;
832
833  trigger:
834         return DEFAULT_POLLMASK|POLLERR|POLLPRI;
835 }
836
837 void sysfs_notify_dirent(struct sysfs_dirent *sd)
838 {
839         struct sysfs_open_dirent *od;
840         unsigned long flags;
841
842         spin_lock_irqsave(&sysfs_open_dirent_lock, flags);
843
844         if (!WARN_ON(sysfs_type(sd) != SYSFS_KOBJ_ATTR)) {
845                 od = sd->s_attr.open;
846                 if (od) {
847                         atomic_inc(&od->event);
848                         wake_up_interruptible(&od->poll);
849                 }
850         }
851
852         spin_unlock_irqrestore(&sysfs_open_dirent_lock, flags);
853 }
854 EXPORT_SYMBOL_GPL(sysfs_notify_dirent);
855
856 void sysfs_notify(struct kobject *k, const char *dir, const char *attr)
857 {
858         struct sysfs_dirent *sd = k->sd;
859
860         mutex_lock(&sysfs_mutex);
861
862         if (sd && dir)
863                 sd = sysfs_find_dirent(sd, dir, NULL);
864         if (sd && attr)
865                 sd = sysfs_find_dirent(sd, attr, NULL);
866         if (sd)
867                 sysfs_notify_dirent(sd);
868
869         mutex_unlock(&sysfs_mutex);
870 }
871 EXPORT_SYMBOL_GPL(sysfs_notify);
872
873 const struct file_operations kernfs_file_operations = {
874         .read           = kernfs_file_read,
875         .write          = kernfs_file_write,
876         .llseek         = generic_file_llseek,
877         .mmap           = kernfs_file_mmap,
878         .open           = kernfs_file_open,
879         .release        = kernfs_file_release,
880         .poll           = kernfs_file_poll,
881 };
882
883 static const struct kernfs_ops sysfs_file_kfops_empty = {
884 };
885
886 static const struct kernfs_ops sysfs_file_kfops_ro = {
887         .seq_show       = sysfs_kf_seq_show,
888 };
889
890 static const struct kernfs_ops sysfs_file_kfops_wo = {
891         .write          = sysfs_kf_write,
892 };
893
894 static const struct kernfs_ops sysfs_file_kfops_rw = {
895         .seq_show       = sysfs_kf_seq_show,
896         .write          = sysfs_kf_write,
897 };
898
899 static const struct kernfs_ops sysfs_bin_kfops_ro = {
900         .read           = sysfs_kf_bin_read,
901 };
902
903 static const struct kernfs_ops sysfs_bin_kfops_wo = {
904         .write          = sysfs_kf_bin_write,
905 };
906
907 static const struct kernfs_ops sysfs_bin_kfops_rw = {
908         .read           = sysfs_kf_bin_read,
909         .write          = sysfs_kf_bin_write,
910         .mmap           = sysfs_kf_bin_mmap,
911 };
912
913 int sysfs_add_file_mode_ns(struct sysfs_dirent *dir_sd,
914                            const struct attribute *attr, bool is_bin,
915                            umode_t mode, const void *ns)
916 {
917         const struct kernfs_ops *ops;
918         struct sysfs_dirent *sd;
919         loff_t size;
920
921         if (!is_bin) {
922                 struct kobject *kobj = dir_sd->priv;
923                 const struct sysfs_ops *sysfs_ops = kobj->ktype->sysfs_ops;
924
925                 /* every kobject with an attribute needs a ktype assigned */
926                 if (WARN(!sysfs_ops, KERN_ERR
927                          "missing sysfs attribute operations for kobject: %s\n",
928                          kobject_name(kobj)))
929                         return -EINVAL;
930
931                 if (sysfs_ops->show && sysfs_ops->store)
932                         ops = &sysfs_file_kfops_rw;
933                 else if (sysfs_ops->show)
934                         ops = &sysfs_file_kfops_ro;
935                 else if (sysfs_ops->store)
936                         ops = &sysfs_file_kfops_wo;
937                 else
938                         ops = &sysfs_file_kfops_empty;
939
940                 size = PAGE_SIZE;
941         } else {
942                 struct bin_attribute *battr = (void *)attr;
943
944                 if ((battr->read && battr->write) || battr->mmap)
945                         ops = &sysfs_bin_kfops_rw;
946                 else if (battr->read)
947                         ops = &sysfs_bin_kfops_ro;
948                 else if (battr->write)
949                         ops = &sysfs_bin_kfops_wo;
950                 else
951                         ops = &sysfs_file_kfops_empty;
952
953                 size = battr->size;
954         }
955
956         sd = kernfs_create_file_ns(dir_sd, attr->name, mode, size,
957                                    ops, (void *)attr, ns);
958         if (IS_ERR(sd)) {
959                 if (PTR_ERR(sd) == -EEXIST)
960                         sysfs_warn_dup(dir_sd, attr->name);
961                 return PTR_ERR(sd);
962         }
963         return 0;
964 }
965
966 /**
967  * kernfs_create_file_ns - create a file
968  * @parent: directory to create the file in
969  * @name: name of the file
970  * @mode: mode of the file
971  * @size: size of the file
972  * @ops: kernfs operations for the file
973  * @priv: private data for the file
974  * @ns: optional namespace tag of the file
975  *
976  * Returns the created node on success, ERR_PTR() value on error.
977  */
978 struct sysfs_dirent *kernfs_create_file_ns(struct sysfs_dirent *parent,
979                                            const char *name,
980                                            umode_t mode, loff_t size,
981                                            const struct kernfs_ops *ops,
982                                            void *priv, const void *ns)
983 {
984         struct sysfs_addrm_cxt acxt;
985         struct sysfs_dirent *sd;
986         int rc;
987
988         sd = sysfs_new_dirent(name, (mode & S_IALLUGO) | S_IFREG,
989                               SYSFS_KOBJ_ATTR);
990         if (!sd)
991                 return ERR_PTR(-ENOMEM);
992
993         sd->s_attr.ops = ops;
994         sd->s_attr.size = size;
995         sd->s_ns = ns;
996         sd->priv = priv;
997         sysfs_dirent_init_lockdep(sd);
998
999         /*
1000          * sd->s_attr.ops is accesible only while holding active ref.  We
1001          * need to know whether some ops are implemented outside active
1002          * ref.  Cache their existence in flags.
1003          */
1004         if (ops->seq_show)
1005                 sd->s_flags |= SYSFS_FLAG_HAS_SEQ_SHOW;
1006         if (ops->mmap)
1007                 sd->s_flags |= SYSFS_FLAG_HAS_MMAP;
1008
1009         sysfs_addrm_start(&acxt);
1010         rc = __sysfs_add_one(&acxt, sd, parent);
1011         sysfs_addrm_finish(&acxt);
1012
1013         if (rc) {
1014                 sysfs_put(sd);
1015                 return ERR_PTR(rc);
1016         }
1017         return sd;
1018 }
1019
1020 int sysfs_add_file(struct sysfs_dirent *dir_sd, const struct attribute *attr,
1021                    bool is_bin)
1022 {
1023         return sysfs_add_file_mode_ns(dir_sd, attr, is_bin, attr->mode, NULL);
1024 }
1025
1026 /**
1027  * sysfs_create_file_ns - create an attribute file for an object with custom ns
1028  * @kobj: object we're creating for
1029  * @attr: attribute descriptor
1030  * @ns: namespace the new file should belong to
1031  */
1032 int sysfs_create_file_ns(struct kobject *kobj, const struct attribute *attr,
1033                          const void *ns)
1034 {
1035         BUG_ON(!kobj || !kobj->sd || !attr);
1036
1037         return sysfs_add_file_mode_ns(kobj->sd, attr, false, attr->mode, ns);
1038
1039 }
1040 EXPORT_SYMBOL_GPL(sysfs_create_file_ns);
1041
1042 int sysfs_create_files(struct kobject *kobj, const struct attribute **ptr)
1043 {
1044         int err = 0;
1045         int i;
1046
1047         for (i = 0; ptr[i] && !err; i++)
1048                 err = sysfs_create_file(kobj, ptr[i]);
1049         if (err)
1050                 while (--i >= 0)
1051                         sysfs_remove_file(kobj, ptr[i]);
1052         return err;
1053 }
1054 EXPORT_SYMBOL_GPL(sysfs_create_files);
1055
1056 /**
1057  * sysfs_add_file_to_group - add an attribute file to a pre-existing group.
1058  * @kobj: object we're acting for.
1059  * @attr: attribute descriptor.
1060  * @group: group name.
1061  */
1062 int sysfs_add_file_to_group(struct kobject *kobj,
1063                 const struct attribute *attr, const char *group)
1064 {
1065         struct sysfs_dirent *dir_sd;
1066         int error;
1067
1068         if (group)
1069                 dir_sd = sysfs_get_dirent(kobj->sd, group);
1070         else
1071                 dir_sd = sysfs_get(kobj->sd);
1072
1073         if (!dir_sd)
1074                 return -ENOENT;
1075
1076         error = sysfs_add_file(dir_sd, attr, false);
1077         sysfs_put(dir_sd);
1078
1079         return error;
1080 }
1081 EXPORT_SYMBOL_GPL(sysfs_add_file_to_group);
1082
1083 /**
1084  * sysfs_chmod_file - update the modified mode value on an object attribute.
1085  * @kobj: object we're acting for.
1086  * @attr: attribute descriptor.
1087  * @mode: file permissions.
1088  *
1089  */
1090 int sysfs_chmod_file(struct kobject *kobj, const struct attribute *attr,
1091                      umode_t mode)
1092 {
1093         struct sysfs_dirent *sd;
1094         struct iattr newattrs;
1095         int rc;
1096
1097         sd = sysfs_get_dirent(kobj->sd, attr->name);
1098         if (!sd)
1099                 return -ENOENT;
1100
1101         newattrs.ia_mode = (mode & S_IALLUGO) | (sd->s_mode & ~S_IALLUGO);
1102         newattrs.ia_valid = ATTR_MODE;
1103
1104         rc = kernfs_setattr(sd, &newattrs);
1105
1106         sysfs_put(sd);
1107         return rc;
1108 }
1109 EXPORT_SYMBOL_GPL(sysfs_chmod_file);
1110
1111 /**
1112  * sysfs_remove_file_ns - remove an object attribute with a custom ns tag
1113  * @kobj: object we're acting for
1114  * @attr: attribute descriptor
1115  * @ns: namespace tag of the file to remove
1116  *
1117  * Hash the attribute name and namespace tag and kill the victim.
1118  */
1119 void sysfs_remove_file_ns(struct kobject *kobj, const struct attribute *attr,
1120                           const void *ns)
1121 {
1122         struct sysfs_dirent *dir_sd = kobj->sd;
1123
1124         kernfs_remove_by_name_ns(dir_sd, attr->name, ns);
1125 }
1126 EXPORT_SYMBOL_GPL(sysfs_remove_file_ns);
1127
1128 void sysfs_remove_files(struct kobject *kobj, const struct attribute **ptr)
1129 {
1130         int i;
1131         for (i = 0; ptr[i]; i++)
1132                 sysfs_remove_file(kobj, ptr[i]);
1133 }
1134 EXPORT_SYMBOL_GPL(sysfs_remove_files);
1135
1136 /**
1137  * sysfs_remove_file_from_group - remove an attribute file from a group.
1138  * @kobj: object we're acting for.
1139  * @attr: attribute descriptor.
1140  * @group: group name.
1141  */
1142 void sysfs_remove_file_from_group(struct kobject *kobj,
1143                 const struct attribute *attr, const char *group)
1144 {
1145         struct sysfs_dirent *dir_sd;
1146
1147         if (group)
1148                 dir_sd = sysfs_get_dirent(kobj->sd, group);
1149         else
1150                 dir_sd = sysfs_get(kobj->sd);
1151         if (dir_sd) {
1152                 kernfs_remove_by_name(dir_sd, attr->name);
1153                 sysfs_put(dir_sd);
1154         }
1155 }
1156 EXPORT_SYMBOL_GPL(sysfs_remove_file_from_group);
1157
1158 /**
1159  *      sysfs_create_bin_file - create binary file for object.
1160  *      @kobj:  object.
1161  *      @attr:  attribute descriptor.
1162  */
1163 int sysfs_create_bin_file(struct kobject *kobj,
1164                           const struct bin_attribute *attr)
1165 {
1166         BUG_ON(!kobj || !kobj->sd || !attr);
1167
1168         return sysfs_add_file(kobj->sd, &attr->attr, true);
1169 }
1170 EXPORT_SYMBOL_GPL(sysfs_create_bin_file);
1171
1172 /**
1173  *      sysfs_remove_bin_file - remove binary file for object.
1174  *      @kobj:  object.
1175  *      @attr:  attribute descriptor.
1176  */
1177 void sysfs_remove_bin_file(struct kobject *kobj,
1178                            const struct bin_attribute *attr)
1179 {
1180         kernfs_remove_by_name(kobj->sd, attr->attr.name);
1181 }
1182 EXPORT_SYMBOL_GPL(sysfs_remove_bin_file);
1183
1184 struct sysfs_schedule_callback_struct {
1185         struct list_head        workq_list;
1186         struct kobject          *kobj;
1187         void                    (*func)(void *);
1188         void                    *data;
1189         struct module           *owner;
1190         struct work_struct      work;
1191 };
1192
1193 static struct workqueue_struct *sysfs_workqueue;
1194 static DEFINE_MUTEX(sysfs_workq_mutex);
1195 static LIST_HEAD(sysfs_workq);
1196 static void sysfs_schedule_callback_work(struct work_struct *work)
1197 {
1198         struct sysfs_schedule_callback_struct *ss = container_of(work,
1199                         struct sysfs_schedule_callback_struct, work);
1200
1201         (ss->func)(ss->data);
1202         kobject_put(ss->kobj);
1203         module_put(ss->owner);
1204         mutex_lock(&sysfs_workq_mutex);
1205         list_del(&ss->workq_list);
1206         mutex_unlock(&sysfs_workq_mutex);
1207         kfree(ss);
1208 }
1209
1210 /**
1211  * sysfs_schedule_callback - helper to schedule a callback for a kobject
1212  * @kobj: object we're acting for.
1213  * @func: callback function to invoke later.
1214  * @data: argument to pass to @func.
1215  * @owner: module owning the callback code
1216  *
1217  * sysfs attribute methods must not unregister themselves or their parent
1218  * kobject (which would amount to the same thing).  Attempts to do so will
1219  * deadlock, since unregistration is mutually exclusive with driver
1220  * callbacks.
1221  *
1222  * Instead methods can call this routine, which will attempt to allocate
1223  * and schedule a workqueue request to call back @func with @data as its
1224  * argument in the workqueue's process context.  @kobj will be pinned
1225  * until @func returns.
1226  *
1227  * Returns 0 if the request was submitted, -ENOMEM if storage could not
1228  * be allocated, -ENODEV if a reference to @owner isn't available,
1229  * -EAGAIN if a callback has already been scheduled for @kobj.
1230  */
1231 int sysfs_schedule_callback(struct kobject *kobj, void (*func)(void *),
1232                 void *data, struct module *owner)
1233 {
1234         struct sysfs_schedule_callback_struct *ss, *tmp;
1235
1236         if (!try_module_get(owner))
1237                 return -ENODEV;
1238
1239         mutex_lock(&sysfs_workq_mutex);
1240         list_for_each_entry_safe(ss, tmp, &sysfs_workq, workq_list)
1241                 if (ss->kobj == kobj) {
1242                         module_put(owner);
1243                         mutex_unlock(&sysfs_workq_mutex);
1244                         return -EAGAIN;
1245                 }
1246         mutex_unlock(&sysfs_workq_mutex);
1247
1248         if (sysfs_workqueue == NULL) {
1249                 sysfs_workqueue = create_singlethread_workqueue("sysfsd");
1250                 if (sysfs_workqueue == NULL) {
1251                         module_put(owner);
1252                         return -ENOMEM;
1253                 }
1254         }
1255
1256         ss = kmalloc(sizeof(*ss), GFP_KERNEL);
1257         if (!ss) {
1258                 module_put(owner);
1259                 return -ENOMEM;
1260         }
1261         kobject_get(kobj);
1262         ss->kobj = kobj;
1263         ss->func = func;
1264         ss->data = data;
1265         ss->owner = owner;
1266         INIT_WORK(&ss->work, sysfs_schedule_callback_work);
1267         INIT_LIST_HEAD(&ss->workq_list);
1268         mutex_lock(&sysfs_workq_mutex);
1269         list_add_tail(&ss->workq_list, &sysfs_workq);
1270         mutex_unlock(&sysfs_workq_mutex);
1271         queue_work(sysfs_workqueue, &ss->work);
1272         return 0;
1273 }
1274 EXPORT_SYMBOL_GPL(sysfs_schedule_callback);