2 * Copyright (c) 2014 Nicira, Inc.
3 * Copyright (c) 2014 Netronome.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at:
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
24 struct hmap_node node;
30 uint32_t base; /* IDs in the range of [base, base + n_ids). */
31 uint32_t n_ids; /* Total number of ids in the pool. */
32 uint32_t next_free_id; /* Possible next free id. */
35 static void id_pool_init(struct id_pool *pool,
36 uint32_t base, uint32_t n_ids);
37 static void id_pool_uninit(struct id_pool *pool);
38 static struct id_node *id_pool_find(struct id_pool *pool, uint32_t id);
41 id_pool_create(uint32_t base, uint32_t n_ids)
45 pool = xmalloc(sizeof *pool);
46 id_pool_init(pool, base, n_ids);
52 id_pool_destroy(struct id_pool *pool)
61 id_pool_init(struct id_pool *pool, uint32_t base, uint32_t n_ids)
65 pool->next_free_id = base;
66 hmap_init(&pool->map);
70 id_pool_uninit(struct id_pool *pool)
72 struct id_node *id_node, *next;
74 HMAP_FOR_EACH_SAFE(id_node, next, node, &pool->map) {
75 hmap_remove(&pool->map, &id_node->node);
79 hmap_destroy(&pool->map);
82 static struct id_node *
83 id_pool_find(struct id_pool *pool, uint32_t id)
86 struct id_node *id_node;
88 hash = hash_int(id, 0);
89 HMAP_FOR_EACH_WITH_HASH(id_node, node, hash, &pool->map) {
90 if (id == id_node->id) {
98 id_pool_add(struct id_pool *pool, uint32_t id)
100 struct id_node *id_node = xmalloc(sizeof *id_node);
104 hash = hash_int(id, 0);
105 hmap_insert(&pool->map, &id_node->node, hash);
109 id_pool_alloc_id(struct id_pool *pool, uint32_t *id_)
113 if (pool->n_ids == 0) {
117 if (!(id_pool_find(pool, pool->next_free_id))) {
118 id = pool->next_free_id;
122 for(id = pool->base; id < pool->base + pool->n_ids; id++) {
123 if (!id_pool_find(pool, id)) {
132 id_pool_add(pool, id);
134 if (id < pool->base + pool->n_ids) {
135 pool->next_free_id = id + 1;
137 pool->next_free_id = pool->base;
145 id_pool_free_id(struct id_pool *pool, uint32_t id)
147 struct id_node *id_node;
148 if (id > pool->base && (id <= pool->base + pool->n_ids)) {
149 id_node = id_pool_find(pool, id);
151 hmap_remove(&pool->map, &id_node->node);