1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef __UTIL_H
18 #define __UTIL_H
19 #include <plat/inc/plat.h>
20 #include "toolchain.h"
21 #include <limits.h>
22 #include <stdbool.h>
23 #include <stddef.h>
24 
25 #define ARRAY_SIZE(a)   (sizeof((a)) / sizeof((a)[0]))
26 
27 #ifndef alignof
28 #define alignof(type) offsetof(struct { char x; type field; }, field)
29 #endif
30 
31 #define container_of(addr, struct_name, field_name) \
32     ((struct_name *)((char *)(addr) - offsetof(struct_name, field_name)))
33 
IS_POWER_OF_TWO(unsigned int n)34 static inline bool IS_POWER_OF_TWO(unsigned int n)
35 {
36     return !(n & (n - 1));
37 }
38 
LOG2_FLOOR(unsigned int n)39 static inline int LOG2_FLOOR(unsigned int n)
40 {
41     if (UNLIKELY(n == 0))
42         return INT_MIN;
43 
44     // floor(log2(n)) = MSB(n) = (# of bits) - (# of leading zeros) - 1
45     return 8 * sizeof(n) - CLZ(n) - 1;
46 }
47 
LOG2_CEIL(unsigned int n)48 static inline int LOG2_CEIL(unsigned int n)
49 {
50     return IS_POWER_OF_TWO(n) ? LOG2_FLOOR(n) : LOG2_FLOOR(n) + 1;
51 }
52 
53 #ifdef SYSCALL_VARARGS_PARAMS_PASSED_AS_PTRS
54   #define VA_LIST_TO_INTEGER(__vl)  ((uintptr_t)(&__vl))
55   #define INTEGER_TO_VA_LIST(__ptr)  (*(va_list*)(__ptr))
56 #else
57   #define VA_LIST_TO_INTEGER(__vl)  (*(uintptr_t*)(&__vl))
58   #define INTEGER_TO_VA_LIST(__ptr)  ({uintptr_t tmp = __ptr; (*(va_list*)(&tmp)); })
59 #endif
60 
61 #endif /* __UTIL_H */
62