1 // SPDX-License-Identifier: GPL-2.0
3 * Range add and subtract
5 #include <linux/kernel.h>
6 #include <linux/init.h>
7 #include <linux/sort.h>
8 #include <linux/string.h>
9 #include <linux/range.h>
11 int add_range(struct range *range, int az, int nr_range, u64 start, u64 end)
20 range[nr_range].start = start;
21 range[nr_range].end = end;
28 int add_range_with_merge(struct range *range, int az, int nr_range,
36 /* get new start/end: */
37 for (i = 0; i < nr_range; i++) {
38 u64 common_start, common_end;
43 common_start = max(range[i].start, start);
44 common_end = min(range[i].end, end);
45 if (common_start > common_end)
48 /* new start/end, will add it back at last */
49 start = min(range[i].start, start);
50 end = max(range[i].end, end);
52 memmove(&range[i], &range[i + 1],
53 (nr_range - (i + 1)) * sizeof(range[i]));
54 range[nr_range - 1].start = 0;
55 range[nr_range - 1].end = 0;
61 return add_range(range, az, nr_range, start, end);
64 void subtract_range(struct range *range, int az, u64 start, u64 end)
71 for (j = 0; j < az; j++) {
75 if (start <= range[j].start && end >= range[j].end) {
81 if (start <= range[j].start && end < range[j].end &&
82 range[j].start < end) {
88 if (start > range[j].start && end >= range[j].end &&
89 range[j].end > start) {
94 if (start > range[j].start && end < range[j].end) {
95 /* Find the new spare: */
96 for (i = 0; i < az; i++) {
97 if (range[i].end == 0)
101 range[i].end = range[j].end;
102 range[i].start = end;
104 pr_err("%s: run out of slot in ranges\n",
107 range[j].end = start;
113 static int cmp_range(const void *x1, const void *x2)
115 const struct range *r1 = x1;
116 const struct range *r2 = x2;
118 if (r1->start < r2->start)
120 if (r1->start > r2->start)
125 int clean_sort_range(struct range *range, int az)
127 int i, j, k = az - 1, nr_range = az;
129 for (i = 0; i < k; i++) {
132 for (j = k; j > i; j--) {
140 range[i].start = range[k].start;
141 range[i].end = range[k].end;
147 for (i = 0; i < az; i++) {
155 sort(range, nr_range, sizeof(struct range), cmp_range, NULL);
160 void sort_range(struct range *range, int nr_range)
163 sort(range, nr_range, sizeof(struct range), cmp_range, NULL);