2 * Range add and subtract
4 #include <linux/kernel.h>
5 #include <linux/init.h>
6 #include <linux/sort.h>
8 #include <linux/range.h>
10 int add_range(struct range
*range
, int az
, int nr_range
, u64 start
, u64 end
)
19 range
[nr_range
].start
= start
;
20 range
[nr_range
].end
= end
;
27 int add_range_with_merge(struct range
*range
, int az
, int nr_range
,
35 /* Try to merge it with old one: */
36 for (i
= 0; i
< nr_range
; i
++) {
37 u64 final_start
, final_end
;
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 final_start
= min(range
[i
].start
, start
);
49 final_end
= max(range
[i
].end
, end
);
51 range
[i
].start
= final_start
;
52 range
[i
].end
= final_end
;
57 return add_range(range
, az
, nr_range
, start
, end
);
60 void subtract_range(struct range
*range
, int az
, u64 start
, u64 end
)
67 for (j
= 0; j
< az
; j
++) {
71 if (start
<= range
[j
].start
&& end
>= range
[j
].end
) {
77 if (start
<= range
[j
].start
&& end
< range
[j
].end
&&
78 range
[j
].start
< end
) {
84 if (start
> range
[j
].start
&& end
>= range
[j
].end
&&
85 range
[j
].end
> start
) {
90 if (start
> range
[j
].start
&& end
< range
[j
].end
) {
91 /* Find the new spare: */
92 for (i
= 0; i
< az
; i
++) {
93 if (range
[i
].end
== 0)
97 range
[i
].end
= range
[j
].end
;
100 pr_err("%s: run out of slot in ranges\n",
103 range
[j
].end
= start
;
109 static int cmp_range(const void *x1
, const void *x2
)
111 const struct range
*r1
= x1
;
112 const struct range
*r2
= x2
;
118 return start1
- start2
;
121 int clean_sort_range(struct range
*range
, int az
)
123 int i
, j
, k
= az
- 1, nr_range
= az
;
125 for (i
= 0; i
< k
; i
++) {
128 for (j
= k
; j
> i
; j
--) {
136 range
[i
].start
= range
[k
].start
;
137 range
[i
].end
= range
[k
].end
;
143 for (i
= 0; i
< az
; i
++) {
151 sort(range
, nr_range
, sizeof(struct range
), cmp_range
, NULL
);
156 void sort_range(struct range
*range
, int nr_range
)
159 sort(range
, nr_range
, sizeof(struct range
), cmp_range
, NULL
);