| 1 | /* SPDX-License-Identifier: GPL-2.0 */ |
| 2 | #ifndef _LINUX_VIRTIO_FEATURES_H |
| 3 | #define _LINUX_VIRTIO_FEATURES_H |
| 4 | |
| 5 | #include <linux/bits.h> |
| 6 | #include <linux/bug.h> |
| 7 | #include <linux/string.h> |
| 8 | |
| 9 | #define VIRTIO_FEATURES_U64S 2 |
| 10 | #define VIRTIO_FEATURES_BITS (VIRTIO_FEATURES_U64S * 64) |
| 11 | |
| 12 | #define VIRTIO_BIT(b) BIT_ULL((b) & 0x3f) |
| 13 | #define VIRTIO_U64(b) ((b) >> 6) |
| 14 | |
| 15 | #define VIRTIO_DECLARE_FEATURES(name) \ |
| 16 | union { \ |
| 17 | u64 name; \ |
| 18 | u64 name##_array[VIRTIO_FEATURES_U64S];\ |
| 19 | } |
| 20 | |
| 21 | static inline bool virtio_features_chk_bit(unsigned int bit) |
| 22 | { |
| 23 | if (__builtin_constant_p(bit)) { |
| 24 | /* |
| 25 | * Don't care returning the correct value: the build |
| 26 | * will fail before any bad features access |
| 27 | */ |
| 28 | BUILD_BUG_ON(bit >= VIRTIO_FEATURES_BITS); |
| 29 | } else { |
| 30 | if (WARN_ON_ONCE(bit >= VIRTIO_FEATURES_BITS)) |
| 31 | return false; |
| 32 | } |
| 33 | return true; |
| 34 | } |
| 35 | |
| 36 | static inline bool virtio_features_test_bit(const u64 *features, |
| 37 | unsigned int bit) |
| 38 | { |
| 39 | return virtio_features_chk_bit(bit) && |
| 40 | !!(features[VIRTIO_U64(bit)] & VIRTIO_BIT(bit)); |
| 41 | } |
| 42 | |
| 43 | static inline void virtio_features_set_bit(u64 *features, |
| 44 | unsigned int bit) |
| 45 | { |
| 46 | if (virtio_features_chk_bit(bit)) |
| 47 | features[VIRTIO_U64(bit)] |= VIRTIO_BIT(bit); |
| 48 | } |
| 49 | |
| 50 | static inline void virtio_features_clear_bit(u64 *features, |
| 51 | unsigned int bit) |
| 52 | { |
| 53 | if (virtio_features_chk_bit(bit)) |
| 54 | features[VIRTIO_U64(bit)] &= ~VIRTIO_BIT(bit); |
| 55 | } |
| 56 | |
| 57 | static inline void virtio_features_zero(u64 *features) |
| 58 | { |
| 59 | memset(features, 0, sizeof(features[0]) * VIRTIO_FEATURES_U64S); |
| 60 | } |
| 61 | |
| 62 | static inline void virtio_features_from_u64(u64 *features, u64 from) |
| 63 | { |
| 64 | virtio_features_zero(features); |
| 65 | features[0] = from; |
| 66 | } |
| 67 | |
| 68 | static inline bool virtio_features_equal(const u64 *f1, const u64 *f2) |
| 69 | { |
| 70 | int i; |
| 71 | |
| 72 | for (i = 0; i < VIRTIO_FEATURES_U64S; ++i) |
| 73 | if (f1[i] != f2[i]) |
| 74 | return false; |
| 75 | return true; |
| 76 | } |
| 77 | |
| 78 | static inline void virtio_features_copy(u64 *to, const u64 *from) |
| 79 | { |
| 80 | memcpy(to, from, sizeof(to[0]) * VIRTIO_FEATURES_U64S); |
| 81 | } |
| 82 | |
| 83 | static inline void virtio_features_andnot(u64 *to, const u64 *f1, const u64 *f2) |
| 84 | { |
| 85 | int i; |
| 86 | |
| 87 | for (i = 0; i < VIRTIO_FEATURES_U64S; i++) |
| 88 | to[i] = f1[i] & ~f2[i]; |
| 89 | } |
| 90 | |
| 91 | #endif |
| 92 | |