1 /*
2  * Copyright (c) 2017, Nordic Semiconductor ASA
3  * All rights reserved.
4  *
5  * SPDX-License-Identifier: BSD-3-Clause
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright notice, this
11  *    list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
18  *    contributors may be used to endorse or promote products derived from this
19  *    software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
25  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  *
33  */
34 
35 #ifndef NRF_802154_UTILS_H__
36 #define NRF_802154_UTILS_H__
37 
38 #include "nrf_802154_assert.h"
39 #include <stdint.h>
40 #include <string.h>
41 #include "nrfx.h"
42 #include <soc/nrfx_coredep.h>
43 
44 /**
45  * @defgroup nrf_802154_utils Utils definitions used in the 802.15.4 driver
46  * @{
47  * @ingroup nrf_802154
48  * @brief Definitions of utils used in the 802.15.4 driver.
49  */
50 
51 /**@brief RTC clock frequency. */
52 #define NRF_802154_RTC_FREQUENCY               32768UL
53 
54 /**@brief Defines the number of microseconds in one second. */
55 #define NRF_802154_US_PER_S                    1000000ULL
56 
57 /**@brief Number of microseconds in one RTC tick (rounded up). */
58 #define NRF_802154_US_PER_TICK                 NRF_802154_RTC_TICKS_TO_US(1)
59 
60 /**@brief Number of bits to shift RTC_FREQUENCY and US_PER_S to achieve the division by greatest common divisor. */
61 #define NRF_802154_FREQUENCY_US_PER_S_GCD_BITS 6
62 
63 /**@brief Ceil division helper. */
64 #define NRF_802154_DIVIDE_AND_CEIL(A, B)       (((A) + (B)-1) / (B))
65 
66 /**@brief Defines the conversion of RTC ticks to microseconds (us). */
67 #define NRF_802154_RTC_TICKS_TO_US(ticks)                                          \
68     NRF_802154_DIVIDE_AND_CEIL(                                                    \
69         (ticks) * (NRF_802154_US_PER_S >> NRF_802154_FREQUENCY_US_PER_S_GCD_BITS), \
70         (NRF_802154_RTC_FREQUENCY >> NRF_802154_FREQUENCY_US_PER_S_GCD_BITS))
71 
72 /**@brief Macro to get the number of elements in an array.
73  *
74  * @param[in] X   Array.
75  */
76 #define NUMELTS(X)                      (sizeof((X)) / sizeof(X[0]))
77 
78 /**@brief Active waiting for given number of microseconds.
79  *
80  * It is guaranteed that execution of this macro will take at least @c time_in_us
81  * number of microseconds.
82  */
83 #define nrf_802154_delay_us(time_in_us) nrfx_coredep_delay_us(time_in_us)
84 
85 /**@brief Type holding MCU critical section state.
86  *
87  * Variable of this type is required to hold state saved by @ref nrf_802154_mcu_critical_enter
88  * and restored by @ref nrf_802154_mcu_critical_exit.
89  */
90 typedef uint32_t nrf_802154_mcu_critical_state_t;
91 
92 /**@brief Enters critical section on MCU level.
93  *
94  * Use @ref nrf_802154_mcu_critical_exit complementary. Consider following code:
95  * @code
96  * nrf_802154_mcu_critical_state_t mcu_cs;
97  * nrf_802154_mcu_critical_enter(mcu_cs);
98  * // do your critical stuff as fast as possible
99  * nrf_802154_mcu_critical_exit(mcu_cs);
100  * @endcode
101  *
102  * @param mcu_critical_state    Variable of @ref nrf_802154_mcu_critical_state_t where current
103  *                              state of MCU level critical section will be stored.
104  */
105 #define nrf_802154_mcu_critical_enter(mcu_critical_state) \
106     do                                                    \
107     {                                                     \
108         (mcu_critical_state) = __get_PRIMASK();           \
109         __disable_irq();                                  \
110     }                                                     \
111     while (0)
112 
113 /**@brief Exits critical section on MCU level.
114  *
115  * This shall be used complementary to @ref nrf_802154_mcu_critical_enter.
116  *
117  * @param mcu_critical_state    Variable of @ref nrf_802154_mcu_critical_state_t where
118  *                              state of MCU level critical section is stored by
119  *                              former call to @ref nrf_802154_mcu_critical_enter
120  */
121 #define nrf_802154_mcu_critical_exit(mcu_critical_state) \
122     do                                                   \
123     {                                                    \
124         __set_PRIMASK(mcu_critical_state);               \
125     }                                                    \
126     while (0)
127 
NRF_802154_US_TO_RTC_TICKS(uint64_t time)128 static inline uint64_t NRF_802154_US_TO_RTC_TICKS(uint64_t time)
129 {
130     uint64_t t1, u1;
131     uint64_t result;
132 
133     /* The required range for time is [0..315360000000000], and the calculation below is
134        verified to work within a broader range [0...2^49 ~ 17 years].
135 
136        This first step in the calculation is to find out how many units
137        of 15625 us there are in the input_us, because 512 RTC units
138        correspond _exactly_ to 15625 us. The desired calculation is therefore
139        t1 = time / 15625, but the division is slow and therefore let's calculate
140        t1 = time * k instead. The constant k is 1/15625, shifted up by as many bits
141        as possible without causing overflow during the calculation.
142 
143        49 bits are needed to store the maximum value that time can have, and the
144        lowest 13 bits in that value can be shifted away because a minimum of 14 bits
145        are needed to store the divisor.
146 
147        This means that the time can be reduced to 49 - 13 = 36 bits to make space
148        for k.
149 
150        The most suitable number of shift for the value 1/15625 = 0.000064
151        (binary 0.00000000000001000011000110111101111...) is 41, because that results
152        in a 28-bit number that does not cause overflow in the multiplication.
153 
154        ((2^41)/15625) is equal to 0x8637bd0, and is written in a hexadecimal representation
155        to show the bit width of the number. Shifting is limited to 41 bits because:
156          1  The time uses up to 49 bits;
157          2) The time can only be shifted down 13 bits to avoid shifting away
158             a full unit of 15625 microseconds;
159          3) The maximum value of the calculation would otherwise overflow (that is,
160             (315360000000000 >> 13) * 0x8637bd0 = 0x4b300bfcd0aefde0 would no longer be less than
161             0Xffffffffffffffff).
162 
163        There is a possible loss of precision, so that t1 will be up to 93*15625 _smaller_
164        than the accurate number. This is taken into account in the next step.
165      */
166 
167     t1     = ((time >> 13) * 0x8637bd0) >> 28; // ((time >> 13) * (2^41 / 15625)) >> (41 - 13)
168     result = t1 * 512;
169     t1     = time - t1 * 15625;
170 
171     /* This second step of the calculation is to find out how many RTC units there are
172        still left in the remaining microseconds.
173 
174        ((2^56)/15625) is equal to 0x431bde82d7b, and is written in a hexadecimal representation
175        to show the bit width of the number. Shifting 56 bits is determined by the worst
176        case value of t1. The constant is selected by using the same methodology as in the
177        first step of the calculation above.
178 
179        The possible loss of precision in the calculation above can make t1 93*15625 lower
180        than it should have been here. The worst case found is that t1 can be 1453125, and
181        therefore there is no overflow in the calculation
182        1453125 * 0x431bde82d7b = 0x5cfffffffff76627 (that is, it is less than 0xffffffffffffffff).
183 
184        15625 below is the binary representation of 30.51757813 (11110.100001001)
185        scaled up by 2^9, and the calculation below are therefore using that scale.
186 
187        Rounding up to the nearest RTC tick is done by adding the value of the least
188        significant bits of the fraction (that is, adding the value of bits 1..47 of the scaled
189        up timer unit size (2^47)) to the calculated value before scaling the final
190        value down to RTC ticks.*/
191 
192     // ceil((time * (2^56 / 15625)) >> (56 - 9))
193     NRF_802154_ASSERT(t1 <= 1453125);
194     u1   = (t1 * 0x431bde82d7b); // (time * (2^56 / 15625))
195     u1  += 0x7fffffffffff;       // round up
196     u1 >>= 47;                   // ceil(u1 >> (56 - 9))
197 
198     result += u1;
199 
200     return result;
201 }
202 
203 /**
204  *@}
205  **/
206 
207 #endif // NRF_802154_UTILS_H__
208