Revert "Bluetooth: Store advertising handle so it can be re-enabled"
[platform/kernel/linux-rpi.git] / kernel / resource.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *      linux/kernel/resource.c
4  *
5  * Copyright (C) 1999   Linus Torvalds
6  * Copyright (C) 1999   Martin Mares <mj@ucw.cz>
7  *
8  * Arbitrary resource management.
9  */
10
11 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
12
13 #include <linux/export.h>
14 #include <linux/errno.h>
15 #include <linux/ioport.h>
16 #include <linux/init.h>
17 #include <linux/slab.h>
18 #include <linux/spinlock.h>
19 #include <linux/fs.h>
20 #include <linux/proc_fs.h>
21 #include <linux/pseudo_fs.h>
22 #include <linux/sched.h>
23 #include <linux/seq_file.h>
24 #include <linux/device.h>
25 #include <linux/pfn.h>
26 #include <linux/mm.h>
27 #include <linux/mount.h>
28 #include <linux/resource_ext.h>
29 #include <uapi/linux/magic.h>
30 #include <asm/io.h>
31
32
33 struct resource ioport_resource = {
34         .name   = "PCI IO",
35         .start  = 0,
36         .end    = IO_SPACE_LIMIT,
37         .flags  = IORESOURCE_IO,
38 };
39 EXPORT_SYMBOL(ioport_resource);
40
41 struct resource iomem_resource = {
42         .name   = "PCI mem",
43         .start  = 0,
44         .end    = -1,
45         .flags  = IORESOURCE_MEM,
46 };
47 EXPORT_SYMBOL(iomem_resource);
48
49 /* constraints to be met while allocating resources */
50 struct resource_constraint {
51         resource_size_t min, max, align;
52         resource_size_t (*alignf)(void *, const struct resource *,
53                         resource_size_t, resource_size_t);
54         void *alignf_data;
55 };
56
57 static DEFINE_RWLOCK(resource_lock);
58
59 static struct resource *next_resource(struct resource *p)
60 {
61         if (p->child)
62                 return p->child;
63         while (!p->sibling && p->parent)
64                 p = p->parent;
65         return p->sibling;
66 }
67
68 static struct resource *next_resource_skip_children(struct resource *p)
69 {
70         while (!p->sibling && p->parent)
71                 p = p->parent;
72         return p->sibling;
73 }
74
75 #define for_each_resource(_root, _p, _skip_children) \
76         for ((_p) = (_root)->child; (_p); \
77              (_p) = (_skip_children) ? next_resource_skip_children(_p) : \
78                                        next_resource(_p))
79
80 static void *r_next(struct seq_file *m, void *v, loff_t *pos)
81 {
82         struct resource *p = v;
83         (*pos)++;
84         return (void *)next_resource(p);
85 }
86
87 #ifdef CONFIG_PROC_FS
88
89 enum { MAX_IORES_LEVEL = 5 };
90
91 static void *r_start(struct seq_file *m, loff_t *pos)
92         __acquires(resource_lock)
93 {
94         struct resource *p = pde_data(file_inode(m->file));
95         loff_t l = 0;
96         read_lock(&resource_lock);
97         for (p = p->child; p && l < *pos; p = r_next(m, p, &l))
98                 ;
99         return p;
100 }
101
102 static void r_stop(struct seq_file *m, void *v)
103         __releases(resource_lock)
104 {
105         read_unlock(&resource_lock);
106 }
107
108 static int r_show(struct seq_file *m, void *v)
109 {
110         struct resource *root = pde_data(file_inode(m->file));
111         struct resource *r = v, *p;
112         unsigned long long start, end;
113         int width = root->end < 0x10000 ? 4 : 8;
114         int depth;
115
116         for (depth = 0, p = r; depth < MAX_IORES_LEVEL; depth++, p = p->parent)
117                 if (p->parent == root)
118                         break;
119
120         if (file_ns_capable(m->file, &init_user_ns, CAP_SYS_ADMIN)) {
121                 start = r->start;
122                 end = r->end;
123         } else {
124                 start = end = 0;
125         }
126
127         seq_printf(m, "%*s%0*llx-%0*llx : %s\n",
128                         depth * 2, "",
129                         width, start,
130                         width, end,
131                         r->name ? r->name : "<BAD>");
132         return 0;
133 }
134
135 static const struct seq_operations resource_op = {
136         .start  = r_start,
137         .next   = r_next,
138         .stop   = r_stop,
139         .show   = r_show,
140 };
141
142 static int __init ioresources_init(void)
143 {
144         proc_create_seq_data("ioports", 0, NULL, &resource_op,
145                         &ioport_resource);
146         proc_create_seq_data("iomem", 0, NULL, &resource_op, &iomem_resource);
147         return 0;
148 }
149 __initcall(ioresources_init);
150
151 #endif /* CONFIG_PROC_FS */
152
153 static void free_resource(struct resource *res)
154 {
155         /**
156          * If the resource was allocated using memblock early during boot
157          * we'll leak it here: we can only return full pages back to the
158          * buddy and trying to be smart and reusing them eventually in
159          * alloc_resource() overcomplicates resource handling.
160          */
161         if (res && PageSlab(virt_to_head_page(res)))
162                 kfree(res);
163 }
164
165 static struct resource *alloc_resource(gfp_t flags)
166 {
167         return kzalloc(sizeof(struct resource), flags);
168 }
169
170 /* Return the conflict entry if you can't request it */
171 static struct resource * __request_resource(struct resource *root, struct resource *new)
172 {
173         resource_size_t start = new->start;
174         resource_size_t end = new->end;
175         struct resource *tmp, **p;
176
177         if (end < start)
178                 return root;
179         if (start < root->start)
180                 return root;
181         if (end > root->end)
182                 return root;
183         p = &root->child;
184         for (;;) {
185                 tmp = *p;
186                 if (!tmp || tmp->start > end) {
187                         new->sibling = tmp;
188                         *p = new;
189                         new->parent = root;
190                         return NULL;
191                 }
192                 p = &tmp->sibling;
193                 if (tmp->end < start)
194                         continue;
195                 return tmp;
196         }
197 }
198
199 static int __release_resource(struct resource *old, bool release_child)
200 {
201         struct resource *tmp, **p, *chd;
202
203         if (!old->parent) {
204                 WARN(old->sibling, "sibling but no parent");
205                 if (old->sibling)
206                         return -EINVAL;
207                 return 0;
208         }
209         p = &old->parent->child;
210         for (;;) {
211                 tmp = *p;
212                 if (!tmp)
213                         break;
214                 if (tmp == old) {
215                         if (release_child || !(tmp->child)) {
216                                 *p = tmp->sibling;
217                         } else {
218                                 for (chd = tmp->child;; chd = chd->sibling) {
219                                         chd->parent = tmp->parent;
220                                         if (!(chd->sibling))
221                                                 break;
222                                 }
223                                 *p = tmp->child;
224                                 chd->sibling = tmp->sibling;
225                         }
226                         old->parent = NULL;
227                         return 0;
228                 }
229                 p = &tmp->sibling;
230         }
231         return -EINVAL;
232 }
233
234 static void __release_child_resources(struct resource *r)
235 {
236         struct resource *tmp, *p;
237         resource_size_t size;
238
239         p = r->child;
240         r->child = NULL;
241         while (p) {
242                 tmp = p;
243                 p = p->sibling;
244
245                 tmp->parent = NULL;
246                 tmp->sibling = NULL;
247                 __release_child_resources(tmp);
248
249                 printk(KERN_DEBUG "release child resource %pR\n", tmp);
250                 /* need to restore size, and keep flags */
251                 size = resource_size(tmp);
252                 tmp->start = 0;
253                 tmp->end = size - 1;
254         }
255 }
256
257 void release_child_resources(struct resource *r)
258 {
259         write_lock(&resource_lock);
260         __release_child_resources(r);
261         write_unlock(&resource_lock);
262 }
263
264 /**
265  * request_resource_conflict - request and reserve an I/O or memory resource
266  * @root: root resource descriptor
267  * @new: resource descriptor desired by caller
268  *
269  * Returns 0 for success, conflict resource on error.
270  */
271 struct resource *request_resource_conflict(struct resource *root, struct resource *new)
272 {
273         struct resource *conflict;
274
275         write_lock(&resource_lock);
276         conflict = __request_resource(root, new);
277         write_unlock(&resource_lock);
278         return conflict;
279 }
280
281 /**
282  * request_resource - request and reserve an I/O or memory resource
283  * @root: root resource descriptor
284  * @new: resource descriptor desired by caller
285  *
286  * Returns 0 for success, negative error code on error.
287  */
288 int request_resource(struct resource *root, struct resource *new)
289 {
290         struct resource *conflict;
291
292         conflict = request_resource_conflict(root, new);
293         return conflict ? -EBUSY : 0;
294 }
295
296 EXPORT_SYMBOL(request_resource);
297
298 /**
299  * release_resource - release a previously reserved resource
300  * @old: resource pointer
301  */
302 int release_resource(struct resource *old)
303 {
304         int retval;
305
306         write_lock(&resource_lock);
307         retval = __release_resource(old, true);
308         write_unlock(&resource_lock);
309         return retval;
310 }
311
312 EXPORT_SYMBOL(release_resource);
313
314 /**
315  * find_next_iomem_res - Finds the lowest iomem resource that covers part of
316  *                       [@start..@end].
317  *
318  * If a resource is found, returns 0 and @*res is overwritten with the part
319  * of the resource that's within [@start..@end]; if none is found, returns
320  * -ENODEV.  Returns -EINVAL for invalid parameters.
321  *
322  * @start:      start address of the resource searched for
323  * @end:        end address of same resource
324  * @flags:      flags which the resource must have
325  * @desc:       descriptor the resource must have
326  * @res:        return ptr, if resource found
327  *
328  * The caller must specify @start, @end, @flags, and @desc
329  * (which may be IORES_DESC_NONE).
330  */
331 static int find_next_iomem_res(resource_size_t start, resource_size_t end,
332                                unsigned long flags, unsigned long desc,
333                                struct resource *res)
334 {
335         struct resource *p;
336
337         if (!res)
338                 return -EINVAL;
339
340         if (start >= end)
341                 return -EINVAL;
342
343         read_lock(&resource_lock);
344
345         for (p = iomem_resource.child; p; p = next_resource(p)) {
346                 /* If we passed the resource we are looking for, stop */
347                 if (p->start > end) {
348                         p = NULL;
349                         break;
350                 }
351
352                 /* Skip until we find a range that matches what we look for */
353                 if (p->end < start)
354                         continue;
355
356                 if ((p->flags & flags) != flags)
357                         continue;
358                 if ((desc != IORES_DESC_NONE) && (desc != p->desc))
359                         continue;
360
361                 /* Found a match, break */
362                 break;
363         }
364
365         if (p) {
366                 /* copy data */
367                 *res = (struct resource) {
368                         .start = max(start, p->start),
369                         .end = min(end, p->end),
370                         .flags = p->flags,
371                         .desc = p->desc,
372                         .parent = p->parent,
373                 };
374         }
375
376         read_unlock(&resource_lock);
377         return p ? 0 : -ENODEV;
378 }
379
380 static int __walk_iomem_res_desc(resource_size_t start, resource_size_t end,
381                                  unsigned long flags, unsigned long desc,
382                                  void *arg,
383                                  int (*func)(struct resource *, void *))
384 {
385         struct resource res;
386         int ret = -EINVAL;
387
388         while (start < end &&
389                !find_next_iomem_res(start, end, flags, desc, &res)) {
390                 ret = (*func)(&res, arg);
391                 if (ret)
392                         break;
393
394                 start = res.end + 1;
395         }
396
397         return ret;
398 }
399
400 /**
401  * walk_iomem_res_desc - Walks through iomem resources and calls func()
402  *                       with matching resource ranges.
403  * *
404  * @desc: I/O resource descriptor. Use IORES_DESC_NONE to skip @desc check.
405  * @flags: I/O resource flags
406  * @start: start addr
407  * @end: end addr
408  * @arg: function argument for the callback @func
409  * @func: callback function that is called for each qualifying resource area
410  *
411  * All the memory ranges which overlap start,end and also match flags and
412  * desc are valid candidates.
413  *
414  * NOTE: For a new descriptor search, define a new IORES_DESC in
415  * <linux/ioport.h> and set it in 'desc' of a target resource entry.
416  */
417 int walk_iomem_res_desc(unsigned long desc, unsigned long flags, u64 start,
418                 u64 end, void *arg, int (*func)(struct resource *, void *))
419 {
420         return __walk_iomem_res_desc(start, end, flags, desc, arg, func);
421 }
422 EXPORT_SYMBOL_GPL(walk_iomem_res_desc);
423
424 /*
425  * This function calls the @func callback against all memory ranges of type
426  * System RAM which are marked as IORESOURCE_SYSTEM_RAM and IORESOUCE_BUSY.
427  * Now, this function is only for System RAM, it deals with full ranges and
428  * not PFNs. If resources are not PFN-aligned, dealing with PFNs can truncate
429  * ranges.
430  */
431 int walk_system_ram_res(u64 start, u64 end, void *arg,
432                         int (*func)(struct resource *, void *))
433 {
434         unsigned long flags = IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY;
435
436         return __walk_iomem_res_desc(start, end, flags, IORES_DESC_NONE, arg,
437                                      func);
438 }
439
440 /*
441  * This function calls the @func callback against all memory ranges, which
442  * are ranges marked as IORESOURCE_MEM and IORESOUCE_BUSY.
443  */
444 int walk_mem_res(u64 start, u64 end, void *arg,
445                  int (*func)(struct resource *, void *))
446 {
447         unsigned long flags = IORESOURCE_MEM | IORESOURCE_BUSY;
448
449         return __walk_iomem_res_desc(start, end, flags, IORES_DESC_NONE, arg,
450                                      func);
451 }
452
453 /*
454  * This function calls the @func callback against all memory ranges of type
455  * System RAM which are marked as IORESOURCE_SYSTEM_RAM and IORESOUCE_BUSY.
456  * It is to be used only for System RAM.
457  */
458 int walk_system_ram_range(unsigned long start_pfn, unsigned long nr_pages,
459                           void *arg, int (*func)(unsigned long, unsigned long, void *))
460 {
461         resource_size_t start, end;
462         unsigned long flags;
463         struct resource res;
464         unsigned long pfn, end_pfn;
465         int ret = -EINVAL;
466
467         start = (u64) start_pfn << PAGE_SHIFT;
468         end = ((u64)(start_pfn + nr_pages) << PAGE_SHIFT) - 1;
469         flags = IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY;
470         while (start < end &&
471                !find_next_iomem_res(start, end, flags, IORES_DESC_NONE, &res)) {
472                 pfn = PFN_UP(res.start);
473                 end_pfn = PFN_DOWN(res.end + 1);
474                 if (end_pfn > pfn)
475                         ret = (*func)(pfn, end_pfn - pfn, arg);
476                 if (ret)
477                         break;
478                 start = res.end + 1;
479         }
480         return ret;
481 }
482
483 static int __is_ram(unsigned long pfn, unsigned long nr_pages, void *arg)
484 {
485         return 1;
486 }
487
488 /*
489  * This generic page_is_ram() returns true if specified address is
490  * registered as System RAM in iomem_resource list.
491  */
492 int __weak page_is_ram(unsigned long pfn)
493 {
494         return walk_system_ram_range(pfn, 1, NULL, __is_ram) == 1;
495 }
496 EXPORT_SYMBOL_GPL(page_is_ram);
497
498 static int __region_intersects(struct resource *parent, resource_size_t start,
499                                size_t size, unsigned long flags,
500                                unsigned long desc)
501 {
502         struct resource res;
503         int type = 0; int other = 0;
504         struct resource *p;
505
506         res.start = start;
507         res.end = start + size - 1;
508
509         for (p = parent->child; p ; p = p->sibling) {
510                 bool is_type = (((p->flags & flags) == flags) &&
511                                 ((desc == IORES_DESC_NONE) ||
512                                  (desc == p->desc)));
513
514                 if (resource_overlaps(p, &res))
515                         is_type ? type++ : other++;
516         }
517
518         if (type == 0)
519                 return REGION_DISJOINT;
520
521         if (other == 0)
522                 return REGION_INTERSECTS;
523
524         return REGION_MIXED;
525 }
526
527 /**
528  * region_intersects() - determine intersection of region with known resources
529  * @start: region start address
530  * @size: size of region
531  * @flags: flags of resource (in iomem_resource)
532  * @desc: descriptor of resource (in iomem_resource) or IORES_DESC_NONE
533  *
534  * Check if the specified region partially overlaps or fully eclipses a
535  * resource identified by @flags and @desc (optional with IORES_DESC_NONE).
536  * Return REGION_DISJOINT if the region does not overlap @flags/@desc,
537  * return REGION_MIXED if the region overlaps @flags/@desc and another
538  * resource, and return REGION_INTERSECTS if the region overlaps @flags/@desc
539  * and no other defined resource. Note that REGION_INTERSECTS is also
540  * returned in the case when the specified region overlaps RAM and undefined
541  * memory holes.
542  *
543  * region_intersect() is used by memory remapping functions to ensure
544  * the user is not remapping RAM and is a vast speed up over walking
545  * through the resource table page by page.
546  */
547 int region_intersects(resource_size_t start, size_t size, unsigned long flags,
548                       unsigned long desc)
549 {
550         int ret;
551
552         read_lock(&resource_lock);
553         ret = __region_intersects(&iomem_resource, start, size, flags, desc);
554         read_unlock(&resource_lock);
555
556         return ret;
557 }
558 EXPORT_SYMBOL_GPL(region_intersects);
559
560 void __weak arch_remove_reservations(struct resource *avail)
561 {
562 }
563
564 static resource_size_t simple_align_resource(void *data,
565                                              const struct resource *avail,
566                                              resource_size_t size,
567                                              resource_size_t align)
568 {
569         return avail->start;
570 }
571
572 static void resource_clip(struct resource *res, resource_size_t min,
573                           resource_size_t max)
574 {
575         if (res->start < min)
576                 res->start = min;
577         if (res->end > max)
578                 res->end = max;
579 }
580
581 /*
582  * Find empty slot in the resource tree with the given range and
583  * alignment constraints
584  */
585 static int __find_resource(struct resource *root, struct resource *old,
586                          struct resource *new,
587                          resource_size_t  size,
588                          struct resource_constraint *constraint)
589 {
590         struct resource *this = root->child;
591         struct resource tmp = *new, avail, alloc;
592
593         tmp.start = root->start;
594         /*
595          * Skip past an allocated resource that starts at 0, since the assignment
596          * of this->start - 1 to tmp->end below would cause an underflow.
597          */
598         if (this && this->start == root->start) {
599                 tmp.start = (this == old) ? old->start : this->end + 1;
600                 this = this->sibling;
601         }
602         for(;;) {
603                 if (this)
604                         tmp.end = (this == old) ?  this->end : this->start - 1;
605                 else
606                         tmp.end = root->end;
607
608                 if (tmp.end < tmp.start)
609                         goto next;
610
611                 resource_clip(&tmp, constraint->min, constraint->max);
612                 arch_remove_reservations(&tmp);
613
614                 /* Check for overflow after ALIGN() */
615                 avail.start = ALIGN(tmp.start, constraint->align);
616                 avail.end = tmp.end;
617                 avail.flags = new->flags & ~IORESOURCE_UNSET;
618                 if (avail.start >= tmp.start) {
619                         alloc.flags = avail.flags;
620                         alloc.start = constraint->alignf(constraint->alignf_data, &avail,
621                                         size, constraint->align);
622                         alloc.end = alloc.start + size - 1;
623                         if (alloc.start <= alloc.end &&
624                             resource_contains(&avail, &alloc)) {
625                                 new->start = alloc.start;
626                                 new->end = alloc.end;
627                                 return 0;
628                         }
629                 }
630
631 next:           if (!this || this->end == root->end)
632                         break;
633
634                 if (this != old)
635                         tmp.start = this->end + 1;
636                 this = this->sibling;
637         }
638         return -EBUSY;
639 }
640
641 /*
642  * Find empty slot in the resource tree given range and alignment.
643  */
644 static int find_resource(struct resource *root, struct resource *new,
645                         resource_size_t size,
646                         struct resource_constraint  *constraint)
647 {
648         return  __find_resource(root, NULL, new, size, constraint);
649 }
650
651 /**
652  * reallocate_resource - allocate a slot in the resource tree given range & alignment.
653  *      The resource will be relocated if the new size cannot be reallocated in the
654  *      current location.
655  *
656  * @root: root resource descriptor
657  * @old:  resource descriptor desired by caller
658  * @newsize: new size of the resource descriptor
659  * @constraint: the size and alignment constraints to be met.
660  */
661 static int reallocate_resource(struct resource *root, struct resource *old,
662                                resource_size_t newsize,
663                                struct resource_constraint *constraint)
664 {
665         int err=0;
666         struct resource new = *old;
667         struct resource *conflict;
668
669         write_lock(&resource_lock);
670
671         if ((err = __find_resource(root, old, &new, newsize, constraint)))
672                 goto out;
673
674         if (resource_contains(&new, old)) {
675                 old->start = new.start;
676                 old->end = new.end;
677                 goto out;
678         }
679
680         if (old->child) {
681                 err = -EBUSY;
682                 goto out;
683         }
684
685         if (resource_contains(old, &new)) {
686                 old->start = new.start;
687                 old->end = new.end;
688         } else {
689                 __release_resource(old, true);
690                 *old = new;
691                 conflict = __request_resource(root, old);
692                 BUG_ON(conflict);
693         }
694 out:
695         write_unlock(&resource_lock);
696         return err;
697 }
698
699
700 /**
701  * allocate_resource - allocate empty slot in the resource tree given range & alignment.
702  *      The resource will be reallocated with a new size if it was already allocated
703  * @root: root resource descriptor
704  * @new: resource descriptor desired by caller
705  * @size: requested resource region size
706  * @min: minimum boundary to allocate
707  * @max: maximum boundary to allocate
708  * @align: alignment requested, in bytes
709  * @alignf: alignment function, optional, called if not NULL
710  * @alignf_data: arbitrary data to pass to the @alignf function
711  */
712 int allocate_resource(struct resource *root, struct resource *new,
713                       resource_size_t size, resource_size_t min,
714                       resource_size_t max, resource_size_t align,
715                       resource_size_t (*alignf)(void *,
716                                                 const struct resource *,
717                                                 resource_size_t,
718                                                 resource_size_t),
719                       void *alignf_data)
720 {
721         int err;
722         struct resource_constraint constraint;
723
724         if (!alignf)
725                 alignf = simple_align_resource;
726
727         constraint.min = min;
728         constraint.max = max;
729         constraint.align = align;
730         constraint.alignf = alignf;
731         constraint.alignf_data = alignf_data;
732
733         if ( new->parent ) {
734                 /* resource is already allocated, try reallocating with
735                    the new constraints */
736                 return reallocate_resource(root, new, size, &constraint);
737         }
738
739         write_lock(&resource_lock);
740         err = find_resource(root, new, size, &constraint);
741         if (err >= 0 && __request_resource(root, new))
742                 err = -EBUSY;
743         write_unlock(&resource_lock);
744         return err;
745 }
746
747 EXPORT_SYMBOL(allocate_resource);
748
749 /**
750  * lookup_resource - find an existing resource by a resource start address
751  * @root: root resource descriptor
752  * @start: resource start address
753  *
754  * Returns a pointer to the resource if found, NULL otherwise
755  */
756 struct resource *lookup_resource(struct resource *root, resource_size_t start)
757 {
758         struct resource *res;
759
760         read_lock(&resource_lock);
761         for (res = root->child; res; res = res->sibling) {
762                 if (res->start == start)
763                         break;
764         }
765         read_unlock(&resource_lock);
766
767         return res;
768 }
769
770 /*
771  * Insert a resource into the resource tree. If successful, return NULL,
772  * otherwise return the conflicting resource (compare to __request_resource())
773  */
774 static struct resource * __insert_resource(struct resource *parent, struct resource *new)
775 {
776         struct resource *first, *next;
777
778         for (;; parent = first) {
779                 first = __request_resource(parent, new);
780                 if (!first)
781                         return first;
782
783                 if (first == parent)
784                         return first;
785                 if (WARN_ON(first == new))      /* duplicated insertion */
786                         return first;
787
788                 if ((first->start > new->start) || (first->end < new->end))
789                         break;
790                 if ((first->start == new->start) && (first->end == new->end))
791                         break;
792         }
793
794         for (next = first; ; next = next->sibling) {
795                 /* Partial overlap? Bad, and unfixable */
796                 if (next->start < new->start || next->end > new->end)
797                         return next;
798                 if (!next->sibling)
799                         break;
800                 if (next->sibling->start > new->end)
801                         break;
802         }
803
804         new->parent = parent;
805         new->sibling = next->sibling;
806         new->child = first;
807
808         next->sibling = NULL;
809         for (next = first; next; next = next->sibling)
810                 next->parent = new;
811
812         if (parent->child == first) {
813                 parent->child = new;
814         } else {
815                 next = parent->child;
816                 while (next->sibling != first)
817                         next = next->sibling;
818                 next->sibling = new;
819         }
820         return NULL;
821 }
822
823 /**
824  * insert_resource_conflict - Inserts resource in the resource tree
825  * @parent: parent of the new resource
826  * @new: new resource to insert
827  *
828  * Returns 0 on success, conflict resource if the resource can't be inserted.
829  *
830  * This function is equivalent to request_resource_conflict when no conflict
831  * happens. If a conflict happens, and the conflicting resources
832  * entirely fit within the range of the new resource, then the new
833  * resource is inserted and the conflicting resources become children of
834  * the new resource.
835  *
836  * This function is intended for producers of resources, such as FW modules
837  * and bus drivers.
838  */
839 struct resource *insert_resource_conflict(struct resource *parent, struct resource *new)
840 {
841         struct resource *conflict;
842
843         write_lock(&resource_lock);
844         conflict = __insert_resource(parent, new);
845         write_unlock(&resource_lock);
846         return conflict;
847 }
848
849 /**
850  * insert_resource - Inserts a resource in the resource tree
851  * @parent: parent of the new resource
852  * @new: new resource to insert
853  *
854  * Returns 0 on success, -EBUSY if the resource can't be inserted.
855  *
856  * This function is intended for producers of resources, such as FW modules
857  * and bus drivers.
858  */
859 int insert_resource(struct resource *parent, struct resource *new)
860 {
861         struct resource *conflict;
862
863         conflict = insert_resource_conflict(parent, new);
864         return conflict ? -EBUSY : 0;
865 }
866 EXPORT_SYMBOL_GPL(insert_resource);
867
868 /**
869  * insert_resource_expand_to_fit - Insert a resource into the resource tree
870  * @root: root resource descriptor
871  * @new: new resource to insert
872  *
873  * Insert a resource into the resource tree, possibly expanding it in order
874  * to make it encompass any conflicting resources.
875  */
876 void insert_resource_expand_to_fit(struct resource *root, struct resource *new)
877 {
878         if (new->parent)
879                 return;
880
881         write_lock(&resource_lock);
882         for (;;) {
883                 struct resource *conflict;
884
885                 conflict = __insert_resource(root, new);
886                 if (!conflict)
887                         break;
888                 if (conflict == root)
889                         break;
890
891                 /* Ok, expand resource to cover the conflict, then try again .. */
892                 if (conflict->start < new->start)
893                         new->start = conflict->start;
894                 if (conflict->end > new->end)
895                         new->end = conflict->end;
896
897                 pr_info("Expanded resource %s due to conflict with %s\n", new->name, conflict->name);
898         }
899         write_unlock(&resource_lock);
900 }
901 /*
902  * Not for general consumption, only early boot memory map parsing, PCI
903  * resource discovery, and late discovery of CXL resources are expected
904  * to use this interface. The former are built-in and only the latter,
905  * CXL, is a module.
906  */
907 EXPORT_SYMBOL_NS_GPL(insert_resource_expand_to_fit, CXL);
908
909 /**
910  * remove_resource - Remove a resource in the resource tree
911  * @old: resource to remove
912  *
913  * Returns 0 on success, -EINVAL if the resource is not valid.
914  *
915  * This function removes a resource previously inserted by insert_resource()
916  * or insert_resource_conflict(), and moves the children (if any) up to
917  * where they were before.  insert_resource() and insert_resource_conflict()
918  * insert a new resource, and move any conflicting resources down to the
919  * children of the new resource.
920  *
921  * insert_resource(), insert_resource_conflict() and remove_resource() are
922  * intended for producers of resources, such as FW modules and bus drivers.
923  */
924 int remove_resource(struct resource *old)
925 {
926         int retval;
927
928         write_lock(&resource_lock);
929         retval = __release_resource(old, false);
930         write_unlock(&resource_lock);
931         return retval;
932 }
933 EXPORT_SYMBOL_GPL(remove_resource);
934
935 static int __adjust_resource(struct resource *res, resource_size_t start,
936                                 resource_size_t size)
937 {
938         struct resource *tmp, *parent = res->parent;
939         resource_size_t end = start + size - 1;
940         int result = -EBUSY;
941
942         if (!parent)
943                 goto skip;
944
945         if ((start < parent->start) || (end > parent->end))
946                 goto out;
947
948         if (res->sibling && (res->sibling->start <= end))
949                 goto out;
950
951         tmp = parent->child;
952         if (tmp != res) {
953                 while (tmp->sibling != res)
954                         tmp = tmp->sibling;
955                 if (start <= tmp->end)
956                         goto out;
957         }
958
959 skip:
960         for (tmp = res->child; tmp; tmp = tmp->sibling)
961                 if ((tmp->start < start) || (tmp->end > end))
962                         goto out;
963
964         res->start = start;
965         res->end = end;
966         result = 0;
967
968  out:
969         return result;
970 }
971
972 /**
973  * adjust_resource - modify a resource's start and size
974  * @res: resource to modify
975  * @start: new start value
976  * @size: new size
977  *
978  * Given an existing resource, change its start and size to match the
979  * arguments.  Returns 0 on success, -EBUSY if it can't fit.
980  * Existing children of the resource are assumed to be immutable.
981  */
982 int adjust_resource(struct resource *res, resource_size_t start,
983                     resource_size_t size)
984 {
985         int result;
986
987         write_lock(&resource_lock);
988         result = __adjust_resource(res, start, size);
989         write_unlock(&resource_lock);
990         return result;
991 }
992 EXPORT_SYMBOL(adjust_resource);
993
994 static void __init
995 __reserve_region_with_split(struct resource *root, resource_size_t start,
996                             resource_size_t end, const char *name)
997 {
998         struct resource *parent = root;
999         struct resource *conflict;
1000         struct resource *res = alloc_resource(GFP_ATOMIC);
1001         struct resource *next_res = NULL;
1002         int type = resource_type(root);
1003
1004         if (!res)
1005                 return;
1006
1007         res->name = name;
1008         res->start = start;
1009         res->end = end;
1010         res->flags = type | IORESOURCE_BUSY;
1011         res->desc = IORES_DESC_NONE;
1012
1013         while (1) {
1014
1015                 conflict = __request_resource(parent, res);
1016                 if (!conflict) {
1017                         if (!next_res)
1018                                 break;
1019                         res = next_res;
1020                         next_res = NULL;
1021                         continue;
1022                 }
1023
1024                 /* conflict covered whole area */
1025                 if (conflict->start <= res->start &&
1026                                 conflict->end >= res->end) {
1027                         free_resource(res);
1028                         WARN_ON(next_res);
1029                         break;
1030                 }
1031
1032                 /* failed, split and try again */
1033                 if (conflict->start > res->start) {
1034                         end = res->end;
1035                         res->end = conflict->start - 1;
1036                         if (conflict->end < end) {
1037                                 next_res = alloc_resource(GFP_ATOMIC);
1038                                 if (!next_res) {
1039                                         free_resource(res);
1040                                         break;
1041                                 }
1042                                 next_res->name = name;
1043                                 next_res->start = conflict->end + 1;
1044                                 next_res->end = end;
1045                                 next_res->flags = type | IORESOURCE_BUSY;
1046                                 next_res->desc = IORES_DESC_NONE;
1047                         }
1048                 } else {
1049                         res->start = conflict->end + 1;
1050                 }
1051         }
1052
1053 }
1054
1055 void __init
1056 reserve_region_with_split(struct resource *root, resource_size_t start,
1057                           resource_size_t end, const char *name)
1058 {
1059         int abort = 0;
1060
1061         write_lock(&resource_lock);
1062         if (root->start > start || root->end < end) {
1063                 pr_err("requested range [0x%llx-0x%llx] not in root %pr\n",
1064                        (unsigned long long)start, (unsigned long long)end,
1065                        root);
1066                 if (start > root->end || end < root->start)
1067                         abort = 1;
1068                 else {
1069                         if (end > root->end)
1070                                 end = root->end;
1071                         if (start < root->start)
1072                                 start = root->start;
1073                         pr_err("fixing request to [0x%llx-0x%llx]\n",
1074                                (unsigned long long)start,
1075                                (unsigned long long)end);
1076                 }
1077                 dump_stack();
1078         }
1079         if (!abort)
1080                 __reserve_region_with_split(root, start, end, name);
1081         write_unlock(&resource_lock);
1082 }
1083
1084 /**
1085  * resource_alignment - calculate resource's alignment
1086  * @res: resource pointer
1087  *
1088  * Returns alignment on success, 0 (invalid alignment) on failure.
1089  */
1090 resource_size_t resource_alignment(struct resource *res)
1091 {
1092         switch (res->flags & (IORESOURCE_SIZEALIGN | IORESOURCE_STARTALIGN)) {
1093         case IORESOURCE_SIZEALIGN:
1094                 return resource_size(res);
1095         case IORESOURCE_STARTALIGN:
1096                 return res->start;
1097         default:
1098                 return 0;
1099         }
1100 }
1101
1102 /*
1103  * This is compatibility stuff for IO resources.
1104  *
1105  * Note how this, unlike the above, knows about
1106  * the IO flag meanings (busy etc).
1107  *
1108  * request_region creates a new busy region.
1109  *
1110  * release_region releases a matching busy region.
1111  */
1112
1113 static DECLARE_WAIT_QUEUE_HEAD(muxed_resource_wait);
1114
1115 static struct inode *iomem_inode;
1116
1117 #ifdef CONFIG_IO_STRICT_DEVMEM
1118 static void revoke_iomem(struct resource *res)
1119 {
1120         /* pairs with smp_store_release() in iomem_init_inode() */
1121         struct inode *inode = smp_load_acquire(&iomem_inode);
1122
1123         /*
1124          * Check that the initialization has completed. Losing the race
1125          * is ok because it means drivers are claiming resources before
1126          * the fs_initcall level of init and prevent iomem_get_mapping users
1127          * from establishing mappings.
1128          */
1129         if (!inode)
1130                 return;
1131
1132         /*
1133          * The expectation is that the driver has successfully marked
1134          * the resource busy by this point, so devmem_is_allowed()
1135          * should start returning false, however for performance this
1136          * does not iterate the entire resource range.
1137          */
1138         if (devmem_is_allowed(PHYS_PFN(res->start)) &&
1139             devmem_is_allowed(PHYS_PFN(res->end))) {
1140                 /*
1141                  * *cringe* iomem=relaxed says "go ahead, what's the
1142                  * worst that can happen?"
1143                  */
1144                 return;
1145         }
1146
1147         unmap_mapping_range(inode->i_mapping, res->start, resource_size(res), 1);
1148 }
1149 #else
1150 static void revoke_iomem(struct resource *res) {}
1151 #endif
1152
1153 struct address_space *iomem_get_mapping(void)
1154 {
1155         /*
1156          * This function is only called from file open paths, hence guaranteed
1157          * that fs_initcalls have completed and no need to check for NULL. But
1158          * since revoke_iomem can be called before the initcall we still need
1159          * the barrier to appease checkers.
1160          */
1161         return smp_load_acquire(&iomem_inode)->i_mapping;
1162 }
1163
1164 static int __request_region_locked(struct resource *res, struct resource *parent,
1165                                    resource_size_t start, resource_size_t n,
1166                                    const char *name, int flags)
1167 {
1168         DECLARE_WAITQUEUE(wait, current);
1169
1170         res->name = name;
1171         res->start = start;
1172         res->end = start + n - 1;
1173
1174         for (;;) {
1175                 struct resource *conflict;
1176
1177                 res->flags = resource_type(parent) | resource_ext_type(parent);
1178                 res->flags |= IORESOURCE_BUSY | flags;
1179                 res->desc = parent->desc;
1180
1181                 conflict = __request_resource(parent, res);
1182                 if (!conflict)
1183                         break;
1184                 /*
1185                  * mm/hmm.c reserves physical addresses which then
1186                  * become unavailable to other users.  Conflicts are
1187                  * not expected.  Warn to aid debugging if encountered.
1188                  */
1189                 if (conflict->desc == IORES_DESC_DEVICE_PRIVATE_MEMORY) {
1190                         pr_warn("Unaddressable device %s %pR conflicts with %pR",
1191                                 conflict->name, conflict, res);
1192                 }
1193                 if (conflict != parent) {
1194                         if (!(conflict->flags & IORESOURCE_BUSY)) {
1195                                 parent = conflict;
1196                                 continue;
1197                         }
1198                 }
1199                 if (conflict->flags & flags & IORESOURCE_MUXED) {
1200                         add_wait_queue(&muxed_resource_wait, &wait);
1201                         write_unlock(&resource_lock);
1202                         set_current_state(TASK_UNINTERRUPTIBLE);
1203                         schedule();
1204                         remove_wait_queue(&muxed_resource_wait, &wait);
1205                         write_lock(&resource_lock);
1206                         continue;
1207                 }
1208                 /* Uhhuh, that didn't work out.. */
1209                 return -EBUSY;
1210         }
1211
1212         return 0;
1213 }
1214
1215 /**
1216  * __request_region - create a new busy resource region
1217  * @parent: parent resource descriptor
1218  * @start: resource start address
1219  * @n: resource region size
1220  * @name: reserving caller's ID string
1221  * @flags: IO resource flags
1222  */
1223 struct resource *__request_region(struct resource *parent,
1224                                   resource_size_t start, resource_size_t n,
1225                                   const char *name, int flags)
1226 {
1227         struct resource *res = alloc_resource(GFP_KERNEL);
1228         int ret;
1229
1230         if (!res)
1231                 return NULL;
1232
1233         write_lock(&resource_lock);
1234         ret = __request_region_locked(res, parent, start, n, name, flags);
1235         write_unlock(&resource_lock);
1236
1237         if (ret) {
1238                 free_resource(res);
1239                 return NULL;
1240         }
1241
1242         if (parent == &iomem_resource)
1243                 revoke_iomem(res);
1244
1245         return res;
1246 }
1247 EXPORT_SYMBOL(__request_region);
1248
1249 /**
1250  * __release_region - release a previously reserved resource region
1251  * @parent: parent resource descriptor
1252  * @start: resource start address
1253  * @n: resource region size
1254  *
1255  * The described resource region must match a currently busy region.
1256  */
1257 void __release_region(struct resource *parent, resource_size_t start,
1258                       resource_size_t n)
1259 {
1260         struct resource **p;
1261         resource_size_t end;
1262
1263         p = &parent->child;
1264         end = start + n - 1;
1265
1266         write_lock(&resource_lock);
1267
1268         for (;;) {
1269                 struct resource *res = *p;
1270
1271                 if (!res)
1272                         break;
1273                 if (res->start <= start && res->end >= end) {
1274                         if (!(res->flags & IORESOURCE_BUSY)) {
1275                                 p = &res->child;
1276                                 continue;
1277                         }
1278                         if (res->start != start || res->end != end)
1279                                 break;
1280                         *p = res->sibling;
1281                         write_unlock(&resource_lock);
1282                         if (res->flags & IORESOURCE_MUXED)
1283                                 wake_up(&muxed_resource_wait);
1284                         free_resource(res);
1285                         return;
1286                 }
1287                 p = &res->sibling;
1288         }
1289
1290         write_unlock(&resource_lock);
1291
1292         pr_warn("Trying to free nonexistent resource <%pa-%pa>\n", &start, &end);
1293 }
1294 EXPORT_SYMBOL(__release_region);
1295
1296 #ifdef CONFIG_MEMORY_HOTREMOVE
1297 /**
1298  * release_mem_region_adjustable - release a previously reserved memory region
1299  * @start: resource start address
1300  * @size: resource region size
1301  *
1302  * This interface is intended for memory hot-delete.  The requested region
1303  * is released from a currently busy memory resource.  The requested region
1304  * must either match exactly or fit into a single busy resource entry.  In
1305  * the latter case, the remaining resource is adjusted accordingly.
1306  * Existing children of the busy memory resource must be immutable in the
1307  * request.
1308  *
1309  * Note:
1310  * - Additional release conditions, such as overlapping region, can be
1311  *   supported after they are confirmed as valid cases.
1312  * - When a busy memory resource gets split into two entries, the code
1313  *   assumes that all children remain in the lower address entry for
1314  *   simplicity.  Enhance this logic when necessary.
1315  */
1316 void release_mem_region_adjustable(resource_size_t start, resource_size_t size)
1317 {
1318         struct resource *parent = &iomem_resource;
1319         struct resource *new_res = NULL;
1320         bool alloc_nofail = false;
1321         struct resource **p;
1322         struct resource *res;
1323         resource_size_t end;
1324
1325         end = start + size - 1;
1326         if (WARN_ON_ONCE((start < parent->start) || (end > parent->end)))
1327                 return;
1328
1329         /*
1330          * We free up quite a lot of memory on memory hotunplug (esp., memap),
1331          * just before releasing the region. This is highly unlikely to
1332          * fail - let's play save and make it never fail as the caller cannot
1333          * perform any error handling (e.g., trying to re-add memory will fail
1334          * similarly).
1335          */
1336 retry:
1337         new_res = alloc_resource(GFP_KERNEL | (alloc_nofail ? __GFP_NOFAIL : 0));
1338
1339         p = &parent->child;
1340         write_lock(&resource_lock);
1341
1342         while ((res = *p)) {
1343                 if (res->start >= end)
1344                         break;
1345
1346                 /* look for the next resource if it does not fit into */
1347                 if (res->start > start || res->end < end) {
1348                         p = &res->sibling;
1349                         continue;
1350                 }
1351
1352                 if (!(res->flags & IORESOURCE_MEM))
1353                         break;
1354
1355                 if (!(res->flags & IORESOURCE_BUSY)) {
1356                         p = &res->child;
1357                         continue;
1358                 }
1359
1360                 /* found the target resource; let's adjust accordingly */
1361                 if (res->start == start && res->end == end) {
1362                         /* free the whole entry */
1363                         *p = res->sibling;
1364                         free_resource(res);
1365                 } else if (res->start == start && res->end != end) {
1366                         /* adjust the start */
1367                         WARN_ON_ONCE(__adjust_resource(res, end + 1,
1368                                                        res->end - end));
1369                 } else if (res->start != start && res->end == end) {
1370                         /* adjust the end */
1371                         WARN_ON_ONCE(__adjust_resource(res, res->start,
1372                                                        start - res->start));
1373                 } else {
1374                         /* split into two entries - we need a new resource */
1375                         if (!new_res) {
1376                                 new_res = alloc_resource(GFP_ATOMIC);
1377                                 if (!new_res) {
1378                                         alloc_nofail = true;
1379                                         write_unlock(&resource_lock);
1380                                         goto retry;
1381                                 }
1382                         }
1383                         new_res->name = res->name;
1384                         new_res->start = end + 1;
1385                         new_res->end = res->end;
1386                         new_res->flags = res->flags;
1387                         new_res->desc = res->desc;
1388                         new_res->parent = res->parent;
1389                         new_res->sibling = res->sibling;
1390                         new_res->child = NULL;
1391
1392                         if (WARN_ON_ONCE(__adjust_resource(res, res->start,
1393                                                            start - res->start)))
1394                                 break;
1395                         res->sibling = new_res;
1396                         new_res = NULL;
1397                 }
1398
1399                 break;
1400         }
1401
1402         write_unlock(&resource_lock);
1403         free_resource(new_res);
1404 }
1405 #endif  /* CONFIG_MEMORY_HOTREMOVE */
1406
1407 #ifdef CONFIG_MEMORY_HOTPLUG
1408 static bool system_ram_resources_mergeable(struct resource *r1,
1409                                            struct resource *r2)
1410 {
1411         /* We assume either r1 or r2 is IORESOURCE_SYSRAM_MERGEABLE. */
1412         return r1->flags == r2->flags && r1->end + 1 == r2->start &&
1413                r1->name == r2->name && r1->desc == r2->desc &&
1414                !r1->child && !r2->child;
1415 }
1416
1417 /**
1418  * merge_system_ram_resource - mark the System RAM resource mergeable and try to
1419  *      merge it with adjacent, mergeable resources
1420  * @res: resource descriptor
1421  *
1422  * This interface is intended for memory hotplug, whereby lots of contiguous
1423  * system ram resources are added (e.g., via add_memory*()) by a driver, and
1424  * the actual resource boundaries are not of interest (e.g., it might be
1425  * relevant for DIMMs). Only resources that are marked mergeable, that have the
1426  * same parent, and that don't have any children are considered. All mergeable
1427  * resources must be immutable during the request.
1428  *
1429  * Note:
1430  * - The caller has to make sure that no pointers to resources that are
1431  *   marked mergeable are used anymore after this call - the resource might
1432  *   be freed and the pointer might be stale!
1433  * - release_mem_region_adjustable() will split on demand on memory hotunplug
1434  */
1435 void merge_system_ram_resource(struct resource *res)
1436 {
1437         const unsigned long flags = IORESOURCE_SYSTEM_RAM | IORESOURCE_BUSY;
1438         struct resource *cur;
1439
1440         if (WARN_ON_ONCE((res->flags & flags) != flags))
1441                 return;
1442
1443         write_lock(&resource_lock);
1444         res->flags |= IORESOURCE_SYSRAM_MERGEABLE;
1445
1446         /* Try to merge with next item in the list. */
1447         cur = res->sibling;
1448         if (cur && system_ram_resources_mergeable(res, cur)) {
1449                 res->end = cur->end;
1450                 res->sibling = cur->sibling;
1451                 free_resource(cur);
1452         }
1453
1454         /* Try to merge with previous item in the list. */
1455         cur = res->parent->child;
1456         while (cur && cur->sibling != res)
1457                 cur = cur->sibling;
1458         if (cur && system_ram_resources_mergeable(cur, res)) {
1459                 cur->end = res->end;
1460                 cur->sibling = res->sibling;
1461                 free_resource(res);
1462         }
1463         write_unlock(&resource_lock);
1464 }
1465 #endif  /* CONFIG_MEMORY_HOTPLUG */
1466
1467 /*
1468  * Managed region resource
1469  */
1470 static void devm_resource_release(struct device *dev, void *ptr)
1471 {
1472         struct resource **r = ptr;
1473
1474         release_resource(*r);
1475 }
1476
1477 /**
1478  * devm_request_resource() - request and reserve an I/O or memory resource
1479  * @dev: device for which to request the resource
1480  * @root: root of the resource tree from which to request the resource
1481  * @new: descriptor of the resource to request
1482  *
1483  * This is a device-managed version of request_resource(). There is usually
1484  * no need to release resources requested by this function explicitly since
1485  * that will be taken care of when the device is unbound from its driver.
1486  * If for some reason the resource needs to be released explicitly, because
1487  * of ordering issues for example, drivers must call devm_release_resource()
1488  * rather than the regular release_resource().
1489  *
1490  * When a conflict is detected between any existing resources and the newly
1491  * requested resource, an error message will be printed.
1492  *
1493  * Returns 0 on success or a negative error code on failure.
1494  */
1495 int devm_request_resource(struct device *dev, struct resource *root,
1496                           struct resource *new)
1497 {
1498         struct resource *conflict, **ptr;
1499
1500         ptr = devres_alloc(devm_resource_release, sizeof(*ptr), GFP_KERNEL);
1501         if (!ptr)
1502                 return -ENOMEM;
1503
1504         *ptr = new;
1505
1506         conflict = request_resource_conflict(root, new);
1507         if (conflict) {
1508                 dev_err(dev, "resource collision: %pR conflicts with %s %pR\n",
1509                         new, conflict->name, conflict);
1510                 devres_free(ptr);
1511                 return -EBUSY;
1512         }
1513
1514         devres_add(dev, ptr);
1515         return 0;
1516 }
1517 EXPORT_SYMBOL(devm_request_resource);
1518
1519 static int devm_resource_match(struct device *dev, void *res, void *data)
1520 {
1521         struct resource **ptr = res;
1522
1523         return *ptr == data;
1524 }
1525
1526 /**
1527  * devm_release_resource() - release a previously requested resource
1528  * @dev: device for which to release the resource
1529  * @new: descriptor of the resource to release
1530  *
1531  * Releases a resource previously requested using devm_request_resource().
1532  */
1533 void devm_release_resource(struct device *dev, struct resource *new)
1534 {
1535         WARN_ON(devres_release(dev, devm_resource_release, devm_resource_match,
1536                                new));
1537 }
1538 EXPORT_SYMBOL(devm_release_resource);
1539
1540 struct region_devres {
1541         struct resource *parent;
1542         resource_size_t start;
1543         resource_size_t n;
1544 };
1545
1546 static void devm_region_release(struct device *dev, void *res)
1547 {
1548         struct region_devres *this = res;
1549
1550         __release_region(this->parent, this->start, this->n);
1551 }
1552
1553 static int devm_region_match(struct device *dev, void *res, void *match_data)
1554 {
1555         struct region_devres *this = res, *match = match_data;
1556
1557         return this->parent == match->parent &&
1558                 this->start == match->start && this->n == match->n;
1559 }
1560
1561 struct resource *
1562 __devm_request_region(struct device *dev, struct resource *parent,
1563                       resource_size_t start, resource_size_t n, const char *name)
1564 {
1565         struct region_devres *dr = NULL;
1566         struct resource *res;
1567
1568         dr = devres_alloc(devm_region_release, sizeof(struct region_devres),
1569                           GFP_KERNEL);
1570         if (!dr)
1571                 return NULL;
1572
1573         dr->parent = parent;
1574         dr->start = start;
1575         dr->n = n;
1576
1577         res = __request_region(parent, start, n, name, 0);
1578         if (res)
1579                 devres_add(dev, dr);
1580         else
1581                 devres_free(dr);
1582
1583         return res;
1584 }
1585 EXPORT_SYMBOL(__devm_request_region);
1586
1587 void __devm_release_region(struct device *dev, struct resource *parent,
1588                            resource_size_t start, resource_size_t n)
1589 {
1590         struct region_devres match_data = { parent, start, n };
1591
1592         __release_region(parent, start, n);
1593         WARN_ON(devres_destroy(dev, devm_region_release, devm_region_match,
1594                                &match_data));
1595 }
1596 EXPORT_SYMBOL(__devm_release_region);
1597
1598 /*
1599  * Reserve I/O ports or memory based on "reserve=" kernel parameter.
1600  */
1601 #define MAXRESERVE 4
1602 static int __init reserve_setup(char *str)
1603 {
1604         static int reserved;
1605         static struct resource reserve[MAXRESERVE];
1606
1607         for (;;) {
1608                 unsigned int io_start, io_num;
1609                 int x = reserved;
1610                 struct resource *parent;
1611
1612                 if (get_option(&str, &io_start) != 2)
1613                         break;
1614                 if (get_option(&str, &io_num) == 0)
1615                         break;
1616                 if (x < MAXRESERVE) {
1617                         struct resource *res = reserve + x;
1618
1619                         /*
1620                          * If the region starts below 0x10000, we assume it's
1621                          * I/O port space; otherwise assume it's memory.
1622                          */
1623                         if (io_start < 0x10000) {
1624                                 res->flags = IORESOURCE_IO;
1625                                 parent = &ioport_resource;
1626                         } else {
1627                                 res->flags = IORESOURCE_MEM;
1628                                 parent = &iomem_resource;
1629                         }
1630                         res->name = "reserved";
1631                         res->start = io_start;
1632                         res->end = io_start + io_num - 1;
1633                         res->flags |= IORESOURCE_BUSY;
1634                         res->desc = IORES_DESC_NONE;
1635                         res->child = NULL;
1636                         if (request_resource(parent, res) == 0)
1637                                 reserved = x+1;
1638                 }
1639         }
1640         return 1;
1641 }
1642 __setup("reserve=", reserve_setup);
1643
1644 /*
1645  * Check if the requested addr and size spans more than any slot in the
1646  * iomem resource tree.
1647  */
1648 int iomem_map_sanity_check(resource_size_t addr, unsigned long size)
1649 {
1650         struct resource *p = &iomem_resource;
1651         resource_size_t end = addr + size - 1;
1652         int err = 0;
1653         loff_t l;
1654
1655         read_lock(&resource_lock);
1656         for (p = p->child; p ; p = r_next(NULL, p, &l)) {
1657                 /*
1658                  * We can probably skip the resources without
1659                  * IORESOURCE_IO attribute?
1660                  */
1661                 if (p->start > end)
1662                         continue;
1663                 if (p->end < addr)
1664                         continue;
1665                 if (PFN_DOWN(p->start) <= PFN_DOWN(addr) &&
1666                     PFN_DOWN(p->end) >= PFN_DOWN(end))
1667                         continue;
1668                 /*
1669                  * if a resource is "BUSY", it's not a hardware resource
1670                  * but a driver mapping of such a resource; we don't want
1671                  * to warn for those; some drivers legitimately map only
1672                  * partial hardware resources. (example: vesafb)
1673                  */
1674                 if (p->flags & IORESOURCE_BUSY)
1675                         continue;
1676
1677                 pr_warn("resource sanity check: requesting [mem %pa-%pa], which spans more than %s %pR\n",
1678                         &addr, &end, p->name, p);
1679                 err = -1;
1680                 break;
1681         }
1682         read_unlock(&resource_lock);
1683
1684         return err;
1685 }
1686
1687 #ifdef CONFIG_STRICT_DEVMEM
1688 static int strict_iomem_checks = 1;
1689 #else
1690 static int strict_iomem_checks;
1691 #endif
1692
1693 /*
1694  * Check if an address is exclusive to the kernel and must not be mapped to
1695  * user space, for example, via /dev/mem.
1696  *
1697  * Returns true if exclusive to the kernel, otherwise returns false.
1698  */
1699 bool resource_is_exclusive(struct resource *root, u64 addr, resource_size_t size)
1700 {
1701         const unsigned int exclusive_system_ram = IORESOURCE_SYSTEM_RAM |
1702                                                   IORESOURCE_EXCLUSIVE;
1703         bool skip_children = false, err = false;
1704         struct resource *p;
1705
1706         read_lock(&resource_lock);
1707         for_each_resource(root, p, skip_children) {
1708                 if (p->start >= addr + size)
1709                         break;
1710                 if (p->end < addr) {
1711                         skip_children = true;
1712                         continue;
1713                 }
1714                 skip_children = false;
1715
1716                 /*
1717                  * IORESOURCE_SYSTEM_RAM resources are exclusive if
1718                  * IORESOURCE_EXCLUSIVE is set, even if they
1719                  * are not busy and even if "iomem=relaxed" is set. The
1720                  * responsible driver dynamically adds/removes system RAM within
1721                  * such an area and uncontrolled access is dangerous.
1722                  */
1723                 if ((p->flags & exclusive_system_ram) == exclusive_system_ram) {
1724                         err = true;
1725                         break;
1726                 }
1727
1728                 /*
1729                  * A resource is exclusive if IORESOURCE_EXCLUSIVE is set
1730                  * or CONFIG_IO_STRICT_DEVMEM is enabled and the
1731                  * resource is busy.
1732                  */
1733                 if (!strict_iomem_checks || !(p->flags & IORESOURCE_BUSY))
1734                         continue;
1735                 if (IS_ENABLED(CONFIG_IO_STRICT_DEVMEM)
1736                                 || p->flags & IORESOURCE_EXCLUSIVE) {
1737                         err = true;
1738                         break;
1739                 }
1740         }
1741         read_unlock(&resource_lock);
1742
1743         return err;
1744 }
1745
1746 bool iomem_is_exclusive(u64 addr)
1747 {
1748         return resource_is_exclusive(&iomem_resource, addr & PAGE_MASK,
1749                                      PAGE_SIZE);
1750 }
1751
1752 struct resource_entry *resource_list_create_entry(struct resource *res,
1753                                                   size_t extra_size)
1754 {
1755         struct resource_entry *entry;
1756
1757         entry = kzalloc(sizeof(*entry) + extra_size, GFP_KERNEL);
1758         if (entry) {
1759                 INIT_LIST_HEAD(&entry->node);
1760                 entry->res = res ? res : &entry->__res;
1761         }
1762
1763         return entry;
1764 }
1765 EXPORT_SYMBOL(resource_list_create_entry);
1766
1767 void resource_list_free(struct list_head *head)
1768 {
1769         struct resource_entry *entry, *tmp;
1770
1771         list_for_each_entry_safe(entry, tmp, head, node)
1772                 resource_list_destroy_entry(entry);
1773 }
1774 EXPORT_SYMBOL(resource_list_free);
1775
1776 #ifdef CONFIG_GET_FREE_REGION
1777 #define GFR_DESCENDING          (1UL << 0)
1778 #define GFR_REQUEST_REGION      (1UL << 1)
1779 #define GFR_DEFAULT_ALIGN (1UL << PA_SECTION_SHIFT)
1780
1781 static resource_size_t gfr_start(struct resource *base, resource_size_t size,
1782                                  resource_size_t align, unsigned long flags)
1783 {
1784         if (flags & GFR_DESCENDING) {
1785                 resource_size_t end;
1786
1787                 end = min_t(resource_size_t, base->end,
1788                             (1ULL << MAX_PHYSMEM_BITS) - 1);
1789                 return end - size + 1;
1790         }
1791
1792         return ALIGN(base->start, align);
1793 }
1794
1795 static bool gfr_continue(struct resource *base, resource_size_t addr,
1796                          resource_size_t size, unsigned long flags)
1797 {
1798         if (flags & GFR_DESCENDING)
1799                 return addr > size && addr >= base->start;
1800         /*
1801          * In the ascend case be careful that the last increment by
1802          * @size did not wrap 0.
1803          */
1804         return addr > addr - size &&
1805                addr <= min_t(resource_size_t, base->end,
1806                              (1ULL << MAX_PHYSMEM_BITS) - 1);
1807 }
1808
1809 static resource_size_t gfr_next(resource_size_t addr, resource_size_t size,
1810                                 unsigned long flags)
1811 {
1812         if (flags & GFR_DESCENDING)
1813                 return addr - size;
1814         return addr + size;
1815 }
1816
1817 static void remove_free_mem_region(void *_res)
1818 {
1819         struct resource *res = _res;
1820
1821         if (res->parent)
1822                 remove_resource(res);
1823         free_resource(res);
1824 }
1825
1826 static struct resource *
1827 get_free_mem_region(struct device *dev, struct resource *base,
1828                     resource_size_t size, const unsigned long align,
1829                     const char *name, const unsigned long desc,
1830                     const unsigned long flags)
1831 {
1832         resource_size_t addr;
1833         struct resource *res;
1834         struct region_devres *dr = NULL;
1835
1836         size = ALIGN(size, align);
1837
1838         res = alloc_resource(GFP_KERNEL);
1839         if (!res)
1840                 return ERR_PTR(-ENOMEM);
1841
1842         if (dev && (flags & GFR_REQUEST_REGION)) {
1843                 dr = devres_alloc(devm_region_release,
1844                                 sizeof(struct region_devres), GFP_KERNEL);
1845                 if (!dr) {
1846                         free_resource(res);
1847                         return ERR_PTR(-ENOMEM);
1848                 }
1849         } else if (dev) {
1850                 if (devm_add_action_or_reset(dev, remove_free_mem_region, res))
1851                         return ERR_PTR(-ENOMEM);
1852         }
1853
1854         write_lock(&resource_lock);
1855         for (addr = gfr_start(base, size, align, flags);
1856              gfr_continue(base, addr, align, flags);
1857              addr = gfr_next(addr, align, flags)) {
1858                 if (__region_intersects(base, addr, size, 0, IORES_DESC_NONE) !=
1859                     REGION_DISJOINT)
1860                         continue;
1861
1862                 if (flags & GFR_REQUEST_REGION) {
1863                         if (__request_region_locked(res, &iomem_resource, addr,
1864                                                     size, name, 0))
1865                                 break;
1866
1867                         if (dev) {
1868                                 dr->parent = &iomem_resource;
1869                                 dr->start = addr;
1870                                 dr->n = size;
1871                                 devres_add(dev, dr);
1872                         }
1873
1874                         res->desc = desc;
1875                         write_unlock(&resource_lock);
1876
1877
1878                         /*
1879                          * A driver is claiming this region so revoke any
1880                          * mappings.
1881                          */
1882                         revoke_iomem(res);
1883                 } else {
1884                         res->start = addr;
1885                         res->end = addr + size - 1;
1886                         res->name = name;
1887                         res->desc = desc;
1888                         res->flags = IORESOURCE_MEM;
1889
1890                         /*
1891                          * Only succeed if the resource hosts an exclusive
1892                          * range after the insert
1893                          */
1894                         if (__insert_resource(base, res) || res->child)
1895                                 break;
1896
1897                         write_unlock(&resource_lock);
1898                 }
1899
1900                 return res;
1901         }
1902         write_unlock(&resource_lock);
1903
1904         if (flags & GFR_REQUEST_REGION) {
1905                 free_resource(res);
1906                 devres_free(dr);
1907         } else if (dev)
1908                 devm_release_action(dev, remove_free_mem_region, res);
1909
1910         return ERR_PTR(-ERANGE);
1911 }
1912
1913 /**
1914  * devm_request_free_mem_region - find free region for device private memory
1915  *
1916  * @dev: device struct to bind the resource to
1917  * @size: size in bytes of the device memory to add
1918  * @base: resource tree to look in
1919  *
1920  * This function tries to find an empty range of physical address big enough to
1921  * contain the new resource, so that it can later be hotplugged as ZONE_DEVICE
1922  * memory, which in turn allocates struct pages.
1923  */
1924 struct resource *devm_request_free_mem_region(struct device *dev,
1925                 struct resource *base, unsigned long size)
1926 {
1927         unsigned long flags = GFR_DESCENDING | GFR_REQUEST_REGION;
1928
1929         return get_free_mem_region(dev, base, size, GFR_DEFAULT_ALIGN,
1930                                    dev_name(dev),
1931                                    IORES_DESC_DEVICE_PRIVATE_MEMORY, flags);
1932 }
1933 EXPORT_SYMBOL_GPL(devm_request_free_mem_region);
1934
1935 struct resource *request_free_mem_region(struct resource *base,
1936                 unsigned long size, const char *name)
1937 {
1938         unsigned long flags = GFR_DESCENDING | GFR_REQUEST_REGION;
1939
1940         return get_free_mem_region(NULL, base, size, GFR_DEFAULT_ALIGN, name,
1941                                    IORES_DESC_DEVICE_PRIVATE_MEMORY, flags);
1942 }
1943 EXPORT_SYMBOL_GPL(request_free_mem_region);
1944
1945 /**
1946  * alloc_free_mem_region - find a free region relative to @base
1947  * @base: resource that will parent the new resource
1948  * @size: size in bytes of memory to allocate from @base
1949  * @align: alignment requirements for the allocation
1950  * @name: resource name
1951  *
1952  * Buses like CXL, that can dynamically instantiate new memory regions,
1953  * need a method to allocate physical address space for those regions.
1954  * Allocate and insert a new resource to cover a free, unclaimed by a
1955  * descendant of @base, range in the span of @base.
1956  */
1957 struct resource *alloc_free_mem_region(struct resource *base,
1958                                        unsigned long size, unsigned long align,
1959                                        const char *name)
1960 {
1961         /* Default of ascending direction and insert resource */
1962         unsigned long flags = 0;
1963
1964         return get_free_mem_region(NULL, base, size, align, name,
1965                                    IORES_DESC_NONE, flags);
1966 }
1967 EXPORT_SYMBOL_NS_GPL(alloc_free_mem_region, CXL);
1968 #endif /* CONFIG_GET_FREE_REGION */
1969
1970 static int __init strict_iomem(char *str)
1971 {
1972         if (strstr(str, "relaxed"))
1973                 strict_iomem_checks = 0;
1974         if (strstr(str, "strict"))
1975                 strict_iomem_checks = 1;
1976         return 1;
1977 }
1978
1979 static int iomem_fs_init_fs_context(struct fs_context *fc)
1980 {
1981         return init_pseudo(fc, DEVMEM_MAGIC) ? 0 : -ENOMEM;
1982 }
1983
1984 static struct file_system_type iomem_fs_type = {
1985         .name           = "iomem",
1986         .owner          = THIS_MODULE,
1987         .init_fs_context = iomem_fs_init_fs_context,
1988         .kill_sb        = kill_anon_super,
1989 };
1990
1991 static int __init iomem_init_inode(void)
1992 {
1993         static struct vfsmount *iomem_vfs_mount;
1994         static int iomem_fs_cnt;
1995         struct inode *inode;
1996         int rc;
1997
1998         rc = simple_pin_fs(&iomem_fs_type, &iomem_vfs_mount, &iomem_fs_cnt);
1999         if (rc < 0) {
2000                 pr_err("Cannot mount iomem pseudo filesystem: %d\n", rc);
2001                 return rc;
2002         }
2003
2004         inode = alloc_anon_inode(iomem_vfs_mount->mnt_sb);
2005         if (IS_ERR(inode)) {
2006                 rc = PTR_ERR(inode);
2007                 pr_err("Cannot allocate inode for iomem: %d\n", rc);
2008                 simple_release_fs(&iomem_vfs_mount, &iomem_fs_cnt);
2009                 return rc;
2010         }
2011
2012         /*
2013          * Publish iomem revocation inode initialized.
2014          * Pairs with smp_load_acquire() in revoke_iomem().
2015          */
2016         smp_store_release(&iomem_inode, inode);
2017
2018         return 0;
2019 }
2020
2021 fs_initcall(iomem_init_inode);
2022
2023 __setup("iomem=", strict_iomem);