2 * Range add and subtract
4 #include <linux/module.h>
5 #include <linux/init.h>
6 #include <linux/sort.h>
8 #include <linux/range.h>
11 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
14 int add_range(struct range *range, int az, int nr_range, u64 start, u64 end)
23 range[nr_range].start = start;
24 range[nr_range].end = end;
31 int add_range_with_merge(struct range *range, int az, int nr_range,
39 /* Try to merge it with old one: */
40 for (i = 0; i < nr_range; i++) {
41 u64 final_start, final_end;
42 u64 common_start, common_end;
47 common_start = max(range[i].start, start);
48 common_end = min(range[i].end, end);
49 if (common_start > common_end)
52 final_start = min(range[i].start, start);
53 final_end = max(range[i].end, end);
55 range[i].start = final_start;
56 range[i].end = final_end;
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 printk(KERN_ERR "run of slot in ranges\n");
106 range[j].end = start;
112 static int cmp_range(const void *x1, const void *x2)
114 const struct range *r1 = x1;
115 const struct range *r2 = x2;
121 return start1 - start2;
124 int clean_sort_range(struct range *range, int az)
126 int i, j, k = az - 1, nr_range = 0;
128 for (i = 0; i < k; i++) {
131 for (j = k; j > i; j--) {
139 range[i].start = range[k].start;
140 range[i].end = range[k].end;
146 for (i = 0; i < az; i++) {
154 sort(range, nr_range, sizeof(struct range), cmp_range, NULL);
159 void sort_range(struct range *range, int nr_range)
162 sort(range, nr_range, sizeof(struct range), cmp_range, NULL);