1 // SPDX-License-Identifier: GPL-2.0-only
3 * linux/kernel/resource.c
5 * Copyright (C) 1999 Linus Torvalds
6 * Copyright (C) 1999 Martin Mares <mj@ucw.cz>
8 * Arbitrary resource management.
11 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
13 #include <linux/export.h>
14 #include <linux/errno.h>
15 #include <linux/ioport.h>
16 #include <linux/init.h>
17 #include <linux/slab.h>
18 #include <linux/spinlock.h>
20 #include <linux/proc_fs.h>
21 #include <linux/pseudo_fs.h>
22 #include <linux/sched.h>
23 #include <linux/seq_file.h>
24 #include <linux/device.h>
25 #include <linux/pfn.h>
27 #include <linux/mount.h>
28 #include <linux/resource_ext.h>
29 #include <uapi/linux/magic.h>
33 struct resource ioport_resource = {
36 .end = IO_SPACE_LIMIT,
37 .flags = IORESOURCE_IO,
39 EXPORT_SYMBOL(ioport_resource);
41 struct resource iomem_resource = {
45 .flags = IORESOURCE_MEM,
47 EXPORT_SYMBOL(iomem_resource);
49 /* constraints to be met while allocating resources */
50 struct resource_constraint {
51 resource_size_t min, max, align;
52 resource_size_t (*alignf)(void *, const struct resource *,
53 resource_size_t, resource_size_t);
57 static DEFINE_RWLOCK(resource_lock);
59 static struct resource *next_resource(struct resource *p)
63 while (!p->sibling && p->parent)
68 static struct resource *next_resource_skip_children(struct resource *p)
70 while (!p->sibling && p->parent)
75 #define for_each_resource(_root, _p, _skip_children) \
76 for ((_p) = (_root)->child; (_p); \
77 (_p) = (_skip_children) ? next_resource_skip_children(_p) : \
80 static void *r_next(struct seq_file *m, void *v, loff_t *pos)
82 struct resource *p = v;
84 return (void *)next_resource(p);
89 enum { MAX_IORES_LEVEL = 5 };
91 static void *r_start(struct seq_file *m, loff_t *pos)
92 __acquires(resource_lock)
94 struct resource *p = pde_data(file_inode(m->file));
96 read_lock(&resource_lock);
97 for (p = p->child; p && l < *pos; p = r_next(m, p, &l))
102 static void r_stop(struct seq_file *m, void *v)
103 __releases(resource_lock)
105 read_unlock(&resource_lock);
108 static int r_show(struct seq_file *m, void *v)
110 struct resource *root = pde_data(file_inode(m->file));
111 struct resource *r = v, *p;
112 unsigned long long start, end;
113 int width = root->end < 0x10000 ? 4 : 8;
116 for (depth = 0, p = r; depth < MAX_IORES_LEVEL; depth++, p = p->parent)
117 if (p->parent == root)
120 if (file_ns_capable(m->file, &init_user_ns, CAP_SYS_ADMIN)) {
127 seq_printf(m, "%*s%0*llx-%0*llx : %s\n",
131 r->name ? r->name : "<BAD>");
135 static const struct seq_operations resource_op = {
142 static int __init ioresources_init(void)
144 proc_create_seq_data("ioports", 0, NULL, &resource_op,
146 proc_create_seq_data("iomem", 0, NULL, &resource_op, &iomem_resource);
149 __initcall(ioresources_init);
151 #endif /* CONFIG_PROC_FS */
153 static void free_resource(struct resource *res)
156 * If the resource was allocated using memblock early during boot
157 * we'll leak it here: we can only return full pages back to the
158 * buddy and trying to be smart and reusing them eventually in
159 * alloc_resource() overcomplicates resource handling.
161 if (res && PageSlab(virt_to_head_page(res)))
165 static struct resource *alloc_resource(gfp_t flags)
167 return kzalloc(sizeof(struct resource), flags);
170 /* Return the conflict entry if you can't request it */
171 static struct resource * __request_resource(struct resource *root, struct resource *new)
173 resource_size_t start = new->start;
174 resource_size_t end = new->end;
175 struct resource *tmp, **p;
179 if (start < root->start)
186 if (!tmp || tmp->start > end) {
193 if (tmp->end < start)
199 static int __release_resource(struct resource *old, bool release_child)
201 struct resource *tmp, **p, *chd;
204 WARN(old->sibling, "sibling but no parent");
209 p = &old->parent->child;
215 if (release_child || !(tmp->child)) {
218 for (chd = tmp->child;; chd = chd->sibling) {
219 chd->parent = tmp->parent;
224 chd->sibling = tmp->sibling;
234 static void __release_child_resources(struct resource *r)
236 struct resource *tmp, *p;
237 resource_size_t size;
247 __release_child_resources(tmp);
249 printk(KERN_DEBUG "release child resource %pR\n", tmp);
250 /* need to restore size, and keep flags */
251 size = resource_size(tmp);
257 void release_child_resources(struct resource *r)
259 write_lock(&resource_lock);
260 __release_child_resources(r);
261 write_unlock(&resource_lock);
265 * request_resource_conflict - request and reserve an I/O or memory resource
266 * @root: root resource descriptor
267 * @new: resource descriptor desired by caller
269 * Returns 0 for success, conflict resource on error.
271 struct resource *request_resource_conflict(struct resource *root, struct resource *new)
273 struct resource *conflict;
275 write_lock(&resource_lock);
276 conflict = __request_resource(root, new);
277 write_unlock(&resource_lock);
282 * request_resource - request and reserve an I/O or memory resource
283 * @root: root resource descriptor
284 * @new: resource descriptor desired by caller
286 * Returns 0 for success, negative error code on error.
288 int request_resource(struct resource *root, struct resource *new)
290 struct resource *conflict;
292 conflict = request_resource_conflict(root, new);
293 return conflict ? -EBUSY : 0;
296 EXPORT_SYMBOL(request_resource);
299 * release_resource - release a previously reserved resource
300 * @old: resource pointer
302 int release_resource(struct resource *old)
306 write_lock(&resource_lock);
307 retval = __release_resource(old, true);
308 write_unlock(&resource_lock);
312 EXPORT_SYMBOL(release_resource);
315 * find_next_iomem_res - Finds the lowest iomem resource that covers part of
318 * If a resource is found, returns 0 and @*res is overwritten with the part
319 * of the resource that's within [@start..@end]; if none is found, returns
320 * -ENODEV. Returns -EINVAL for invalid parameters.
322 * @start: start address of the resource searched for
323 * @end: end address of same resource
324 * @flags: flags which the resource must have
325 * @desc: descriptor the resource must have
326 * @res: return ptr, if resource found
328 * The caller must specify @start, @end, @flags, and @desc
329 * (which may be IORES_DESC_NONE).
331 static int find_next_iomem_res(resource_size_t start, resource_size_t end,
332 unsigned long flags, unsigned long desc,
333 struct resource *res)
343 read_lock(&resource_lock);
345 for (p = iomem_resource.child; p; p = next_resource(p)) {
346 /* If we passed the resource we are looking for, stop */
347 if (p->start > end) {
352 /* Skip until we find a range that matches what we look for */
356 if ((p->flags & flags) != flags)
358 if ((desc != IORES_DESC_NONE) && (desc != p->desc))
361 /* Found a match, break */
367 *res = (struct resource) {
368 .start = max(start, p->start),
369 .end = min(end, p->end),
376 read_unlock(&resource_lock);
377 return p ? 0 : -ENODEV;
380 static int __walk_iomem_res_desc(resource_size_t start, resource_size_t end,
381 unsigned long flags, unsigned long desc,
383 int (*func)(struct resource *, void *))
388 while (start < end &&
389 !find_next_iomem_res(start, end, flags, desc, &res)) {
390 ret = (*func)(&res, arg);
401 * walk_iomem_res_desc - Walks through iomem resources and calls func()
402 * with matching resource ranges.
404 * @desc: I/O resource descriptor. Use IORES_DESC_NONE to skip @desc check.
405 * @flags: I/O resource flags
408 * @arg: function argument for the callback @func
409 * @func: callback function that is called for each qualifying resource area
411 * All the memory ranges which overlap start,end and also match flags and
412 * desc are valid candidates.
414 * NOTE: For a new descriptor search, define a new IORES_DESC in
415 * <linux/ioport.h> and set it in 'desc' of a target resource entry.
417 int walk_iomem_res_desc(unsigned long desc, unsigned long flags, u64 start,
418 u64 end, void *arg, int (*func)(struct resource *, void *))
420 return __walk_iomem_res_desc(start, end, flags, desc, arg, func);
422 EXPORT_SYMBOL_GPL(walk_iomem_res_desc);
425 * This function calls the @func callback against all memory ranges of type
426 * System RAM which are marked as IORESOURCE_SYSTEM_RAM and IORESOUCE_BUSY.
427 * Now, this function is only for System RAM, it deals with full ranges and
428 * not PFNs. If resources are not PFN-aligned, dealing with PFNs can truncate
431 int walk_system_ram_res(u64 start, u64 end, void *arg,
432 int (*func)(struct resource *, void *))
434 unsigned long flags = IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY;
436 return __walk_iomem_res_desc(start, end, flags, IORES_DESC_NONE, arg,
441 * This function calls the @func callback against all memory ranges, which
442 * are ranges marked as IORESOURCE_MEM and IORESOUCE_BUSY.
444 int walk_mem_res(u64 start, u64 end, void *arg,
445 int (*func)(struct resource *, void *))
447 unsigned long flags = IORESOURCE_MEM | IORESOURCE_BUSY;
449 return __walk_iomem_res_desc(start, end, flags, IORES_DESC_NONE, arg,
454 * This function calls the @func callback against all memory ranges of type
455 * System RAM which are marked as IORESOURCE_SYSTEM_RAM and IORESOUCE_BUSY.
456 * It is to be used only for System RAM.
458 int walk_system_ram_range(unsigned long start_pfn, unsigned long nr_pages,
459 void *arg, int (*func)(unsigned long, unsigned long, void *))
461 resource_size_t start, end;
464 unsigned long pfn, end_pfn;
467 start = (u64) start_pfn << PAGE_SHIFT;
468 end = ((u64)(start_pfn + nr_pages) << PAGE_SHIFT) - 1;
469 flags = IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY;
470 while (start < end &&
471 !find_next_iomem_res(start, end, flags, IORES_DESC_NONE, &res)) {
472 pfn = PFN_UP(res.start);
473 end_pfn = PFN_DOWN(res.end + 1);
475 ret = (*func)(pfn, end_pfn - pfn, arg);
483 static int __is_ram(unsigned long pfn, unsigned long nr_pages, void *arg)
489 * This generic page_is_ram() returns true if specified address is
490 * registered as System RAM in iomem_resource list.
492 int __weak page_is_ram(unsigned long pfn)
494 return walk_system_ram_range(pfn, 1, NULL, __is_ram) == 1;
496 EXPORT_SYMBOL_GPL(page_is_ram);
498 static int __region_intersects(struct resource *parent, resource_size_t start,
499 size_t size, unsigned long flags,
503 int type = 0; int other = 0;
507 res.end = start + size - 1;
509 for (p = parent->child; p ; p = p->sibling) {
510 bool is_type = (((p->flags & flags) == flags) &&
511 ((desc == IORES_DESC_NONE) ||
514 if (resource_overlaps(p, &res))
515 is_type ? type++ : other++;
519 return REGION_DISJOINT;
522 return REGION_INTERSECTS;
528 * region_intersects() - determine intersection of region with known resources
529 * @start: region start address
530 * @size: size of region
531 * @flags: flags of resource (in iomem_resource)
532 * @desc: descriptor of resource (in iomem_resource) or IORES_DESC_NONE
534 * Check if the specified region partially overlaps or fully eclipses a
535 * resource identified by @flags and @desc (optional with IORES_DESC_NONE).
536 * Return REGION_DISJOINT if the region does not overlap @flags/@desc,
537 * return REGION_MIXED if the region overlaps @flags/@desc and another
538 * resource, and return REGION_INTERSECTS if the region overlaps @flags/@desc
539 * and no other defined resource. Note that REGION_INTERSECTS is also
540 * returned in the case when the specified region overlaps RAM and undefined
543 * region_intersect() is used by memory remapping functions to ensure
544 * the user is not remapping RAM and is a vast speed up over walking
545 * through the resource table page by page.
547 int region_intersects(resource_size_t start, size_t size, unsigned long flags,
552 read_lock(&resource_lock);
553 ret = __region_intersects(&iomem_resource, start, size, flags, desc);
554 read_unlock(&resource_lock);
558 EXPORT_SYMBOL_GPL(region_intersects);
560 void __weak arch_remove_reservations(struct resource *avail)
564 static resource_size_t simple_align_resource(void *data,
565 const struct resource *avail,
566 resource_size_t size,
567 resource_size_t align)
572 static void resource_clip(struct resource *res, resource_size_t min,
575 if (res->start < min)
582 * Find empty slot in the resource tree with the given range and
583 * alignment constraints
585 static int __find_resource(struct resource *root, struct resource *old,
586 struct resource *new,
587 resource_size_t size,
588 struct resource_constraint *constraint)
590 struct resource *this = root->child;
591 struct resource tmp = *new, avail, alloc;
593 tmp.start = root->start;
595 * Skip past an allocated resource that starts at 0, since the assignment
596 * of this->start - 1 to tmp->end below would cause an underflow.
598 if (this && this->start == root->start) {
599 tmp.start = (this == old) ? old->start : this->end + 1;
600 this = this->sibling;
604 tmp.end = (this == old) ? this->end : this->start - 1;
608 if (tmp.end < tmp.start)
611 resource_clip(&tmp, constraint->min, constraint->max);
612 arch_remove_reservations(&tmp);
614 /* Check for overflow after ALIGN() */
615 avail.start = ALIGN(tmp.start, constraint->align);
617 avail.flags = new->flags & ~IORESOURCE_UNSET;
618 if (avail.start >= tmp.start) {
619 alloc.flags = avail.flags;
620 alloc.start = constraint->alignf(constraint->alignf_data, &avail,
621 size, constraint->align);
622 alloc.end = alloc.start + size - 1;
623 if (alloc.start <= alloc.end &&
624 resource_contains(&avail, &alloc)) {
625 new->start = alloc.start;
626 new->end = alloc.end;
631 next: if (!this || this->end == root->end)
635 tmp.start = this->end + 1;
636 this = this->sibling;
642 * Find empty slot in the resource tree given range and alignment.
644 static int find_resource(struct resource *root, struct resource *new,
645 resource_size_t size,
646 struct resource_constraint *constraint)
648 return __find_resource(root, NULL, new, size, constraint);
652 * reallocate_resource - allocate a slot in the resource tree given range & alignment.
653 * The resource will be relocated if the new size cannot be reallocated in the
656 * @root: root resource descriptor
657 * @old: resource descriptor desired by caller
658 * @newsize: new size of the resource descriptor
659 * @constraint: the size and alignment constraints to be met.
661 static int reallocate_resource(struct resource *root, struct resource *old,
662 resource_size_t newsize,
663 struct resource_constraint *constraint)
666 struct resource new = *old;
667 struct resource *conflict;
669 write_lock(&resource_lock);
671 if ((err = __find_resource(root, old, &new, newsize, constraint)))
674 if (resource_contains(&new, old)) {
675 old->start = new.start;
685 if (resource_contains(old, &new)) {
686 old->start = new.start;
689 __release_resource(old, true);
691 conflict = __request_resource(root, old);
695 write_unlock(&resource_lock);
701 * allocate_resource - allocate empty slot in the resource tree given range & alignment.
702 * The resource will be reallocated with a new size if it was already allocated
703 * @root: root resource descriptor
704 * @new: resource descriptor desired by caller
705 * @size: requested resource region size
706 * @min: minimum boundary to allocate
707 * @max: maximum boundary to allocate
708 * @align: alignment requested, in bytes
709 * @alignf: alignment function, optional, called if not NULL
710 * @alignf_data: arbitrary data to pass to the @alignf function
712 int allocate_resource(struct resource *root, struct resource *new,
713 resource_size_t size, resource_size_t min,
714 resource_size_t max, resource_size_t align,
715 resource_size_t (*alignf)(void *,
716 const struct resource *,
722 struct resource_constraint constraint;
725 alignf = simple_align_resource;
727 constraint.min = min;
728 constraint.max = max;
729 constraint.align = align;
730 constraint.alignf = alignf;
731 constraint.alignf_data = alignf_data;
734 /* resource is already allocated, try reallocating with
735 the new constraints */
736 return reallocate_resource(root, new, size, &constraint);
739 write_lock(&resource_lock);
740 err = find_resource(root, new, size, &constraint);
741 if (err >= 0 && __request_resource(root, new))
743 write_unlock(&resource_lock);
747 EXPORT_SYMBOL(allocate_resource);
750 * lookup_resource - find an existing resource by a resource start address
751 * @root: root resource descriptor
752 * @start: resource start address
754 * Returns a pointer to the resource if found, NULL otherwise
756 struct resource *lookup_resource(struct resource *root, resource_size_t start)
758 struct resource *res;
760 read_lock(&resource_lock);
761 for (res = root->child; res; res = res->sibling) {
762 if (res->start == start)
765 read_unlock(&resource_lock);
771 * Insert a resource into the resource tree. If successful, return NULL,
772 * otherwise return the conflicting resource (compare to __request_resource())
774 static struct resource * __insert_resource(struct resource *parent, struct resource *new)
776 struct resource *first, *next;
778 for (;; parent = first) {
779 first = __request_resource(parent, new);
785 if (WARN_ON(first == new)) /* duplicated insertion */
788 if ((first->start > new->start) || (first->end < new->end))
790 if ((first->start == new->start) && (first->end == new->end))
794 for (next = first; ; next = next->sibling) {
795 /* Partial overlap? Bad, and unfixable */
796 if (next->start < new->start || next->end > new->end)
800 if (next->sibling->start > new->end)
804 new->parent = parent;
805 new->sibling = next->sibling;
808 next->sibling = NULL;
809 for (next = first; next; next = next->sibling)
812 if (parent->child == first) {
815 next = parent->child;
816 while (next->sibling != first)
817 next = next->sibling;
824 * insert_resource_conflict - Inserts resource in the resource tree
825 * @parent: parent of the new resource
826 * @new: new resource to insert
828 * Returns 0 on success, conflict resource if the resource can't be inserted.
830 * This function is equivalent to request_resource_conflict when no conflict
831 * happens. If a conflict happens, and the conflicting resources
832 * entirely fit within the range of the new resource, then the new
833 * resource is inserted and the conflicting resources become children of
836 * This function is intended for producers of resources, such as FW modules
839 struct resource *insert_resource_conflict(struct resource *parent, struct resource *new)
841 struct resource *conflict;
843 write_lock(&resource_lock);
844 conflict = __insert_resource(parent, new);
845 write_unlock(&resource_lock);
850 * insert_resource - Inserts a resource in the resource tree
851 * @parent: parent of the new resource
852 * @new: new resource to insert
854 * Returns 0 on success, -EBUSY if the resource can't be inserted.
856 * This function is intended for producers of resources, such as FW modules
859 int insert_resource(struct resource *parent, struct resource *new)
861 struct resource *conflict;
863 conflict = insert_resource_conflict(parent, new);
864 return conflict ? -EBUSY : 0;
866 EXPORT_SYMBOL_GPL(insert_resource);
869 * insert_resource_expand_to_fit - Insert a resource into the resource tree
870 * @root: root resource descriptor
871 * @new: new resource to insert
873 * Insert a resource into the resource tree, possibly expanding it in order
874 * to make it encompass any conflicting resources.
876 void insert_resource_expand_to_fit(struct resource *root, struct resource *new)
881 write_lock(&resource_lock);
883 struct resource *conflict;
885 conflict = __insert_resource(root, new);
888 if (conflict == root)
891 /* Ok, expand resource to cover the conflict, then try again .. */
892 if (conflict->start < new->start)
893 new->start = conflict->start;
894 if (conflict->end > new->end)
895 new->end = conflict->end;
897 pr_info("Expanded resource %s due to conflict with %s\n", new->name, conflict->name);
899 write_unlock(&resource_lock);
902 * Not for general consumption, only early boot memory map parsing, PCI
903 * resource discovery, and late discovery of CXL resources are expected
904 * to use this interface. The former are built-in and only the latter,
907 EXPORT_SYMBOL_NS_GPL(insert_resource_expand_to_fit, CXL);
910 * remove_resource - Remove a resource in the resource tree
911 * @old: resource to remove
913 * Returns 0 on success, -EINVAL if the resource is not valid.
915 * This function removes a resource previously inserted by insert_resource()
916 * or insert_resource_conflict(), and moves the children (if any) up to
917 * where they were before. insert_resource() and insert_resource_conflict()
918 * insert a new resource, and move any conflicting resources down to the
919 * children of the new resource.
921 * insert_resource(), insert_resource_conflict() and remove_resource() are
922 * intended for producers of resources, such as FW modules and bus drivers.
924 int remove_resource(struct resource *old)
928 write_lock(&resource_lock);
929 retval = __release_resource(old, false);
930 write_unlock(&resource_lock);
933 EXPORT_SYMBOL_GPL(remove_resource);
935 static int __adjust_resource(struct resource *res, resource_size_t start,
936 resource_size_t size)
938 struct resource *tmp, *parent = res->parent;
939 resource_size_t end = start + size - 1;
945 if ((start < parent->start) || (end > parent->end))
948 if (res->sibling && (res->sibling->start <= end))
953 while (tmp->sibling != res)
955 if (start <= tmp->end)
960 for (tmp = res->child; tmp; tmp = tmp->sibling)
961 if ((tmp->start < start) || (tmp->end > end))
973 * adjust_resource - modify a resource's start and size
974 * @res: resource to modify
975 * @start: new start value
978 * Given an existing resource, change its start and size to match the
979 * arguments. Returns 0 on success, -EBUSY if it can't fit.
980 * Existing children of the resource are assumed to be immutable.
982 int adjust_resource(struct resource *res, resource_size_t start,
983 resource_size_t size)
987 write_lock(&resource_lock);
988 result = __adjust_resource(res, start, size);
989 write_unlock(&resource_lock);
992 EXPORT_SYMBOL(adjust_resource);
995 __reserve_region_with_split(struct resource *root, resource_size_t start,
996 resource_size_t end, const char *name)
998 struct resource *parent = root;
999 struct resource *conflict;
1000 struct resource *res = alloc_resource(GFP_ATOMIC);
1001 struct resource *next_res = NULL;
1002 int type = resource_type(root);
1010 res->flags = type | IORESOURCE_BUSY;
1011 res->desc = IORES_DESC_NONE;
1015 conflict = __request_resource(parent, res);
1024 /* conflict covered whole area */
1025 if (conflict->start <= res->start &&
1026 conflict->end >= res->end) {
1032 /* failed, split and try again */
1033 if (conflict->start > res->start) {
1035 res->end = conflict->start - 1;
1036 if (conflict->end < end) {
1037 next_res = alloc_resource(GFP_ATOMIC);
1042 next_res->name = name;
1043 next_res->start = conflict->end + 1;
1044 next_res->end = end;
1045 next_res->flags = type | IORESOURCE_BUSY;
1046 next_res->desc = IORES_DESC_NONE;
1049 res->start = conflict->end + 1;
1056 reserve_region_with_split(struct resource *root, resource_size_t start,
1057 resource_size_t end, const char *name)
1061 write_lock(&resource_lock);
1062 if (root->start > start || root->end < end) {
1063 pr_err("requested range [0x%llx-0x%llx] not in root %pr\n",
1064 (unsigned long long)start, (unsigned long long)end,
1066 if (start > root->end || end < root->start)
1069 if (end > root->end)
1071 if (start < root->start)
1072 start = root->start;
1073 pr_err("fixing request to [0x%llx-0x%llx]\n",
1074 (unsigned long long)start,
1075 (unsigned long long)end);
1080 __reserve_region_with_split(root, start, end, name);
1081 write_unlock(&resource_lock);
1085 * resource_alignment - calculate resource's alignment
1086 * @res: resource pointer
1088 * Returns alignment on success, 0 (invalid alignment) on failure.
1090 resource_size_t resource_alignment(struct resource *res)
1092 switch (res->flags & (IORESOURCE_SIZEALIGN | IORESOURCE_STARTALIGN)) {
1093 case IORESOURCE_SIZEALIGN:
1094 return resource_size(res);
1095 case IORESOURCE_STARTALIGN:
1103 * This is compatibility stuff for IO resources.
1105 * Note how this, unlike the above, knows about
1106 * the IO flag meanings (busy etc).
1108 * request_region creates a new busy region.
1110 * release_region releases a matching busy region.
1113 static DECLARE_WAIT_QUEUE_HEAD(muxed_resource_wait);
1115 static struct inode *iomem_inode;
1117 #ifdef CONFIG_IO_STRICT_DEVMEM
1118 static void revoke_iomem(struct resource *res)
1120 /* pairs with smp_store_release() in iomem_init_inode() */
1121 struct inode *inode = smp_load_acquire(&iomem_inode);
1124 * Check that the initialization has completed. Losing the race
1125 * is ok because it means drivers are claiming resources before
1126 * the fs_initcall level of init and prevent iomem_get_mapping users
1127 * from establishing mappings.
1133 * The expectation is that the driver has successfully marked
1134 * the resource busy by this point, so devmem_is_allowed()
1135 * should start returning false, however for performance this
1136 * does not iterate the entire resource range.
1138 if (devmem_is_allowed(PHYS_PFN(res->start)) &&
1139 devmem_is_allowed(PHYS_PFN(res->end))) {
1141 * *cringe* iomem=relaxed says "go ahead, what's the
1142 * worst that can happen?"
1147 unmap_mapping_range(inode->i_mapping, res->start, resource_size(res), 1);
1150 static void revoke_iomem(struct resource *res) {}
1153 struct address_space *iomem_get_mapping(void)
1156 * This function is only called from file open paths, hence guaranteed
1157 * that fs_initcalls have completed and no need to check for NULL. But
1158 * since revoke_iomem can be called before the initcall we still need
1159 * the barrier to appease checkers.
1161 return smp_load_acquire(&iomem_inode)->i_mapping;
1164 static int __request_region_locked(struct resource *res, struct resource *parent,
1165 resource_size_t start, resource_size_t n,
1166 const char *name, int flags)
1168 DECLARE_WAITQUEUE(wait, current);
1172 res->end = start + n - 1;
1175 struct resource *conflict;
1177 res->flags = resource_type(parent) | resource_ext_type(parent);
1178 res->flags |= IORESOURCE_BUSY | flags;
1179 res->desc = parent->desc;
1181 conflict = __request_resource(parent, res);
1185 * mm/hmm.c reserves physical addresses which then
1186 * become unavailable to other users. Conflicts are
1187 * not expected. Warn to aid debugging if encountered.
1189 if (conflict->desc == IORES_DESC_DEVICE_PRIVATE_MEMORY) {
1190 pr_warn("Unaddressable device %s %pR conflicts with %pR",
1191 conflict->name, conflict, res);
1193 if (conflict != parent) {
1194 if (!(conflict->flags & IORESOURCE_BUSY)) {
1199 if (conflict->flags & flags & IORESOURCE_MUXED) {
1200 add_wait_queue(&muxed_resource_wait, &wait);
1201 write_unlock(&resource_lock);
1202 set_current_state(TASK_UNINTERRUPTIBLE);
1204 remove_wait_queue(&muxed_resource_wait, &wait);
1205 write_lock(&resource_lock);
1208 /* Uhhuh, that didn't work out.. */
1216 * __request_region - create a new busy resource region
1217 * @parent: parent resource descriptor
1218 * @start: resource start address
1219 * @n: resource region size
1220 * @name: reserving caller's ID string
1221 * @flags: IO resource flags
1223 struct resource *__request_region(struct resource *parent,
1224 resource_size_t start, resource_size_t n,
1225 const char *name, int flags)
1227 struct resource *res = alloc_resource(GFP_KERNEL);
1233 write_lock(&resource_lock);
1234 ret = __request_region_locked(res, parent, start, n, name, flags);
1235 write_unlock(&resource_lock);
1242 if (parent == &iomem_resource)
1247 EXPORT_SYMBOL(__request_region);
1250 * __release_region - release a previously reserved resource region
1251 * @parent: parent resource descriptor
1252 * @start: resource start address
1253 * @n: resource region size
1255 * The described resource region must match a currently busy region.
1257 void __release_region(struct resource *parent, resource_size_t start,
1260 struct resource **p;
1261 resource_size_t end;
1264 end = start + n - 1;
1266 write_lock(&resource_lock);
1269 struct resource *res = *p;
1273 if (res->start <= start && res->end >= end) {
1274 if (!(res->flags & IORESOURCE_BUSY)) {
1278 if (res->start != start || res->end != end)
1281 write_unlock(&resource_lock);
1282 if (res->flags & IORESOURCE_MUXED)
1283 wake_up(&muxed_resource_wait);
1290 write_unlock(&resource_lock);
1292 pr_warn("Trying to free nonexistent resource <%pa-%pa>\n", &start, &end);
1294 EXPORT_SYMBOL(__release_region);
1296 #ifdef CONFIG_MEMORY_HOTREMOVE
1298 * release_mem_region_adjustable - release a previously reserved memory region
1299 * @start: resource start address
1300 * @size: resource region size
1302 * This interface is intended for memory hot-delete. The requested region
1303 * is released from a currently busy memory resource. The requested region
1304 * must either match exactly or fit into a single busy resource entry. In
1305 * the latter case, the remaining resource is adjusted accordingly.
1306 * Existing children of the busy memory resource must be immutable in the
1310 * - Additional release conditions, such as overlapping region, can be
1311 * supported after they are confirmed as valid cases.
1312 * - When a busy memory resource gets split into two entries, the code
1313 * assumes that all children remain in the lower address entry for
1314 * simplicity. Enhance this logic when necessary.
1316 void release_mem_region_adjustable(resource_size_t start, resource_size_t size)
1318 struct resource *parent = &iomem_resource;
1319 struct resource *new_res = NULL;
1320 bool alloc_nofail = false;
1321 struct resource **p;
1322 struct resource *res;
1323 resource_size_t end;
1325 end = start + size - 1;
1326 if (WARN_ON_ONCE((start < parent->start) || (end > parent->end)))
1330 * We free up quite a lot of memory on memory hotunplug (esp., memap),
1331 * just before releasing the region. This is highly unlikely to
1332 * fail - let's play save and make it never fail as the caller cannot
1333 * perform any error handling (e.g., trying to re-add memory will fail
1337 new_res = alloc_resource(GFP_KERNEL | (alloc_nofail ? __GFP_NOFAIL : 0));
1340 write_lock(&resource_lock);
1342 while ((res = *p)) {
1343 if (res->start >= end)
1346 /* look for the next resource if it does not fit into */
1347 if (res->start > start || res->end < end) {
1352 if (!(res->flags & IORESOURCE_MEM))
1355 if (!(res->flags & IORESOURCE_BUSY)) {
1360 /* found the target resource; let's adjust accordingly */
1361 if (res->start == start && res->end == end) {
1362 /* free the whole entry */
1365 } else if (res->start == start && res->end != end) {
1366 /* adjust the start */
1367 WARN_ON_ONCE(__adjust_resource(res, end + 1,
1369 } else if (res->start != start && res->end == end) {
1370 /* adjust the end */
1371 WARN_ON_ONCE(__adjust_resource(res, res->start,
1372 start - res->start));
1374 /* split into two entries - we need a new resource */
1376 new_res = alloc_resource(GFP_ATOMIC);
1378 alloc_nofail = true;
1379 write_unlock(&resource_lock);
1383 new_res->name = res->name;
1384 new_res->start = end + 1;
1385 new_res->end = res->end;
1386 new_res->flags = res->flags;
1387 new_res->desc = res->desc;
1388 new_res->parent = res->parent;
1389 new_res->sibling = res->sibling;
1390 new_res->child = NULL;
1392 if (WARN_ON_ONCE(__adjust_resource(res, res->start,
1393 start - res->start)))
1395 res->sibling = new_res;
1402 write_unlock(&resource_lock);
1403 free_resource(new_res);
1405 #endif /* CONFIG_MEMORY_HOTREMOVE */
1407 #ifdef CONFIG_MEMORY_HOTPLUG
1408 static bool system_ram_resources_mergeable(struct resource *r1,
1409 struct resource *r2)
1411 /* We assume either r1 or r2 is IORESOURCE_SYSRAM_MERGEABLE. */
1412 return r1->flags == r2->flags && r1->end + 1 == r2->start &&
1413 r1->name == r2->name && r1->desc == r2->desc &&
1414 !r1->child && !r2->child;
1418 * merge_system_ram_resource - mark the System RAM resource mergeable and try to
1419 * merge it with adjacent, mergeable resources
1420 * @res: resource descriptor
1422 * This interface is intended for memory hotplug, whereby lots of contiguous
1423 * system ram resources are added (e.g., via add_memory*()) by a driver, and
1424 * the actual resource boundaries are not of interest (e.g., it might be
1425 * relevant for DIMMs). Only resources that are marked mergeable, that have the
1426 * same parent, and that don't have any children are considered. All mergeable
1427 * resources must be immutable during the request.
1430 * - The caller has to make sure that no pointers to resources that are
1431 * marked mergeable are used anymore after this call - the resource might
1432 * be freed and the pointer might be stale!
1433 * - release_mem_region_adjustable() will split on demand on memory hotunplug
1435 void merge_system_ram_resource(struct resource *res)
1437 const unsigned long flags = IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY;
1438 struct resource *cur;
1440 if (WARN_ON_ONCE((res->flags & flags) != flags))
1443 write_lock(&resource_lock);
1444 res->flags |= IORESOURCE_SYSRAM_MERGEABLE;
1446 /* Try to merge with next item in the list. */
1448 if (cur && system_ram_resources_mergeable(res, cur)) {
1449 res->end = cur->end;
1450 res->sibling = cur->sibling;
1454 /* Try to merge with previous item in the list. */
1455 cur = res->parent->child;
1456 while (cur && cur->sibling != res)
1458 if (cur && system_ram_resources_mergeable(cur, res)) {
1459 cur->end = res->end;
1460 cur->sibling = res->sibling;
1463 write_unlock(&resource_lock);
1465 #endif /* CONFIG_MEMORY_HOTPLUG */
1468 * Managed region resource
1470 static void devm_resource_release(struct device *dev, void *ptr)
1472 struct resource **r = ptr;
1474 release_resource(*r);
1478 * devm_request_resource() - request and reserve an I/O or memory resource
1479 * @dev: device for which to request the resource
1480 * @root: root of the resource tree from which to request the resource
1481 * @new: descriptor of the resource to request
1483 * This is a device-managed version of request_resource(). There is usually
1484 * no need to release resources requested by this function explicitly since
1485 * that will be taken care of when the device is unbound from its driver.
1486 * If for some reason the resource needs to be released explicitly, because
1487 * of ordering issues for example, drivers must call devm_release_resource()
1488 * rather than the regular release_resource().
1490 * When a conflict is detected between any existing resources and the newly
1491 * requested resource, an error message will be printed.
1493 * Returns 0 on success or a negative error code on failure.
1495 int devm_request_resource(struct device *dev, struct resource *root,
1496 struct resource *new)
1498 struct resource *conflict, **ptr;
1500 ptr = devres_alloc(devm_resource_release, sizeof(*ptr), GFP_KERNEL);
1506 conflict = request_resource_conflict(root, new);
1508 dev_err(dev, "resource collision: %pR conflicts with %s %pR\n",
1509 new, conflict->name, conflict);
1514 devres_add(dev, ptr);
1517 EXPORT_SYMBOL(devm_request_resource);
1519 static int devm_resource_match(struct device *dev, void *res, void *data)
1521 struct resource **ptr = res;
1523 return *ptr == data;
1527 * devm_release_resource() - release a previously requested resource
1528 * @dev: device for which to release the resource
1529 * @new: descriptor of the resource to release
1531 * Releases a resource previously requested using devm_request_resource().
1533 void devm_release_resource(struct device *dev, struct resource *new)
1535 WARN_ON(devres_release(dev, devm_resource_release, devm_resource_match,
1538 EXPORT_SYMBOL(devm_release_resource);
1540 struct region_devres {
1541 struct resource *parent;
1542 resource_size_t start;
1546 static void devm_region_release(struct device *dev, void *res)
1548 struct region_devres *this = res;
1550 __release_region(this->parent, this->start, this->n);
1553 static int devm_region_match(struct device *dev, void *res, void *match_data)
1555 struct region_devres *this = res, *match = match_data;
1557 return this->parent == match->parent &&
1558 this->start == match->start && this->n == match->n;
1562 __devm_request_region(struct device *dev, struct resource *parent,
1563 resource_size_t start, resource_size_t n, const char *name)
1565 struct region_devres *dr = NULL;
1566 struct resource *res;
1568 dr = devres_alloc(devm_region_release, sizeof(struct region_devres),
1573 dr->parent = parent;
1577 res = __request_region(parent, start, n, name, 0);
1579 devres_add(dev, dr);
1585 EXPORT_SYMBOL(__devm_request_region);
1587 void __devm_release_region(struct device *dev, struct resource *parent,
1588 resource_size_t start, resource_size_t n)
1590 struct region_devres match_data = { parent, start, n };
1592 __release_region(parent, start, n);
1593 WARN_ON(devres_destroy(dev, devm_region_release, devm_region_match,
1596 EXPORT_SYMBOL(__devm_release_region);
1599 * Reserve I/O ports or memory based on "reserve=" kernel parameter.
1601 #define MAXRESERVE 4
1602 static int __init reserve_setup(char *str)
1604 static int reserved;
1605 static struct resource reserve[MAXRESERVE];
1608 unsigned int io_start, io_num;
1610 struct resource *parent;
1612 if (get_option(&str, &io_start) != 2)
1614 if (get_option(&str, &io_num) == 0)
1616 if (x < MAXRESERVE) {
1617 struct resource *res = reserve + x;
1620 * If the region starts below 0x10000, we assume it's
1621 * I/O port space; otherwise assume it's memory.
1623 if (io_start < 0x10000) {
1624 res->flags = IORESOURCE_IO;
1625 parent = &ioport_resource;
1627 res->flags = IORESOURCE_MEM;
1628 parent = &iomem_resource;
1630 res->name = "reserved";
1631 res->start = io_start;
1632 res->end = io_start + io_num - 1;
1633 res->flags |= IORESOURCE_BUSY;
1634 res->desc = IORES_DESC_NONE;
1636 if (request_resource(parent, res) == 0)
1642 __setup("reserve=", reserve_setup);
1645 * Check if the requested addr and size spans more than any slot in the
1646 * iomem resource tree.
1648 int iomem_map_sanity_check(resource_size_t addr, unsigned long size)
1650 struct resource *p = &iomem_resource;
1651 resource_size_t end = addr + size - 1;
1655 read_lock(&resource_lock);
1656 for (p = p->child; p ; p = r_next(NULL, p, &l)) {
1658 * We can probably skip the resources without
1659 * IORESOURCE_IO attribute?
1665 if (PFN_DOWN(p->start) <= PFN_DOWN(addr) &&
1666 PFN_DOWN(p->end) >= PFN_DOWN(end))
1669 * if a resource is "BUSY", it's not a hardware resource
1670 * but a driver mapping of such a resource; we don't want
1671 * to warn for those; some drivers legitimately map only
1672 * partial hardware resources. (example: vesafb)
1674 if (p->flags & IORESOURCE_BUSY)
1677 pr_warn("resource sanity check: requesting [mem %pa-%pa], which spans more than %s %pR\n",
1678 &addr, &end, p->name, p);
1682 read_unlock(&resource_lock);
1687 #ifdef CONFIG_STRICT_DEVMEM
1688 static int strict_iomem_checks = 1;
1690 static int strict_iomem_checks;
1694 * Check if an address is exclusive to the kernel and must not be mapped to
1695 * user space, for example, via /dev/mem.
1697 * Returns true if exclusive to the kernel, otherwise returns false.
1699 bool resource_is_exclusive(struct resource *root, u64 addr, resource_size_t size)
1701 const unsigned int exclusive_system_ram = IORESOURCE_SYSTEM_RAM |
1702 IORESOURCE_EXCLUSIVE;
1703 bool skip_children = false, err = false;
1706 read_lock(&resource_lock);
1707 for_each_resource(root, p, skip_children) {
1708 if (p->start >= addr + size)
1710 if (p->end < addr) {
1711 skip_children = true;
1714 skip_children = false;
1717 * IORESOURCE_SYSTEM_RAM resources are exclusive if
1718 * IORESOURCE_EXCLUSIVE is set, even if they
1719 * are not busy and even if "iomem=relaxed" is set. The
1720 * responsible driver dynamically adds/removes system RAM within
1721 * such an area and uncontrolled access is dangerous.
1723 if ((p->flags & exclusive_system_ram) == exclusive_system_ram) {
1729 * A resource is exclusive if IORESOURCE_EXCLUSIVE is set
1730 * or CONFIG_IO_STRICT_DEVMEM is enabled and the
1733 if (!strict_iomem_checks || !(p->flags & IORESOURCE_BUSY))
1735 if (IS_ENABLED(CONFIG_IO_STRICT_DEVMEM)
1736 || p->flags & IORESOURCE_EXCLUSIVE) {
1741 read_unlock(&resource_lock);
1746 bool iomem_is_exclusive(u64 addr)
1748 return resource_is_exclusive(&iomem_resource, addr & PAGE_MASK,
1752 struct resource_entry *resource_list_create_entry(struct resource *res,
1755 struct resource_entry *entry;
1757 entry = kzalloc(sizeof(*entry) + extra_size, GFP_KERNEL);
1759 INIT_LIST_HEAD(&entry->node);
1760 entry->res = res ? res : &entry->__res;
1765 EXPORT_SYMBOL(resource_list_create_entry);
1767 void resource_list_free(struct list_head *head)
1769 struct resource_entry *entry, *tmp;
1771 list_for_each_entry_safe(entry, tmp, head, node)
1772 resource_list_destroy_entry(entry);
1774 EXPORT_SYMBOL(resource_list_free);
1776 #ifdef CONFIG_GET_FREE_REGION
1777 #define GFR_DESCENDING (1UL << 0)
1778 #define GFR_REQUEST_REGION (1UL << 1)
1779 #define GFR_DEFAULT_ALIGN (1UL << PA_SECTION_SHIFT)
1781 static resource_size_t gfr_start(struct resource *base, resource_size_t size,
1782 resource_size_t align, unsigned long flags)
1784 if (flags & GFR_DESCENDING) {
1785 resource_size_t end;
1787 end = min_t(resource_size_t, base->end,
1788 (1ULL << MAX_PHYSMEM_BITS) - 1);
1789 return end - size + 1;
1792 return ALIGN(base->start, align);
1795 static bool gfr_continue(struct resource *base, resource_size_t addr,
1796 resource_size_t size, unsigned long flags)
1798 if (flags & GFR_DESCENDING)
1799 return addr > size && addr >= base->start;
1801 * In the ascend case be careful that the last increment by
1802 * @size did not wrap 0.
1804 return addr > addr - size &&
1805 addr <= min_t(resource_size_t, base->end,
1806 (1ULL << MAX_PHYSMEM_BITS) - 1);
1809 static resource_size_t gfr_next(resource_size_t addr, resource_size_t size,
1810 unsigned long flags)
1812 if (flags & GFR_DESCENDING)
1817 static void remove_free_mem_region(void *_res)
1819 struct resource *res = _res;
1822 remove_resource(res);
1826 static struct resource *
1827 get_free_mem_region(struct device *dev, struct resource *base,
1828 resource_size_t size, const unsigned long align,
1829 const char *name, const unsigned long desc,
1830 const unsigned long flags)
1832 resource_size_t addr;
1833 struct resource *res;
1834 struct region_devres *dr = NULL;
1836 size = ALIGN(size, align);
1838 res = alloc_resource(GFP_KERNEL);
1840 return ERR_PTR(-ENOMEM);
1842 if (dev && (flags & GFR_REQUEST_REGION)) {
1843 dr = devres_alloc(devm_region_release,
1844 sizeof(struct region_devres), GFP_KERNEL);
1847 return ERR_PTR(-ENOMEM);
1850 if (devm_add_action_or_reset(dev, remove_free_mem_region, res))
1851 return ERR_PTR(-ENOMEM);
1854 write_lock(&resource_lock);
1855 for (addr = gfr_start(base, size, align, flags);
1856 gfr_continue(base, addr, align, flags);
1857 addr = gfr_next(addr, align, flags)) {
1858 if (__region_intersects(base, addr, size, 0, IORES_DESC_NONE) !=
1862 if (flags & GFR_REQUEST_REGION) {
1863 if (__request_region_locked(res, &iomem_resource, addr,
1868 dr->parent = &iomem_resource;
1871 devres_add(dev, dr);
1875 write_unlock(&resource_lock);
1879 * A driver is claiming this region so revoke any
1885 res->end = addr + size - 1;
1888 res->flags = IORESOURCE_MEM;
1891 * Only succeed if the resource hosts an exclusive
1892 * range after the insert
1894 if (__insert_resource(base, res) || res->child)
1897 write_unlock(&resource_lock);
1902 write_unlock(&resource_lock);
1904 if (flags & GFR_REQUEST_REGION) {
1908 devm_release_action(dev, remove_free_mem_region, res);
1910 return ERR_PTR(-ERANGE);
1914 * devm_request_free_mem_region - find free region for device private memory
1916 * @dev: device struct to bind the resource to
1917 * @size: size in bytes of the device memory to add
1918 * @base: resource tree to look in
1920 * This function tries to find an empty range of physical address big enough to
1921 * contain the new resource, so that it can later be hotplugged as ZONE_DEVICE
1922 * memory, which in turn allocates struct pages.
1924 struct resource *devm_request_free_mem_region(struct device *dev,
1925 struct resource *base, unsigned long size)
1927 unsigned long flags = GFR_DESCENDING | GFR_REQUEST_REGION;
1929 return get_free_mem_region(dev, base, size, GFR_DEFAULT_ALIGN,
1931 IORES_DESC_DEVICE_PRIVATE_MEMORY, flags);
1933 EXPORT_SYMBOL_GPL(devm_request_free_mem_region);
1935 struct resource *request_free_mem_region(struct resource *base,
1936 unsigned long size, const char *name)
1938 unsigned long flags = GFR_DESCENDING | GFR_REQUEST_REGION;
1940 return get_free_mem_region(NULL, base, size, GFR_DEFAULT_ALIGN, name,
1941 IORES_DESC_DEVICE_PRIVATE_MEMORY, flags);
1943 EXPORT_SYMBOL_GPL(request_free_mem_region);
1946 * alloc_free_mem_region - find a free region relative to @base
1947 * @base: resource that will parent the new resource
1948 * @size: size in bytes of memory to allocate from @base
1949 * @align: alignment requirements for the allocation
1950 * @name: resource name
1952 * Buses like CXL, that can dynamically instantiate new memory regions,
1953 * need a method to allocate physical address space for those regions.
1954 * Allocate and insert a new resource to cover a free, unclaimed by a
1955 * descendant of @base, range in the span of @base.
1957 struct resource *alloc_free_mem_region(struct resource *base,
1958 unsigned long size, unsigned long align,
1961 /* Default of ascending direction and insert resource */
1962 unsigned long flags = 0;
1964 return get_free_mem_region(NULL, base, size, align, name,
1965 IORES_DESC_NONE, flags);
1967 EXPORT_SYMBOL_NS_GPL(alloc_free_mem_region, CXL);
1968 #endif /* CONFIG_GET_FREE_REGION */
1970 static int __init strict_iomem(char *str)
1972 if (strstr(str, "relaxed"))
1973 strict_iomem_checks = 0;
1974 if (strstr(str, "strict"))
1975 strict_iomem_checks = 1;
1979 static int iomem_fs_init_fs_context(struct fs_context *fc)
1981 return init_pseudo(fc, DEVMEM_MAGIC) ? 0 : -ENOMEM;
1984 static struct file_system_type iomem_fs_type = {
1986 .owner = THIS_MODULE,
1987 .init_fs_context = iomem_fs_init_fs_context,
1988 .kill_sb = kill_anon_super,
1991 static int __init iomem_init_inode(void)
1993 static struct vfsmount *iomem_vfs_mount;
1994 static int iomem_fs_cnt;
1995 struct inode *inode;
1998 rc = simple_pin_fs(&iomem_fs_type, &iomem_vfs_mount, &iomem_fs_cnt);
2000 pr_err("Cannot mount iomem pseudo filesystem: %d\n", rc);
2004 inode = alloc_anon_inode(iomem_vfs_mount->mnt_sb);
2005 if (IS_ERR(inode)) {
2006 rc = PTR_ERR(inode);
2007 pr_err("Cannot allocate inode for iomem: %d\n", rc);
2008 simple_release_fs(&iomem_vfs_mount, &iomem_fs_cnt);
2013 * Publish iomem revocation inode initialized.
2014 * Pairs with smp_load_acquire() in revoke_iomem().
2016 smp_store_release(&iomem_inode, inode);
2021 fs_initcall(iomem_init_inode);
2023 __setup("iomem=", strict_iomem);