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 free index queue");
40 allocator
->size
= index_count
;
41 allocator
->position
= 0;
43 CDS_INIT_LIST_HEAD(&allocator
->unused_list
);
49 uint64_t lttng_index_allocator_get_index_count(struct lttng_index_allocator
*allocator
)
51 return allocator
->size
;
54 enum lttng_index_allocator_status
lttng_index_allocator_alloc(
55 struct lttng_index_allocator
*allocator
,
56 uint64_t *allocated_index
)
58 enum lttng_index_allocator_status status
=
59 LTTNG_INDEX_ALLOCATOR_STATUS_OK
;
61 if (cds_list_empty(&allocator
->unused_list
)) {
62 if (allocator
->position
>= allocator
->size
) {
63 /* No indices left. */
64 status
= LTTNG_INDEX_ALLOCATOR_STATUS_EMPTY
;
68 *allocated_index
= allocator
->position
++;
70 struct lttng_index
*index
;
72 index
= cds_list_first_entry(&allocator
->unused_list
,
73 typeof(*index
), head
);
74 cds_list_del(&index
->head
);
75 *allocated_index
= index
->index
;
83 enum lttng_index_allocator_status
lttng_index_allocator_release(
84 struct lttng_index_allocator
*allocator
, uint64_t idx
)
86 struct lttng_index
*index
= NULL
;
87 enum lttng_index_allocator_status status
=
88 LTTNG_INDEX_ALLOCATOR_STATUS_OK
;
90 assert(idx
< allocator
->size
);
92 index
= zmalloc(sizeof(*index
));
94 PERROR("Failed to allocate free index queue");
95 status
= LTTNG_INDEX_ALLOCATOR_STATUS_ERROR
;
100 cds_list_add_tail(&index
->head
, &allocator
->unused_list
);
106 void lttng_index_allocator_destroy(struct lttng_index_allocator
*allocator
)
108 struct lttng_index
*index
= NULL
, *tmp_index
= NULL
;
114 cds_list_for_each_entry_safe(index
, tmp_index
,
115 &allocator
->unused_list
, head
) {
116 cds_list_del(&index
->head
);