Kevin O'Connor | b306459 | 2012-08-14 21:20:10 -0400 | [diff] [blame] | 1 | #ifndef __BYTEORDER_H |
| 2 | #define __BYTEORDER_H |
| 3 | |
Kevin O'Connor | 5a7545c | 2013-09-14 22:54:44 -0400 | [diff] [blame] | 4 | #include "types.h" // u32 |
| 5 | |
Kevin O'Connor | b306459 | 2012-08-14 21:20:10 -0400 | [diff] [blame] | 6 | static inline u16 __swab16_constant(u16 val) { |
| 7 | return (val<<8) | (val>>8); |
| 8 | } |
| 9 | static inline u32 __swab32_constant(u32 val) { |
| 10 | return (val<<24) | ((val&0xff00)<<8) | ((val&0xff0000)>>8) | (val>>24); |
| 11 | } |
| 12 | static inline u64 __swab64_constant(u64 val) { |
| 13 | return ((u64)__swab32_constant(val) << 32) | __swab32_constant(val>>32); |
| 14 | } |
| 15 | static inline u32 __swab32(u32 val) { |
| 16 | asm("bswapl %0" : "+r"(val)); |
| 17 | return val; |
| 18 | } |
| 19 | static inline u64 __swab64(u64 val) { |
| 20 | union u64_u32_u i, o; |
| 21 | i.val = val; |
Kevin O'Connor | b306459 | 2012-08-14 21:20:10 -0400 | [diff] [blame] | 22 | o.lo = __swab32(i.hi); |
Kevin O'Connor | 30e6af0 | 2012-09-15 12:17:37 -0400 | [diff] [blame] | 23 | o.hi = __swab32(i.lo); |
Kevin O'Connor | b306459 | 2012-08-14 21:20:10 -0400 | [diff] [blame] | 24 | return o.val; |
| 25 | } |
| 26 | |
| 27 | #define swab16(x) __swab16_constant(x) |
| 28 | #define swab32(x) (__builtin_constant_p((u32)(x)) \ |
| 29 | ? __swab32_constant(x) : __swab32(x)) |
| 30 | #define swab64(x) (__builtin_constant_p((u64)(x)) \ |
| 31 | ? __swab64_constant(x) : __swab64(x)) |
| 32 | |
| 33 | static inline u16 cpu_to_le16(u16 x) { |
| 34 | return x; |
| 35 | } |
| 36 | static inline u32 cpu_to_le32(u32 x) { |
| 37 | return x; |
| 38 | } |
| 39 | static inline u64 cpu_to_le64(u64 x) { |
| 40 | return x; |
| 41 | } |
| 42 | static inline u16 le16_to_cpu(u16 x) { |
| 43 | return x; |
| 44 | } |
| 45 | static inline u32 le32_to_cpu(u32 x) { |
| 46 | return x; |
| 47 | } |
David Woodhouse | e78e761 | 2013-02-23 00:24:47 +0000 | [diff] [blame] | 48 | static inline u64 le64_to_cpu(u64 x) { |
Kevin O'Connor | b306459 | 2012-08-14 21:20:10 -0400 | [diff] [blame] | 49 | return x; |
| 50 | } |
| 51 | |
| 52 | static inline u16 cpu_to_be16(u16 x) { |
| 53 | return swab16(x); |
| 54 | } |
| 55 | static inline u32 cpu_to_be32(u32 x) { |
| 56 | return swab32(x); |
| 57 | } |
| 58 | static inline u64 cpu_to_be64(u64 x) { |
| 59 | return swab64(x); |
| 60 | } |
| 61 | static inline u16 be16_to_cpu(u16 x) { |
| 62 | return swab16(x); |
| 63 | } |
| 64 | static inline u32 be32_to_cpu(u32 x) { |
| 65 | return swab32(x); |
| 66 | } |
David Woodhouse | e78e761 | 2013-02-23 00:24:47 +0000 | [diff] [blame] | 67 | static inline u64 be64_to_cpu(u64 x) { |
Kevin O'Connor | b306459 | 2012-08-14 21:20:10 -0400 | [diff] [blame] | 68 | return swab64(x); |
| 69 | } |
| 70 | |
| 71 | #endif // byteorder.h |