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/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 #define UNUSED_PARAM(param) (void) (param) 28 29 #ifndef alignof 30 #define alignof(type) offsetof(struct { char x; type field; }, field) 31 #endif 32 /* 33 * this macro does not consume bytes from any segment; if condition is true it is a zero-sized array; 34 * if some compilers do try to allocate space for them we create a special section for those checks 35 * and discard this section at link time 36 */ 37 #define C_STATIC_ASSERT(name, condition) \ 38 static const char __attribute__((used, section(".static_assert"))) \ 39 static_assert_check_ ## name [(condition) ? 0 : -1] = {} 40 41 #define unlikely(x) (x) 42 #define likely(x) (x) 43 44 #define container_of(addr, struct_name, field_name) \ 45 ((struct_name *)((char *)(addr) - offsetof(struct_name, field_name))) 46 47 static inline bool IS_POWER_OF_TWO(unsigned int n) 48 { 49 return !(n & (n - 1)); 50 } 51 52 static inline int LOG2_FLOOR(unsigned int n) 53 { 54 if (UNLIKELY(n == 0)) 55 return INT_MIN; 56 57 // floor(log2(n)) = MSB(n) = (# of bits) - (# of leading zeros) - 1 58 return 8 * sizeof(n) - CLZ(n) - 1; 59 } 60 61 static inline int LOG2_CEIL(unsigned int n) 62 { 63 return IS_POWER_OF_TWO(n) ? LOG2_FLOOR(n) : LOG2_FLOOR(n) + 1; 64 } 65 66 #ifdef SYSCALL_VARARGS_PARAMS_PASSED_AS_PTRS 67 #define VA_LIST_TO_INTEGER(__vl) ((uintptr_t)(&__vl)) 68 #define INTEGER_TO_VA_LIST(__ptr) (*(va_list*)(__ptr)) 69 #else 70 #define VA_LIST_TO_INTEGER(__vl) (*(uintptr_t*)(&__vl)) 71 #define INTEGER_TO_VA_LIST(__ptr) ({uintptr_t tmp = __ptr; (*(va_list*)(&tmp)); }) 72 #endif 73 74 #endif /* __UTIL_H */ 75