1 // SPDX-License-Identifier: GPL-2.0
3 * linux/drivers/char/mem.c
5 * Copyright (C) 1991, 1992 Linus Torvalds
8 * Jan-11-1998, C. Scott Ananian <cananian@alumni.princeton.edu>
9 * Shared /dev/zero mmapping support, Feb 2000, Kanoj Sarcar <kanoj@sgi.com>
13 #include <linux/miscdevice.h>
14 #include <linux/slab.h>
15 #include <linux/vmalloc.h>
16 #include <linux/mman.h>
17 #include <linux/random.h>
18 #include <linux/init.h>
19 #include <linux/raw.h>
20 #include <linux/tty.h>
21 #include <linux/capability.h>
22 #include <linux/ptrace.h>
23 #include <linux/device.h>
24 #include <linux/highmem.h>
25 #include <linux/backing-dev.h>
26 #include <linux/shmem_fs.h>
27 #include <linux/splice.h>
28 #include <linux/pfn.h>
29 #include <linux/export.h>
31 #include <linux/uio.h>
32 #include <linux/uaccess.h>
33 #include <linux/security.h>
34 #include <linux/pseudo_fs.h>
35 #include <uapi/linux/magic.h>
36 #include <linux/mount.h>
39 # include <linux/efi.h>
42 #define DEVMEM_MINOR 1
43 #define DEVPORT_MINOR 4
45 static inline unsigned long size_inside_page(unsigned long start,
50 sz = PAGE_SIZE - (start & (PAGE_SIZE - 1));
55 #ifndef ARCH_HAS_VALID_PHYS_ADDR_RANGE
56 static inline int valid_phys_addr_range(phys_addr_t addr, size_t count)
58 return addr + count <= __pa(high_memory);
61 static inline int valid_mmap_phys_addr_range(unsigned long pfn, size_t size)
67 #ifdef CONFIG_STRICT_DEVMEM
68 static inline int page_is_allowed(unsigned long pfn)
70 return devmem_is_allowed(pfn);
72 static inline int range_is_allowed(unsigned long pfn, unsigned long size)
74 u64 from = ((u64)pfn) << PAGE_SHIFT;
79 if (!devmem_is_allowed(pfn))
87 static inline int page_is_allowed(unsigned long pfn)
91 static inline int range_is_allowed(unsigned long pfn, unsigned long size)
97 #ifndef unxlate_dev_mem_ptr
98 #define unxlate_dev_mem_ptr unxlate_dev_mem_ptr
99 void __weak unxlate_dev_mem_ptr(phys_addr_t phys, void *addr)
104 static inline bool should_stop_iteration(void)
108 return fatal_signal_pending(current);
112 * This funcion reads the *physical* memory. The f_pos points directly to the
115 static ssize_t read_mem(struct file *file, char __user *buf,
116 size_t count, loff_t *ppos)
118 phys_addr_t p = *ppos;
127 if (!valid_phys_addr_range(p, count))
130 #ifdef __ARCH_HAS_NO_PAGE_ZERO_MAPPED
131 /* we don't have page 0 mapped on sparc and m68k.. */
133 sz = size_inside_page(p, count);
135 if (clear_user(buf, sz))
145 bounce = kmalloc(PAGE_SIZE, GFP_KERNEL);
150 unsigned long remaining;
153 sz = size_inside_page(p, count);
156 allowed = page_is_allowed(p >> PAGE_SHIFT);
162 /* Show zeros for restricted memory. */
163 remaining = clear_user(buf, sz);
166 * On ia64 if a page has been mapped somewhere as
167 * uncached, then it must also be accessed uncached
168 * by the kernel or data corruption may occur.
170 ptr = xlate_dev_mem_ptr(p);
174 probe = copy_from_kernel_nofault(bounce, ptr, sz);
175 unxlate_dev_mem_ptr(p, ptr);
179 remaining = copy_to_user(buf, bounce, sz);
189 if (should_stop_iteration())
202 static ssize_t write_mem(struct file *file, const char __user *buf,
203 size_t count, loff_t *ppos)
205 phys_addr_t p = *ppos;
207 unsigned long copied;
213 if (!valid_phys_addr_range(p, count))
218 #ifdef __ARCH_HAS_NO_PAGE_ZERO_MAPPED
219 /* we don't have page 0 mapped on sparc and m68k.. */
221 sz = size_inside_page(p, count);
222 /* Hmm. Do something? */
233 sz = size_inside_page(p, count);
235 allowed = page_is_allowed(p >> PAGE_SHIFT);
239 /* Skip actual writing when a page is marked as restricted. */
242 * On ia64 if a page has been mapped somewhere as
243 * uncached, then it must also be accessed uncached
244 * by the kernel or data corruption may occur.
246 ptr = xlate_dev_mem_ptr(p);
253 copied = copy_from_user(ptr, buf, sz);
254 unxlate_dev_mem_ptr(p, ptr);
256 written += sz - copied;
267 if (should_stop_iteration())
275 int __weak phys_mem_access_prot_allowed(struct file *file,
276 unsigned long pfn, unsigned long size, pgprot_t *vma_prot)
281 #ifndef __HAVE_PHYS_MEM_ACCESS_PROT
284 * Architectures vary in how they handle caching for addresses
285 * outside of main memory.
288 #ifdef pgprot_noncached
289 static int uncached_access(struct file *file, phys_addr_t addr)
291 #if defined(CONFIG_IA64)
293 * On ia64, we ignore O_DSYNC because we cannot tolerate memory
296 return !(efi_mem_attributes(addr) & EFI_MEMORY_WB);
299 * Accessing memory above the top the kernel knows about or through a
301 * that was marked O_DSYNC will be done non-cached.
303 if (file->f_flags & O_DSYNC)
305 return addr >= __pa(high_memory);
310 static pgprot_t phys_mem_access_prot(struct file *file, unsigned long pfn,
311 unsigned long size, pgprot_t vma_prot)
313 #ifdef pgprot_noncached
314 phys_addr_t offset = pfn << PAGE_SHIFT;
316 if (uncached_access(file, offset))
317 return pgprot_noncached(vma_prot);
324 static unsigned long get_unmapped_area_mem(struct file *file,
330 if (!valid_mmap_phys_addr_range(pgoff, len))
331 return (unsigned long) -EINVAL;
332 return pgoff << PAGE_SHIFT;
335 /* permit direct mmap, for read, write or exec */
336 static unsigned memory_mmap_capabilities(struct file *file)
338 return NOMMU_MAP_DIRECT |
339 NOMMU_MAP_READ | NOMMU_MAP_WRITE | NOMMU_MAP_EXEC;
342 static unsigned zero_mmap_capabilities(struct file *file)
344 return NOMMU_MAP_COPY;
347 /* can't do an in-place private mapping if there's no MMU */
348 static inline int private_mapping_ok(struct vm_area_struct *vma)
350 return vma->vm_flags & VM_MAYSHARE;
354 static inline int private_mapping_ok(struct vm_area_struct *vma)
360 static const struct vm_operations_struct mmap_mem_ops = {
361 #ifdef CONFIG_HAVE_IOREMAP_PROT
362 .access = generic_access_phys
366 static int mmap_mem(struct file *file, struct vm_area_struct *vma)
368 size_t size = vma->vm_end - vma->vm_start;
369 phys_addr_t offset = (phys_addr_t)vma->vm_pgoff << PAGE_SHIFT;
371 /* Does it even fit in phys_addr_t? */
372 if (offset >> PAGE_SHIFT != vma->vm_pgoff)
375 /* It's illegal to wrap around the end of the physical address space. */
376 if (offset + (phys_addr_t)size - 1 < offset)
379 if (!valid_mmap_phys_addr_range(vma->vm_pgoff, size))
382 if (!private_mapping_ok(vma))
385 if (!range_is_allowed(vma->vm_pgoff, size))
388 if (!phys_mem_access_prot_allowed(file, vma->vm_pgoff, size,
392 vma->vm_page_prot = phys_mem_access_prot(file, vma->vm_pgoff,
396 vma->vm_ops = &mmap_mem_ops;
398 /* Remap-pfn-range will mark the range VM_IO */
399 if (remap_pfn_range(vma,
403 vma->vm_page_prot)) {
409 static int mmap_kmem(struct file *file, struct vm_area_struct *vma)
413 /* Turn a kernel-virtual address into a physical page frame */
414 pfn = __pa((u64)vma->vm_pgoff << PAGE_SHIFT) >> PAGE_SHIFT;
417 * RED-PEN: on some architectures there is more mapped memory than
418 * available in mem_map which pfn_valid checks for. Perhaps should add a
421 * RED-PEN: vmalloc is not supported right now.
427 return mmap_mem(file, vma);
431 * This function reads the *virtual* memory as seen by the kernel.
433 static ssize_t read_kmem(struct file *file, char __user *buf,
434 size_t count, loff_t *ppos)
436 unsigned long p = *ppos;
437 ssize_t low_count, read, sz;
438 char *kbuf; /* k-addr because vread() takes vmlist_lock rwlock */
442 if (p < (unsigned long) high_memory) {
444 if (count > (unsigned long)high_memory - p)
445 low_count = (unsigned long)high_memory - p;
447 #ifdef __ARCH_HAS_NO_PAGE_ZERO_MAPPED
448 /* we don't have page 0 mapped on sparc and m68k.. */
449 if (p < PAGE_SIZE && low_count > 0) {
450 sz = size_inside_page(p, low_count);
451 if (clear_user(buf, sz))
460 while (low_count > 0) {
461 sz = size_inside_page(p, low_count);
464 * On ia64 if a page has been mapped somewhere as
465 * uncached, then it must also be accessed uncached
466 * by the kernel or data corruption may occur
468 kbuf = xlate_dev_kmem_ptr((void *)p);
469 if (!virt_addr_valid(kbuf))
472 if (copy_to_user(buf, kbuf, sz))
479 if (should_stop_iteration()) {
487 kbuf = (char *)__get_free_page(GFP_KERNEL);
491 sz = size_inside_page(p, count);
492 if (!is_vmalloc_or_module_addr((void *)p)) {
496 sz = vread(kbuf, (char *)p, sz);
499 if (copy_to_user(buf, kbuf, sz)) {
507 if (should_stop_iteration())
510 free_page((unsigned long)kbuf);
513 return read ? read : err;
517 static ssize_t do_write_kmem(unsigned long p, const char __user *buf,
518 size_t count, loff_t *ppos)
521 unsigned long copied;
524 #ifdef __ARCH_HAS_NO_PAGE_ZERO_MAPPED
525 /* we don't have page 0 mapped on sparc and m68k.. */
527 sz = size_inside_page(p, count);
528 /* Hmm. Do something? */
539 sz = size_inside_page(p, count);
542 * On ia64 if a page has been mapped somewhere as uncached, then
543 * it must also be accessed uncached by the kernel or data
544 * corruption may occur.
546 ptr = xlate_dev_kmem_ptr((void *)p);
547 if (!virt_addr_valid(ptr))
550 copied = copy_from_user(ptr, buf, sz);
552 written += sz - copied;
561 if (should_stop_iteration())
570 * This function writes to the *virtual* memory as seen by the kernel.
572 static ssize_t write_kmem(struct file *file, const char __user *buf,
573 size_t count, loff_t *ppos)
575 unsigned long p = *ppos;
578 char *kbuf; /* k-addr because vwrite() takes vmlist_lock rwlock */
581 if (p < (unsigned long) high_memory) {
582 unsigned long to_write = min_t(unsigned long, count,
583 (unsigned long)high_memory - p);
584 wrote = do_write_kmem(p, buf, to_write, ppos);
585 if (wrote != to_write)
593 kbuf = (char *)__get_free_page(GFP_KERNEL);
595 return wrote ? wrote : -ENOMEM;
597 unsigned long sz = size_inside_page(p, count);
600 if (!is_vmalloc_or_module_addr((void *)p)) {
604 n = copy_from_user(kbuf, buf, sz);
609 vwrite(kbuf, (char *)p, sz);
614 if (should_stop_iteration())
617 free_page((unsigned long)kbuf);
621 return virtr + wrote ? : err;
624 static ssize_t read_port(struct file *file, char __user *buf,
625 size_t count, loff_t *ppos)
627 unsigned long i = *ppos;
628 char __user *tmp = buf;
630 if (!access_ok(buf, count))
632 while (count-- > 0 && i < 65536) {
633 if (__put_user(inb(i), tmp) < 0)
642 static ssize_t write_port(struct file *file, const char __user *buf,
643 size_t count, loff_t *ppos)
645 unsigned long i = *ppos;
646 const char __user *tmp = buf;
648 if (!access_ok(buf, count))
650 while (count-- > 0 && i < 65536) {
653 if (__get_user(c, tmp)) {
666 static ssize_t read_null(struct file *file, char __user *buf,
667 size_t count, loff_t *ppos)
672 static ssize_t write_null(struct file *file, const char __user *buf,
673 size_t count, loff_t *ppos)
678 static ssize_t read_iter_null(struct kiocb *iocb, struct iov_iter *to)
683 static ssize_t write_iter_null(struct kiocb *iocb, struct iov_iter *from)
685 size_t count = iov_iter_count(from);
686 iov_iter_advance(from, count);
690 static int pipe_to_null(struct pipe_inode_info *info, struct pipe_buffer *buf,
691 struct splice_desc *sd)
696 static ssize_t splice_write_null(struct pipe_inode_info *pipe, struct file *out,
697 loff_t *ppos, size_t len, unsigned int flags)
699 return splice_from_pipe(pipe, out, ppos, len, flags, pipe_to_null);
702 static ssize_t read_iter_zero(struct kiocb *iocb, struct iov_iter *iter)
706 while (iov_iter_count(iter)) {
707 size_t chunk = iov_iter_count(iter), n;
709 if (chunk > PAGE_SIZE)
710 chunk = PAGE_SIZE; /* Just for latency reasons */
711 n = iov_iter_zero(chunk, iter);
712 if (!n && iov_iter_count(iter))
713 return written ? written : -EFAULT;
715 if (signal_pending(current))
716 return written ? written : -ERESTARTSYS;
722 static ssize_t read_zero(struct file *file, char __user *buf,
723 size_t count, loff_t *ppos)
728 size_t chunk = min_t(size_t, count, PAGE_SIZE);
731 left = clear_user(buf + cleared, chunk);
732 if (unlikely(left)) {
733 cleared += (chunk - left);
741 if (signal_pending(current))
749 static int mmap_zero(struct file *file, struct vm_area_struct *vma)
754 if (vma->vm_flags & VM_SHARED)
755 return shmem_zero_setup(vma);
756 vma_set_anonymous(vma);
760 static unsigned long get_unmapped_area_zero(struct file *file,
761 unsigned long addr, unsigned long len,
762 unsigned long pgoff, unsigned long flags)
765 if (flags & MAP_SHARED) {
767 * mmap_zero() will call shmem_zero_setup() to create a file,
768 * so use shmem's get_unmapped_area in case it can be huge;
769 * and pass NULL for file as in mmap.c's get_unmapped_area(),
770 * so as not to confuse shmem with our handle on "/dev/zero".
772 return shmem_get_unmapped_area(NULL, addr, len, pgoff, flags);
775 /* Otherwise flags & MAP_PRIVATE: with no shmem object beneath it */
776 return current->mm->get_unmapped_area(file, addr, len, pgoff, flags);
782 static ssize_t write_full(struct file *file, const char __user *buf,
783 size_t count, loff_t *ppos)
789 * Special lseek() function for /dev/null and /dev/zero. Most notably, you
790 * can fopen() both devices with "a" now. This was previously impossible.
793 static loff_t null_lseek(struct file *file, loff_t offset, int orig)
795 return file->f_pos = 0;
799 * The memory devices use the full 32/64 bits of the offset, and so we cannot
800 * check against negative addresses: they are ok. The return value is weird,
801 * though, in that case (0).
803 * also note that seeking relative to the "end of file" isn't supported:
804 * it has no meaning, so it returns -EINVAL.
806 static loff_t memory_lseek(struct file *file, loff_t offset, int orig)
810 inode_lock(file_inode(file));
813 offset += file->f_pos;
816 /* to avoid userland mistaking f_pos=-9 as -EBADF=-9 */
817 if ((unsigned long long)offset >= -MAX_ERRNO) {
821 file->f_pos = offset;
823 force_successful_syscall_return();
828 inode_unlock(file_inode(file));
832 static struct inode *devmem_inode;
834 #ifdef CONFIG_IO_STRICT_DEVMEM
835 void revoke_devmem(struct resource *res)
837 /* pairs with smp_store_release() in devmem_init_inode() */
838 struct inode *inode = smp_load_acquire(&devmem_inode);
841 * Check that the initialization has completed. Losing the race
842 * is ok because it means drivers are claiming resources before
843 * the fs_initcall level of init and prevent /dev/mem from
844 * establishing mappings.
850 * The expectation is that the driver has successfully marked
851 * the resource busy by this point, so devmem_is_allowed()
852 * should start returning false, however for performance this
853 * does not iterate the entire resource range.
855 if (devmem_is_allowed(PHYS_PFN(res->start)) &&
856 devmem_is_allowed(PHYS_PFN(res->end))) {
858 * *cringe* iomem=relaxed says "go ahead, what's the
859 * worst that can happen?"
864 unmap_mapping_range(inode->i_mapping, res->start, resource_size(res), 1);
868 static int open_port(struct inode *inode, struct file *filp)
872 if (!capable(CAP_SYS_RAWIO))
875 rc = security_locked_down(LOCKDOWN_DEV_MEM);
879 if (iminor(inode) != DEVMEM_MINOR)
883 * Use a unified address space to have a single point to manage
884 * revocations when drivers want to take over a /dev/mem mapped
887 inode->i_mapping = devmem_inode->i_mapping;
888 filp->f_mapping = inode->i_mapping;
893 #define zero_lseek null_lseek
894 #define full_lseek null_lseek
895 #define write_zero write_null
896 #define write_iter_zero write_iter_null
897 #define open_mem open_port
898 #define open_kmem open_mem
900 static const struct file_operations __maybe_unused mem_fops = {
901 .llseek = memory_lseek,
907 .get_unmapped_area = get_unmapped_area_mem,
908 .mmap_capabilities = memory_mmap_capabilities,
912 static const struct file_operations __maybe_unused kmem_fops = {
913 .llseek = memory_lseek,
919 .get_unmapped_area = get_unmapped_area_mem,
920 .mmap_capabilities = memory_mmap_capabilities,
924 static const struct file_operations null_fops = {
925 .llseek = null_lseek,
928 .read_iter = read_iter_null,
929 .write_iter = write_iter_null,
930 .splice_write = splice_write_null,
933 static const struct file_operations __maybe_unused port_fops = {
934 .llseek = memory_lseek,
940 static const struct file_operations zero_fops = {
941 .llseek = zero_lseek,
943 .read_iter = read_iter_zero,
945 .write_iter = write_iter_zero,
947 .get_unmapped_area = get_unmapped_area_zero,
949 .mmap_capabilities = zero_mmap_capabilities,
953 static const struct file_operations full_fops = {
954 .llseek = full_lseek,
955 .read_iter = read_iter_zero,
959 static const struct memdev {
962 const struct file_operations *fops;
966 [DEVMEM_MINOR] = { "mem", 0, &mem_fops, FMODE_UNSIGNED_OFFSET },
968 #ifdef CONFIG_DEVKMEM
969 [2] = { "kmem", 0, &kmem_fops, FMODE_UNSIGNED_OFFSET },
971 [3] = { "null", 0666, &null_fops, 0 },
972 #ifdef CONFIG_DEVPORT
973 [4] = { "port", 0, &port_fops, 0 },
975 [5] = { "zero", 0666, &zero_fops, 0 },
976 [7] = { "full", 0666, &full_fops, 0 },
977 [8] = { "random", 0666, &random_fops, 0 },
978 [9] = { "urandom", 0666, &urandom_fops, 0 },
980 [11] = { "kmsg", 0644, &kmsg_fops, 0 },
984 static int memory_open(struct inode *inode, struct file *filp)
987 const struct memdev *dev;
989 minor = iminor(inode);
990 if (minor >= ARRAY_SIZE(devlist))
993 dev = &devlist[minor];
997 filp->f_op = dev->fops;
998 filp->f_mode |= dev->fmode;
1000 if (dev->fops->open)
1001 return dev->fops->open(inode, filp);
1006 static const struct file_operations memory_fops = {
1007 .open = memory_open,
1008 .llseek = noop_llseek,
1011 static char *mem_devnode(struct device *dev, umode_t *mode)
1013 if (mode && devlist[MINOR(dev->devt)].mode)
1014 *mode = devlist[MINOR(dev->devt)].mode;
1018 static struct class *mem_class;
1020 static int devmem_fs_init_fs_context(struct fs_context *fc)
1022 return init_pseudo(fc, DEVMEM_MAGIC) ? 0 : -ENOMEM;
1025 static struct file_system_type devmem_fs_type = {
1027 .owner = THIS_MODULE,
1028 .init_fs_context = devmem_fs_init_fs_context,
1029 .kill_sb = kill_anon_super,
1032 static int devmem_init_inode(void)
1034 static struct vfsmount *devmem_vfs_mount;
1035 static int devmem_fs_cnt;
1036 struct inode *inode;
1039 rc = simple_pin_fs(&devmem_fs_type, &devmem_vfs_mount, &devmem_fs_cnt);
1041 pr_err("Cannot mount /dev/mem pseudo filesystem: %d\n", rc);
1045 inode = alloc_anon_inode(devmem_vfs_mount->mnt_sb);
1046 if (IS_ERR(inode)) {
1047 rc = PTR_ERR(inode);
1048 pr_err("Cannot allocate inode for /dev/mem: %d\n", rc);
1049 simple_release_fs(&devmem_vfs_mount, &devmem_fs_cnt);
1054 * Publish /dev/mem initialized.
1055 * Pairs with smp_load_acquire() in revoke_devmem().
1057 smp_store_release(&devmem_inode, inode);
1062 static int __init chr_dev_init(void)
1066 if (register_chrdev(MEM_MAJOR, "mem", &memory_fops))
1067 printk("unable to get major %d for memory devs\n", MEM_MAJOR);
1069 mem_class = class_create(THIS_MODULE, "mem");
1070 if (IS_ERR(mem_class))
1071 return PTR_ERR(mem_class);
1073 mem_class->devnode = mem_devnode;
1074 for (minor = 1; minor < ARRAY_SIZE(devlist); minor++) {
1075 if (!devlist[minor].name)
1081 if ((minor == DEVPORT_MINOR) && !arch_has_dev_port())
1083 if ((minor == DEVMEM_MINOR) && devmem_init_inode() != 0)
1086 device_create(mem_class, NULL, MKDEV(MEM_MAJOR, minor),
1087 NULL, devlist[minor].name);
1093 fs_initcall(chr_dev_init);