1 /*
2  * Copyright (c) 2023 Intel Corporation
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 /**
8  * @file
9  * @brief Module for tracking page use within memory banks
10  *
11  * The memory management drivers may use the routines within this module
12  * to track page use within their memory banks. This information in turn
13  * could be leveraged by them to determine when to power them on or off to
14  * better conserve energy.
15  */
16 
17 #include <zephyr/kernel.h>
18 #include <zephyr/drivers/mm/mm_drv_bank.h>
19 #include <zephyr/sys/mem_stats.h>
20 
sys_mm_drv_bank_init(struct mem_drv_bank * bank,uint32_t bank_pages)21 void sys_mm_drv_bank_init(struct mem_drv_bank *bank, uint32_t bank_pages)
22 {
23 	bank->unmapped_pages = 0;
24 	bank->mapped_pages = bank_pages;
25 	bank->max_mapped_pages = bank_pages;
26 }
27 
sys_mm_drv_bank_page_mapped(struct mem_drv_bank * bank)28 uint32_t sys_mm_drv_bank_page_mapped(struct mem_drv_bank *bank)
29 {
30 	bank->unmapped_pages--;
31 	bank->mapped_pages++;
32 	if (bank->mapped_pages > bank->max_mapped_pages) {
33 		bank->max_mapped_pages = bank->mapped_pages;
34 	}
35 	return bank->mapped_pages;
36 }
37 
sys_mm_drv_bank_page_unmapped(struct mem_drv_bank * bank)38 uint32_t sys_mm_drv_bank_page_unmapped(struct mem_drv_bank *bank)
39 {
40 	bank->unmapped_pages++;
41 	bank->mapped_pages--;
42 	return bank->unmapped_pages;
43 }
44 
sys_mm_drv_bank_stats_get(struct mem_drv_bank * bank,struct sys_memory_stats * stats)45 void sys_mm_drv_bank_stats_get(struct mem_drv_bank *bank,
46 			       struct sys_memory_stats *stats)
47 {
48 	stats->free_bytes          = bank->unmapped_pages *
49 				     CONFIG_MM_DRV_PAGE_SIZE;
50 	stats->allocated_bytes     = bank->mapped_pages *
51 				     CONFIG_MM_DRV_PAGE_SIZE;
52 	stats->max_allocated_bytes = bank->max_mapped_pages *
53 				     CONFIG_MM_DRV_PAGE_SIZE;
54 }
55 
sys_mm_drv_bank_stats_reset_max(struct mem_drv_bank * bank)56 void sys_mm_drv_bank_stats_reset_max(struct mem_drv_bank *bank)
57 {
58 	bank->max_mapped_pages = bank->mapped_pages;
59 }
60