blob: cfb534e76aea976261e1ca275be77bc9a7cfd832 [file] [log] [blame]
Karl Meakin88851f92024-05-10 13:59:08 +01001/*
2 * Copyright 2024 The Hafnium Authors.
3 *
4 * Use of this source code is governed by a BSD-style
5 * license that can be found in the LICENSE file or at
6 * https://opensource.org/licenses/BSD-3-Clause.
7 */
8
Karl Meakin88851f92024-05-10 13:59:08 +01009/**
10 * NOTE: The below macroos use the notation `[hi:lo]` to mean the bits
11 * from `lo` up-to and including `hi`. This matches the notation used in the
12 * FF-A specification.
13 * Examples:
14 * - bits `[4:0]` of `0xAF` are `1111`,
15 * - bits `[7:4]` of `0xAF` are `1010`,
16 * - bits `[31:0]` means the lower half of a 64-bit integer
17 * - bits `[63:32]` means the upper half of a 64-bit integer
18 * - bits `[63:0]` means the whole 64-bit integer
19 */
20
21/**
22 * Isolate the `n`th bit of `value`.
23 */
Karl Meakin1e4d4ee2024-11-27 16:01:44 +000024
25#define GET_BIT(value, n) \
26 __extension__({ \
27 static_assert((n) < 64, "n out of bounds"); \
28 ((value) & (UINT64_C(1) << (n))); \
29 })
Karl Meakin88851f92024-05-10 13:59:08 +010030
31/**
32 * Return true if the `n`th bit of `value` is 1.
33 */
34#define IS_BIT_SET(value, n) (GET_BIT(value, n) != 0)
35
36/**
37 * Return true if the `n`th bit of `value` is 0.
38 */
39#define IS_BIT_UNSET(value, n) (GET_BIT(value, n) == 0)
40
41/**
42 * Return a mask suitable for isolating bits `[hi:lo]` of a 64-bit
43 * integer.
44 */
Karl Meakin1e4d4ee2024-11-27 16:01:44 +000045
46#define GET_BITS_MASK(hi, lo) \
47 __extension__({ \
48 static_assert((hi) < 64, "hi out of bounds"); \
49 static_assert((hi) >= (lo), "hi must be >= lo"); \
50 (((~UINT64_C(0)) - (UINT64_C(1) << (lo)) + 1) & \
51 (~UINT64_C(0) >> (64 - 1 - (hi)))); \
52 })
Karl Meakin88851f92024-05-10 13:59:08 +010053
54/**
55 * Isolate bits `[hi:lo]` of `value`.
56 */
Karl Meakina5ea9092024-05-28 15:40:33 +010057#define GET_BITS(value, hi, lo) ((value) & GET_BITS_MASK(hi, lo))
Karl Meakin88851f92024-05-10 13:59:08 +010058
59/**
60 * Return true if any bits `[lo:hi]` of `value` are 1.
61 */
62#define ANY_BITS_SET(value, hi, lo) (GET_BITS(value, hi, lo) != 0)
63
64/**
65 * Return true if all bits `[lo:hi]` of `value` are 1.
66 */
67#define ALL_BITS_SET(value, hi, lo) \
68 (GET_BITS(value, hi, lo) == GET_BITS_MASK(hi, lo))
69
70/**
71 * Return true if any bits `[lo:hi]` of `value` are 0.
72 */
73#define ANY_BITS_UNSET(value, hi, lo) (!ALL_BITS_SET(value, hi, lo))
74
75/**
76 * Return true if all bits `[lo:hi]` of `value` are 0.
77 */
78#define ALL_BITS_UNSET(value, hi, lo) (!ANY_BITS_SET(value, hi, lo))