1 /*
2  * Copyright 2021 Google LLC.
3  * SPDX-License-Identifier: Apache-2.0
4  */
5 
6 #ifndef DRIVERS_SYSCON_SYSCON_COMMON_H_
7 #define DRIVERS_SYSCON_SYSCON_COMMON_H_
8 
9 #include <zephyr/sys/util.h>
10 
11 #ifdef __cplusplus
12 extern "C" {
13 #endif
14 
15 /**
16  * @brief Align and check register address
17  *
18  * @param reg Pointer to the register address in question.
19  * @param reg_size The size of the syscon register region.
20  * @param reg_width The width of a single register (in bytes).
21  *
22  * @retval 0 if the register read is valid.
23  * @retval -EINVAL if the read is invalid.
24  */
syscon_sanitize_reg(uint16_t * reg,size_t reg_size,uint8_t reg_width)25 static inline int syscon_sanitize_reg(uint16_t *reg, size_t reg_size, uint8_t reg_width)
26 {
27 	/* Avoid unaligned readings */
28 	*reg = ROUND_DOWN(*reg, reg_width);
29 
30 	/* Check for out-of-bounds readings */
31 	if (*reg >= reg_size) {
32 		return -EINVAL;
33 	}
34 
35 	return 0;
36 }
37 
38 #ifdef __cplusplus
39 }
40 #endif
41 
42 #endif /* DRIVERS_SYSCON_SYSCON_COMMON_H_ */
43