xref: /nrf52832-nimble/rt-thread/components/drivers/cputime/cputime_cortexm.c (revision 042d53a763ad75cb1465103098bb88c245d95138)
1 /*
2  * Copyright (c) 2006-2018, RT-Thread Development Team
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  *
6  * Change Logs:
7  * Date           Author            Notes
8  * 2017-12-23     Bernard           first version
9  */
10 
11 #include <rthw.h>
12 #include <rtdevice.h>
13 #include <rtthread.h>
14 
15 #include <board.h>
16 
17 /* Use Cycle counter of Data Watchpoint and Trace Register for CPU time */
18 
19 static float cortexm_cputime_getres(void)
20 {
21     float ret = 1000 * 1000 * 1000;
22 
23     ret = ret / SystemCoreClock;
24     return ret;
25 }
26 
27 static uint32_t cortexm_cputime_gettime(void)
28 {
29     return DWT->CYCCNT;
30 }
31 
32 const static struct rt_clock_cputime_ops _cortexm_ops =
33 {
34     cortexm_cputime_getres,
35     cortexm_cputime_gettime
36 };
37 
38 int cortexm_cputime_init(void)
39 {
40     /* check support bit */
41     if ((DWT->CTRL & (1UL << DWT_CTRL_NOCYCCNT_Pos)) == 0)
42     {
43         /* enable trace*/
44         CoreDebug->DEMCR |= (1UL << CoreDebug_DEMCR_TRCENA_Pos);
45 
46         /* whether cycle counter not enabled */
47         if ((DWT->CTRL & (1UL << DWT_CTRL_CYCCNTENA_Pos)) == 0)
48         {
49             /* enable cycle counter */
50             DWT->CTRL |= (1UL << DWT_CTRL_CYCCNTENA_Pos);
51         }
52 
53         clock_cpu_setops(&_cortexm_ops);
54     }
55 
56     return 0;
57 }
58 INIT_BOARD_EXPORT(cortexm_cputime_init);
59