MCCI Trusted Bootloader
Simple trusted bootloader and tools for small embedded systems
mcci_bootloader_bits.h
Go to the documentation of this file.
1/*
2
3Module: mcci_bootloader_bits.h
4
5Function:
6 Bit macros for the MCCI bootloader.
7
8Copyright and License:
9 This file copyright (C) 2021 by
10
11 MCCI Corporation
12 3520 Krums Corners Road
13 Ithaca, NY 14850
14
15 See accompanying LICENSE file for copyright and license information.
16
17Author:
18 Terry Moore, MCCI Corporation March 2021
19
20*/
21
22#ifndef _mcci_bootloader_bits_h_
23#define _mcci_bootloader_bits_h_ /* prevent multiple includes */
24
25#pragma once
26
27#ifdef __cplusplus
28extern "C" {
29#endif
30
31///
32/// \brief compute log2 of an power of 2.
33///
34/// This can be used at compile time or run time.
35///
36/// \see Knuth V4 7.1.3 (49).
37///
38#define MCCI_BOOTLOADER_LOG2_POW2(x) \
39 ((x) == 0 ? -1 : \
40 (((x) & 0x5555555555555555u) == 0 ? 1 : 0) + \
41 (((x) & 0x3333333333333333u) == 0 ? 2 : 0) + \
42 (((x) & 0x0f0f0f0f0f0f0f0fu) == 0 ? 4 : 0) + \
43 (((x) & 0x00FF00FF00FF00FFu) == 0 ? 8 : 0) + \
44 (((x) & 0x0000FFFF0000FFFFu) == 0 ? 16 : 0) + \
45 (((x) & 0x00000000FFFFFFFFu) == 0 ? 32 : 0))
46
47///
48/// \brief get shift count from field mask.
49///
50/// \param[in] x field mask; bitmask should be of form 0*11*0*
51///
52/// \details
53/// We might have some 64-bit fields, so...
54/// this goes through through bit 63. We use `~(x)+1` to form the unsigned twos-
55/// complement of \c x without trying to negate an unsigned or doing
56/// a type-cast. Avoids warnings on some compilers. This is exactly
57/// what Knuth calls "rho" (the ruler function).
58///
59/// \see Knuth V4 7.1.3.
60///
61#define MCCI_BOOTLOADER_FIELD_SHIFT(x) MCCI_BOOTLOADER_LOG2_POW2((x) & (~(x)+1))
62
63/*! get LSB from field mask */
64#define MCCI_BOOTLOADER_FIELD_LSB(fmask) \
65 ((fmask) & (~(fmask) + 1u))
66
67/*! generate field value (properly positioned) */
68#define MCCI_BOOTLOADER_VALUE_MAKE_FIELD(val, fmask) \
69 (MCCI_BOOTLOADER_FIELD_LSB(fmask) * (val))
70
71/*! generate field value (properly positioned) */
72#define MCCI_BOOTLOADER_FIELD_SET_VALUE(fmask, val) \
73 (MCCI_BOOTLOADER_FIELD_LSB(fmask) * (val))
74
75/*! extract and normalize value of field */
76#define MCCI_BOOTLOADER_VALUE_GET_FIELD(val, fmask) \
77 (((val) & (fmask)) >> MCCI_BOOTLOADER_FIELD_SHIFT(fmask))
78
79#ifdef __cplusplus
80}
81#endif
82
83#endif /* _mcci_bootloader_bits_h_ */