1 /* 2 * Copyright (C) 2014 Felix Fietkau <nbd@openwrt.org> 3 * Copyright (C) 2004 - 2009 Ivo van Doorn <IvDoorn@gmail.com> 4 * 5 * This program is free software; you can redistribute it and/or modify 6 * it under the terms of the GNU General Public License version 2 7 * as published by the Free Software Foundation 8 * 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 */ 14 15 #ifndef __MT76_UTIL_H 16 #define __MT76_UTIL_H 17 18 /* 19 * Power of two check, this will check 20 * if the mask that has been given contains and contiguous set of bits. 21 * Note that we cannot use the is_power_of_2() function since this 22 * check must be done at compile-time. 23 */ 24 #define is_power_of_two(x) ( !((x) & ((x)-1)) ) 25 #define low_bit_mask(x) ( ((x)-1) & ~(x) ) 26 #define is_valid_mask(x) is_power_of_two(1LU + (x) + low_bit_mask(x)) 27 28 /* 29 * Macros to find first set bit in a variable. 30 * These macros behave the same as the __ffs() functions but 31 * the most important difference that this is done during 32 * compile-time rather then run-time. 33 */ 34 #define compile_ffs2(__x) \ 35 __builtin_choose_expr(((__x) & 0x1), 0, 1) 36 37 #define compile_ffs4(__x) \ 38 __builtin_choose_expr(((__x) & 0x3), \ 39 (compile_ffs2((__x))), \ 40 (compile_ffs2((__x) >> 2) + 2)) 41 42 #define compile_ffs8(__x) \ 43 __builtin_choose_expr(((__x) & 0xf), \ 44 (compile_ffs4((__x))), \ 45 (compile_ffs4((__x) >> 4) + 4)) 46 47 #define compile_ffs16(__x) \ 48 __builtin_choose_expr(((__x) & 0xff), \ 49 (compile_ffs8((__x))), \ 50 (compile_ffs8((__x) >> 8) + 8)) 51 52 #define compile_ffs32(__x) \ 53 __builtin_choose_expr(((__x) & 0xffff), \ 54 (compile_ffs16((__x))), \ 55 (compile_ffs16((__x) >> 16) + 16)) 56 57 /* 58 * This macro will check the requirements for the FIELD{8,16,32} macros 59 * The mask should be a constant non-zero contiguous set of bits which 60 * does not exceed the given typelimit. 61 */ 62 #define FIELD_CHECK(__mask) \ 63 BUILD_BUG_ON(!(__mask) || !is_valid_mask(__mask)) 64 65 #define MT76_SET(_mask, _val) \ 66 ({ \ 67 FIELD_CHECK(_mask); \ 68 (((u32) (_val)) << compile_ffs32(_mask)) & _mask; \ 69 }) 70 71 #define MT76_GET(_mask, _val) \ 72 ({ \ 73 FIELD_CHECK(_mask); \ 74 (u32) (((_val) & _mask) >> compile_ffs32(_mask)); \ 75 }) 76 77 #endif 78