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