1 /*
2  * Copyright (c) 2018 Intel Corporation.
3  * Copyright (c) 2021 Nordic Semiconductor ASA.
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include "pm_stats.h"
9 
10 #include <zephyr/init.h>
11 #include <zephyr/kernel.h>
12 #include <zephyr/stats/stats.h>
13 #include <zephyr/sys/printk.h>
14 
15 STATS_SECT_START(pm_stats)
16 STATS_SECT_ENTRY32(state_count)
17 STATS_SECT_ENTRY32(state_last_cycles)
18 STATS_SECT_ENTRY32(state_total_cycles)
19 STATS_SECT_END;
20 
21 STATS_NAME_START(pm_stats)
22 STATS_NAME(pm_stats, state_count)
23 STATS_NAME(pm_stats, state_last_cycles)
24 STATS_NAME(pm_stats, state_total_cycles)
25 STATS_NAME_END(pm_stats);
26 
27 static STATS_SECT_DECL(pm_stats) stats[CONFIG_MP_MAX_NUM_CPUS][PM_STATE_COUNT];
28 
29 #define PM_STAT_NAME_LEN sizeof("pm_cpu_XXX_state_X_stats")
30 static char names[CONFIG_MP_MAX_NUM_CPUS][PM_STATE_COUNT][PM_STAT_NAME_LEN];
31 static uint32_t time_start[CONFIG_MP_MAX_NUM_CPUS];
32 static uint32_t time_stop[CONFIG_MP_MAX_NUM_CPUS];
33 
pm_stats_init(void)34 static int pm_stats_init(void)
35 {
36 
37 	unsigned int num_cpus = arch_num_cpus();
38 
39 	for (uint8_t i = 0U; i < num_cpus; i++) {
40 		for (uint8_t j = 0U; j < PM_STATE_COUNT; j++) {
41 			snprintk(names[i][j], PM_STAT_NAME_LEN,
42 				 "pm_cpu_%03d_state_%1d_stats", i, j);
43 			stats_init(&(stats[i][j].s_hdr), STATS_SIZE_32, 3U,
44 				   STATS_NAME_INIT_PARMS(pm_stats));
45 			stats_register(names[i][j], &(stats[i][j].s_hdr));
46 		}
47 	}
48 
49 	return 0;
50 }
51 
52 SYS_INIT(pm_stats_init, PRE_KERNEL_1, CONFIG_KERNEL_INIT_PRIORITY_DEFAULT);
53 
pm_stats_start(void)54 void pm_stats_start(void)
55 {
56 	time_start[_current_cpu->id] = k_cycle_get_32();
57 }
58 
pm_stats_stop(void)59 void pm_stats_stop(void)
60 {
61 	time_stop[_current_cpu->id] = k_cycle_get_32();
62 }
63 
pm_stats_update(enum pm_state state)64 void pm_stats_update(enum pm_state state)
65 {
66 	uint8_t cpu = _current_cpu->id;
67 	uint32_t time_total = time_stop[cpu] - time_start[cpu];
68 
69 	STATS_INC(stats[cpu][state], state_count);
70 	STATS_INCN(stats[cpu][state], state_total_cycles, time_total);
71 	STATS_SET(stats[cpu][state], state_last_cycles, time_total);
72 }
73