summaryrefslogtreecommitdiff
path: root/gxp-range-alloc.c
blob: 73aa6af9df8354055e7b0b9852917b7904194581 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
// SPDX-License-Identifier: GPL-2.0
/*
 * GXP ranged resource allocator.
 *
 * Copyright (C) 2021 Google LLC
 */

#include "gxp-range-alloc.h"

struct range_alloc *range_alloc_create(int start, int end)
{
	struct range_alloc *ra;
	int count;
	int size;

	count = end - start;
	if (count <= 0)
		return ERR_PTR(-EINVAL);

	size = sizeof(struct range_alloc) + count * sizeof(int);
	ra = kzalloc(size, GFP_KERNEL);
	if (!ra)
		return ERR_PTR(-ENOMEM);

	ra->total_count = count;
	ra->free_count = count;
	ra->start_index = start;
	mutex_init(&ra->lock);

	return ra;
}

int range_alloc_get(struct range_alloc *r, int element)
{
	int index = element - r->start_index;

	mutex_lock(&r->lock);
	if (index < 0 || index >= r->total_count) {
		mutex_unlock(&r->lock);
		return -EINVAL;
	}

	if (r->elements[index]) {
		mutex_unlock(&r->lock);
		return -EBUSY;
	}

	r->elements[index] = 1;
	r->free_count--;

	mutex_unlock(&r->lock);
	return 0;
}

int range_alloc_get_any(struct range_alloc *r, int *element)
{
	int i;

	mutex_lock(&r->lock);
	if (!r->free_count) {
		mutex_unlock(&r->lock);
		return -ENOMEM;
	}

	for (i = 0; i < r->total_count; i++) {
		if (r->elements[i] == 0) {
			r->elements[i] = 1;
			r->free_count--;
			*element = i + r->start_index;
			mutex_unlock(&r->lock);
			return 0;
		}
	}
	mutex_unlock(&r->lock);
	return -ENOMEM;
}

int range_alloc_put(struct range_alloc *r, int element)
{
	int index = element - r->start_index;

	mutex_lock(&r->lock);
	if (index < 0 || index >= r->total_count) {
		mutex_unlock(&r->lock);
		return -EINVAL;
	}

	if (r->elements[index] == 0) {
		mutex_unlock(&r->lock);
		return -EBUSY;
	}

	r->elements[index] = 0;
	r->free_count++;

	mutex_unlock(&r->lock);
	return 0;
}

int range_alloc_num_free(struct range_alloc *r)
{
	int free_count;

	mutex_lock(&r->lock);
	free_count = r->free_count;
	mutex_unlock(&r->lock);

	return free_count;
}

int range_alloc_destroy(struct range_alloc *r)
{
	if (!r)
		return -EFAULT;
	kfree(r);

	return 0;
}