1 /*
2  * Copyright (c) 2006-2021, RT-Thread Development Team
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  *
6  * Change Logs:
7  * Date           Author       Notes
8  * 2021-08-25     RT-Thread    First version
9  * 2023-09-15     xqyjlj       perf rt_hw_interrupt_disable/enable
10  */
11 #include <rthw.h>
12 #include <rtthread.h>
13 #include <resource_id.h>
14 
resource_id_init(resource_id_t * mgr,int size,void ** res)15 void resource_id_init(resource_id_t *mgr, int size, void **res)
16 {
17     if (mgr)
18     {
19         mgr->size = size;
20         mgr->_res = res;
21         mgr->noused = 0;
22         mgr->_free = RT_NULL;
23         rt_spin_lock_init(&(mgr->spinlock));
24     }
25 }
26 
resource_id_get(resource_id_t * mgr)27 int resource_id_get(resource_id_t *mgr)
28 {
29     rt_base_t level;
30     void **cur;
31 
32     level = rt_spin_lock_irqsave(&(mgr->spinlock));
33     if (mgr->_free)
34     {
35         cur = mgr->_free;
36         mgr->_free = (void **)*mgr->_free;
37         rt_spin_unlock_irqrestore(&(mgr->spinlock), level);
38         return cur - mgr->_res;
39     }
40     else if (mgr->noused < mgr->size)
41     {
42         cur = &mgr->_res[mgr->noused++];
43         rt_spin_unlock_irqrestore(&(mgr->spinlock), level);
44         return cur - mgr->_res;
45     }
46 
47     return -1;
48 }
49 
resource_id_put(resource_id_t * mgr,int no)50 void resource_id_put(resource_id_t *mgr, int no)
51 {
52     rt_base_t level;
53     void **cur;
54 
55     if (no >= 0 && no < mgr->size)
56     {
57         level = rt_spin_lock_irqsave(&(mgr->spinlock));
58         cur = &mgr->_res[no];
59         *cur = (void *)mgr->_free;
60         mgr->_free = cur;
61         rt_spin_unlock_irqrestore(&(mgr->spinlock), level);
62     }
63 }
64