2 * Copyright (C) 2020 Francis Deslauriers <francis.deslauriers@efficios.com>
4 * SPDX-License-Identifier: GPL-2.0-only
12 #include <urcu/list.h>
17 #include "index-allocator.h"
19 struct lttng_index_allocator
{
20 struct cds_list_head unused_list
;
27 struct cds_list_head head
;
30 struct lttng_index_allocator
*lttng_index_allocator_create(
33 struct lttng_index_allocator
*allocator
= NULL
;
35 allocator
= zmalloc(sizeof(*allocator
));
37 PERROR("Failed to allocate index allocator");
41 allocator
->size
= index_count
;
42 allocator
->position
= 0;
44 CDS_INIT_LIST_HEAD(&allocator
->unused_list
);
50 uint64_t lttng_index_allocator_get_index_count(struct lttng_index_allocator
*allocator
)
52 return allocator
->size
;
55 enum lttng_index_allocator_status
lttng_index_allocator_alloc(
56 struct lttng_index_allocator
*allocator
,
57 uint64_t *allocated_index
)
59 enum lttng_index_allocator_status status
=
60 LTTNG_INDEX_ALLOCATOR_STATUS_OK
;
62 if (cds_list_empty(&allocator
->unused_list
)) {
63 if (allocator
->position
>= allocator
->size
) {
64 /* No indices left. */
65 status
= LTTNG_INDEX_ALLOCATOR_STATUS_EMPTY
;
69 *allocated_index
= allocator
->position
++;
71 struct lttng_index
*index
;
73 index
= cds_list_first_entry(&allocator
->unused_list
,
74 typeof(*index
), head
);
75 cds_list_del(&index
->head
);
76 *allocated_index
= index
->index
;
84 enum lttng_index_allocator_status
lttng_index_allocator_release(
85 struct lttng_index_allocator
*allocator
, uint64_t idx
)
87 struct lttng_index
*index
= NULL
;
88 enum lttng_index_allocator_status status
=
89 LTTNG_INDEX_ALLOCATOR_STATUS_OK
;
91 assert(idx
< allocator
->size
);
93 index
= zmalloc(sizeof(*index
));
95 PERROR("Failed to allocate free index queue");
96 status
= LTTNG_INDEX_ALLOCATOR_STATUS_ERROR
;
101 cds_list_add_tail(&index
->head
, &allocator
->unused_list
);
107 void lttng_index_allocator_destroy(struct lttng_index_allocator
*allocator
)
109 struct lttng_index
*index
= NULL
, *tmp_index
= NULL
;
115 if (lttng_index_allocator_get_index_count(allocator
) > 0) {
116 WARN("Destroying index allocator with %" PRIu64
117 " slot indexes still in use",
118 lttng_index_allocator_get_index_count(allocator
));
121 cds_list_for_each_entry_safe(index
, tmp_index
,
122 &allocator
->unused_list
, head
) {
123 cds_list_del(&index
->head
);