1 /*
2  * Copyright (C) 2015-2019 Alibaba Group Holding Limited
3  */
4 
5 #include "k_api.h"
6 
7 #if (RHINO_CONFIG_SCHED_CFS > 0)
8 static struct k_rbtree_root_t  cfs_root = RBT_ROOT;
9 
10 /*
11  * Insert @key into rbtree, On success, return 0, else return -1
12  */
node_insert(struct k_rbtree_root_t * root,cfs_node * node,lr_timer_t key)13 static void node_insert(struct k_rbtree_root_t *root, cfs_node *node, lr_timer_t key)
14 {
15     struct k_rbtree_node_t **tmp = &(root->rbt_node), *parent = NULL;
16 
17     /* Figure out where to put new node */
18     while (*tmp) {
19         cfs_node *my = k_rbtree_entry(*tmp, cfs_node, rbt_node);
20         parent = *tmp;
21         if (key <= my->key)
22             tmp = &((*tmp)->rbt_left);
23         else if (key > my->key)
24             tmp = &((*tmp)->rbt_right);
25     }
26 
27     node->key = key;
28 
29     /* Add new node and rebalance tree. */
30     k_rbtree_link_node(&node->rbt_node, parent, tmp);
31     k_rbtree_insert_color(&node->rbt_node, root);
32 }
33 
cfs_node_insert(cfs_node * node,lr_timer_t key)34 void cfs_node_insert(cfs_node *node, lr_timer_t key)
35 {
36     node_insert(&cfs_root, node, key);
37 }
38 
cfs_node_del(cfs_node * node)39 void cfs_node_del(cfs_node *node)
40 {
41     k_rbtree_erase(&node->rbt_node, &cfs_root);
42 }
43 
cfs_node_min_get(void)44 lr_timer_t cfs_node_min_get(void)
45 {
46     struct k_rbtree_node_t *tmp;
47     cfs_node        *node_cfs;
48 
49     tmp  = k_rbtree_first(&cfs_root);
50     if (tmp == NULL) {
51         return 0;
52     }
53 
54     node_cfs = k_rbtree_entry(tmp, cfs_node, rbt_node);
55     return node_cfs->key;
56 }
57 
cfs_preferred_task_get(void)58 ktask_t *cfs_preferred_task_get(void)
59 {
60     struct k_rbtree_node_t *tmp;
61     cfs_node        *node_cfs;
62     ktask_t         *task;
63 
64     tmp  = k_rbtree_first(&cfs_root);
65     if (tmp == NULL) {
66         return 0;
67     }
68 
69     node_cfs = k_rbtree_entry(tmp, cfs_node, rbt_node);
70     task     = krhino_list_entry(node_cfs, ktask_t, node);
71 
72     return task;
73 }
74 #endif
75 
76