xref: /linux-6.15/kernel/resource.c (revision 48376a4f)
1457c8996SThomas Gleixner // SPDX-License-Identifier: GPL-2.0-only
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  *	linux/kernel/resource.c
41da177e4SLinus Torvalds  *
51da177e4SLinus Torvalds  * Copyright (C) 1999	Linus Torvalds
61da177e4SLinus Torvalds  * Copyright (C) 1999	Martin Mares <[email protected]>
71da177e4SLinus Torvalds  *
81da177e4SLinus Torvalds  * Arbitrary resource management.
91da177e4SLinus Torvalds  */
101da177e4SLinus Torvalds 
1165fed8f6SOctavian Purdila #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
1265fed8f6SOctavian Purdila 
139984de1aSPaul Gortmaker #include <linux/export.h>
141da177e4SLinus Torvalds #include <linux/errno.h>
151da177e4SLinus Torvalds #include <linux/ioport.h>
161da177e4SLinus Torvalds #include <linux/init.h>
171da177e4SLinus Torvalds #include <linux/slab.h>
181da177e4SLinus Torvalds #include <linux/spinlock.h>
191da177e4SLinus Torvalds #include <linux/fs.h>
201da177e4SLinus Torvalds #include <linux/proc_fs.h>
2171a1d8edSDaniel Vetter #include <linux/pseudo_fs.h>
228b6d043bSAlan Cox #include <linux/sched.h>
231da177e4SLinus Torvalds #include <linux/seq_file.h>
249ac7849eSTejun Heo #include <linux/device.h>
25d68612b2SSuresh Siddha #include <linux/pfn.h>
26ebff7d8fSYasuaki Ishimatsu #include <linux/mm.h>
2771a1d8edSDaniel Vetter #include <linux/mount.h>
2890e97820SJiang Liu #include <linux/resource_ext.h>
2971a1d8edSDaniel Vetter #include <uapi/linux/magic.h>
307acf164bSBaoquan He #include <linux/string.h>
317acf164bSBaoquan He #include <linux/vmalloc.h>
321da177e4SLinus Torvalds #include <asm/io.h>
331da177e4SLinus Torvalds 
341da177e4SLinus Torvalds 
351da177e4SLinus Torvalds struct resource ioport_resource = {
361da177e4SLinus Torvalds 	.name	= "PCI IO",
376550e07fSGreg Kroah-Hartman 	.start	= 0,
381da177e4SLinus Torvalds 	.end	= IO_SPACE_LIMIT,
391da177e4SLinus Torvalds 	.flags	= IORESOURCE_IO,
401da177e4SLinus Torvalds };
411da177e4SLinus Torvalds EXPORT_SYMBOL(ioport_resource);
421da177e4SLinus Torvalds 
431da177e4SLinus Torvalds struct resource iomem_resource = {
441da177e4SLinus Torvalds 	.name	= "PCI mem",
456550e07fSGreg Kroah-Hartman 	.start	= 0,
466550e07fSGreg Kroah-Hartman 	.end	= -1,
471da177e4SLinus Torvalds 	.flags	= IORESOURCE_MEM,
481da177e4SLinus Torvalds };
491da177e4SLinus Torvalds EXPORT_SYMBOL(iomem_resource);
501da177e4SLinus Torvalds 
511da177e4SLinus Torvalds static DEFINE_RWLOCK(resource_lock);
521da177e4SLinus Torvalds 
53d7ce9c73SHuang Ying /*
54d7ce9c73SHuang Ying  * Return the next node of @p in pre-order tree traversal.  If
55d7ce9c73SHuang Ying  * @skip_children is true, skip the descendant nodes of @p in
56d7ce9c73SHuang Ying  * traversal.  If @p is a descendant of @subtree_root, only traverse
57d7ce9c73SHuang Ying  * the subtree under @subtree_root.
58d7ce9c73SHuang Ying  */
next_resource(struct resource * p,bool skip_children,struct resource * subtree_root)59d7ce9c73SHuang Ying static struct resource *next_resource(struct resource *p, bool skip_children,
60d7ce9c73SHuang Ying 				      struct resource *subtree_root)
611da177e4SLinus Torvalds {
6210dabdf4SAndy Shevchenko 	if (!skip_children && p->child)
631da177e4SLinus Torvalds 		return p->child;
64d7ce9c73SHuang Ying 	while (!p->sibling && p->parent) {
651da177e4SLinus Torvalds 		p = p->parent;
66d7ce9c73SHuang Ying 		if (p == subtree_root)
67d7ce9c73SHuang Ying 			return NULL;
68d7ce9c73SHuang Ying 	}
691da177e4SLinus Torvalds 	return p->sibling;
701da177e4SLinus Torvalds }
711da177e4SLinus Torvalds 
72d7ce9c73SHuang Ying /*
73d7ce9c73SHuang Ying  * Traverse the resource subtree under @_root in pre-order, excluding
74d7ce9c73SHuang Ying  * @_root itself.
75d7ce9c73SHuang Ying  *
76d7ce9c73SHuang Ying  * NOTE: '__p' is introduced to avoid shadowing '_p' outside of loop.
77d7ce9c73SHuang Ying  * And it is referenced to avoid unused variable warning.
78d7ce9c73SHuang Ying  */
79b78dfa05SDavid Hildenbrand #define for_each_resource(_root, _p, _skip_children) \
80d7ce9c73SHuang Ying 	for (typeof(_root) __root = (_root), __p = _p = __root->child;	\
81d7ce9c73SHuang Ying 	     __p && _p; _p = next_resource(_p, _skip_children, __root))
82b78dfa05SDavid Hildenbrand 
8313eb8375SIngo Molnar #ifdef CONFIG_PROC_FS
8413eb8375SIngo Molnar 
8513eb8375SIngo Molnar enum { MAX_IORES_LEVEL = 5 };
8613eb8375SIngo Molnar 
r_start(struct seq_file * m,loff_t * pos)871da177e4SLinus Torvalds static void *r_start(struct seq_file *m, loff_t *pos)
881da177e4SLinus Torvalds 	__acquires(resource_lock)
891da177e4SLinus Torvalds {
90441f0dd8SAndy Shevchenko 	struct resource *root = pde_data(file_inode(m->file));
91441f0dd8SAndy Shevchenko 	struct resource *p;
92441f0dd8SAndy Shevchenko 	loff_t l = *pos;
93441f0dd8SAndy Shevchenko 
941da177e4SLinus Torvalds 	read_lock(&resource_lock);
95441f0dd8SAndy Shevchenko 	for_each_resource(root, p, false) {
96441f0dd8SAndy Shevchenko 		if (l-- == 0)
97441f0dd8SAndy Shevchenko 			break;
98441f0dd8SAndy Shevchenko 	}
99441f0dd8SAndy Shevchenko 
1001da177e4SLinus Torvalds 	return p;
1011da177e4SLinus Torvalds }
1021da177e4SLinus Torvalds 
r_next(struct seq_file * m,void * v,loff_t * pos)103441f0dd8SAndy Shevchenko static void *r_next(struct seq_file *m, void *v, loff_t *pos)
104441f0dd8SAndy Shevchenko {
105441f0dd8SAndy Shevchenko 	struct resource *p = v;
10610dabdf4SAndy Shevchenko 
107441f0dd8SAndy Shevchenko 	(*pos)++;
10810dabdf4SAndy Shevchenko 
109d7ce9c73SHuang Ying 	return (void *)next_resource(p, false, NULL);
110441f0dd8SAndy Shevchenko }
111441f0dd8SAndy Shevchenko 
r_stop(struct seq_file * m,void * v)1121da177e4SLinus Torvalds static void r_stop(struct seq_file *m, void *v)
1131da177e4SLinus Torvalds 	__releases(resource_lock)
1141da177e4SLinus Torvalds {
1151da177e4SLinus Torvalds 	read_unlock(&resource_lock);
1161da177e4SLinus Torvalds }
1171da177e4SLinus Torvalds 
r_show(struct seq_file * m,void * v)1181da177e4SLinus Torvalds static int r_show(struct seq_file *m, void *v)
1191da177e4SLinus Torvalds {
120359745d7SMuchun Song 	struct resource *root = pde_data(file_inode(m->file));
1211da177e4SLinus Torvalds 	struct resource *r = v, *p;
12251d7b120SLinus Torvalds 	unsigned long long start, end;
1231da177e4SLinus Torvalds 	int width = root->end < 0x10000 ? 4 : 8;
1241da177e4SLinus Torvalds 	int depth;
1251da177e4SLinus Torvalds 
1261da177e4SLinus Torvalds 	for (depth = 0, p = r; depth < MAX_IORES_LEVEL; depth++, p = p->parent)
1271da177e4SLinus Torvalds 		if (p->parent == root)
1281da177e4SLinus Torvalds 			break;
12951d7b120SLinus Torvalds 
13051d7b120SLinus Torvalds 	if (file_ns_capable(m->file, &init_user_ns, CAP_SYS_ADMIN)) {
13151d7b120SLinus Torvalds 		start = r->start;
13251d7b120SLinus Torvalds 		end = r->end;
13351d7b120SLinus Torvalds 	} else {
13451d7b120SLinus Torvalds 		start = end = 0;
13551d7b120SLinus Torvalds 	}
13651d7b120SLinus Torvalds 
137685143acSGreg Kroah-Hartman 	seq_printf(m, "%*s%0*llx-%0*llx : %s\n",
1381da177e4SLinus Torvalds 			depth * 2, "",
13951d7b120SLinus Torvalds 			width, start,
14051d7b120SLinus Torvalds 			width, end,
1411da177e4SLinus Torvalds 			r->name ? r->name : "<BAD>");
1421da177e4SLinus Torvalds 	return 0;
1431da177e4SLinus Torvalds }
1441da177e4SLinus Torvalds 
14515ad7cdcSHelge Deller static const struct seq_operations resource_op = {
1461da177e4SLinus Torvalds 	.start	= r_start,
1471da177e4SLinus Torvalds 	.next	= r_next,
1481da177e4SLinus Torvalds 	.stop	= r_stop,
1491da177e4SLinus Torvalds 	.show	= r_show,
1501da177e4SLinus Torvalds };
1511da177e4SLinus Torvalds 
ioresources_init(void)1521da177e4SLinus Torvalds static int __init ioresources_init(void)
1531da177e4SLinus Torvalds {
1544e292a96SChristoph Hellwig 	proc_create_seq_data("ioports", 0, NULL, &resource_op,
1554e292a96SChristoph Hellwig 			&ioport_resource);
1564e292a96SChristoph Hellwig 	proc_create_seq_data("iomem", 0, NULL, &resource_op, &iomem_resource);
1571da177e4SLinus Torvalds 	return 0;
1581da177e4SLinus Torvalds }
1591da177e4SLinus Torvalds __initcall(ioresources_init);
1601da177e4SLinus Torvalds 
1611da177e4SLinus Torvalds #endif /* CONFIG_PROC_FS */
1621da177e4SLinus Torvalds 
free_resource(struct resource * res)163ebff7d8fSYasuaki Ishimatsu static void free_resource(struct resource *res)
164ebff7d8fSYasuaki Ishimatsu {
1650cbcc929SMiaohe Lin 	/**
1660cbcc929SMiaohe Lin 	 * If the resource was allocated using memblock early during boot
1670cbcc929SMiaohe Lin 	 * we'll leak it here: we can only return full pages back to the
1680cbcc929SMiaohe Lin 	 * buddy and trying to be smart and reusing them eventually in
1690cbcc929SMiaohe Lin 	 * alloc_resource() overcomplicates resource handling.
1700cbcc929SMiaohe Lin 	 */
1710cbcc929SMiaohe Lin 	if (res && PageSlab(virt_to_head_page(res)))
172ebff7d8fSYasuaki Ishimatsu 		kfree(res);
173ebff7d8fSYasuaki Ishimatsu }
174ebff7d8fSYasuaki Ishimatsu 
alloc_resource(gfp_t flags)175ebff7d8fSYasuaki Ishimatsu static struct resource *alloc_resource(gfp_t flags)
176ebff7d8fSYasuaki Ishimatsu {
1770cbcc929SMiaohe Lin 	return kzalloc(sizeof(struct resource), flags);
178ebff7d8fSYasuaki Ishimatsu }
179ebff7d8fSYasuaki Ishimatsu 
1801da177e4SLinus Torvalds /* Return the conflict entry if you can't request it */
__request_resource(struct resource * root,struct resource * new)1811da177e4SLinus Torvalds static struct resource * __request_resource(struct resource *root, struct resource *new)
1821da177e4SLinus Torvalds {
183d75fc8bbSGreg Kroah-Hartman 	resource_size_t start = new->start;
184d75fc8bbSGreg Kroah-Hartman 	resource_size_t end = new->end;
1851da177e4SLinus Torvalds 	struct resource *tmp, **p;
1861da177e4SLinus Torvalds 
1871da177e4SLinus Torvalds 	if (end < start)
1881da177e4SLinus Torvalds 		return root;
1891da177e4SLinus Torvalds 	if (start < root->start)
1901da177e4SLinus Torvalds 		return root;
1911da177e4SLinus Torvalds 	if (end > root->end)
1921da177e4SLinus Torvalds 		return root;
1931da177e4SLinus Torvalds 	p = &root->child;
1941da177e4SLinus Torvalds 	for (;;) {
1951da177e4SLinus Torvalds 		tmp = *p;
1961da177e4SLinus Torvalds 		if (!tmp || tmp->start > end) {
1971da177e4SLinus Torvalds 			new->sibling = tmp;
1981da177e4SLinus Torvalds 			*p = new;
1991da177e4SLinus Torvalds 			new->parent = root;
2001da177e4SLinus Torvalds 			return NULL;
2011da177e4SLinus Torvalds 		}
2021da177e4SLinus Torvalds 		p = &tmp->sibling;
2031da177e4SLinus Torvalds 		if (tmp->end < start)
2041da177e4SLinus Torvalds 			continue;
2051da177e4SLinus Torvalds 		return tmp;
2061da177e4SLinus Torvalds 	}
2071da177e4SLinus Torvalds }
2081da177e4SLinus Torvalds 
__release_resource(struct resource * old,bool release_child)209ff3cc952SToshi Kani static int __release_resource(struct resource *old, bool release_child)
2101da177e4SLinus Torvalds {
211ff3cc952SToshi Kani 	struct resource *tmp, **p, *chd;
2121da177e4SLinus Torvalds 
2131da177e4SLinus Torvalds 	p = &old->parent->child;
2141da177e4SLinus Torvalds 	for (;;) {
2151da177e4SLinus Torvalds 		tmp = *p;
2161da177e4SLinus Torvalds 		if (!tmp)
2171da177e4SLinus Torvalds 			break;
2181da177e4SLinus Torvalds 		if (tmp == old) {
219ff3cc952SToshi Kani 			if (release_child || !(tmp->child)) {
2201da177e4SLinus Torvalds 				*p = tmp->sibling;
221ff3cc952SToshi Kani 			} else {
222ff3cc952SToshi Kani 				for (chd = tmp->child;; chd = chd->sibling) {
223ff3cc952SToshi Kani 					chd->parent = tmp->parent;
224ff3cc952SToshi Kani 					if (!(chd->sibling))
225ff3cc952SToshi Kani 						break;
226ff3cc952SToshi Kani 				}
227ff3cc952SToshi Kani 				*p = tmp->child;
228ff3cc952SToshi Kani 				chd->sibling = tmp->sibling;
229ff3cc952SToshi Kani 			}
2301da177e4SLinus Torvalds 			old->parent = NULL;
2311da177e4SLinus Torvalds 			return 0;
2321da177e4SLinus Torvalds 		}
2331da177e4SLinus Torvalds 		p = &tmp->sibling;
2341da177e4SLinus Torvalds 	}
2351da177e4SLinus Torvalds 	return -EINVAL;
2361da177e4SLinus Torvalds }
2371da177e4SLinus Torvalds 
__release_child_resources(struct resource * r)2385eeec0ecSYinghai Lu static void __release_child_resources(struct resource *r)
2395eeec0ecSYinghai Lu {
2405eeec0ecSYinghai Lu 	struct resource *tmp, *p;
2415eeec0ecSYinghai Lu 	resource_size_t size;
2425eeec0ecSYinghai Lu 
2435eeec0ecSYinghai Lu 	p = r->child;
2445eeec0ecSYinghai Lu 	r->child = NULL;
2455eeec0ecSYinghai Lu 	while (p) {
2465eeec0ecSYinghai Lu 		tmp = p;
2475eeec0ecSYinghai Lu 		p = p->sibling;
2485eeec0ecSYinghai Lu 
2495eeec0ecSYinghai Lu 		tmp->parent = NULL;
2505eeec0ecSYinghai Lu 		tmp->sibling = NULL;
2515eeec0ecSYinghai Lu 		__release_child_resources(tmp);
2525eeec0ecSYinghai Lu 
2535eeec0ecSYinghai Lu 		printk(KERN_DEBUG "release child resource %pR\n", tmp);
2545eeec0ecSYinghai Lu 		/* need to restore size, and keep flags */
2555eeec0ecSYinghai Lu 		size = resource_size(tmp);
2565eeec0ecSYinghai Lu 		tmp->start = 0;
2575eeec0ecSYinghai Lu 		tmp->end = size - 1;
2585eeec0ecSYinghai Lu 	}
2595eeec0ecSYinghai Lu }
2605eeec0ecSYinghai Lu 
release_child_resources(struct resource * r)2615eeec0ecSYinghai Lu void release_child_resources(struct resource *r)
2625eeec0ecSYinghai Lu {
2635eeec0ecSYinghai Lu 	write_lock(&resource_lock);
2645eeec0ecSYinghai Lu 	__release_child_resources(r);
2655eeec0ecSYinghai Lu 	write_unlock(&resource_lock);
2665eeec0ecSYinghai Lu }
2675eeec0ecSYinghai Lu 
268e1ca66d1SRandy Dunlap /**
26966f1207bSBjorn Helgaas  * request_resource_conflict - request and reserve an I/O or memory resource
27066f1207bSBjorn Helgaas  * @root: root resource descriptor
27166f1207bSBjorn Helgaas  * @new: resource descriptor desired by caller
27266f1207bSBjorn Helgaas  *
27366f1207bSBjorn Helgaas  * Returns 0 for success, conflict resource on error.
27466f1207bSBjorn Helgaas  */
request_resource_conflict(struct resource * root,struct resource * new)27566f1207bSBjorn Helgaas struct resource *request_resource_conflict(struct resource *root, struct resource *new)
27666f1207bSBjorn Helgaas {
27766f1207bSBjorn Helgaas 	struct resource *conflict;
27866f1207bSBjorn Helgaas 
27966f1207bSBjorn Helgaas 	write_lock(&resource_lock);
28066f1207bSBjorn Helgaas 	conflict = __request_resource(root, new);
28166f1207bSBjorn Helgaas 	write_unlock(&resource_lock);
28266f1207bSBjorn Helgaas 	return conflict;
28366f1207bSBjorn Helgaas }
28466f1207bSBjorn Helgaas 
28566f1207bSBjorn Helgaas /**
286e1ca66d1SRandy Dunlap  * request_resource - request and reserve an I/O or memory resource
287e1ca66d1SRandy Dunlap  * @root: root resource descriptor
288e1ca66d1SRandy Dunlap  * @new: resource descriptor desired by caller
289e1ca66d1SRandy Dunlap  *
290e1ca66d1SRandy Dunlap  * Returns 0 for success, negative error code on error.
291e1ca66d1SRandy Dunlap  */
request_resource(struct resource * root,struct resource * new)2921da177e4SLinus Torvalds int request_resource(struct resource *root, struct resource *new)
2931da177e4SLinus Torvalds {
2941da177e4SLinus Torvalds 	struct resource *conflict;
2951da177e4SLinus Torvalds 
29666f1207bSBjorn Helgaas 	conflict = request_resource_conflict(root, new);
2971da177e4SLinus Torvalds 	return conflict ? -EBUSY : 0;
2981da177e4SLinus Torvalds }
2991da177e4SLinus Torvalds 
3001da177e4SLinus Torvalds EXPORT_SYMBOL(request_resource);
3011da177e4SLinus Torvalds 
302e1ca66d1SRandy Dunlap /**
303e1ca66d1SRandy Dunlap  * release_resource - release a previously reserved resource
304e1ca66d1SRandy Dunlap  * @old: resource pointer
305e1ca66d1SRandy Dunlap  */
release_resource(struct resource * old)3061da177e4SLinus Torvalds int release_resource(struct resource *old)
3071da177e4SLinus Torvalds {
3081da177e4SLinus Torvalds 	int retval;
3091da177e4SLinus Torvalds 
3101da177e4SLinus Torvalds 	write_lock(&resource_lock);
311ff3cc952SToshi Kani 	retval = __release_resource(old, true);
3121da177e4SLinus Torvalds 	write_unlock(&resource_lock);
3131da177e4SLinus Torvalds 	return retval;
3141da177e4SLinus Torvalds }
3151da177e4SLinus Torvalds 
3161da177e4SLinus Torvalds EXPORT_SYMBOL(release_resource);
3171da177e4SLinus Torvalds 
is_type_match(struct resource * p,unsigned long flags,unsigned long desc)318ba1eccc1SAndy Shevchenko static bool is_type_match(struct resource *p, unsigned long flags, unsigned long desc)
319ba1eccc1SAndy Shevchenko {
320ba1eccc1SAndy Shevchenko 	return (p->flags & flags) == flags && (desc == IORES_DESC_NONE || desc == p->desc);
321ba1eccc1SAndy Shevchenko }
322ba1eccc1SAndy Shevchenko 
323f26621e6SBorislav Petkov /**
3243be8da57SMauro Carvalho Chehab  * find_next_iomem_res - Finds the lowest iomem resource that covers part of
3253be8da57SMauro Carvalho Chehab  *			 [@start..@end].
326010a93bfSBjorn Helgaas  *
327f26621e6SBorislav Petkov  * If a resource is found, returns 0 and @*res is overwritten with the part
328f26621e6SBorislav Petkov  * of the resource that's within [@start..@end]; if none is found, returns
32949f17c26SNadav Amit  * -ENODEV.  Returns -EINVAL for invalid parameters.
330010a93bfSBjorn Helgaas  *
331f26621e6SBorislav Petkov  * @start:	start address of the resource searched for
332f26621e6SBorislav Petkov  * @end:	end address of same resource
333f26621e6SBorislav Petkov  * @flags:	flags which the resource must have
334f26621e6SBorislav Petkov  * @desc:	descriptor the resource must have
335f26621e6SBorislav Petkov  * @res:	return ptr, if resource found
3363be8da57SMauro Carvalho Chehab  *
3373be8da57SMauro Carvalho Chehab  * The caller must specify @start, @end, @flags, and @desc
3383be8da57SMauro Carvalho Chehab  * (which may be IORES_DESC_NONE).
3392842f114SKAMEZAWA Hiroyuki  */
find_next_iomem_res(resource_size_t start,resource_size_t end,unsigned long flags,unsigned long desc,struct resource * res)340010a93bfSBjorn Helgaas static int find_next_iomem_res(resource_size_t start, resource_size_t end,
341010a93bfSBjorn Helgaas 			       unsigned long flags, unsigned long desc,
34297523a4eSDavid Hildenbrand 			       struct resource *res)
3432842f114SKAMEZAWA Hiroyuki {
3442842f114SKAMEZAWA Hiroyuki 	struct resource *p;
3452842f114SKAMEZAWA Hiroyuki 
346b69c2e20SBorislav Petkov 	if (!res)
347b69c2e20SBorislav Petkov 		return -EINVAL;
3482842f114SKAMEZAWA Hiroyuki 
349b69c2e20SBorislav Petkov 	if (start >= end)
350b69c2e20SBorislav Petkov 		return -EINVAL;
351800df627SVivek Goyal 
3522842f114SKAMEZAWA Hiroyuki 	read_lock(&resource_lock);
3538c86e70aSVivek Goyal 
354441f0dd8SAndy Shevchenko 	for_each_resource(&iomem_resource, p, false) {
35575639875SNadav Amit 		/* If we passed the resource we are looking for, stop */
3562842f114SKAMEZAWA Hiroyuki 		if (p->start > end) {
3572842f114SKAMEZAWA Hiroyuki 			p = NULL;
3582842f114SKAMEZAWA Hiroyuki 			break;
3592842f114SKAMEZAWA Hiroyuki 		}
36075639875SNadav Amit 
36175639875SNadav Amit 		/* Skip until we find a range that matches what we look for */
36275639875SNadav Amit 		if (p->end < start)
36375639875SNadav Amit 			continue;
36475639875SNadav Amit 
36575639875SNadav Amit 		/* Found a match, break */
366ba1eccc1SAndy Shevchenko 		if (is_type_match(p, flags, desc))
3672842f114SKAMEZAWA Hiroyuki 			break;
3682842f114SKAMEZAWA Hiroyuki 	}
3698c86e70aSVivek Goyal 
37049f17c26SNadav Amit 	if (p) {
3712842f114SKAMEZAWA Hiroyuki 		/* copy data */
37273fb952dSDan Williams 		*res = (struct resource) {
37373fb952dSDan Williams 			.start = max(start, p->start),
37473fb952dSDan Williams 			.end = min(end, p->end),
37573fb952dSDan Williams 			.flags = p->flags,
37673fb952dSDan Williams 			.desc = p->desc,
37773fb952dSDan Williams 			.parent = p->parent,
37873fb952dSDan Williams 		};
37949f17c26SNadav Amit 	}
38049f17c26SNadav Amit 
38149f17c26SNadav Amit 	read_unlock(&resource_lock);
38249f17c26SNadav Amit 	return p ? 0 : -ENODEV;
3832842f114SKAMEZAWA Hiroyuki }
384908eedc6SKAMEZAWA Hiroyuki 
__walk_iomem_res_desc(resource_size_t start,resource_size_t end,unsigned long flags,unsigned long desc,void * arg,int (* func)(struct resource *,void *))385010a93bfSBjorn Helgaas static int __walk_iomem_res_desc(resource_size_t start, resource_size_t end,
386010a93bfSBjorn Helgaas 				 unsigned long flags, unsigned long desc,
38797523a4eSDavid Hildenbrand 				 void *arg,
3881d2e733bSTom Lendacky 				 int (*func)(struct resource *, void *))
3894ac2aed8STom Lendacky {
390010a93bfSBjorn Helgaas 	struct resource res;
3915cd401acSDave Hansen 	int ret = -EINVAL;
3924ac2aed8STom Lendacky 
393010a93bfSBjorn Helgaas 	while (start < end &&
39497523a4eSDavid Hildenbrand 	       !find_next_iomem_res(start, end, flags, desc, &res)) {
395010a93bfSBjorn Helgaas 		ret = (*func)(&res, arg);
3964ac2aed8STom Lendacky 		if (ret)
3974ac2aed8STom Lendacky 			break;
3984ac2aed8STom Lendacky 
399010a93bfSBjorn Helgaas 		start = res.end + 1;
4004ac2aed8STom Lendacky 	}
4014ac2aed8STom Lendacky 
4024ac2aed8STom Lendacky 	return ret;
4034ac2aed8STom Lendacky }
4044ac2aed8STom Lendacky 
405b69c2e20SBorislav Petkov /**
4063be8da57SMauro Carvalho Chehab  * walk_iomem_res_desc - Walks through iomem resources and calls func()
4073be8da57SMauro Carvalho Chehab  *			 with matching resource ranges.
4083be8da57SMauro Carvalho Chehab  * *
4093f33647cSToshi Kani  * @desc: I/O resource descriptor. Use IORES_DESC_NONE to skip @desc check.
4103f33647cSToshi Kani  * @flags: I/O resource flags
4113f33647cSToshi Kani  * @start: start addr
4123f33647cSToshi Kani  * @end: end addr
413f75d6515SRandy Dunlap  * @arg: function argument for the callback @func
414f75d6515SRandy Dunlap  * @func: callback function that is called for each qualifying resource area
4153f33647cSToshi Kani  *
4163be8da57SMauro Carvalho Chehab  * All the memory ranges which overlap start,end and also match flags and
4173be8da57SMauro Carvalho Chehab  * desc are valid candidates.
4183be8da57SMauro Carvalho Chehab  *
4193f33647cSToshi Kani  * NOTE: For a new descriptor search, define a new IORES_DESC in
4203f33647cSToshi Kani  * <linux/ioport.h> and set it in 'desc' of a target resource entry.
4213f33647cSToshi Kani  */
walk_iomem_res_desc(unsigned long desc,unsigned long flags,u64 start,u64 end,void * arg,int (* func)(struct resource *,void *))4223f33647cSToshi Kani int walk_iomem_res_desc(unsigned long desc, unsigned long flags, u64 start,
4231d2e733bSTom Lendacky 		u64 end, void *arg, int (*func)(struct resource *, void *))
4243f33647cSToshi Kani {
42597523a4eSDavid Hildenbrand 	return __walk_iomem_res_desc(start, end, flags, desc, arg, func);
4263f33647cSToshi Kani }
427d76401adSDan Williams EXPORT_SYMBOL_GPL(walk_iomem_res_desc);
4283f33647cSToshi Kani 
4293f33647cSToshi Kani /*
430bd7e6cb3SToshi Kani  * This function calls the @func callback against all memory ranges of type
431bd7e6cb3SToshi Kani  * System RAM which are marked as IORESOURCE_SYSTEM_RAM and IORESOUCE_BUSY.
432bd7e6cb3SToshi Kani  * Now, this function is only for System RAM, it deals with full ranges and
433bd7e6cb3SToshi Kani  * not PFNs. If resources are not PFN-aligned, dealing with PFNs can truncate
434bd7e6cb3SToshi Kani  * ranges.
4358c86e70aSVivek Goyal  */
walk_system_ram_res(u64 start,u64 end,void * arg,int (* func)(struct resource *,void *))4368c86e70aSVivek Goyal int walk_system_ram_res(u64 start, u64 end, void *arg,
4371d2e733bSTom Lendacky 			int (*func)(struct resource *, void *))
4388c86e70aSVivek Goyal {
439010a93bfSBjorn Helgaas 	unsigned long flags = IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY;
4408c86e70aSVivek Goyal 
44197523a4eSDavid Hildenbrand 	return __walk_iomem_res_desc(start, end, flags, IORES_DESC_NONE, arg,
44297523a4eSDavid Hildenbrand 				     func);
4438c86e70aSVivek Goyal }
4448c86e70aSVivek Goyal 
4450e4c12b4STom Lendacky /*
4467acf164bSBaoquan He  * This function, being a variant of walk_system_ram_res(), calls the @func
4477acf164bSBaoquan He  * callback against all memory ranges of type System RAM which are marked as
4487acf164bSBaoquan He  * IORESOURCE_SYSTEM_RAM and IORESOUCE_BUSY in reversed order, i.e., from
4497acf164bSBaoquan He  * higher to lower.
4507acf164bSBaoquan He  */
walk_system_ram_res_rev(u64 start,u64 end,void * arg,int (* func)(struct resource *,void *))4517acf164bSBaoquan He int walk_system_ram_res_rev(u64 start, u64 end, void *arg,
4527acf164bSBaoquan He 				int (*func)(struct resource *, void *))
4537acf164bSBaoquan He {
4547acf164bSBaoquan He 	struct resource res, *rams;
4557acf164bSBaoquan He 	int rams_size = 16, i;
4567acf164bSBaoquan He 	unsigned long flags;
4577acf164bSBaoquan He 	int ret = -1;
4587acf164bSBaoquan He 
4597acf164bSBaoquan He 	/* create a list */
4607acf164bSBaoquan He 	rams = kvcalloc(rams_size, sizeof(struct resource), GFP_KERNEL);
4617acf164bSBaoquan He 	if (!rams)
4627acf164bSBaoquan He 		return ret;
4637acf164bSBaoquan He 
4647acf164bSBaoquan He 	flags = IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY;
4657acf164bSBaoquan He 	i = 0;
4667acf164bSBaoquan He 	while ((start < end) &&
4677acf164bSBaoquan He 		(!find_next_iomem_res(start, end, flags, IORES_DESC_NONE, &res))) {
4687acf164bSBaoquan He 		if (i >= rams_size) {
4697acf164bSBaoquan He 			/* re-alloc */
4707acf164bSBaoquan He 			struct resource *rams_new;
4717acf164bSBaoquan He 
472590b9d57SDanilo Krummrich 			rams_new = kvrealloc(rams, (rams_size + 16) * sizeof(struct resource),
4737acf164bSBaoquan He 					     GFP_KERNEL);
4747acf164bSBaoquan He 			if (!rams_new)
4757acf164bSBaoquan He 				goto out;
4767acf164bSBaoquan He 
4777acf164bSBaoquan He 			rams = rams_new;
4787acf164bSBaoquan He 			rams_size += 16;
4797acf164bSBaoquan He 		}
4807acf164bSBaoquan He 
481b125a0deSGregory Price 		rams[i++] = res;
4827acf164bSBaoquan He 		start = res.end + 1;
4837acf164bSBaoquan He 	}
4847acf164bSBaoquan He 
4857acf164bSBaoquan He 	/* go reverse */
4867acf164bSBaoquan He 	for (i--; i >= 0; i--) {
4877acf164bSBaoquan He 		ret = (*func)(&rams[i], arg);
4887acf164bSBaoquan He 		if (ret)
4897acf164bSBaoquan He 			break;
4907acf164bSBaoquan He 	}
4917acf164bSBaoquan He 
4927acf164bSBaoquan He out:
4937acf164bSBaoquan He 	kvfree(rams);
4947acf164bSBaoquan He 	return ret;
4957acf164bSBaoquan He }
4967acf164bSBaoquan He 
4977acf164bSBaoquan He /*
4980e4c12b4STom Lendacky  * This function calls the @func callback against all memory ranges, which
4990e4c12b4STom Lendacky  * are ranges marked as IORESOURCE_MEM and IORESOUCE_BUSY.
5000e4c12b4STom Lendacky  */
walk_mem_res(u64 start,u64 end,void * arg,int (* func)(struct resource *,void *))5010e4c12b4STom Lendacky int walk_mem_res(u64 start, u64 end, void *arg,
5020e4c12b4STom Lendacky 		 int (*func)(struct resource *, void *))
5030e4c12b4STom Lendacky {
504010a93bfSBjorn Helgaas 	unsigned long flags = IORESOURCE_MEM | IORESOURCE_BUSY;
5050e4c12b4STom Lendacky 
50697523a4eSDavid Hildenbrand 	return __walk_iomem_res_desc(start, end, flags, IORES_DESC_NONE, arg,
50797523a4eSDavid Hildenbrand 				     func);
5080e4c12b4STom Lendacky }
5090e4c12b4STom Lendacky 
5108c86e70aSVivek Goyal /*
511bd7e6cb3SToshi Kani  * This function calls the @func callback against all memory ranges of type
512bd7e6cb3SToshi Kani  * System RAM which are marked as IORESOURCE_SYSTEM_RAM and IORESOUCE_BUSY.
513bd7e6cb3SToshi Kani  * It is to be used only for System RAM.
514908eedc6SKAMEZAWA Hiroyuki  */
walk_system_ram_range(unsigned long start_pfn,unsigned long nr_pages,void * arg,int (* func)(unsigned long,unsigned long,void *))515908eedc6SKAMEZAWA Hiroyuki int walk_system_ram_range(unsigned long start_pfn, unsigned long nr_pages,
516908eedc6SKAMEZAWA Hiroyuki 			  void *arg, int (*func)(unsigned long, unsigned long, void *))
51775884fb1SKAMEZAWA Hiroyuki {
518010a93bfSBjorn Helgaas 	resource_size_t start, end;
519010a93bfSBjorn Helgaas 	unsigned long flags;
52075884fb1SKAMEZAWA Hiroyuki 	struct resource res;
52137b99dd5SWu Fengguang 	unsigned long pfn, end_pfn;
5225cd401acSDave Hansen 	int ret = -EINVAL;
523908eedc6SKAMEZAWA Hiroyuki 
524010a93bfSBjorn Helgaas 	start = (u64) start_pfn << PAGE_SHIFT;
525010a93bfSBjorn Helgaas 	end = ((u64)(start_pfn + nr_pages) << PAGE_SHIFT) - 1;
526010a93bfSBjorn Helgaas 	flags = IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY;
527010a93bfSBjorn Helgaas 	while (start < end &&
52897523a4eSDavid Hildenbrand 	       !find_next_iomem_res(start, end, flags, IORES_DESC_NONE, &res)) {
52900ff9a91SDavid Hildenbrand 		pfn = PFN_UP(res.start);
53000ff9a91SDavid Hildenbrand 		end_pfn = PFN_DOWN(res.end + 1);
53137b99dd5SWu Fengguang 		if (end_pfn > pfn)
53237b99dd5SWu Fengguang 			ret = (*func)(pfn, end_pfn - pfn, arg);
53375884fb1SKAMEZAWA Hiroyuki 		if (ret)
53475884fb1SKAMEZAWA Hiroyuki 			break;
535010a93bfSBjorn Helgaas 		start = res.end + 1;
53675884fb1SKAMEZAWA Hiroyuki 	}
53775884fb1SKAMEZAWA Hiroyuki 	return ret;
53875884fb1SKAMEZAWA Hiroyuki }
53975884fb1SKAMEZAWA Hiroyuki 
__is_ram(unsigned long pfn,unsigned long nr_pages,void * arg)54061ef2489SWu Fengguang static int __is_ram(unsigned long pfn, unsigned long nr_pages, void *arg)
54161ef2489SWu Fengguang {
54261ef2489SWu Fengguang 	return 1;
54361ef2489SWu Fengguang }
5444ac2aed8STom Lendacky 
54561ef2489SWu Fengguang /*
54661ef2489SWu Fengguang  * This generic page_is_ram() returns true if specified address is
547bd7e6cb3SToshi Kani  * registered as System RAM in iomem_resource list.
54861ef2489SWu Fengguang  */
page_is_ram(unsigned long pfn)549e5273007SAndrew Morton int __weak page_is_ram(unsigned long pfn)
55061ef2489SWu Fengguang {
55161ef2489SWu Fengguang 	return walk_system_ram_range(pfn, 1, NULL, __is_ram) == 1;
55261ef2489SWu Fengguang }
553c5a13032SChen Gong EXPORT_SYMBOL_GPL(page_is_ram);
55461ef2489SWu Fengguang 
__region_intersects(struct resource * parent,resource_size_t start,size_t size,unsigned long flags,unsigned long desc)55514b80582SDan Williams static int __region_intersects(struct resource *parent, resource_size_t start,
55614b80582SDan Williams 			       size_t size, unsigned long flags,
55714b80582SDan Williams 			       unsigned long desc)
558d486ccb2SAlistair Popple {
559d486ccb2SAlistair Popple 	int type = 0; int other = 0;
560b4afe418SHuang Ying 	struct resource *p, *dp;
5615c1edea7SAndy Shevchenko 	struct resource res, o;
562ba1eccc1SAndy Shevchenko 	bool covered;
563d486ccb2SAlistair Popple 
564*48376a4fSAndy Shevchenko 	res = DEFINE_RES(start, size, 0);
565d486ccb2SAlistair Popple 
56614b80582SDan Williams 	for (p = parent->child; p ; p = p->sibling) {
5675c1edea7SAndy Shevchenko 		if (!resource_intersection(p, &res, &o))
568b4afe418SHuang Ying 			continue;
569ba1eccc1SAndy Shevchenko 		if (is_type_match(p, flags, desc)) {
570b4afe418SHuang Ying 			type++;
571b4afe418SHuang Ying 			continue;
572b4afe418SHuang Ying 		}
573b4afe418SHuang Ying 		/*
574b4afe418SHuang Ying 		 * Continue to search in descendant resources as if the
575b4afe418SHuang Ying 		 * matched descendant resources cover some ranges of 'p'.
576b4afe418SHuang Ying 		 *
577b4afe418SHuang Ying 		 * |------------- "CXL Window 0" ------------|
578b4afe418SHuang Ying 		 * |-- "System RAM" --|
579b4afe418SHuang Ying 		 *
580b4afe418SHuang Ying 		 * will behave similar as the following fake resource
581b4afe418SHuang Ying 		 * tree when searching "System RAM".
582b4afe418SHuang Ying 		 *
583b4afe418SHuang Ying 		 * |-- "System RAM" --||-- "CXL Window 0a" --|
584b4afe418SHuang Ying 		 */
585b4afe418SHuang Ying 		covered = false;
586b4afe418SHuang Ying 		for_each_resource(p, dp, false) {
587b4afe418SHuang Ying 			if (!resource_overlaps(dp, &res))
588b4afe418SHuang Ying 				continue;
589ba1eccc1SAndy Shevchenko 			if (is_type_match(dp, flags, desc)) {
590b4afe418SHuang Ying 				type++;
591b4afe418SHuang Ying 				/*
5925c1edea7SAndy Shevchenko 				 * Range from 'o.start' to 'dp->start'
593b4afe418SHuang Ying 				 * isn't covered by matched resource.
594b4afe418SHuang Ying 				 */
5955c1edea7SAndy Shevchenko 				if (dp->start > o.start)
596b4afe418SHuang Ying 					break;
5975c1edea7SAndy Shevchenko 				if (dp->end >= o.end) {
598b4afe418SHuang Ying 					covered = true;
599b4afe418SHuang Ying 					break;
600b4afe418SHuang Ying 				}
601b4afe418SHuang Ying 				/* Remove covered range */
6025c1edea7SAndy Shevchenko 				o.start = max(o.start, dp->end + 1);
603b4afe418SHuang Ying 			}
604b4afe418SHuang Ying 		}
605b4afe418SHuang Ying 		if (!covered)
606b4afe418SHuang Ying 			other++;
607d486ccb2SAlistair Popple 	}
608d486ccb2SAlistair Popple 
609d486ccb2SAlistair Popple 	if (type == 0)
610d486ccb2SAlistair Popple 		return REGION_DISJOINT;
611d486ccb2SAlistair Popple 
612d486ccb2SAlistair Popple 	if (other == 0)
613d486ccb2SAlistair Popple 		return REGION_INTERSECTS;
614d486ccb2SAlistair Popple 
615d486ccb2SAlistair Popple 	return REGION_MIXED;
616d486ccb2SAlistair Popple }
617d486ccb2SAlistair Popple 
618124fe20dSDan Williams /**
619124fe20dSDan Williams  * region_intersects() - determine intersection of region with known resources
620124fe20dSDan Williams  * @start: region start address
621124fe20dSDan Williams  * @size: size of region
6221c29f25bSToshi Kani  * @flags: flags of resource (in iomem_resource)
6231c29f25bSToshi Kani  * @desc: descriptor of resource (in iomem_resource) or IORES_DESC_NONE
62467cf13ceSMike Travis  *
625124fe20dSDan Williams  * Check if the specified region partially overlaps or fully eclipses a
6261c29f25bSToshi Kani  * resource identified by @flags and @desc (optional with IORES_DESC_NONE).
6271c29f25bSToshi Kani  * Return REGION_DISJOINT if the region does not overlap @flags/@desc,
6281c29f25bSToshi Kani  * return REGION_MIXED if the region overlaps @flags/@desc and another
6291c29f25bSToshi Kani  * resource, and return REGION_INTERSECTS if the region overlaps @flags/@desc
6301c29f25bSToshi Kani  * and no other defined resource. Note that REGION_INTERSECTS is also
6311c29f25bSToshi Kani  * returned in the case when the specified region overlaps RAM and undefined
6321c29f25bSToshi Kani  * memory holes.
633124fe20dSDan Williams  *
634124fe20dSDan Williams  * region_intersect() is used by memory remapping functions to ensure
635124fe20dSDan Williams  * the user is not remapping RAM and is a vast speed up over walking
636124fe20dSDan Williams  * through the resource table page by page.
63767cf13ceSMike Travis  */
region_intersects(resource_size_t start,size_t size,unsigned long flags,unsigned long desc)6381c29f25bSToshi Kani int region_intersects(resource_size_t start, size_t size, unsigned long flags,
6391c29f25bSToshi Kani 		      unsigned long desc)
64067cf13ceSMike Travis {
641d486ccb2SAlistair Popple 	int ret;
642f6c6010aSWei Yang 
64367cf13ceSMike Travis 	read_lock(&resource_lock);
64414b80582SDan Williams 	ret = __region_intersects(&iomem_resource, start, size, flags, desc);
64567cf13ceSMike Travis 	read_unlock(&resource_lock);
646124fe20dSDan Williams 
647d486ccb2SAlistair Popple 	return ret;
64867cf13ceSMike Travis }
6491c29f25bSToshi Kani EXPORT_SYMBOL_GPL(region_intersects);
65067cf13ceSMike Travis 
arch_remove_reservations(struct resource * avail)651fcb11918SBjorn Helgaas void __weak arch_remove_reservations(struct resource *avail)
652fcb11918SBjorn Helgaas {
653fcb11918SBjorn Helgaas }
654fcb11918SBjorn Helgaas 
resource_clip(struct resource * res,resource_size_t min,resource_size_t max)6555d6b1fa3SBjorn Helgaas static void resource_clip(struct resource *res, resource_size_t min,
6565d6b1fa3SBjorn Helgaas 			  resource_size_t max)
6575d6b1fa3SBjorn Helgaas {
6585d6b1fa3SBjorn Helgaas 	if (res->start < min)
6595d6b1fa3SBjorn Helgaas 		res->start = min;
6605d6b1fa3SBjorn Helgaas 	if (res->end > max)
6615d6b1fa3SBjorn Helgaas 		res->end = max;
6625d6b1fa3SBjorn Helgaas }
6635d6b1fa3SBjorn Helgaas 
6641da177e4SLinus Torvalds /*
6658559125bSIlpo Järvinen  * Find empty space in the resource tree with the given range and
66623c570a6SRam Pai  * alignment constraints
6671da177e4SLinus Torvalds  */
__find_resource_space(struct resource * root,struct resource * old,struct resource * new,resource_size_t size,struct resource_constraint * constraint)6688559125bSIlpo Järvinen static int __find_resource_space(struct resource *root, struct resource *old,
6698559125bSIlpo Järvinen 				 struct resource *new, resource_size_t size,
67023c570a6SRam Pai 				 struct resource_constraint *constraint)
6711da177e4SLinus Torvalds {
6721da177e4SLinus Torvalds 	struct resource *this = root->child;
673a1862e31SBjorn Helgaas 	struct resource tmp = *new, avail, alloc;
674094c0ce5SIlpo Järvinen 	resource_alignf alignf = constraint->alignf;
6751da177e4SLinus Torvalds 
6760e2c8b8fSDominik Brodowski 	tmp.start = root->start;
6771da177e4SLinus Torvalds 	/*
678c0f5ac54SBjorn Helgaas 	 * Skip past an allocated resource that starts at 0, since the assignment
679c0f5ac54SBjorn Helgaas 	 * of this->start - 1 to tmp->end below would cause an underflow.
6801da177e4SLinus Torvalds 	 */
68123c570a6SRam Pai 	if (this && this->start == root->start) {
68223c570a6SRam Pai 		tmp.start = (this == old) ? old->start : this->end + 1;
6831da177e4SLinus Torvalds 		this = this->sibling;
6841da177e4SLinus Torvalds 	}
6851da177e4SLinus Torvalds 	for(;;) {
6861da177e4SLinus Torvalds 		if (this)
68723c570a6SRam Pai 			tmp.end = (this == old) ?  this->end : this->start - 1;
6881da177e4SLinus Torvalds 		else
6890e2c8b8fSDominik Brodowski 			tmp.end = root->end;
6905d6b1fa3SBjorn Helgaas 
69147ea91b4SRam Pai 		if (tmp.end < tmp.start)
69247ea91b4SRam Pai 			goto next;
69347ea91b4SRam Pai 
69423c570a6SRam Pai 		resource_clip(&tmp, constraint->min, constraint->max);
695fcb11918SBjorn Helgaas 		arch_remove_reservations(&tmp);
696a9cea017SBjorn Helgaas 
697a1862e31SBjorn Helgaas 		/* Check for overflow after ALIGN() */
69823c570a6SRam Pai 		avail.start = ALIGN(tmp.start, constraint->align);
699a1862e31SBjorn Helgaas 		avail.end = tmp.end;
7005edb93b8SBjorn Helgaas 		avail.flags = new->flags & ~IORESOURCE_UNSET;
701a1862e31SBjorn Helgaas 		if (avail.start >= tmp.start) {
7025edb93b8SBjorn Helgaas 			alloc.flags = avail.flags;
703094c0ce5SIlpo Järvinen 			if (alignf) {
704094c0ce5SIlpo Järvinen 				alloc.start = alignf(constraint->alignf_data,
705094c0ce5SIlpo Järvinen 						     &avail, size, constraint->align);
706094c0ce5SIlpo Järvinen 			} else {
707094c0ce5SIlpo Järvinen 				alloc.start = avail.start;
708094c0ce5SIlpo Järvinen 			}
7096909ba14SBjorn Helgaas 			alloc.end = alloc.start + size - 1;
71060bb83b8STakashi Iwai 			if (alloc.start <= alloc.end &&
71160bb83b8STakashi Iwai 			    resource_contains(&avail, &alloc)) {
7126909ba14SBjorn Helgaas 				new->start = alloc.start;
7136909ba14SBjorn Helgaas 				new->end = alloc.end;
7141da177e4SLinus Torvalds 				return 0;
7151da177e4SLinus Torvalds 			}
716a1862e31SBjorn Helgaas 		}
71747ea91b4SRam Pai 
71847ea91b4SRam Pai next:		if (!this || this->end == root->end)
7191da177e4SLinus Torvalds 			break;
72047ea91b4SRam Pai 
72123c570a6SRam Pai 		if (this != old)
7220e2c8b8fSDominik Brodowski 			tmp.start = this->end + 1;
7231da177e4SLinus Torvalds 		this = this->sibling;
7241da177e4SLinus Torvalds 	}
7251da177e4SLinus Torvalds 	return -EBUSY;
7261da177e4SLinus Torvalds }
7271da177e4SLinus Torvalds 
728f958625cSIlpo Järvinen /**
729f958625cSIlpo Järvinen  * find_resource_space - Find empty space in the resource tree
730f958625cSIlpo Järvinen  * @root:	Root resource descriptor
731f958625cSIlpo Järvinen  * @new:	Resource descriptor awaiting an empty resource space
732f958625cSIlpo Järvinen  * @size:	The minimum size of the empty space
733f958625cSIlpo Järvinen  * @constraint:	The range and alignment constraints to be met
734f958625cSIlpo Järvinen  *
735f958625cSIlpo Järvinen  * Finds an empty space under @root in the resource tree satisfying range and
736f958625cSIlpo Järvinen  * alignment @constraints.
737f958625cSIlpo Järvinen  *
738f958625cSIlpo Järvinen  * Return:
739f958625cSIlpo Järvinen  * * %0		- if successful, @new members start, end, and flags are altered.
740f958625cSIlpo Järvinen  * * %-EBUSY	- if no empty space was found.
74123c570a6SRam Pai  */
find_resource_space(struct resource * root,struct resource * new,resource_size_t size,struct resource_constraint * constraint)74227002253SIlpo Järvinen int find_resource_space(struct resource *root, struct resource *new,
74323c570a6SRam Pai 			resource_size_t size,
74423c570a6SRam Pai 			struct resource_constraint *constraint)
74523c570a6SRam Pai {
7468559125bSIlpo Järvinen 	return  __find_resource_space(root, NULL, new, size, constraint);
74723c570a6SRam Pai }
74827002253SIlpo Järvinen EXPORT_SYMBOL_GPL(find_resource_space);
74923c570a6SRam Pai 
750e1ca66d1SRandy Dunlap /**
75123c570a6SRam Pai  * reallocate_resource - allocate a slot in the resource tree given range & alignment.
75223c570a6SRam Pai  *	The resource will be relocated if the new size cannot be reallocated in the
75323c570a6SRam Pai  *	current location.
75423c570a6SRam Pai  *
75523c570a6SRam Pai  * @root: root resource descriptor
75623c570a6SRam Pai  * @old:  resource descriptor desired by caller
75723c570a6SRam Pai  * @newsize: new size of the resource descriptor
758834b251bSIlpo Järvinen  * @constraint: the memory range and alignment constraints to be met.
75923c570a6SRam Pai  */
reallocate_resource(struct resource * root,struct resource * old,resource_size_t newsize,struct resource_constraint * constraint)76028ab49ffSDaeseok Youn static int reallocate_resource(struct resource *root, struct resource *old,
76123c570a6SRam Pai 			       resource_size_t newsize,
76223c570a6SRam Pai 			       struct resource_constraint *constraint)
76323c570a6SRam Pai {
76423c570a6SRam Pai 	int err=0;
76523c570a6SRam Pai 	struct resource new = *old;
76623c570a6SRam Pai 	struct resource *conflict;
76723c570a6SRam Pai 
76823c570a6SRam Pai 	write_lock(&resource_lock);
76923c570a6SRam Pai 
7708559125bSIlpo Järvinen 	if ((err = __find_resource_space(root, old, &new, newsize, constraint)))
77123c570a6SRam Pai 		goto out;
77223c570a6SRam Pai 
77323c570a6SRam Pai 	if (resource_contains(&new, old)) {
77423c570a6SRam Pai 		old->start = new.start;
77523c570a6SRam Pai 		old->end = new.end;
77623c570a6SRam Pai 		goto out;
77723c570a6SRam Pai 	}
77823c570a6SRam Pai 
77923c570a6SRam Pai 	if (old->child) {
78023c570a6SRam Pai 		err = -EBUSY;
78123c570a6SRam Pai 		goto out;
78223c570a6SRam Pai 	}
78323c570a6SRam Pai 
78423c570a6SRam Pai 	if (resource_contains(old, &new)) {
78523c570a6SRam Pai 		old->start = new.start;
78623c570a6SRam Pai 		old->end = new.end;
78723c570a6SRam Pai 	} else {
788ff3cc952SToshi Kani 		__release_resource(old, true);
78923c570a6SRam Pai 		*old = new;
79023c570a6SRam Pai 		conflict = __request_resource(root, old);
79123c570a6SRam Pai 		BUG_ON(conflict);
79223c570a6SRam Pai 	}
79323c570a6SRam Pai out:
79423c570a6SRam Pai 	write_unlock(&resource_lock);
79523c570a6SRam Pai 	return err;
79623c570a6SRam Pai }
79723c570a6SRam Pai 
79823c570a6SRam Pai 
79923c570a6SRam Pai /**
80023c570a6SRam Pai  * allocate_resource - allocate empty slot in the resource tree given range & alignment.
80123c570a6SRam Pai  * 	The resource will be reallocated with a new size if it was already allocated
802e1ca66d1SRandy Dunlap  * @root: root resource descriptor
803e1ca66d1SRandy Dunlap  * @new: resource descriptor desired by caller
804e1ca66d1SRandy Dunlap  * @size: requested resource region size
805ee5e5683SWei Yang  * @min: minimum boundary to allocate
806ee5e5683SWei Yang  * @max: maximum boundary to allocate
807e1ca66d1SRandy Dunlap  * @align: alignment requested, in bytes
808e1ca66d1SRandy Dunlap  * @alignf: alignment function, optional, called if not NULL
809e1ca66d1SRandy Dunlap  * @alignf_data: arbitrary data to pass to the @alignf function
8101da177e4SLinus Torvalds  */
allocate_resource(struct resource * root,struct resource * new,resource_size_t size,resource_size_t min,resource_size_t max,resource_size_t align,resource_alignf alignf,void * alignf_data)8111da177e4SLinus Torvalds int allocate_resource(struct resource *root, struct resource *new,
812d75fc8bbSGreg Kroah-Hartman 		      resource_size_t size, resource_size_t min,
813d75fc8bbSGreg Kroah-Hartman 		      resource_size_t max, resource_size_t align,
8144eed3dd7SIlpo Järvinen 		      resource_alignf alignf,
8151da177e4SLinus Torvalds 		      void *alignf_data)
8161da177e4SLinus Torvalds {
8171da177e4SLinus Torvalds 	int err;
81823c570a6SRam Pai 	struct resource_constraint constraint;
8191da177e4SLinus Torvalds 
82023c570a6SRam Pai 	constraint.min = min;
82123c570a6SRam Pai 	constraint.max = max;
82223c570a6SRam Pai 	constraint.align = align;
82323c570a6SRam Pai 	constraint.alignf = alignf;
82423c570a6SRam Pai 	constraint.alignf_data = alignf_data;
82523c570a6SRam Pai 
82623c570a6SRam Pai 	if ( new->parent ) {
82723c570a6SRam Pai 		/* resource is already allocated, try reallocating with
82823c570a6SRam Pai 		   the new constraints */
82923c570a6SRam Pai 		return reallocate_resource(root, new, size, &constraint);
83023c570a6SRam Pai 	}
83123c570a6SRam Pai 
8321da177e4SLinus Torvalds 	write_lock(&resource_lock);
8338559125bSIlpo Järvinen 	err = find_resource_space(root, new, size, &constraint);
8341da177e4SLinus Torvalds 	if (err >= 0 && __request_resource(root, new))
8351da177e4SLinus Torvalds 		err = -EBUSY;
8361da177e4SLinus Torvalds 	write_unlock(&resource_lock);
8371da177e4SLinus Torvalds 	return err;
8381da177e4SLinus Torvalds }
8391da177e4SLinus Torvalds 
8401da177e4SLinus Torvalds EXPORT_SYMBOL(allocate_resource);
8411da177e4SLinus Torvalds 
8421c388919SGeert Uytterhoeven /**
8431c388919SGeert Uytterhoeven  * lookup_resource - find an existing resource by a resource start address
8441c388919SGeert Uytterhoeven  * @root: root resource descriptor
8451c388919SGeert Uytterhoeven  * @start: resource start address
8461c388919SGeert Uytterhoeven  *
8471c388919SGeert Uytterhoeven  * Returns a pointer to the resource if found, NULL otherwise
8481c388919SGeert Uytterhoeven  */
lookup_resource(struct resource * root,resource_size_t start)8491c388919SGeert Uytterhoeven struct resource *lookup_resource(struct resource *root, resource_size_t start)
8501c388919SGeert Uytterhoeven {
8511c388919SGeert Uytterhoeven 	struct resource *res;
8521c388919SGeert Uytterhoeven 
8531c388919SGeert Uytterhoeven 	read_lock(&resource_lock);
8541c388919SGeert Uytterhoeven 	for (res = root->child; res; res = res->sibling) {
8551c388919SGeert Uytterhoeven 		if (res->start == start)
8561c388919SGeert Uytterhoeven 			break;
8571c388919SGeert Uytterhoeven 	}
8581c388919SGeert Uytterhoeven 	read_unlock(&resource_lock);
8591c388919SGeert Uytterhoeven 
8601c388919SGeert Uytterhoeven 	return res;
8611c388919SGeert Uytterhoeven }
8621c388919SGeert Uytterhoeven 
863bef69ea0SLinus Torvalds /*
864bef69ea0SLinus Torvalds  * Insert a resource into the resource tree. If successful, return NULL,
865bef69ea0SLinus Torvalds  * otherwise return the conflicting resource (compare to __request_resource())
8661da177e4SLinus Torvalds  */
__insert_resource(struct resource * parent,struct resource * new)867bef69ea0SLinus Torvalds static struct resource * __insert_resource(struct resource *parent, struct resource *new)
8681da177e4SLinus Torvalds {
8691da177e4SLinus Torvalds 	struct resource *first, *next;
8701da177e4SLinus Torvalds 
871d33b6fbaSMatthew Wilcox 	for (;; parent = first) {
8721da177e4SLinus Torvalds 		first = __request_resource(parent, new);
8731da177e4SLinus Torvalds 		if (!first)
874bef69ea0SLinus Torvalds 			return first;
8751da177e4SLinus Torvalds 
8761da177e4SLinus Torvalds 		if (first == parent)
877bef69ea0SLinus Torvalds 			return first;
8785de1cb2dSHuang Shijie 		if (WARN_ON(first == new))	/* duplicated insertion */
8795de1cb2dSHuang Shijie 			return first;
8801da177e4SLinus Torvalds 
881d33b6fbaSMatthew Wilcox 		if ((first->start > new->start) || (first->end < new->end))
882d33b6fbaSMatthew Wilcox 			break;
883d33b6fbaSMatthew Wilcox 		if ((first->start == new->start) && (first->end == new->end))
884d33b6fbaSMatthew Wilcox 			break;
8851da177e4SLinus Torvalds 	}
8861da177e4SLinus Torvalds 
8871da177e4SLinus Torvalds 	for (next = first; ; next = next->sibling) {
8881da177e4SLinus Torvalds 		/* Partial overlap? Bad, and unfixable */
8891da177e4SLinus Torvalds 		if (next->start < new->start || next->end > new->end)
890bef69ea0SLinus Torvalds 			return next;
8911da177e4SLinus Torvalds 		if (!next->sibling)
8921da177e4SLinus Torvalds 			break;
8931da177e4SLinus Torvalds 		if (next->sibling->start > new->end)
8941da177e4SLinus Torvalds 			break;
8951da177e4SLinus Torvalds 	}
8961da177e4SLinus Torvalds 
8971da177e4SLinus Torvalds 	new->parent = parent;
8981da177e4SLinus Torvalds 	new->sibling = next->sibling;
8991da177e4SLinus Torvalds 	new->child = first;
9001da177e4SLinus Torvalds 
9011da177e4SLinus Torvalds 	next->sibling = NULL;
9021da177e4SLinus Torvalds 	for (next = first; next; next = next->sibling)
9031da177e4SLinus Torvalds 		next->parent = new;
9041da177e4SLinus Torvalds 
9051da177e4SLinus Torvalds 	if (parent->child == first) {
9061da177e4SLinus Torvalds 		parent->child = new;
9071da177e4SLinus Torvalds 	} else {
9081da177e4SLinus Torvalds 		next = parent->child;
9091da177e4SLinus Torvalds 		while (next->sibling != first)
9101da177e4SLinus Torvalds 			next = next->sibling;
9111da177e4SLinus Torvalds 		next->sibling = new;
9121da177e4SLinus Torvalds 	}
913bef69ea0SLinus Torvalds 	return NULL;
914bef69ea0SLinus Torvalds }
9151da177e4SLinus Torvalds 
916bef69ea0SLinus Torvalds /**
91766f1207bSBjorn Helgaas  * insert_resource_conflict - Inserts resource in the resource tree
918bef69ea0SLinus Torvalds  * @parent: parent of the new resource
919bef69ea0SLinus Torvalds  * @new: new resource to insert
920bef69ea0SLinus Torvalds  *
92166f1207bSBjorn Helgaas  * Returns 0 on success, conflict resource if the resource can't be inserted.
922bef69ea0SLinus Torvalds  *
92366f1207bSBjorn Helgaas  * This function is equivalent to request_resource_conflict when no conflict
924bef69ea0SLinus Torvalds  * happens. If a conflict happens, and the conflicting resources
925bef69ea0SLinus Torvalds  * entirely fit within the range of the new resource, then the new
926bef69ea0SLinus Torvalds  * resource is inserted and the conflicting resources become children of
927bef69ea0SLinus Torvalds  * the new resource.
928ff3cc952SToshi Kani  *
929ff3cc952SToshi Kani  * This function is intended for producers of resources, such as FW modules
930ff3cc952SToshi Kani  * and bus drivers.
931bef69ea0SLinus Torvalds  */
insert_resource_conflict(struct resource * parent,struct resource * new)93266f1207bSBjorn Helgaas struct resource *insert_resource_conflict(struct resource *parent, struct resource *new)
933bef69ea0SLinus Torvalds {
934bef69ea0SLinus Torvalds 	struct resource *conflict;
935bef69ea0SLinus Torvalds 
936bef69ea0SLinus Torvalds 	write_lock(&resource_lock);
937bef69ea0SLinus Torvalds 	conflict = __insert_resource(parent, new);
9381da177e4SLinus Torvalds 	write_unlock(&resource_lock);
93966f1207bSBjorn Helgaas 	return conflict;
94066f1207bSBjorn Helgaas }
94166f1207bSBjorn Helgaas 
94266f1207bSBjorn Helgaas /**
94366f1207bSBjorn Helgaas  * insert_resource - Inserts a resource in the resource tree
94466f1207bSBjorn Helgaas  * @parent: parent of the new resource
94566f1207bSBjorn Helgaas  * @new: new resource to insert
94666f1207bSBjorn Helgaas  *
94766f1207bSBjorn Helgaas  * Returns 0 on success, -EBUSY if the resource can't be inserted.
948ff3cc952SToshi Kani  *
949ff3cc952SToshi Kani  * This function is intended for producers of resources, such as FW modules
950ff3cc952SToshi Kani  * and bus drivers.
95166f1207bSBjorn Helgaas  */
insert_resource(struct resource * parent,struct resource * new)95266f1207bSBjorn Helgaas int insert_resource(struct resource *parent, struct resource *new)
95366f1207bSBjorn Helgaas {
95466f1207bSBjorn Helgaas 	struct resource *conflict;
95566f1207bSBjorn Helgaas 
95666f1207bSBjorn Helgaas 	conflict = insert_resource_conflict(parent, new);
957bef69ea0SLinus Torvalds 	return conflict ? -EBUSY : 0;
958bef69ea0SLinus Torvalds }
9598095d0f2SToshi Kani EXPORT_SYMBOL_GPL(insert_resource);
960bef69ea0SLinus Torvalds 
961bef69ea0SLinus Torvalds /**
962bef69ea0SLinus Torvalds  * insert_resource_expand_to_fit - Insert a resource into the resource tree
9636781f4aeSRandy Dunlap  * @root: root resource descriptor
964bef69ea0SLinus Torvalds  * @new: new resource to insert
965bef69ea0SLinus Torvalds  *
966bef69ea0SLinus Torvalds  * Insert a resource into the resource tree, possibly expanding it in order
967bef69ea0SLinus Torvalds  * to make it encompass any conflicting resources.
968bef69ea0SLinus Torvalds  */
insert_resource_expand_to_fit(struct resource * root,struct resource * new)969bef69ea0SLinus Torvalds void insert_resource_expand_to_fit(struct resource *root, struct resource *new)
970bef69ea0SLinus Torvalds {
971bef69ea0SLinus Torvalds 	if (new->parent)
972bef69ea0SLinus Torvalds 		return;
973bef69ea0SLinus Torvalds 
974bef69ea0SLinus Torvalds 	write_lock(&resource_lock);
975bef69ea0SLinus Torvalds 	for (;;) {
976bef69ea0SLinus Torvalds 		struct resource *conflict;
977bef69ea0SLinus Torvalds 
978bef69ea0SLinus Torvalds 		conflict = __insert_resource(root, new);
979bef69ea0SLinus Torvalds 		if (!conflict)
980bef69ea0SLinus Torvalds 			break;
981bef69ea0SLinus Torvalds 		if (conflict == root)
982bef69ea0SLinus Torvalds 			break;
983bef69ea0SLinus Torvalds 
984bef69ea0SLinus Torvalds 		/* Ok, expand resource to cover the conflict, then try again .. */
985bef69ea0SLinus Torvalds 		if (conflict->start < new->start)
986bef69ea0SLinus Torvalds 			new->start = conflict->start;
987bef69ea0SLinus Torvalds 		if (conflict->end > new->end)
988bef69ea0SLinus Torvalds 			new->end = conflict->end;
989bef69ea0SLinus Torvalds 
9902a4e6285SAndy Shevchenko 		pr_info("Expanded resource %s due to conflict with %s\n", new->name, conflict->name);
991bef69ea0SLinus Torvalds 	}
992bef69ea0SLinus Torvalds 	write_unlock(&resource_lock);
9931da177e4SLinus Torvalds }
994974854abSDan Williams /*
995974854abSDan Williams  * Not for general consumption, only early boot memory map parsing, PCI
996974854abSDan Williams  * resource discovery, and late discovery of CXL resources are expected
997974854abSDan Williams  * to use this interface. The former are built-in and only the latter,
998974854abSDan Williams  * CXL, is a module.
999974854abSDan Williams  */
1000cdd30ebbSPeter Zijlstra EXPORT_SYMBOL_NS_GPL(insert_resource_expand_to_fit, "CXL");
10011da177e4SLinus Torvalds 
1002ff3cc952SToshi Kani /**
1003ff3cc952SToshi Kani  * remove_resource - Remove a resource in the resource tree
1004ff3cc952SToshi Kani  * @old: resource to remove
1005ff3cc952SToshi Kani  *
1006ff3cc952SToshi Kani  * Returns 0 on success, -EINVAL if the resource is not valid.
1007ff3cc952SToshi Kani  *
1008ff3cc952SToshi Kani  * This function removes a resource previously inserted by insert_resource()
1009ff3cc952SToshi Kani  * or insert_resource_conflict(), and moves the children (if any) up to
1010ff3cc952SToshi Kani  * where they were before.  insert_resource() and insert_resource_conflict()
1011ff3cc952SToshi Kani  * insert a new resource, and move any conflicting resources down to the
1012ff3cc952SToshi Kani  * children of the new resource.
1013ff3cc952SToshi Kani  *
1014ff3cc952SToshi Kani  * insert_resource(), insert_resource_conflict() and remove_resource() are
1015ff3cc952SToshi Kani  * intended for producers of resources, such as FW modules and bus drivers.
1016ff3cc952SToshi Kani  */
remove_resource(struct resource * old)1017ff3cc952SToshi Kani int remove_resource(struct resource *old)
1018ff3cc952SToshi Kani {
1019ff3cc952SToshi Kani 	int retval;
1020ff3cc952SToshi Kani 
1021ff3cc952SToshi Kani 	write_lock(&resource_lock);
1022ff3cc952SToshi Kani 	retval = __release_resource(old, false);
1023ff3cc952SToshi Kani 	write_unlock(&resource_lock);
1024ff3cc952SToshi Kani 	return retval;
1025ff3cc952SToshi Kani }
10268095d0f2SToshi Kani EXPORT_SYMBOL_GPL(remove_resource);
1027ff3cc952SToshi Kani 
__adjust_resource(struct resource * res,resource_size_t start,resource_size_t size)1028ae8e3a91SToshi Kani static int __adjust_resource(struct resource *res, resource_size_t start,
1029ae8e3a91SToshi Kani 				resource_size_t size)
10301da177e4SLinus Torvalds {
10311da177e4SLinus Torvalds 	struct resource *tmp, *parent = res->parent;
1032d75fc8bbSGreg Kroah-Hartman 	resource_size_t end = start + size - 1;
10331da177e4SLinus Torvalds 	int result = -EBUSY;
10341da177e4SLinus Torvalds 
103582ec90eaSYinghai Lu 	if (!parent)
103682ec90eaSYinghai Lu 		goto skip;
103782ec90eaSYinghai Lu 
10381da177e4SLinus Torvalds 	if ((start < parent->start) || (end > parent->end))
10391da177e4SLinus Torvalds 		goto out;
10401da177e4SLinus Torvalds 
10411da177e4SLinus Torvalds 	if (res->sibling && (res->sibling->start <= end))
10421da177e4SLinus Torvalds 		goto out;
10431da177e4SLinus Torvalds 
10441da177e4SLinus Torvalds 	tmp = parent->child;
10451da177e4SLinus Torvalds 	if (tmp != res) {
10461da177e4SLinus Torvalds 		while (tmp->sibling != res)
10471da177e4SLinus Torvalds 			tmp = tmp->sibling;
10481da177e4SLinus Torvalds 		if (start <= tmp->end)
10491da177e4SLinus Torvalds 			goto out;
10501da177e4SLinus Torvalds 	}
10511da177e4SLinus Torvalds 
105282ec90eaSYinghai Lu skip:
105382ec90eaSYinghai Lu 	for (tmp = res->child; tmp; tmp = tmp->sibling)
105482ec90eaSYinghai Lu 		if ((tmp->start < start) || (tmp->end > end))
105582ec90eaSYinghai Lu 			goto out;
105682ec90eaSYinghai Lu 
10571da177e4SLinus Torvalds 	res->start = start;
10581da177e4SLinus Torvalds 	res->end = end;
10591da177e4SLinus Torvalds 	result = 0;
10601da177e4SLinus Torvalds 
10611da177e4SLinus Torvalds  out:
1062ae8e3a91SToshi Kani 	return result;
1063ae8e3a91SToshi Kani }
1064ae8e3a91SToshi Kani 
1065ae8e3a91SToshi Kani /**
1066ae8e3a91SToshi Kani  * adjust_resource - modify a resource's start and size
1067ae8e3a91SToshi Kani  * @res: resource to modify
1068ae8e3a91SToshi Kani  * @start: new start value
1069ae8e3a91SToshi Kani  * @size: new size
1070ae8e3a91SToshi Kani  *
1071ae8e3a91SToshi Kani  * Given an existing resource, change its start and size to match the
1072ae8e3a91SToshi Kani  * arguments.  Returns 0 on success, -EBUSY if it can't fit.
1073ae8e3a91SToshi Kani  * Existing children of the resource are assumed to be immutable.
1074ae8e3a91SToshi Kani  */
adjust_resource(struct resource * res,resource_size_t start,resource_size_t size)1075ae8e3a91SToshi Kani int adjust_resource(struct resource *res, resource_size_t start,
1076ae8e3a91SToshi Kani 		    resource_size_t size)
1077ae8e3a91SToshi Kani {
1078ae8e3a91SToshi Kani 	int result;
1079ae8e3a91SToshi Kani 
1080ae8e3a91SToshi Kani 	write_lock(&resource_lock);
1081ae8e3a91SToshi Kani 	result = __adjust_resource(res, start, size);
10821da177e4SLinus Torvalds 	write_unlock(&resource_lock);
10831da177e4SLinus Torvalds 	return result;
10841da177e4SLinus Torvalds }
108524105748SCong Wang EXPORT_SYMBOL(adjust_resource);
10861da177e4SLinus Torvalds 
1087b69c2e20SBorislav Petkov static void __init
__reserve_region_with_split(struct resource * root,resource_size_t start,resource_size_t end,const char * name)1088b69c2e20SBorislav Petkov __reserve_region_with_split(struct resource *root, resource_size_t start,
1089b69c2e20SBorislav Petkov 			    resource_size_t end, const char *name)
1090268364a0SYinghai Lu {
1091268364a0SYinghai Lu 	struct resource *parent = root;
1092268364a0SYinghai Lu 	struct resource *conflict;
1093ebff7d8fSYasuaki Ishimatsu 	struct resource *res = alloc_resource(GFP_ATOMIC);
10944965f566ST Makphaibulchoke 	struct resource *next_res = NULL;
1095f37e2334SBjorn Helgaas 	int type = resource_type(root);
1096268364a0SYinghai Lu 
1097268364a0SYinghai Lu 	if (!res)
1098268364a0SYinghai Lu 		return;
1099268364a0SYinghai Lu 
1100268364a0SYinghai Lu 	res->name = name;
1101268364a0SYinghai Lu 	res->start = start;
1102268364a0SYinghai Lu 	res->end = end;
1103f37e2334SBjorn Helgaas 	res->flags = type | IORESOURCE_BUSY;
110443ee493bSToshi Kani 	res->desc = IORES_DESC_NONE;
1105268364a0SYinghai Lu 
11064965f566ST Makphaibulchoke 	while (1) {
1107268364a0SYinghai Lu 
11084965f566ST Makphaibulchoke 		conflict = __request_resource(parent, res);
11094965f566ST Makphaibulchoke 		if (!conflict) {
11104965f566ST Makphaibulchoke 			if (!next_res)
11114965f566ST Makphaibulchoke 				break;
11124965f566ST Makphaibulchoke 			res = next_res;
11134965f566ST Makphaibulchoke 			next_res = NULL;
11144965f566ST Makphaibulchoke 			continue;
11154965f566ST Makphaibulchoke 		}
1116268364a0SYinghai Lu 
11171cf44baaSIngo Molnar 		/* conflict covered whole area */
11184965f566ST Makphaibulchoke 		if (conflict->start <= res->start &&
11194965f566ST Makphaibulchoke 				conflict->end >= res->end) {
1120ebff7d8fSYasuaki Ishimatsu 			free_resource(res);
11214965f566ST Makphaibulchoke 			WARN_ON(next_res);
11224965f566ST Makphaibulchoke 			break;
11234965f566ST Makphaibulchoke 		}
1124268364a0SYinghai Lu 
11254965f566ST Makphaibulchoke 		/* failed, split and try again */
11264965f566ST Makphaibulchoke 		if (conflict->start > res->start) {
11274965f566ST Makphaibulchoke 			end = res->end;
11284965f566ST Makphaibulchoke 			res->end = conflict->start - 1;
11294965f566ST Makphaibulchoke 			if (conflict->end < end) {
1130ebff7d8fSYasuaki Ishimatsu 				next_res = alloc_resource(GFP_ATOMIC);
11314965f566ST Makphaibulchoke 				if (!next_res) {
1132ebff7d8fSYasuaki Ishimatsu 					free_resource(res);
11334965f566ST Makphaibulchoke 					break;
11344965f566ST Makphaibulchoke 				}
11354965f566ST Makphaibulchoke 				next_res->name = name;
11364965f566ST Makphaibulchoke 				next_res->start = conflict->end + 1;
11374965f566ST Makphaibulchoke 				next_res->end = end;
1138f37e2334SBjorn Helgaas 				next_res->flags = type | IORESOURCE_BUSY;
113943ee493bSToshi Kani 				next_res->desc = IORES_DESC_NONE;
11404965f566ST Makphaibulchoke 			}
11414965f566ST Makphaibulchoke 		} else {
11424965f566ST Makphaibulchoke 			res->start = conflict->end + 1;
11434965f566ST Makphaibulchoke 		}
11444965f566ST Makphaibulchoke 	}
11454965f566ST Makphaibulchoke 
1146268364a0SYinghai Lu }
1147268364a0SYinghai Lu 
1148b69c2e20SBorislav Petkov void __init
reserve_region_with_split(struct resource * root,resource_size_t start,resource_size_t end,const char * name)1149b69c2e20SBorislav Petkov reserve_region_with_split(struct resource *root, resource_size_t start,
1150b69c2e20SBorislav Petkov 			  resource_size_t end, const char *name)
1151268364a0SYinghai Lu {
115265fed8f6SOctavian Purdila 	int abort = 0;
115365fed8f6SOctavian Purdila 
1154268364a0SYinghai Lu 	write_lock(&resource_lock);
115565fed8f6SOctavian Purdila 	if (root->start > start || root->end < end) {
115665fed8f6SOctavian Purdila 		pr_err("requested range [0x%llx-0x%llx] not in root %pr\n",
115765fed8f6SOctavian Purdila 		       (unsigned long long)start, (unsigned long long)end,
115865fed8f6SOctavian Purdila 		       root);
115965fed8f6SOctavian Purdila 		if (start > root->end || end < root->start)
116065fed8f6SOctavian Purdila 			abort = 1;
116165fed8f6SOctavian Purdila 		else {
116265fed8f6SOctavian Purdila 			if (end > root->end)
116365fed8f6SOctavian Purdila 				end = root->end;
116465fed8f6SOctavian Purdila 			if (start < root->start)
116565fed8f6SOctavian Purdila 				start = root->start;
116665fed8f6SOctavian Purdila 			pr_err("fixing request to [0x%llx-0x%llx]\n",
116765fed8f6SOctavian Purdila 			       (unsigned long long)start,
116865fed8f6SOctavian Purdila 			       (unsigned long long)end);
116965fed8f6SOctavian Purdila 		}
117065fed8f6SOctavian Purdila 		dump_stack();
117165fed8f6SOctavian Purdila 	}
117265fed8f6SOctavian Purdila 	if (!abort)
1173268364a0SYinghai Lu 		__reserve_region_with_split(root, start, end, name);
1174268364a0SYinghai Lu 	write_unlock(&resource_lock);
1175268364a0SYinghai Lu }
1176268364a0SYinghai Lu 
117788452565SIvan Kokshaysky /**
117888452565SIvan Kokshaysky  * resource_alignment - calculate resource's alignment
117988452565SIvan Kokshaysky  * @res: resource pointer
118088452565SIvan Kokshaysky  *
118188452565SIvan Kokshaysky  * Returns alignment on success, 0 (invalid alignment) on failure.
118288452565SIvan Kokshaysky  */
resource_alignment(struct resource * res)118388452565SIvan Kokshaysky resource_size_t resource_alignment(struct resource *res)
118488452565SIvan Kokshaysky {
118588452565SIvan Kokshaysky 	switch (res->flags & (IORESOURCE_SIZEALIGN | IORESOURCE_STARTALIGN)) {
118688452565SIvan Kokshaysky 	case IORESOURCE_SIZEALIGN:
11871a4e564bSMagnus Damm 		return resource_size(res);
118888452565SIvan Kokshaysky 	case IORESOURCE_STARTALIGN:
118988452565SIvan Kokshaysky 		return res->start;
119088452565SIvan Kokshaysky 	default:
119188452565SIvan Kokshaysky 		return 0;
119288452565SIvan Kokshaysky 	}
119388452565SIvan Kokshaysky }
119488452565SIvan Kokshaysky 
11951da177e4SLinus Torvalds /*
11961da177e4SLinus Torvalds  * This is compatibility stuff for IO resources.
11971da177e4SLinus Torvalds  *
11981da177e4SLinus Torvalds  * Note how this, unlike the above, knows about
11991da177e4SLinus Torvalds  * the IO flag meanings (busy etc).
12001da177e4SLinus Torvalds  *
1201e1ca66d1SRandy Dunlap  * request_region creates a new busy region.
12021da177e4SLinus Torvalds  *
1203e1ca66d1SRandy Dunlap  * release_region releases a matching busy region.
1204e1ca66d1SRandy Dunlap  */
1205e1ca66d1SRandy Dunlap 
12068b6d043bSAlan Cox static DECLARE_WAIT_QUEUE_HEAD(muxed_resource_wait);
12078b6d043bSAlan Cox 
120871a1d8edSDaniel Vetter static struct inode *iomem_inode;
120971a1d8edSDaniel Vetter 
121071a1d8edSDaniel Vetter #ifdef CONFIG_IO_STRICT_DEVMEM
revoke_iomem(struct resource * res)121171a1d8edSDaniel Vetter static void revoke_iomem(struct resource *res)
121271a1d8edSDaniel Vetter {
121371a1d8edSDaniel Vetter 	/* pairs with smp_store_release() in iomem_init_inode() */
121471a1d8edSDaniel Vetter 	struct inode *inode = smp_load_acquire(&iomem_inode);
121571a1d8edSDaniel Vetter 
121671a1d8edSDaniel Vetter 	/*
121771a1d8edSDaniel Vetter 	 * Check that the initialization has completed. Losing the race
121871a1d8edSDaniel Vetter 	 * is ok because it means drivers are claiming resources before
121971a1d8edSDaniel Vetter 	 * the fs_initcall level of init and prevent iomem_get_mapping users
122071a1d8edSDaniel Vetter 	 * from establishing mappings.
122171a1d8edSDaniel Vetter 	 */
122271a1d8edSDaniel Vetter 	if (!inode)
122371a1d8edSDaniel Vetter 		return;
122471a1d8edSDaniel Vetter 
122571a1d8edSDaniel Vetter 	/*
122671a1d8edSDaniel Vetter 	 * The expectation is that the driver has successfully marked
122771a1d8edSDaniel Vetter 	 * the resource busy by this point, so devmem_is_allowed()
122871a1d8edSDaniel Vetter 	 * should start returning false, however for performance this
122971a1d8edSDaniel Vetter 	 * does not iterate the entire resource range.
123071a1d8edSDaniel Vetter 	 */
123171a1d8edSDaniel Vetter 	if (devmem_is_allowed(PHYS_PFN(res->start)) &&
123271a1d8edSDaniel Vetter 	    devmem_is_allowed(PHYS_PFN(res->end))) {
123371a1d8edSDaniel Vetter 		/*
123471a1d8edSDaniel Vetter 		 * *cringe* iomem=relaxed says "go ahead, what's the
123571a1d8edSDaniel Vetter 		 * worst that can happen?"
123671a1d8edSDaniel Vetter 		 */
123771a1d8edSDaniel Vetter 		return;
123871a1d8edSDaniel Vetter 	}
123971a1d8edSDaniel Vetter 
124071a1d8edSDaniel Vetter 	unmap_mapping_range(inode->i_mapping, res->start, resource_size(res), 1);
124171a1d8edSDaniel Vetter }
124271a1d8edSDaniel Vetter #else
revoke_iomem(struct resource * res)124371a1d8edSDaniel Vetter static void revoke_iomem(struct resource *res) {}
124471a1d8edSDaniel Vetter #endif
124571a1d8edSDaniel Vetter 
iomem_get_mapping(void)124671a1d8edSDaniel Vetter struct address_space *iomem_get_mapping(void)
124771a1d8edSDaniel Vetter {
124871a1d8edSDaniel Vetter 	/*
124971a1d8edSDaniel Vetter 	 * This function is only called from file open paths, hence guaranteed
125071a1d8edSDaniel Vetter 	 * that fs_initcalls have completed and no need to check for NULL. But
125171a1d8edSDaniel Vetter 	 * since revoke_iomem can be called before the initcall we still need
125271a1d8edSDaniel Vetter 	 * the barrier to appease checkers.
125371a1d8edSDaniel Vetter 	 */
125471a1d8edSDaniel Vetter 	return smp_load_acquire(&iomem_inode)->i_mapping;
125571a1d8edSDaniel Vetter }
125671a1d8edSDaniel Vetter 
__request_region_locked(struct resource * res,struct resource * parent,resource_size_t start,resource_size_t n,const char * name,int flags)125763cdafe0SAlistair Popple static int __request_region_locked(struct resource *res, struct resource *parent,
1258d75fc8bbSGreg Kroah-Hartman 				   resource_size_t start, resource_size_t n,
1259e8de1481SArjan van de Ven 				   const char *name, int flags)
12601da177e4SLinus Torvalds {
12618b6d043bSAlan Cox 	DECLARE_WAITQUEUE(wait, current);
1262c26ec88eSBjorn Helgaas 
12631da177e4SLinus Torvalds 	res->name = name;
12641da177e4SLinus Torvalds 	res->start = start;
12651da177e4SLinus Torvalds 	res->end = start + n - 1;
12661da177e4SLinus Torvalds 
12671da177e4SLinus Torvalds 	for (;;) {
12681da177e4SLinus Torvalds 		struct resource *conflict;
12691da177e4SLinus Torvalds 
12704e0d8f7eSToshi Kani 		res->flags = resource_type(parent) | resource_ext_type(parent);
12714e0d8f7eSToshi Kani 		res->flags |= IORESOURCE_BUSY | flags;
12724e0d8f7eSToshi Kani 		res->desc = parent->desc;
12734e0d8f7eSToshi Kani 
12741da177e4SLinus Torvalds 		conflict = __request_resource(parent, res);
12751da177e4SLinus Torvalds 		if (!conflict)
12761da177e4SLinus Torvalds 			break;
1277b926b7f3SDave Hansen 		/*
1278b926b7f3SDave Hansen 		 * mm/hmm.c reserves physical addresses which then
1279b926b7f3SDave Hansen 		 * become unavailable to other users.  Conflicts are
1280b926b7f3SDave Hansen 		 * not expected.  Warn to aid debugging if encountered.
1281b926b7f3SDave Hansen 		 */
1282b926b7f3SDave Hansen 		if (conflict->desc == IORES_DESC_DEVICE_PRIVATE_MEMORY) {
1283b926b7f3SDave Hansen 			pr_warn("Unaddressable device %s %pR conflicts with %pR",
1284b926b7f3SDave Hansen 				conflict->name, conflict, res);
1285b926b7f3SDave Hansen 		}
12861da177e4SLinus Torvalds 		if (conflict != parent) {
128759ceeaafSSimon Guinot 			if (!(conflict->flags & IORESOURCE_BUSY)) {
12881da177e4SLinus Torvalds 				parent = conflict;
12891da177e4SLinus Torvalds 				continue;
12901da177e4SLinus Torvalds 			}
129159ceeaafSSimon Guinot 		}
12928b6d043bSAlan Cox 		if (conflict->flags & flags & IORESOURCE_MUXED) {
12938b6d043bSAlan Cox 			add_wait_queue(&muxed_resource_wait, &wait);
12948b6d043bSAlan Cox 			write_unlock(&resource_lock);
12958b6d043bSAlan Cox 			set_current_state(TASK_UNINTERRUPTIBLE);
12968b6d043bSAlan Cox 			schedule();
12978b6d043bSAlan Cox 			remove_wait_queue(&muxed_resource_wait, &wait);
12988b6d043bSAlan Cox 			write_lock(&resource_lock);
12998b6d043bSAlan Cox 			continue;
13008b6d043bSAlan Cox 		}
13011da177e4SLinus Torvalds 		/* Uhhuh, that didn't work out.. */
130263cdafe0SAlistair Popple 		return -EBUSY;
13031da177e4SLinus Torvalds 	}
130463cdafe0SAlistair Popple 
130563cdafe0SAlistair Popple 	return 0;
130663cdafe0SAlistair Popple }
130763cdafe0SAlistair Popple 
130863cdafe0SAlistair Popple /**
130963cdafe0SAlistair Popple  * __request_region - create a new busy resource region
131063cdafe0SAlistair Popple  * @parent: parent resource descriptor
131163cdafe0SAlistair Popple  * @start: resource start address
131263cdafe0SAlistair Popple  * @n: resource region size
131363cdafe0SAlistair Popple  * @name: reserving caller's ID string
131463cdafe0SAlistair Popple  * @flags: IO resource flags
131563cdafe0SAlistair Popple  */
__request_region(struct resource * parent,resource_size_t start,resource_size_t n,const char * name,int flags)131663cdafe0SAlistair Popple struct resource *__request_region(struct resource *parent,
131763cdafe0SAlistair Popple 				  resource_size_t start, resource_size_t n,
131863cdafe0SAlistair Popple 				  const char *name, int flags)
131963cdafe0SAlistair Popple {
132063cdafe0SAlistair Popple 	struct resource *res = alloc_resource(GFP_KERNEL);
132163cdafe0SAlistair Popple 	int ret;
132263cdafe0SAlistair Popple 
132363cdafe0SAlistair Popple 	if (!res)
132463cdafe0SAlistair Popple 		return NULL;
132563cdafe0SAlistair Popple 
132663cdafe0SAlistair Popple 	write_lock(&resource_lock);
132763cdafe0SAlistair Popple 	ret = __request_region_locked(res, parent, start, n, name, flags);
13281da177e4SLinus Torvalds 	write_unlock(&resource_lock);
13293234ac66SDan Williams 
133063cdafe0SAlistair Popple 	if (ret) {
133163cdafe0SAlistair Popple 		free_resource(res);
133263cdafe0SAlistair Popple 		return NULL;
133363cdafe0SAlistair Popple 	}
133463cdafe0SAlistair Popple 
133563cdafe0SAlistair Popple 	if (parent == &iomem_resource)
133671a1d8edSDaniel Vetter 		revoke_iomem(res);
13373234ac66SDan Williams 
13381da177e4SLinus Torvalds 	return res;
13391da177e4SLinus Torvalds }
13401da177e4SLinus Torvalds EXPORT_SYMBOL(__request_region);
13411da177e4SLinus Torvalds 
1342e1ca66d1SRandy Dunlap /**
1343e1ca66d1SRandy Dunlap  * __release_region - release a previously reserved resource region
1344e1ca66d1SRandy Dunlap  * @parent: parent resource descriptor
1345e1ca66d1SRandy Dunlap  * @start: resource start address
1346e1ca66d1SRandy Dunlap  * @n: resource region size
1347e1ca66d1SRandy Dunlap  *
1348e1ca66d1SRandy Dunlap  * The described resource region must match a currently busy region.
1349e1ca66d1SRandy Dunlap  */
__release_region(struct resource * parent,resource_size_t start,resource_size_t n)1350d75fc8bbSGreg Kroah-Hartman void __release_region(struct resource *parent, resource_size_t start,
1351d75fc8bbSGreg Kroah-Hartman 		      resource_size_t n)
13521da177e4SLinus Torvalds {
13531da177e4SLinus Torvalds 	struct resource **p;
1354d75fc8bbSGreg Kroah-Hartman 	resource_size_t end;
13551da177e4SLinus Torvalds 
13561da177e4SLinus Torvalds 	p = &parent->child;
13571da177e4SLinus Torvalds 	end = start + n - 1;
13581da177e4SLinus Torvalds 
13591da177e4SLinus Torvalds 	write_lock(&resource_lock);
13601da177e4SLinus Torvalds 
13611da177e4SLinus Torvalds 	for (;;) {
13621da177e4SLinus Torvalds 		struct resource *res = *p;
13631da177e4SLinus Torvalds 
13641da177e4SLinus Torvalds 		if (!res)
13651da177e4SLinus Torvalds 			break;
13661da177e4SLinus Torvalds 		if (res->start <= start && res->end >= end) {
13671da177e4SLinus Torvalds 			if (!(res->flags & IORESOURCE_BUSY)) {
13681da177e4SLinus Torvalds 				p = &res->child;
13691da177e4SLinus Torvalds 				continue;
13701da177e4SLinus Torvalds 			}
13711da177e4SLinus Torvalds 			if (res->start != start || res->end != end)
13721da177e4SLinus Torvalds 				break;
13731da177e4SLinus Torvalds 			*p = res->sibling;
13741da177e4SLinus Torvalds 			write_unlock(&resource_lock);
13758b6d043bSAlan Cox 			if (res->flags & IORESOURCE_MUXED)
13768b6d043bSAlan Cox 				wake_up(&muxed_resource_wait);
1377ebff7d8fSYasuaki Ishimatsu 			free_resource(res);
13781da177e4SLinus Torvalds 			return;
13791da177e4SLinus Torvalds 		}
13801da177e4SLinus Torvalds 		p = &res->sibling;
13811da177e4SLinus Torvalds 	}
13821da177e4SLinus Torvalds 
13831da177e4SLinus Torvalds 	write_unlock(&resource_lock);
13841da177e4SLinus Torvalds 
13852a4e6285SAndy Shevchenko 	pr_warn("Trying to free nonexistent resource <%pa-%pa>\n", &start, &end);
13861da177e4SLinus Torvalds }
13871da177e4SLinus Torvalds EXPORT_SYMBOL(__release_region);
13881da177e4SLinus Torvalds 
1389825f787bSToshi Kani #ifdef CONFIG_MEMORY_HOTREMOVE
1390825f787bSToshi Kani /**
1391825f787bSToshi Kani  * release_mem_region_adjustable - release a previously reserved memory region
1392825f787bSToshi Kani  * @start: resource start address
1393825f787bSToshi Kani  * @size: resource region size
1394825f787bSToshi Kani  *
1395825f787bSToshi Kani  * This interface is intended for memory hot-delete.  The requested region
1396825f787bSToshi Kani  * is released from a currently busy memory resource.  The requested region
1397825f787bSToshi Kani  * must either match exactly or fit into a single busy resource entry.  In
1398825f787bSToshi Kani  * the latter case, the remaining resource is adjusted accordingly.
1399825f787bSToshi Kani  * Existing children of the busy memory resource must be immutable in the
1400825f787bSToshi Kani  * request.
1401825f787bSToshi Kani  *
1402825f787bSToshi Kani  * Note:
1403825f787bSToshi Kani  * - Additional release conditions, such as overlapping region, can be
1404825f787bSToshi Kani  *   supported after they are confirmed as valid cases.
1405825f787bSToshi Kani  * - When a busy memory resource gets split into two entries, the code
1406825f787bSToshi Kani  *   assumes that all children remain in the lower address entry for
1407825f787bSToshi Kani  *   simplicity.  Enhance this logic when necessary.
1408825f787bSToshi Kani  */
release_mem_region_adjustable(resource_size_t start,resource_size_t size)1409cb8e3c8bSDavid Hildenbrand void release_mem_region_adjustable(resource_size_t start, resource_size_t size)
1410825f787bSToshi Kani {
1411cb8e3c8bSDavid Hildenbrand 	struct resource *parent = &iomem_resource;
1412ec62d04eSDavid Hildenbrand 	struct resource *new_res = NULL;
1413ec62d04eSDavid Hildenbrand 	bool alloc_nofail = false;
1414825f787bSToshi Kani 	struct resource **p;
1415825f787bSToshi Kani 	struct resource *res;
1416825f787bSToshi Kani 	resource_size_t end;
1417825f787bSToshi Kani 
1418825f787bSToshi Kani 	end = start + size - 1;
1419ec62d04eSDavid Hildenbrand 	if (WARN_ON_ONCE((start < parent->start) || (end > parent->end)))
1420ec62d04eSDavid Hildenbrand 		return;
1421825f787bSToshi Kani 
1422ec62d04eSDavid Hildenbrand 	/*
1423ec62d04eSDavid Hildenbrand 	 * We free up quite a lot of memory on memory hotunplug (esp., memap),
1424ec62d04eSDavid Hildenbrand 	 * just before releasing the region. This is highly unlikely to
1425ec62d04eSDavid Hildenbrand 	 * fail - let's play save and make it never fail as the caller cannot
1426ec62d04eSDavid Hildenbrand 	 * perform any error handling (e.g., trying to re-add memory will fail
1427ec62d04eSDavid Hildenbrand 	 * similarly).
1428ec62d04eSDavid Hildenbrand 	 */
1429ec62d04eSDavid Hildenbrand retry:
1430ec62d04eSDavid Hildenbrand 	new_res = alloc_resource(GFP_KERNEL | (alloc_nofail ? __GFP_NOFAIL : 0));
1431825f787bSToshi Kani 
1432825f787bSToshi Kani 	p = &parent->child;
1433825f787bSToshi Kani 	write_lock(&resource_lock);
1434825f787bSToshi Kani 
1435825f787bSToshi Kani 	while ((res = *p)) {
1436825f787bSToshi Kani 		if (res->start >= end)
1437825f787bSToshi Kani 			break;
1438825f787bSToshi Kani 
1439825f787bSToshi Kani 		/* look for the next resource if it does not fit into */
1440825f787bSToshi Kani 		if (res->start > start || res->end < end) {
1441825f787bSToshi Kani 			p = &res->sibling;
1442825f787bSToshi Kani 			continue;
1443825f787bSToshi Kani 		}
1444825f787bSToshi Kani 
1445825f787bSToshi Kani 		if (!(res->flags & IORESOURCE_MEM))
1446825f787bSToshi Kani 			break;
1447825f787bSToshi Kani 
1448825f787bSToshi Kani 		if (!(res->flags & IORESOURCE_BUSY)) {
1449825f787bSToshi Kani 			p = &res->child;
1450825f787bSToshi Kani 			continue;
1451825f787bSToshi Kani 		}
1452825f787bSToshi Kani 
1453825f787bSToshi Kani 		/* found the target resource; let's adjust accordingly */
1454825f787bSToshi Kani 		if (res->start == start && res->end == end) {
1455825f787bSToshi Kani 			/* free the whole entry */
1456825f787bSToshi Kani 			*p = res->sibling;
1457ebff7d8fSYasuaki Ishimatsu 			free_resource(res);
1458825f787bSToshi Kani 		} else if (res->start == start && res->end != end) {
1459825f787bSToshi Kani 			/* adjust the start */
1460ec62d04eSDavid Hildenbrand 			WARN_ON_ONCE(__adjust_resource(res, end + 1,
1461ec62d04eSDavid Hildenbrand 						       res->end - end));
1462825f787bSToshi Kani 		} else if (res->start != start && res->end == end) {
1463825f787bSToshi Kani 			/* adjust the end */
1464ec62d04eSDavid Hildenbrand 			WARN_ON_ONCE(__adjust_resource(res, res->start,
1465ec62d04eSDavid Hildenbrand 						       start - res->start));
1466825f787bSToshi Kani 		} else {
1467ec62d04eSDavid Hildenbrand 			/* split into two entries - we need a new resource */
1468825f787bSToshi Kani 			if (!new_res) {
1469ec62d04eSDavid Hildenbrand 				new_res = alloc_resource(GFP_ATOMIC);
1470ec62d04eSDavid Hildenbrand 				if (!new_res) {
1471ec62d04eSDavid Hildenbrand 					alloc_nofail = true;
1472ec62d04eSDavid Hildenbrand 					write_unlock(&resource_lock);
1473ec62d04eSDavid Hildenbrand 					goto retry;
1474ec62d04eSDavid Hildenbrand 				}
1475825f787bSToshi Kani 			}
1476825f787bSToshi Kani 			new_res->name = res->name;
1477825f787bSToshi Kani 			new_res->start = end + 1;
1478825f787bSToshi Kani 			new_res->end = res->end;
1479825f787bSToshi Kani 			new_res->flags = res->flags;
148043ee493bSToshi Kani 			new_res->desc = res->desc;
1481825f787bSToshi Kani 			new_res->parent = res->parent;
1482825f787bSToshi Kani 			new_res->sibling = res->sibling;
1483825f787bSToshi Kani 			new_res->child = NULL;
1484825f787bSToshi Kani 
1485ec62d04eSDavid Hildenbrand 			if (WARN_ON_ONCE(__adjust_resource(res, res->start,
1486ec62d04eSDavid Hildenbrand 							   start - res->start)))
1487825f787bSToshi Kani 				break;
1488825f787bSToshi Kani 			res->sibling = new_res;
1489825f787bSToshi Kani 			new_res = NULL;
1490825f787bSToshi Kani 		}
1491825f787bSToshi Kani 
1492825f787bSToshi Kani 		break;
1493825f787bSToshi Kani 	}
1494825f787bSToshi Kani 
1495825f787bSToshi Kani 	write_unlock(&resource_lock);
1496ebff7d8fSYasuaki Ishimatsu 	free_resource(new_res);
1497825f787bSToshi Kani }
1498825f787bSToshi Kani #endif	/* CONFIG_MEMORY_HOTREMOVE */
1499825f787bSToshi Kani 
15009ca6551eSDavid Hildenbrand #ifdef CONFIG_MEMORY_HOTPLUG
system_ram_resources_mergeable(struct resource * r1,struct resource * r2)15019ca6551eSDavid Hildenbrand static bool system_ram_resources_mergeable(struct resource *r1,
15029ca6551eSDavid Hildenbrand 					   struct resource *r2)
15039ca6551eSDavid Hildenbrand {
15049ca6551eSDavid Hildenbrand 	/* We assume either r1 or r2 is IORESOURCE_SYSRAM_MERGEABLE. */
15059ca6551eSDavid Hildenbrand 	return r1->flags == r2->flags && r1->end + 1 == r2->start &&
15069ca6551eSDavid Hildenbrand 	       r1->name == r2->name && r1->desc == r2->desc &&
15079ca6551eSDavid Hildenbrand 	       !r1->child && !r2->child;
15089ca6551eSDavid Hildenbrand }
15099ca6551eSDavid Hildenbrand 
15103be8da57SMauro Carvalho Chehab /**
15119ca6551eSDavid Hildenbrand  * merge_system_ram_resource - mark the System RAM resource mergeable and try to
15129ca6551eSDavid Hildenbrand  *	merge it with adjacent, mergeable resources
15139ca6551eSDavid Hildenbrand  * @res: resource descriptor
15149ca6551eSDavid Hildenbrand  *
15159ca6551eSDavid Hildenbrand  * This interface is intended for memory hotplug, whereby lots of contiguous
15169ca6551eSDavid Hildenbrand  * system ram resources are added (e.g., via add_memory*()) by a driver, and
15179ca6551eSDavid Hildenbrand  * the actual resource boundaries are not of interest (e.g., it might be
15189ca6551eSDavid Hildenbrand  * relevant for DIMMs). Only resources that are marked mergeable, that have the
15199ca6551eSDavid Hildenbrand  * same parent, and that don't have any children are considered. All mergeable
15209ca6551eSDavid Hildenbrand  * resources must be immutable during the request.
15219ca6551eSDavid Hildenbrand  *
15229ca6551eSDavid Hildenbrand  * Note:
15239ca6551eSDavid Hildenbrand  * - The caller has to make sure that no pointers to resources that are
15249ca6551eSDavid Hildenbrand  *   marked mergeable are used anymore after this call - the resource might
15259ca6551eSDavid Hildenbrand  *   be freed and the pointer might be stale!
15269ca6551eSDavid Hildenbrand  * - release_mem_region_adjustable() will split on demand on memory hotunplug
15279ca6551eSDavid Hildenbrand  */
merge_system_ram_resource(struct resource * res)15289ca6551eSDavid Hildenbrand void merge_system_ram_resource(struct resource *res)
15299ca6551eSDavid Hildenbrand {
15309ca6551eSDavid Hildenbrand 	const unsigned long flags = IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY;
15319ca6551eSDavid Hildenbrand 	struct resource *cur;
15329ca6551eSDavid Hildenbrand 
15339ca6551eSDavid Hildenbrand 	if (WARN_ON_ONCE((res->flags & flags) != flags))
15349ca6551eSDavid Hildenbrand 		return;
15359ca6551eSDavid Hildenbrand 
15369ca6551eSDavid Hildenbrand 	write_lock(&resource_lock);
15379ca6551eSDavid Hildenbrand 	res->flags |= IORESOURCE_SYSRAM_MERGEABLE;
15389ca6551eSDavid Hildenbrand 
15399ca6551eSDavid Hildenbrand 	/* Try to merge with next item in the list. */
15409ca6551eSDavid Hildenbrand 	cur = res->sibling;
15419ca6551eSDavid Hildenbrand 	if (cur && system_ram_resources_mergeable(res, cur)) {
15429ca6551eSDavid Hildenbrand 		res->end = cur->end;
15439ca6551eSDavid Hildenbrand 		res->sibling = cur->sibling;
15449ca6551eSDavid Hildenbrand 		free_resource(cur);
15459ca6551eSDavid Hildenbrand 	}
15469ca6551eSDavid Hildenbrand 
15479ca6551eSDavid Hildenbrand 	/* Try to merge with previous item in the list. */
15489ca6551eSDavid Hildenbrand 	cur = res->parent->child;
15499ca6551eSDavid Hildenbrand 	while (cur && cur->sibling != res)
15509ca6551eSDavid Hildenbrand 		cur = cur->sibling;
15519ca6551eSDavid Hildenbrand 	if (cur && system_ram_resources_mergeable(cur, res)) {
15529ca6551eSDavid Hildenbrand 		cur->end = res->end;
15539ca6551eSDavid Hildenbrand 		cur->sibling = res->sibling;
15549ca6551eSDavid Hildenbrand 		free_resource(res);
15559ca6551eSDavid Hildenbrand 	}
15569ca6551eSDavid Hildenbrand 	write_unlock(&resource_lock);
15579ca6551eSDavid Hildenbrand }
15589ca6551eSDavid Hildenbrand #endif	/* CONFIG_MEMORY_HOTPLUG */
15599ca6551eSDavid Hildenbrand 
15601da177e4SLinus Torvalds /*
15619ac7849eSTejun Heo  * Managed region resource
15629ac7849eSTejun Heo  */
devm_resource_release(struct device * dev,void * ptr)15638d38821cSThierry Reding static void devm_resource_release(struct device *dev, void *ptr)
15648d38821cSThierry Reding {
15658d38821cSThierry Reding 	struct resource **r = ptr;
15668d38821cSThierry Reding 
15678d38821cSThierry Reding 	release_resource(*r);
15688d38821cSThierry Reding }
15698d38821cSThierry Reding 
15708d38821cSThierry Reding /**
15718d38821cSThierry Reding  * devm_request_resource() - request and reserve an I/O or memory resource
15728d38821cSThierry Reding  * @dev: device for which to request the resource
15738d38821cSThierry Reding  * @root: root of the resource tree from which to request the resource
15748d38821cSThierry Reding  * @new: descriptor of the resource to request
15758d38821cSThierry Reding  *
15768d38821cSThierry Reding  * This is a device-managed version of request_resource(). There is usually
15778d38821cSThierry Reding  * no need to release resources requested by this function explicitly since
15788d38821cSThierry Reding  * that will be taken care of when the device is unbound from its driver.
15798d38821cSThierry Reding  * If for some reason the resource needs to be released explicitly, because
15808d38821cSThierry Reding  * of ordering issues for example, drivers must call devm_release_resource()
15818d38821cSThierry Reding  * rather than the regular release_resource().
15828d38821cSThierry Reding  *
15838d38821cSThierry Reding  * When a conflict is detected between any existing resources and the newly
15848d38821cSThierry Reding  * requested resource, an error message will be printed.
15858d38821cSThierry Reding  *
15868d38821cSThierry Reding  * Returns 0 on success or a negative error code on failure.
15878d38821cSThierry Reding  */
devm_request_resource(struct device * dev,struct resource * root,struct resource * new)15888d38821cSThierry Reding int devm_request_resource(struct device *dev, struct resource *root,
15898d38821cSThierry Reding 			  struct resource *new)
15908d38821cSThierry Reding {
15918d38821cSThierry Reding 	struct resource *conflict, **ptr;
15928d38821cSThierry Reding 
15938d38821cSThierry Reding 	ptr = devres_alloc(devm_resource_release, sizeof(*ptr), GFP_KERNEL);
15948d38821cSThierry Reding 	if (!ptr)
15958d38821cSThierry Reding 		return -ENOMEM;
15968d38821cSThierry Reding 
15978d38821cSThierry Reding 	*ptr = new;
15988d38821cSThierry Reding 
15998d38821cSThierry Reding 	conflict = request_resource_conflict(root, new);
16008d38821cSThierry Reding 	if (conflict) {
16018d38821cSThierry Reding 		dev_err(dev, "resource collision: %pR conflicts with %s %pR\n",
16028d38821cSThierry Reding 			new, conflict->name, conflict);
16038d38821cSThierry Reding 		devres_free(ptr);
16048d38821cSThierry Reding 		return -EBUSY;
16058d38821cSThierry Reding 	}
16068d38821cSThierry Reding 
16078d38821cSThierry Reding 	devres_add(dev, ptr);
16088d38821cSThierry Reding 	return 0;
16098d38821cSThierry Reding }
16108d38821cSThierry Reding EXPORT_SYMBOL(devm_request_resource);
16118d38821cSThierry Reding 
devm_resource_match(struct device * dev,void * res,void * data)16128d38821cSThierry Reding static int devm_resource_match(struct device *dev, void *res, void *data)
16138d38821cSThierry Reding {
16148d38821cSThierry Reding 	struct resource **ptr = res;
16158d38821cSThierry Reding 
16168d38821cSThierry Reding 	return *ptr == data;
16178d38821cSThierry Reding }
16188d38821cSThierry Reding 
16198d38821cSThierry Reding /**
16208d38821cSThierry Reding  * devm_release_resource() - release a previously requested resource
16218d38821cSThierry Reding  * @dev: device for which to release the resource
16228d38821cSThierry Reding  * @new: descriptor of the resource to release
16238d38821cSThierry Reding  *
16248d38821cSThierry Reding  * Releases a resource previously requested using devm_request_resource().
16258d38821cSThierry Reding  */
devm_release_resource(struct device * dev,struct resource * new)16268d38821cSThierry Reding void devm_release_resource(struct device *dev, struct resource *new)
16278d38821cSThierry Reding {
16288d38821cSThierry Reding 	WARN_ON(devres_release(dev, devm_resource_release, devm_resource_match,
16298d38821cSThierry Reding 			       new));
16308d38821cSThierry Reding }
16318d38821cSThierry Reding EXPORT_SYMBOL(devm_release_resource);
16328d38821cSThierry Reding 
16339ac7849eSTejun Heo struct region_devres {
16349ac7849eSTejun Heo 	struct resource *parent;
16359ac7849eSTejun Heo 	resource_size_t start;
16369ac7849eSTejun Heo 	resource_size_t n;
16379ac7849eSTejun Heo };
16389ac7849eSTejun Heo 
devm_region_release(struct device * dev,void * res)16399ac7849eSTejun Heo static void devm_region_release(struct device *dev, void *res)
16409ac7849eSTejun Heo {
16419ac7849eSTejun Heo 	struct region_devres *this = res;
16429ac7849eSTejun Heo 
16439ac7849eSTejun Heo 	__release_region(this->parent, this->start, this->n);
16449ac7849eSTejun Heo }
16459ac7849eSTejun Heo 
devm_region_match(struct device * dev,void * res,void * match_data)16469ac7849eSTejun Heo static int devm_region_match(struct device *dev, void *res, void *match_data)
16479ac7849eSTejun Heo {
16489ac7849eSTejun Heo 	struct region_devres *this = res, *match = match_data;
16499ac7849eSTejun Heo 
16509ac7849eSTejun Heo 	return this->parent == match->parent &&
16519ac7849eSTejun Heo 		this->start == match->start && this->n == match->n;
16529ac7849eSTejun Heo }
16539ac7849eSTejun Heo 
1654b69c2e20SBorislav Petkov struct resource *
__devm_request_region(struct device * dev,struct resource * parent,resource_size_t start,resource_size_t n,const char * name)1655b69c2e20SBorislav Petkov __devm_request_region(struct device *dev, struct resource *parent,
1656b69c2e20SBorislav Petkov 		      resource_size_t start, resource_size_t n, const char *name)
16579ac7849eSTejun Heo {
16589ac7849eSTejun Heo 	struct region_devres *dr = NULL;
16599ac7849eSTejun Heo 	struct resource *res;
16609ac7849eSTejun Heo 
16619ac7849eSTejun Heo 	dr = devres_alloc(devm_region_release, sizeof(struct region_devres),
16629ac7849eSTejun Heo 			  GFP_KERNEL);
16639ac7849eSTejun Heo 	if (!dr)
16649ac7849eSTejun Heo 		return NULL;
16659ac7849eSTejun Heo 
16669ac7849eSTejun Heo 	dr->parent = parent;
16679ac7849eSTejun Heo 	dr->start = start;
16689ac7849eSTejun Heo 	dr->n = n;
16699ac7849eSTejun Heo 
1670e8de1481SArjan van de Ven 	res = __request_region(parent, start, n, name, 0);
16719ac7849eSTejun Heo 	if (res)
16729ac7849eSTejun Heo 		devres_add(dev, dr);
16739ac7849eSTejun Heo 	else
16749ac7849eSTejun Heo 		devres_free(dr);
16759ac7849eSTejun Heo 
16769ac7849eSTejun Heo 	return res;
16779ac7849eSTejun Heo }
16789ac7849eSTejun Heo EXPORT_SYMBOL(__devm_request_region);
16799ac7849eSTejun Heo 
__devm_release_region(struct device * dev,struct resource * parent,resource_size_t start,resource_size_t n)16809ac7849eSTejun Heo void __devm_release_region(struct device *dev, struct resource *parent,
16819ac7849eSTejun Heo 			   resource_size_t start, resource_size_t n)
16829ac7849eSTejun Heo {
16839ac7849eSTejun Heo 	struct region_devres match_data = { parent, start, n };
16849ac7849eSTejun Heo 
16851e185723SZijun Hu 	WARN_ON(devres_release(dev, devm_region_release, devm_region_match,
16869ac7849eSTejun Heo 			       &match_data));
16879ac7849eSTejun Heo }
16889ac7849eSTejun Heo EXPORT_SYMBOL(__devm_release_region);
16899ac7849eSTejun Heo 
16909ac7849eSTejun Heo /*
1691ffd2e8dfSBjorn Helgaas  * Reserve I/O ports or memory based on "reserve=" kernel parameter.
16921da177e4SLinus Torvalds  */
16931da177e4SLinus Torvalds #define MAXRESERVE 4
reserve_setup(char * str)16941da177e4SLinus Torvalds static int __init reserve_setup(char *str)
16951da177e4SLinus Torvalds {
16961da177e4SLinus Torvalds 	static int reserved;
16971da177e4SLinus Torvalds 	static struct resource reserve[MAXRESERVE];
16981da177e4SLinus Torvalds 
16991da177e4SLinus Torvalds 	for (;;) {
17008bc1ad7dSZhang Rui 		unsigned int io_start, io_num;
17011da177e4SLinus Torvalds 		int x = reserved;
1702ffd2e8dfSBjorn Helgaas 		struct resource *parent;
17031da177e4SLinus Torvalds 
17041da177e4SLinus Torvalds 		if (get_option(&str, &io_start) != 2)
17051da177e4SLinus Torvalds 			break;
17061da177e4SLinus Torvalds 		if (get_option(&str, &io_num) == 0)
17071da177e4SLinus Torvalds 			break;
17081da177e4SLinus Torvalds 		if (x < MAXRESERVE) {
17091da177e4SLinus Torvalds 			struct resource *res = reserve + x;
1710ffd2e8dfSBjorn Helgaas 
1711ffd2e8dfSBjorn Helgaas 			/*
1712ffd2e8dfSBjorn Helgaas 			 * If the region starts below 0x10000, we assume it's
1713ffd2e8dfSBjorn Helgaas 			 * I/O port space; otherwise assume it's memory.
1714ffd2e8dfSBjorn Helgaas 			 */
1715ffd2e8dfSBjorn Helgaas 			if (io_start < 0x10000) {
17161af56ff0SAndy Shevchenko 				*res = DEFINE_RES_IO_NAMED(io_start, io_num, "reserved");
1717ffd2e8dfSBjorn Helgaas 				parent = &ioport_resource;
1718ffd2e8dfSBjorn Helgaas 			} else {
17191af56ff0SAndy Shevchenko 				*res = DEFINE_RES_MEM_NAMED(io_start, io_num, "reserved");
1720ffd2e8dfSBjorn Helgaas 				parent = &iomem_resource;
1721ffd2e8dfSBjorn Helgaas 			}
1722ffd2e8dfSBjorn Helgaas 			res->flags |= IORESOURCE_BUSY;
1723ffd2e8dfSBjorn Helgaas 			if (request_resource(parent, res) == 0)
17241da177e4SLinus Torvalds 				reserved = x+1;
17251da177e4SLinus Torvalds 		}
17261da177e4SLinus Torvalds 	}
17271da177e4SLinus Torvalds 	return 1;
17281da177e4SLinus Torvalds }
17291da177e4SLinus Torvalds __setup("reserve=", reserve_setup);
1730379daf62SSuresh Siddha 
1731379daf62SSuresh Siddha /*
1732379daf62SSuresh Siddha  * Check if the requested addr and size spans more than any slot in the
1733379daf62SSuresh Siddha  * iomem resource tree.
1734379daf62SSuresh Siddha  */
iomem_map_sanity_check(resource_size_t addr,unsigned long size)1735379daf62SSuresh Siddha int iomem_map_sanity_check(resource_size_t addr, unsigned long size)
1736379daf62SSuresh Siddha {
17372a4e6285SAndy Shevchenko 	resource_size_t end = addr + size - 1;
1738441f0dd8SAndy Shevchenko 	struct resource *p;
1739379daf62SSuresh Siddha 	int err = 0;
1740379daf62SSuresh Siddha 
1741379daf62SSuresh Siddha 	read_lock(&resource_lock);
1742441f0dd8SAndy Shevchenko 	for_each_resource(&iomem_resource, p, false) {
1743379daf62SSuresh Siddha 		/*
1744379daf62SSuresh Siddha 		 * We can probably skip the resources without
1745379daf62SSuresh Siddha 		 * IORESOURCE_IO attribute?
1746379daf62SSuresh Siddha 		 */
17472a4e6285SAndy Shevchenko 		if (p->start > end)
1748379daf62SSuresh Siddha 			continue;
1749379daf62SSuresh Siddha 		if (p->end < addr)
1750379daf62SSuresh Siddha 			continue;
1751d68612b2SSuresh Siddha 		if (PFN_DOWN(p->start) <= PFN_DOWN(addr) &&
17522a4e6285SAndy Shevchenko 		    PFN_DOWN(p->end) >= PFN_DOWN(end))
1753379daf62SSuresh Siddha 			continue;
17543ac52669SArjan van de Ven 		/*
17553ac52669SArjan van de Ven 		 * if a resource is "BUSY", it's not a hardware resource
17563ac52669SArjan van de Ven 		 * but a driver mapping of such a resource; we don't want
17573ac52669SArjan van de Ven 		 * to warn for those; some drivers legitimately map only
17583ac52669SArjan van de Ven 		 * partial hardware resources. (example: vesafb)
17593ac52669SArjan van de Ven 		 */
17603ac52669SArjan van de Ven 		if (p->flags & IORESOURCE_BUSY)
17613ac52669SArjan van de Ven 			continue;
17623ac52669SArjan van de Ven 
17632a4e6285SAndy Shevchenko 		pr_warn("resource sanity check: requesting [mem %pa-%pa], which spans more than %s %pR\n",
17642a4e6285SAndy Shevchenko 			&addr, &end, p->name, p);
1765379daf62SSuresh Siddha 		err = -1;
1766379daf62SSuresh Siddha 		break;
1767379daf62SSuresh Siddha 	}
1768379daf62SSuresh Siddha 	read_unlock(&resource_lock);
1769379daf62SSuresh Siddha 
1770379daf62SSuresh Siddha 	return err;
1771379daf62SSuresh Siddha }
1772e8de1481SArjan van de Ven 
1773e8de1481SArjan van de Ven #ifdef CONFIG_STRICT_DEVMEM
1774e8de1481SArjan van de Ven static int strict_iomem_checks = 1;
1775e8de1481SArjan van de Ven #else
1776e8de1481SArjan van de Ven static int strict_iomem_checks;
1777e8de1481SArjan van de Ven #endif
1778e8de1481SArjan van de Ven 
1779e8de1481SArjan van de Ven /*
1780a9e7b8d4SDavid Hildenbrand  * Check if an address is exclusive to the kernel and must not be mapped to
1781a9e7b8d4SDavid Hildenbrand  * user space, for example, via /dev/mem.
1782a9e7b8d4SDavid Hildenbrand  *
1783a9e7b8d4SDavid Hildenbrand  * Returns true if exclusive to the kernel, otherwise returns false.
1784e8de1481SArjan van de Ven  */
resource_is_exclusive(struct resource * root,u64 addr,resource_size_t size)178527829479SIra Weiny bool resource_is_exclusive(struct resource *root, u64 addr, resource_size_t size)
1786e8de1481SArjan van de Ven {
1787a9e7b8d4SDavid Hildenbrand 	const unsigned int exclusive_system_ram = IORESOURCE_SYSTEM_RAM |
1788a9e7b8d4SDavid Hildenbrand 						  IORESOURCE_EXCLUSIVE;
1789b78dfa05SDavid Hildenbrand 	bool skip_children = false, err = false;
1790b78dfa05SDavid Hildenbrand 	struct resource *p;
1791e8de1481SArjan van de Ven 
1792e8de1481SArjan van de Ven 	read_lock(&resource_lock);
179327829479SIra Weiny 	for_each_resource(root, p, skip_children) {
1794e8de1481SArjan van de Ven 		if (p->start >= addr + size)
1795e8de1481SArjan van de Ven 			break;
1796b78dfa05SDavid Hildenbrand 		if (p->end < addr) {
1797b78dfa05SDavid Hildenbrand 			skip_children = true;
1798e8de1481SArjan van de Ven 			continue;
1799b78dfa05SDavid Hildenbrand 		}
1800b78dfa05SDavid Hildenbrand 		skip_children = false;
1801b78dfa05SDavid Hildenbrand 
180290a545e9SDan Williams 		/*
1803a9e7b8d4SDavid Hildenbrand 		 * IORESOURCE_SYSTEM_RAM resources are exclusive if
1804a9e7b8d4SDavid Hildenbrand 		 * IORESOURCE_EXCLUSIVE is set, even if they
1805a9e7b8d4SDavid Hildenbrand 		 * are not busy and even if "iomem=relaxed" is set. The
1806a9e7b8d4SDavid Hildenbrand 		 * responsible driver dynamically adds/removes system RAM within
1807a9e7b8d4SDavid Hildenbrand 		 * such an area and uncontrolled access is dangerous.
1808a9e7b8d4SDavid Hildenbrand 		 */
1809a9e7b8d4SDavid Hildenbrand 		if ((p->flags & exclusive_system_ram) == exclusive_system_ram) {
1810a9e7b8d4SDavid Hildenbrand 			err = true;
1811a9e7b8d4SDavid Hildenbrand 			break;
1812a9e7b8d4SDavid Hildenbrand 		}
1813a9e7b8d4SDavid Hildenbrand 
1814a9e7b8d4SDavid Hildenbrand 		/*
181590a545e9SDan Williams 		 * A resource is exclusive if IORESOURCE_EXCLUSIVE is set
181690a545e9SDan Williams 		 * or CONFIG_IO_STRICT_DEVMEM is enabled and the
181790a545e9SDan Williams 		 * resource is busy.
181890a545e9SDan Williams 		 */
1819a9e7b8d4SDavid Hildenbrand 		if (!strict_iomem_checks || !(p->flags & IORESOURCE_BUSY))
182090a545e9SDan Williams 			continue;
182190a545e9SDan Williams 		if (IS_ENABLED(CONFIG_IO_STRICT_DEVMEM)
182290a545e9SDan Williams 				|| p->flags & IORESOURCE_EXCLUSIVE) {
18239825b451SYaowei Bai 			err = true;
1824e8de1481SArjan van de Ven 			break;
1825e8de1481SArjan van de Ven 		}
1826e8de1481SArjan van de Ven 	}
1827e8de1481SArjan van de Ven 	read_unlock(&resource_lock);
1828e8de1481SArjan van de Ven 
1829e8de1481SArjan van de Ven 	return err;
1830e8de1481SArjan van de Ven }
1831e8de1481SArjan van de Ven 
iomem_is_exclusive(u64 addr)183227829479SIra Weiny bool iomem_is_exclusive(u64 addr)
183327829479SIra Weiny {
183427829479SIra Weiny 	return resource_is_exclusive(&iomem_resource, addr & PAGE_MASK,
183527829479SIra Weiny 				     PAGE_SIZE);
183627829479SIra Weiny }
183727829479SIra Weiny 
resource_list_create_entry(struct resource * res,size_t extra_size)183890e97820SJiang Liu struct resource_entry *resource_list_create_entry(struct resource *res,
183990e97820SJiang Liu 						  size_t extra_size)
184090e97820SJiang Liu {
184190e97820SJiang Liu 	struct resource_entry *entry;
184290e97820SJiang Liu 
184390e97820SJiang Liu 	entry = kzalloc(sizeof(*entry) + extra_size, GFP_KERNEL);
184490e97820SJiang Liu 	if (entry) {
184590e97820SJiang Liu 		INIT_LIST_HEAD(&entry->node);
184690e97820SJiang Liu 		entry->res = res ? res : &entry->__res;
184790e97820SJiang Liu 	}
184890e97820SJiang Liu 
184990e97820SJiang Liu 	return entry;
185090e97820SJiang Liu }
185190e97820SJiang Liu EXPORT_SYMBOL(resource_list_create_entry);
185290e97820SJiang Liu 
resource_list_free(struct list_head * head)185390e97820SJiang Liu void resource_list_free(struct list_head *head)
185490e97820SJiang Liu {
185590e97820SJiang Liu 	struct resource_entry *entry, *tmp;
185690e97820SJiang Liu 
185790e97820SJiang Liu 	list_for_each_entry_safe(entry, tmp, head, node)
185890e97820SJiang Liu 		resource_list_destroy_entry(entry);
185990e97820SJiang Liu }
186090e97820SJiang Liu EXPORT_SYMBOL(resource_list_free);
186190e97820SJiang Liu 
186214b80582SDan Williams #ifdef CONFIG_GET_FREE_REGION
186314b80582SDan Williams #define GFR_DESCENDING		(1UL << 0)
186414b80582SDan Williams #define GFR_REQUEST_REGION	(1UL << 1)
186599185c10SHuang Ying #ifdef PA_SECTION_SHIFT
186614b80582SDan Williams #define GFR_DEFAULT_ALIGN	(1UL << PA_SECTION_SHIFT)
186799185c10SHuang Ying #else
186899185c10SHuang Ying #define GFR_DEFAULT_ALIGN	PAGE_SIZE
186999185c10SHuang Ying #endif
187014b80582SDan Williams 
gfr_start(struct resource * base,resource_size_t size,resource_size_t align,unsigned long flags)187114b80582SDan Williams static resource_size_t gfr_start(struct resource *base, resource_size_t size,
187214b80582SDan Williams 				 resource_size_t align, unsigned long flags)
18730c385190SChristoph Hellwig {
187414b80582SDan Williams 	if (flags & GFR_DESCENDING) {
187514b80582SDan Williams 		resource_size_t end;
187614b80582SDan Williams 
1877afe789b7SJohn Hubbard 		end = min_t(resource_size_t, base->end, DIRECT_MAP_PHYSMEM_END);
187814b80582SDan Williams 		return end - size + 1;
187914b80582SDan Williams 	}
188014b80582SDan Williams 
1881bacf9c3cSHuang Ying 	return ALIGN(max(base->start, align), align);
188214b80582SDan Williams }
188314b80582SDan Williams 
gfr_continue(struct resource * base,resource_size_t addr,resource_size_t size,unsigned long flags)188414b80582SDan Williams static bool gfr_continue(struct resource *base, resource_size_t addr,
188514b80582SDan Williams 			 resource_size_t size, unsigned long flags)
188614b80582SDan Williams {
188714b80582SDan Williams 	if (flags & GFR_DESCENDING)
188814b80582SDan Williams 		return addr > size && addr >= base->start;
188914b80582SDan Williams 	/*
189014b80582SDan Williams 	 * In the ascend case be careful that the last increment by
189114b80582SDan Williams 	 * @size did not wrap 0.
189214b80582SDan Williams 	 */
189314b80582SDan Williams 	return addr > addr - size &&
1894afe789b7SJohn Hubbard 	       addr <= min_t(resource_size_t, base->end, DIRECT_MAP_PHYSMEM_END);
189514b80582SDan Williams }
189614b80582SDan Williams 
gfr_next(resource_size_t addr,resource_size_t size,unsigned long flags)189714b80582SDan Williams static resource_size_t gfr_next(resource_size_t addr, resource_size_t size,
189814b80582SDan Williams 				unsigned long flags)
189914b80582SDan Williams {
190014b80582SDan Williams 	if (flags & GFR_DESCENDING)
190114b80582SDan Williams 		return addr - size;
190214b80582SDan Williams 	return addr + size;
190314b80582SDan Williams }
190414b80582SDan Williams 
remove_free_mem_region(void * _res)190514b80582SDan Williams static void remove_free_mem_region(void *_res)
190614b80582SDan Williams {
190714b80582SDan Williams 	struct resource *res = _res;
190814b80582SDan Williams 
190914b80582SDan Williams 	if (res->parent)
191014b80582SDan Williams 		remove_resource(res);
191114b80582SDan Williams 	free_resource(res);
191214b80582SDan Williams }
191314b80582SDan Williams 
191414b80582SDan Williams static struct resource *
get_free_mem_region(struct device * dev,struct resource * base,resource_size_t size,const unsigned long align,const char * name,const unsigned long desc,const unsigned long flags)191514b80582SDan Williams get_free_mem_region(struct device *dev, struct resource *base,
191614b80582SDan Williams 		    resource_size_t size, const unsigned long align,
191714b80582SDan Williams 		    const char *name, const unsigned long desc,
191814b80582SDan Williams 		    const unsigned long flags)
191914b80582SDan Williams {
192014b80582SDan Williams 	resource_size_t addr;
19210c385190SChristoph Hellwig 	struct resource *res;
192256fd9491SAlistair Popple 	struct region_devres *dr = NULL;
19230c385190SChristoph Hellwig 
192414b80582SDan Williams 	size = ALIGN(size, align);
19250c385190SChristoph Hellwig 
192656fd9491SAlistair Popple 	res = alloc_resource(GFP_KERNEL);
192756fd9491SAlistair Popple 	if (!res)
192856fd9491SAlistair Popple 		return ERR_PTR(-ENOMEM);
192956fd9491SAlistair Popple 
193014b80582SDan Williams 	if (dev && (flags & GFR_REQUEST_REGION)) {
193156fd9491SAlistair Popple 		dr = devres_alloc(devm_region_release,
193256fd9491SAlistair Popple 				sizeof(struct region_devres), GFP_KERNEL);
193356fd9491SAlistair Popple 		if (!dr) {
193456fd9491SAlistair Popple 			free_resource(res);
193556fd9491SAlistair Popple 			return ERR_PTR(-ENOMEM);
193656fd9491SAlistair Popple 		}
193714b80582SDan Williams 	} else if (dev) {
193814b80582SDan Williams 		if (devm_add_action_or_reset(dev, remove_free_mem_region, res))
193914b80582SDan Williams 			return ERR_PTR(-ENOMEM);
194056fd9491SAlistair Popple 	}
194156fd9491SAlistair Popple 
194256fd9491SAlistair Popple 	write_lock(&resource_lock);
194314b80582SDan Williams 	for (addr = gfr_start(base, size, align, flags);
1944659aa050SAlison Schofield 	     gfr_continue(base, addr, align, flags);
1945659aa050SAlison Schofield 	     addr = gfr_next(addr, align, flags)) {
194614b80582SDan Williams 		if (__region_intersects(base, addr, size, 0, IORES_DESC_NONE) !=
19470c385190SChristoph Hellwig 		    REGION_DISJOINT)
19480c385190SChristoph Hellwig 			continue;
19490c385190SChristoph Hellwig 
195014b80582SDan Williams 		if (flags & GFR_REQUEST_REGION) {
195114b80582SDan Williams 			if (__request_region_locked(res, &iomem_resource, addr,
195214b80582SDan Williams 						    size, name, 0))
195356fd9491SAlistair Popple 				break;
195456fd9491SAlistair Popple 
195556fd9491SAlistair Popple 			if (dev) {
195656fd9491SAlistair Popple 				dr->parent = &iomem_resource;
195756fd9491SAlistair Popple 				dr->start = addr;
195856fd9491SAlistair Popple 				dr->n = size;
195956fd9491SAlistair Popple 				devres_add(dev, dr);
196056fd9491SAlistair Popple 			}
196156fd9491SAlistair Popple 
196214b80582SDan Williams 			res->desc = desc;
196356fd9491SAlistair Popple 			write_unlock(&resource_lock);
196456fd9491SAlistair Popple 
196514b80582SDan Williams 
196656fd9491SAlistair Popple 			/*
196714b80582SDan Williams 			 * A driver is claiming this region so revoke any
196814b80582SDan Williams 			 * mappings.
196956fd9491SAlistair Popple 			 */
197056fd9491SAlistair Popple 			revoke_iomem(res);
197114b80582SDan Williams 		} else {
197276709e0aSAndy Shevchenko 			*res = DEFINE_RES_NAMED_DESC(addr, size, name, IORESOURCE_MEM, desc);
197314b80582SDan Williams 
197414b80582SDan Williams 			/*
197514b80582SDan Williams 			 * Only succeed if the resource hosts an exclusive
197614b80582SDan Williams 			 * range after the insert
197714b80582SDan Williams 			 */
197814b80582SDan Williams 			if (__insert_resource(base, res) || res->child)
197914b80582SDan Williams 				break;
198014b80582SDan Williams 
198114b80582SDan Williams 			write_unlock(&resource_lock);
198214b80582SDan Williams 		}
198314b80582SDan Williams 
19840c385190SChristoph Hellwig 		return res;
19850c385190SChristoph Hellwig 	}
198656fd9491SAlistair Popple 	write_unlock(&resource_lock);
198756fd9491SAlistair Popple 
198814b80582SDan Williams 	if (flags & GFR_REQUEST_REGION) {
198956fd9491SAlistair Popple 		free_resource(res);
199056fd9491SAlistair Popple 		devres_free(dr);
199114b80582SDan Williams 	} else if (dev)
199214b80582SDan Williams 		devm_release_action(dev, remove_free_mem_region, res);
19930c385190SChristoph Hellwig 
19940c385190SChristoph Hellwig 	return ERR_PTR(-ERANGE);
19950c385190SChristoph Hellwig }
19960c385190SChristoph Hellwig 
19970092908dSChristoph Hellwig /**
19980092908dSChristoph Hellwig  * devm_request_free_mem_region - find free region for device private memory
19990092908dSChristoph Hellwig  *
20000092908dSChristoph Hellwig  * @dev: device struct to bind the resource to
20010092908dSChristoph Hellwig  * @size: size in bytes of the device memory to add
20020092908dSChristoph Hellwig  * @base: resource tree to look in
20030092908dSChristoph Hellwig  *
20040092908dSChristoph Hellwig  * This function tries to find an empty range of physical address big enough to
20050092908dSChristoph Hellwig  * contain the new resource, so that it can later be hotplugged as ZONE_DEVICE
20060092908dSChristoph Hellwig  * memory, which in turn allocates struct pages.
20070092908dSChristoph Hellwig  */
devm_request_free_mem_region(struct device * dev,struct resource * base,unsigned long size)20080092908dSChristoph Hellwig struct resource *devm_request_free_mem_region(struct device *dev,
20090092908dSChristoph Hellwig 		struct resource *base, unsigned long size)
20100092908dSChristoph Hellwig {
201114b80582SDan Williams 	unsigned long flags = GFR_DESCENDING | GFR_REQUEST_REGION;
201214b80582SDan Williams 
201314b80582SDan Williams 	return get_free_mem_region(dev, base, size, GFR_DEFAULT_ALIGN,
201414b80582SDan Williams 				   dev_name(dev),
201514b80582SDan Williams 				   IORES_DESC_DEVICE_PRIVATE_MEMORY, flags);
20160092908dSChristoph Hellwig }
20170092908dSChristoph Hellwig EXPORT_SYMBOL_GPL(devm_request_free_mem_region);
20180c385190SChristoph Hellwig 
request_free_mem_region(struct resource * base,unsigned long size,const char * name)20190c385190SChristoph Hellwig struct resource *request_free_mem_region(struct resource *base,
20200c385190SChristoph Hellwig 		unsigned long size, const char *name)
20210c385190SChristoph Hellwig {
202214b80582SDan Williams 	unsigned long flags = GFR_DESCENDING | GFR_REQUEST_REGION;
202314b80582SDan Williams 
202414b80582SDan Williams 	return get_free_mem_region(NULL, base, size, GFR_DEFAULT_ALIGN, name,
202514b80582SDan Williams 				   IORES_DESC_DEVICE_PRIVATE_MEMORY, flags);
20260c385190SChristoph Hellwig }
20270c385190SChristoph Hellwig EXPORT_SYMBOL_GPL(request_free_mem_region);
20280c385190SChristoph Hellwig 
202914b80582SDan Williams /**
203014b80582SDan Williams  * alloc_free_mem_region - find a free region relative to @base
203114b80582SDan Williams  * @base: resource that will parent the new resource
203214b80582SDan Williams  * @size: size in bytes of memory to allocate from @base
203314b80582SDan Williams  * @align: alignment requirements for the allocation
203414b80582SDan Williams  * @name: resource name
203514b80582SDan Williams  *
203614b80582SDan Williams  * Buses like CXL, that can dynamically instantiate new memory regions,
203714b80582SDan Williams  * need a method to allocate physical address space for those regions.
203814b80582SDan Williams  * Allocate and insert a new resource to cover a free, unclaimed by a
203914b80582SDan Williams  * descendant of @base, range in the span of @base.
204014b80582SDan Williams  */
alloc_free_mem_region(struct resource * base,unsigned long size,unsigned long align,const char * name)204114b80582SDan Williams struct resource *alloc_free_mem_region(struct resource *base,
204214b80582SDan Williams 				       unsigned long size, unsigned long align,
204314b80582SDan Williams 				       const char *name)
204414b80582SDan Williams {
204514b80582SDan Williams 	/* Default of ascending direction and insert resource */
204614b80582SDan Williams 	unsigned long flags = 0;
204714b80582SDan Williams 
204814b80582SDan Williams 	return get_free_mem_region(NULL, base, size, align, name,
204914b80582SDan Williams 				   IORES_DESC_NONE, flags);
205014b80582SDan Williams }
205199185c10SHuang Ying EXPORT_SYMBOL_GPL(alloc_free_mem_region);
205214b80582SDan Williams #endif /* CONFIG_GET_FREE_REGION */
20530092908dSChristoph Hellwig 
strict_iomem(char * str)2054e8de1481SArjan van de Ven static int __init strict_iomem(char *str)
2055e8de1481SArjan van de Ven {
2056e8de1481SArjan van de Ven 	if (strstr(str, "relaxed"))
2057e8de1481SArjan van de Ven 		strict_iomem_checks = 0;
2058e8de1481SArjan van de Ven 	if (strstr(str, "strict"))
2059e8de1481SArjan van de Ven 		strict_iomem_checks = 1;
2060e8de1481SArjan van de Ven 	return 1;
2061e8de1481SArjan van de Ven }
2062e8de1481SArjan van de Ven 
iomem_fs_init_fs_context(struct fs_context * fc)206371a1d8edSDaniel Vetter static int iomem_fs_init_fs_context(struct fs_context *fc)
206471a1d8edSDaniel Vetter {
206571a1d8edSDaniel Vetter 	return init_pseudo(fc, DEVMEM_MAGIC) ? 0 : -ENOMEM;
206671a1d8edSDaniel Vetter }
206771a1d8edSDaniel Vetter 
206871a1d8edSDaniel Vetter static struct file_system_type iomem_fs_type = {
206971a1d8edSDaniel Vetter 	.name		= "iomem",
207071a1d8edSDaniel Vetter 	.owner		= THIS_MODULE,
207171a1d8edSDaniel Vetter 	.init_fs_context = iomem_fs_init_fs_context,
207271a1d8edSDaniel Vetter 	.kill_sb	= kill_anon_super,
207371a1d8edSDaniel Vetter };
207471a1d8edSDaniel Vetter 
iomem_init_inode(void)207571a1d8edSDaniel Vetter static int __init iomem_init_inode(void)
207671a1d8edSDaniel Vetter {
207771a1d8edSDaniel Vetter 	static struct vfsmount *iomem_vfs_mount;
207871a1d8edSDaniel Vetter 	static int iomem_fs_cnt;
207971a1d8edSDaniel Vetter 	struct inode *inode;
208071a1d8edSDaniel Vetter 	int rc;
208171a1d8edSDaniel Vetter 
208271a1d8edSDaniel Vetter 	rc = simple_pin_fs(&iomem_fs_type, &iomem_vfs_mount, &iomem_fs_cnt);
208371a1d8edSDaniel Vetter 	if (rc < 0) {
208471a1d8edSDaniel Vetter 		pr_err("Cannot mount iomem pseudo filesystem: %d\n", rc);
208571a1d8edSDaniel Vetter 		return rc;
208671a1d8edSDaniel Vetter 	}
208771a1d8edSDaniel Vetter 
208871a1d8edSDaniel Vetter 	inode = alloc_anon_inode(iomem_vfs_mount->mnt_sb);
208971a1d8edSDaniel Vetter 	if (IS_ERR(inode)) {
209071a1d8edSDaniel Vetter 		rc = PTR_ERR(inode);
209171a1d8edSDaniel Vetter 		pr_err("Cannot allocate inode for iomem: %d\n", rc);
209271a1d8edSDaniel Vetter 		simple_release_fs(&iomem_vfs_mount, &iomem_fs_cnt);
209371a1d8edSDaniel Vetter 		return rc;
209471a1d8edSDaniel Vetter 	}
209571a1d8edSDaniel Vetter 
209671a1d8edSDaniel Vetter 	/*
209771a1d8edSDaniel Vetter 	 * Publish iomem revocation inode initialized.
209871a1d8edSDaniel Vetter 	 * Pairs with smp_load_acquire() in revoke_iomem().
209971a1d8edSDaniel Vetter 	 */
210071a1d8edSDaniel Vetter 	smp_store_release(&iomem_inode, inode);
210171a1d8edSDaniel Vetter 
210271a1d8edSDaniel Vetter 	return 0;
210371a1d8edSDaniel Vetter }
210471a1d8edSDaniel Vetter 
210571a1d8edSDaniel Vetter fs_initcall(iomem_init_inode);
210671a1d8edSDaniel Vetter 
2107e8de1481SArjan van de Ven __setup("iomem=", strict_iomem);
2108