blob: 5d90074dca7550f4935e71127911441c9bc617e2 [file] [log] [blame]
FUJITA Tomonori0291df82008-02-04 22:28:07 -08001/*
2 * IOMMU helper functions for the free area management
3 */
4
5#include <linux/module.h>
6#include <linux/bitops.h>
7
8static unsigned long find_next_zero_area(unsigned long *map,
9 unsigned long size,
10 unsigned long start,
11 unsigned int nr,
12 unsigned long align_mask)
13{
14 unsigned long index, end, i;
15again:
16 index = find_next_zero_bit(map, size, start);
17
18 /* Align allocation */
19 index = (index + align_mask) & ~align_mask;
20
21 end = index + nr;
22 if (end >= size)
23 return -1;
24 for (i = index; i < end; i++) {
25 if (test_bit(i, map)) {
26 start = i+1;
27 goto again;
28 }
29 }
30 return index;
31}
32
FUJITA Tomonorid26dbc52008-09-22 22:35:07 +090033void iommu_area_reserve(unsigned long *map, unsigned long i, int len)
FUJITA Tomonori0291df82008-02-04 22:28:07 -080034{
35 unsigned long end = i + len;
36 while (i < end) {
37 __set_bit(i, map);
38 i++;
39 }
40}
41
FUJITA Tomonori37158632008-03-04 14:29:27 -080042int iommu_is_span_boundary(unsigned int index, unsigned int nr,
43 unsigned long shift,
44 unsigned long boundary_size)
FUJITA Tomonori0291df82008-02-04 22:28:07 -080045{
FUJITA Tomonori37158632008-03-04 14:29:27 -080046 BUG_ON(!is_power_of_2(boundary_size));
47
FUJITA Tomonori0291df82008-02-04 22:28:07 -080048 shift = (shift + index) & (boundary_size - 1);
49 return shift + nr > boundary_size;
50}
51
52unsigned long iommu_area_alloc(unsigned long *map, unsigned long size,
53 unsigned long start, unsigned int nr,
54 unsigned long shift, unsigned long boundary_size,
55 unsigned long align_mask)
56{
57 unsigned long index;
58again:
59 index = find_next_zero_area(map, size, start, nr, align_mask);
60 if (index != -1) {
FUJITA Tomonori37158632008-03-04 14:29:27 -080061 if (iommu_is_span_boundary(index, nr, shift, boundary_size)) {
FUJITA Tomonori0291df82008-02-04 22:28:07 -080062 /* we could do more effectively */
63 start = index + 1;
64 goto again;
65 }
FUJITA Tomonorid26dbc52008-09-22 22:35:07 +090066 iommu_area_reserve(map, index, nr);
FUJITA Tomonori0291df82008-02-04 22:28:07 -080067 }
68 return index;
69}
70EXPORT_SYMBOL(iommu_area_alloc);
71
72void iommu_area_free(unsigned long *map, unsigned long start, unsigned int nr)
73{
74 unsigned long end = start + nr;
75
76 while (start < end) {
77 __clear_bit(start, map);
78 start++;
79 }
80}
81EXPORT_SYMBOL(iommu_area_free);