rtctime_internal.h 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  1. /*
  2. * Copyright 2015 Dius Computing Pty Ltd. All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions
  6. * are met:
  7. *
  8. * - Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * - Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in the
  12. * documentation and/or other materials provided with the
  13. * distribution.
  14. * - Neither the name of the copyright holders nor the names of
  15. * its contributors may be used to endorse or promote products derived
  16. * from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  21. * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
  22. * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  23. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  24. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  25. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  26. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  27. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  28. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  29. * OF THE POSSIBILITY OF SUCH DAMAGE.
  30. *
  31. * @author Bernd Meyer <bmeyer@dius.com.au>
  32. * @author Johny Mattsson <jmattsson@dius.com.au>
  33. */
  34. /*
  35. * It is vital that this file is only included once in the entire
  36. * system.
  37. */
  38. #ifndef _RTCTIME_INTERNAL_H_
  39. #define _RTCTIME_INTERNAL_H_
  40. /*
  41. * The ESP8266 has four distinct power states:
  42. *
  43. * 1) Active --- CPU and modem are powered and running
  44. * 2) Modem Sleep --- CPU is active, but the RF section is powered down
  45. * 3) Light Sleep --- CPU is halted, RF section is powered down. CPU gets reactivated by interrupt
  46. * 4) Deep Sleep --- CPU and RF section are powered down, restart requires a full reset
  47. *
  48. * There are also three (relevant) sources of time information
  49. *
  50. * A) CPU Cycle Counter --- this is incremented at the CPU frequency in modes (1) and (2), but is
  51. * halted in state (3), and gets reset in state (4). Highly precise 32 bit counter
  52. * which overflows roughly every minute. Starts counting as soon as the CPU becomes
  53. * active after a reset. Can cause an interrupt when it hits a particular value;
  54. * This interrupt (and the register that determines the comparison value) are not
  55. * used by the system software, and are available for user code to use.
  56. *
  57. * B) Free Running Counter 2 --- This is a peripheral which gets configured to run at 1/256th of the
  58. * CPU frequency. It is also active in states (1) and (2), and is halted in state (3).
  59. * However, the ESP system code will adjust its value across periods of Light Sleep
  60. * that it initiates, so *in effect*, this counter kind-of remains active in (3).
  61. * While in states (1) and (2), it is as precise as the CPU Cycle. While in state (3),
  62. * however, it is only as precise as the system's knowledge of how long the sleep
  63. * period was. This knowledge is limited (it is based on (C), see below).
  64. * The Free Running Counter 2 is a 32 bit counter which overflows roughly every
  65. * 4 hours, and typically has a resolution of 3.2us. It starts counting as soon as
  66. * it gets configured, which is considerably *after* the time of reset, and in fact
  67. * is not done by the ESP boot loader, but rather by the loaded-from-SPI-flash system
  68. * code. This means it is not yet running when the boot loader calls the configured
  69. * entry point, and the time between reset and the counter starting to run depends on
  70. * the size of code/data to be copied into RAM from the flash.
  71. * The FRC2 is also used by the system software for its internal time keeping, i.e. for
  72. * dealing with any registered ETS_Timers (and derived-from-them timer functionality).
  73. *
  74. * C) "Real Time Clock" --- This peripheral runs from an internal low power RC oscillator, at a frequency
  75. * somewhere in the 120-200kHz range. It keeps running in all power states, and is in
  76. * fact the time source responsible for generating an interrupt (state (3)) or reset
  77. * (state (4)) to end Light and Deep Sleep periods. However, it *does* get reset to
  78. * zero after a reset, even one it caused itself.
  79. * The major issue with the RTC is that it is not using a crystal (support for an
  80. * external 32.768kHz crystal was planned at one point, but was removed from the
  81. * final ESP8266 design), and thus the frequency of the oscillator is dependent on
  82. * a number of parameters, including the chip temperature. The ESP's system software
  83. * contains code to "calibrate" exactly how long one cycle of the oscillator is, and
  84. * uses that calibration to work out how many cycles to sleep for modes (3) and (4).
  85. * However, once the chip has entered a low power state, it quickly cools down, which
  86. * results in the oscillator running faster than during calibration, leading to early
  87. * wakeups. This effect is small (even in relative terms) for short sleep periods (because
  88. * the temperature does not change much over a few hundred milliseconds), but can get
  89. * quite large for extended sleeps.
  90. *
  91. * For added fun, a typical ESP8266 module starts up running the CPU (and thus the cycle counter) at 52MHz,
  92. * but usually this will be switched to 80MHz on application startup, and can later be switched to 160MHz
  93. * under user control. Meanwhile, the FRC2 is usually kept running at 80MHz/256, regardless of the CPU
  94. * clock.
  95. *
  96. *
  97. *
  98. * The code in this file implements a best-effort time keeping solution for the ESP. It keeps track of time
  99. * by switching between various time sources. All state is kept in RAM associated with the RTC, which is
  100. * maintained across Deep Sleep periods.
  101. *
  102. * Internally, time is managed in units of cycles of a (hypothetical) 2080MHz clock, e.g. in units
  103. * of 0.4807692307ns. The reason for this choice is that this covers both the FRC2 and the cycle
  104. * counter periods, while running at 52MHz, 80MHz or 160MHz.
  105. *
  106. * At any given time, the time status indicates whether the FRC2 or the Cycle Counter is the current time
  107. * source, how many unit cycles each LSB of the chosen time source "is worth", and what the unix time in
  108. * unit cycles was when the time source was at 0.
  109. * Given that either time source overflows its 32 bit counter in a relatively short time, the code also
  110. * maintains a "last read 32 bit value" for the selected time source, and on each subsequent read will
  111. * check for overflow and, if necessary, adjust the unix-time-at-time-source-being-zero appropriately.
  112. * In order to avoid missing overflows, a timer gets installed which requests time every 40 seconds.
  113. *
  114. * To avoid race conditions, *none* of the code here must be called from an interrupt context unless
  115. * the user can absolutely guarantee that there will never be a clock source rollover (which can be the
  116. * case for sensor applications that only stay awake for a few seconds). And even then, do so at your
  117. * own risk.
  118. *
  119. *
  120. * Deep sleep is handled by moving the time offset forward *before* the sleep to the scheduled wakeup
  121. * time. Due to the nature of the RTC, the actual wakeup time may be a little bit different, but
  122. * it's the best that can be done. The code attempts to come up with a better calibration value if
  123. * authoritative time is available both before and after a sleep; This works reasonably well, but of
  124. * course is still merely a guess, which may well be somewhat wrong.
  125. *
  126. */
  127. #include <osapi.h>
  128. #include <ets_sys.h>
  129. #include "rom.h"
  130. #include "rtcaccess.h"
  131. #include "user_interface.h"
  132. // Layout of the RTC storage space:
  133. //
  134. // 0: Magic, and time source. Meaningful values are
  135. // * RTC_TIME_MAGIC_SLEEP: Indicates that the device went to sleep under RTCTIME control.
  136. // This is the magic expected on deep sleep wakeup; Any other status means we lost track
  137. // of time, and whatever time offset is stored in state is invalid and must be cleared.
  138. // * RTC_TIME_MAGIC_CCOUNT: Time offset is relative to the Cycle Counter.
  139. // * RTC_TIME_MAGIC_FRC2: Time offset is relative to the Free Running Counter.
  140. // Any values other than these indicate that RTCTIME is not in use and no state is available, nor should
  141. // RTCTIME make any changes to any of the RTC memory space.
  142. //
  143. // 1/2: UNIX time in Unit Cycles when time source had value 0 (64 bit, lower 32 bit in 1, upper in 2).
  144. // If 0, then time is unknown.
  145. // 3: Last used value of time source (32 bit unsigned). If current time source is less, then a rollover happened
  146. // 4: Length of a time source cycle in Unit Cycles.
  147. // 5: cached result of sleep clock calibration. Has the format of system_rtc_clock_cali_proc(),
  148. // or 0 if not available (see 6/7 below)
  149. // 6: Number of microseconds we tried to sleep, or 0 if we didn't sleep since last calibration, ffffffff if invalid
  150. // 7: Number of RTC cycles we decided to sleep, or 0 if we didn't sleep since last calibration, ffffffff if invalid
  151. // 8: Number of microseconds which we add to (1/2) to avoid time going backwards
  152. // 9: microsecond value returned in the last gettimeofday() to "user space".
  153. //
  154. // Entries 6-9 are needed because the RTC cycles/second appears quite temperature dependent,
  155. // and thus is heavily influenced by what else the chip is doing. As such, any calibration against
  156. // the crystal-provided clock (which necessarily would have to happen while the chip is active and
  157. // burning a few milliwatts) will be significantly different from the actual frequency during deep
  158. // sleep.
  159. // Thus, in order to calibrate for deep sleep conditions, we keep track of total sleep microseconds
  160. // and total sleep clock cycles between settimeofday() calls (which presumably are NTP driven), and
  161. // adjust the calibration accordingly on each settimeofday(). This will also track frequency changes
  162. // due to ambient temperature changes.
  163. // 8/9 get used when a settimeofday() would result in turning back time. As that can cause all sorts
  164. // of ugly issues, we *do* adjust (1/2), but compensate by making the same adjustment to (8). Then each
  165. // time gettimeofday() is called, we inspect (9) and determine how much time has passed since the last
  166. // call (yes, this gets it wrong if more than a second has passed, but not in a way that causes issues)
  167. // and try to take up to 6% of that time away from (8) until (8) reaches 0. Also, whenever we go to
  168. // deep sleep, we add (8) to the sleep time, thus catching up all in one go.
  169. // Note that for calculating the next sample-aligned wakeup, we need to use the post-adjustment
  170. // timeofday(), but for calculating actual sleep time, we use the pre-adjustment one, thus bringing
  171. // things back into line.
  172. //
  173. #define RTC_TIME_BASE 0 // Where the RTC timekeeping block starts in RTC user memory slots
  174. #define RTC_TIME_MAGIC_CCOUNT 0x44695573
  175. #define RTC_TIME_MAGIC_FRC2 (RTC_TIME_MAGIC_CCOUNT+1)
  176. #define RTC_TIME_MAGIC_SLEEP (RTC_TIME_MAGIC_CCOUNT+2)
  177. #define UNITCYCLE_MHZ 2080
  178. #define CPU_OVERCLOCK_MHZ 160
  179. #define CPU_DEFAULT_MHZ 80
  180. #define CPU_BOOTUP_MHZ 52
  181. #ifdef RTC_DEBUG_ENABLED
  182. #warn this does not really work....
  183. #define RTC_DBG(...) do { if (rtc_dbg_enabled == 'R') { dbg_printf(__VA_ARGS__); } } while (0)
  184. static char rtc_dbg_enabled;
  185. #define RTC_DBG_ENABLED() rtc_dbg_enabled = 'R'
  186. #define RTC_DBG_NOT_ENABLED() rtc_dbg_enabled = 0
  187. #else
  188. #define RTC_DBG(...)
  189. #define RTC_DBG_ENABLED()
  190. #define RTC_DBG_NOT_ENABLED()
  191. #endif
  192. #define NOINIT_ATTR __attribute__((section(".noinit")))
  193. // RTCTIME storage
  194. #define RTC_TIME_MAGIC_POS (RTC_TIME_BASE+0)
  195. #define RTC_CYCLEOFFSETL_POS (RTC_TIME_BASE+1)
  196. #define RTC_CYCLEOFFSETH_POS (RTC_TIME_BASE+2)
  197. #define RTC_LASTSOURCEVAL_POS (RTC_TIME_BASE+3)
  198. #define RTC_SOURCECYCLEUNITS_POS (RTC_TIME_BASE+4)
  199. #define RTC_CALIBRATION_POS (RTC_TIME_BASE+5)
  200. #define RTC_SLEEPTOTALUS_POS (RTC_TIME_BASE+6)
  201. #define RTC_SLEEPTOTALCYCLES_POS (RTC_TIME_BASE+7)
  202. //#define RTC_TODOFFSETUS_POS (RTC_TIME_BASE+8)
  203. //#define RTC_LASTTODUS_POS (RTC_TIME_BASE+9)
  204. #define RTC_USRATE_POS (RTC_TIME_BASE+8)
  205. NOINIT_ATTR uint32_t rtc_time_magic;
  206. NOINIT_ATTR uint64_t rtc_cycleoffset;
  207. NOINIT_ATTR uint32_t rtc_lastsourceval;
  208. NOINIT_ATTR uint32_t rtc_sourcecycleunits;
  209. NOINIT_ATTR uint32_t rtc_calibration;
  210. NOINIT_ATTR uint32_t rtc_sleeptotalus;
  211. NOINIT_ATTR uint32_t rtc_sleeptotalcycles;
  212. NOINIT_ATTR uint64_t rtc_usatlastrate;
  213. NOINIT_ATTR uint64_t rtc_rateadjustedus;
  214. NOINIT_ATTR uint32_t rtc_todoffsetus;
  215. NOINIT_ATTR uint32_t rtc_lasttodus;
  216. NOINIT_ATTR uint32_t rtc_usrate;
  217. struct rtc_timeval
  218. {
  219. uint32_t tv_sec;
  220. uint32_t tv_usec;
  221. };
  222. static void bbram_load() {
  223. rtc_time_magic = rtc_mem_read(RTC_TIME_MAGIC_POS);
  224. rtc_cycleoffset = rtc_mem_read64(RTC_CYCLEOFFSETL_POS);
  225. rtc_lastsourceval = rtc_mem_read(RTC_LASTSOURCEVAL_POS);
  226. rtc_sourcecycleunits = rtc_mem_read(RTC_SOURCECYCLEUNITS_POS);
  227. rtc_calibration = rtc_mem_read(RTC_CALIBRATION_POS);
  228. rtc_sleeptotalus = rtc_mem_read(RTC_SLEEPTOTALUS_POS);
  229. rtc_sleeptotalcycles = rtc_mem_read(RTC_SLEEPTOTALCYCLES_POS);
  230. rtc_usrate = rtc_mem_read(RTC_USRATE_POS);
  231. }
  232. static void bbram_save() {
  233. RTC_DBG("bbram_save\n");
  234. rtc_mem_write(RTC_TIME_MAGIC_POS , rtc_time_magic);
  235. rtc_mem_write64(RTC_CYCLEOFFSETL_POS , rtc_cycleoffset);
  236. rtc_mem_write(RTC_LASTSOURCEVAL_POS , rtc_lastsourceval);
  237. rtc_mem_write(RTC_SOURCECYCLEUNITS_POS , rtc_sourcecycleunits);
  238. rtc_mem_write(RTC_CALIBRATION_POS , rtc_calibration);
  239. rtc_mem_write(RTC_SLEEPTOTALUS_POS , rtc_sleeptotalus);
  240. rtc_mem_write(RTC_SLEEPTOTALCYCLES_POS , rtc_sleeptotalcycles);
  241. rtc_mem_write(RTC_USRATE_POS , rtc_usrate);
  242. }
  243. static inline uint64_t div2080(uint64_t n) {
  244. n = n >> 5;
  245. uint64_t t = n >> 7;
  246. uint64_t q = t + (t >> 1) + (t >> 2);
  247. q += q >> 3;
  248. q += q >> 12;
  249. q += q >> 24;
  250. q += q >> 48;
  251. uint32_t r = (uint32_t) n - (uint32_t) q * 65;
  252. uint32_t off = (r - (r >> 6)) >> 6;
  253. q = q + off;
  254. return q;
  255. }
  256. static uint32_t div1m(uint32_t *rem, unsigned long long n) {
  257. // 0 -> 0002000000000000 sub
  258. // 0 >> 5 - 0 >> 19 + [-1] -> 00020fffc0000000 add
  259. // 0 >> 9 - 0 >> 6 + [-1] -> 000208ffc0000000 add
  260. // 2 >> 12 - 2 >> 23 -> 000000208bea0080 sub
  261. uint64_t q1 = (n >> 5) - (n >> 19) + n;
  262. uint64_t q2 = q1 + (n >> 9) - (n >> 6);
  263. uint64_t q3 = (q2 >> 12) - (q2 >> 23);
  264. uint64_t q = q1 - n + q2 - q3;
  265. q = q >> 20;
  266. uint32_t r = (uint32_t) n - (uint32_t) q * 1000000;
  267. if (r >= 1000000) {
  268. r -= 1000000;
  269. q++;
  270. }
  271. *rem = r;
  272. return q;
  273. }
  274. static inline uint64_t rtc_time_get_now_us_adjusted();
  275. #define rtc_time_get_magic() rtc_time_magic
  276. static inline bool rtc_time_check_sleep_magic(void)
  277. {
  278. uint32_t magic=rtc_time_get_magic();
  279. return (magic==RTC_TIME_MAGIC_SLEEP);
  280. }
  281. static inline bool rtc_time_check_wake_magic(void)
  282. {
  283. uint32_t magic=rtc_time_get_magic();
  284. return (magic==RTC_TIME_MAGIC_FRC2 || magic==RTC_TIME_MAGIC_CCOUNT);
  285. }
  286. static inline bool rtc_time_check_magic(void)
  287. {
  288. uint32_t magic=rtc_time_get_magic();
  289. return (magic==RTC_TIME_MAGIC_FRC2 || magic==RTC_TIME_MAGIC_CCOUNT || magic==RTC_TIME_MAGIC_SLEEP);
  290. }
  291. static void rtc_time_set_magic(uint32_t new_magic)
  292. {
  293. RTC_DBG("Set magic to %08x\n", new_magic);
  294. rtc_time_magic = new_magic;
  295. bbram_save();
  296. }
  297. static inline void rtc_time_set_sleep_magic(void)
  298. {
  299. rtc_time_set_magic(RTC_TIME_MAGIC_SLEEP);
  300. }
  301. static inline void rtc_time_set_ccount_magic(void)
  302. {
  303. rtc_time_set_magic(RTC_TIME_MAGIC_CCOUNT);
  304. }
  305. static inline void rtc_time_set_frc2_magic(void)
  306. {
  307. rtc_time_set_magic(RTC_TIME_MAGIC_FRC2);
  308. }
  309. static inline void rtc_time_unset_magic(void)
  310. {
  311. rtc_time_set_magic(0);
  312. }
  313. static inline uint32_t rtc_time_read_raw(void)
  314. {
  315. return rtc_reg_read(RTC_COUNTER_ADDR);
  316. }
  317. static inline uint32_t rtc_time_read_raw_ccount(void)
  318. {
  319. return xthal_get_ccount();
  320. }
  321. static inline uint32_t rtc_time_read_raw_frc2(void)
  322. {
  323. return NOW();
  324. }
  325. // Get us the number of Unit Cycles that have elapsed since the source was 0.
  326. // Note: This may in fact adjust the stored cycles-when-source-was-0 entry, so
  327. // we need to make sure we call this before reading that entry
  328. static inline uint64_t rtc_time_source_offset(void)
  329. {
  330. uint32_t magic=rtc_time_get_magic();
  331. uint32_t raw=0;
  332. switch (magic)
  333. {
  334. case RTC_TIME_MAGIC_CCOUNT: raw=rtc_time_read_raw_ccount(); break;
  335. case RTC_TIME_MAGIC_FRC2: raw=rtc_time_read_raw_frc2(); break;
  336. default: return 0; // We are not in a position to offer time
  337. }
  338. uint32_t multiplier = rtc_sourcecycleunits;
  339. uint32_t previous = rtc_lastsourceval;
  340. if (raw<previous)
  341. { // We had a rollover.
  342. uint64_t to_add=(1ULL<<32)*multiplier;
  343. uint64_t base = rtc_cycleoffset;
  344. if (base)
  345. rtc_cycleoffset = base + to_add;
  346. }
  347. rtc_lastsourceval = raw;
  348. return ((uint64_t)raw)*multiplier;
  349. }
  350. static inline uint64_t rtc_time_unix_unitcycles(void)
  351. {
  352. // Note: The order of these two must be maintained, as the first call might change the outcome of the second
  353. uint64_t offset=rtc_time_source_offset();
  354. uint64_t base = rtc_cycleoffset;
  355. if (!base)
  356. return 0; // No known time
  357. return base+offset;
  358. }
  359. static inline uint64_t rtc_time_unix_us(void)
  360. {
  361. #if UNITCYCLE_MHZ == 2080
  362. return div2080(rtc_time_unix_unitcycles());
  363. #else
  364. #error UNITCYCLE_MHZ has an odd value
  365. return rtc_time_unix_unitcycles()/UNITCYCLE_MHZ;
  366. #endif
  367. }
  368. static inline void rtc_time_register_time_reached(uint32_t s, uint32_t us)
  369. {
  370. rtc_lasttodus = us;
  371. }
  372. static inline uint32_t rtc_time_us_since_time_reached(uint32_t s, uint32_t us)
  373. {
  374. uint32_t lastus=rtc_lasttodus;
  375. if (us<lastus)
  376. us+=1000000;
  377. return us-lastus;
  378. }
  379. // A small sanity check so sleep times go completely nuts if someone
  380. // has provided wrong timestamps to gettimeofday.
  381. static inline bool rtc_time_calibration_is_sane(uint32_t cali)
  382. {
  383. return (cali>=(4<<12)) && (cali<=(10<<12));
  384. }
  385. static inline uint32_t rtc_time_get_calibration(void)
  386. {
  387. uint32_t cal=rtc_time_check_magic()?rtc_calibration:0;
  388. if (!cal)
  389. {
  390. // Make a first guess, most likely to be rather bad, but better then nothing.
  391. #ifndef BOOTLOADER_CODE // This will pull in way too much of the system for the bootloader to handle.
  392. ets_delay_us(200);
  393. cal=system_rtc_clock_cali_proc();
  394. rtc_calibration = cal;
  395. #else
  396. cal=6<<12;
  397. #endif
  398. }
  399. return cal;
  400. }
  401. static inline void rtc_time_invalidate_calibration(void)
  402. {
  403. rtc_calibration = 0;
  404. }
  405. static inline uint64_t rtc_time_us_to_ticks(uint64_t us)
  406. {
  407. uint32_t cal=rtc_time_get_calibration();
  408. return (us<<12)/cal;
  409. }
  410. static inline uint64_t rtc_time_get_now_us_raw(void)
  411. {
  412. if (!rtc_time_check_magic())
  413. return 0;
  414. return rtc_time_unix_us();
  415. }
  416. static inline uint64_t rtc_time_get_now_us_adjusted(void)
  417. {
  418. uint64_t raw=rtc_time_get_now_us_raw();
  419. if (!raw)
  420. return 0;
  421. return raw+rtc_todoffsetus;
  422. }
  423. static inline void rtc_time_add_sleep_tracking(uint32_t us, uint32_t cycles)
  424. {
  425. if (rtc_time_check_magic())
  426. {
  427. // us is the one that will grow faster...
  428. uint32_t us_before=rtc_sleeptotalus;
  429. uint32_t us_after=us_before+us;
  430. uint32_t cycles_after=rtc_sleeptotalcycles+cycles;
  431. if (us_after<us_before) // Give up if it would cause an overflow
  432. {
  433. us_after=cycles_after=0xffffffff;
  434. }
  435. rtc_sleeptotalus = us_after;
  436. rtc_sleeptotalcycles = cycles_after;
  437. }
  438. }
  439. extern void rtc_time_enter_deep_sleep_final(void);
  440. static void rtc_time_enter_deep_sleep_us(uint32_t us)
  441. {
  442. rtc_reg_write(0,0);
  443. rtc_reg_write(0,rtc_reg_read(0)&0xffffbfff);
  444. rtc_reg_write(0,rtc_reg_read(0)|0x30);
  445. rtc_reg_write(0x44,4);
  446. rtc_reg_write(0x0c,0x00010010);
  447. rtc_reg_write(0x48,(rtc_reg_read(0x48)&0xffff01ff)|0x0000fc00);
  448. rtc_reg_write(0x48,(rtc_reg_read(0x48)&0xfffffe00)|0x00000080);
  449. rtc_reg_write(RTC_TARGET_ADDR,rtc_time_read_raw()+136);
  450. rtc_reg_write(0x18,8);
  451. rtc_reg_write(0x08,0x00100010);
  452. ets_delay_us(20);
  453. rtc_reg_write(0x9c,17);
  454. rtc_reg_write(0xa0,3);
  455. rtc_reg_write(0x0c,0x640c8);
  456. rtc_reg_write(0,rtc_reg_read(0)&0xffffffcf);
  457. uint32_t cycles=rtc_time_us_to_ticks(us);
  458. rtc_time_add_sleep_tracking(us,cycles);
  459. if (rtc_time_check_wake_magic())
  460. rtc_time_set_sleep_magic();
  461. else
  462. bbram_save();
  463. rtc_reg_write(RTC_TARGET_ADDR,rtc_time_read_raw()+cycles);
  464. rtc_reg_write(0x9c,17);
  465. rtc_reg_write(0xa0,3);
  466. volatile uint32_t* dport4=(volatile uint32_t*)0x3ff00004;
  467. *dport4&=0xfffffffe;
  468. rtc_reg_write(0x40,-1);
  469. rtc_reg_write(0x44,32);
  470. rtc_reg_write(0x10,0);
  471. rtc_time_enter_deep_sleep_final();
  472. }
  473. static void rtc_time_deep_sleep_us(uint32_t us)
  474. {
  475. if (rtc_time_check_magic())
  476. {
  477. uint32_t to_adjust=rtc_todoffsetus;
  478. if (to_adjust)
  479. {
  480. us+=to_adjust;
  481. rtc_todoffsetus = 0;
  482. }
  483. uint64_t now=rtc_time_get_now_us_raw(); // Now the same as _adjusted()
  484. if (now)
  485. { // Need to maintain the clock first. When we wake up, counter will be 0
  486. uint64_t wakeup=now+us;
  487. uint64_t wakeup_cycles=wakeup*UNITCYCLE_MHZ;
  488. // Probly should factor in the rate here TODO
  489. rtc_cycleoffset = wakeup_cycles;
  490. }
  491. }
  492. rtc_time_enter_deep_sleep_us(us);
  493. }
  494. static inline void rtc_time_deep_sleep_until_aligned(uint32_t align, uint32_t min_sleep_us)
  495. {
  496. uint64_t now=rtc_time_get_now_us_adjusted();
  497. uint64_t then=now+min_sleep_us;
  498. if (align)
  499. {
  500. then+=align-1;
  501. then-=(then%align);
  502. }
  503. rtc_time_deep_sleep_us(then-now);
  504. }
  505. static void rtc_time_reset(bool clear_cali)
  506. {
  507. rtc_cycleoffset = 0;
  508. rtc_sleeptotalus = 0;
  509. rtc_sleeptotalcycles = 0;
  510. rtc_todoffsetus = 0;
  511. rtc_lasttodus = 0;
  512. rtc_sourcecycleunits = 0;
  513. rtc_lastsourceval = 0;
  514. rtc_usatlastrate = 0;
  515. rtc_rateadjustedus = 0;
  516. rtc_usrate = 0;
  517. if (clear_cali)
  518. rtc_calibration = 0;
  519. bbram_save();
  520. }
  521. static inline bool rtc_time_have_time(void)
  522. {
  523. return (rtc_time_check_magic() && rtc_cycleoffset!=0);
  524. }
  525. static void rtc_time_select_frc2_source()
  526. {
  527. // FRC2 always runs at 1/256th of the default 80MHz clock, even if the actual clock is different
  528. uint32_t new_multiplier=(256*UNITCYCLE_MHZ+CPU_DEFAULT_MHZ/2)/CPU_DEFAULT_MHZ;
  529. uint64_t now;
  530. uint32_t before;
  531. uint32_t after;
  532. // Deal with race condition here...
  533. do {
  534. before=rtc_time_read_raw_frc2();
  535. now=rtc_time_unix_unitcycles();
  536. after=rtc_time_read_raw_frc2();
  537. } while (before>after);
  538. if (rtc_time_have_time())
  539. {
  540. uint64_t offset=(uint64_t)after*new_multiplier;
  541. rtc_cycleoffset = now-offset;
  542. rtc_lastsourceval = after;
  543. }
  544. rtc_sourcecycleunits = new_multiplier;
  545. rtc_time_set_magic(RTC_TIME_MAGIC_FRC2);
  546. }
  547. static void rtc_time_select_ccount_source(uint32_t mhz, bool first)
  548. {
  549. uint32_t new_multiplier=(UNITCYCLE_MHZ+mhz/2)/mhz;
  550. // Check that
  551. if (new_multiplier*mhz!=UNITCYCLE_MHZ)
  552. ets_printf("Trying to use unsuitable frequency: %dMHz\n",mhz);
  553. if (first)
  554. { // The ccounter has been running at this rate since startup, and the offset is set accordingly
  555. rtc_lastsourceval = 0;
  556. rtc_sourcecycleunits = new_multiplier;
  557. rtc_time_set_magic(RTC_TIME_MAGIC_CCOUNT);
  558. return;
  559. }
  560. uint64_t now;
  561. uint32_t before;
  562. uint32_t after;
  563. // Deal with race condition here...
  564. do {
  565. before=rtc_time_read_raw_ccount();
  566. now=rtc_time_unix_unitcycles();
  567. after=rtc_time_read_raw_ccount();
  568. } while (before>after);
  569. if (rtc_time_have_time())
  570. {
  571. uint64_t offset=(uint64_t)after*new_multiplier;
  572. rtc_cycleoffset = now-offset;
  573. rtc_lastsourceval = after;
  574. }
  575. rtc_sourcecycleunits = new_multiplier;
  576. rtc_time_set_magic(RTC_TIME_MAGIC_CCOUNT);
  577. }
  578. static inline void rtc_time_switch_to_ccount_frequency(uint32_t mhz)
  579. {
  580. if (rtc_time_check_magic())
  581. rtc_time_select_ccount_source(mhz,false);
  582. }
  583. static inline void rtc_time_switch_to_system_clock(void)
  584. {
  585. if (rtc_time_check_magic())
  586. rtc_time_select_frc2_source();
  587. }
  588. static inline void rtc_time_tmrfn(void* arg);
  589. static void rtc_time_install_timer(void)
  590. {
  591. static ETSTimer tmr;
  592. os_timer_setfn(&tmr,rtc_time_tmrfn,NULL);
  593. os_timer_arm(&tmr,10000,1);
  594. }
  595. #if 0 // Kept around for reference....
  596. static inline void rtc_time_ccount_wrap_handler(void* dst_v, uint32_t sp)
  597. {
  598. uint32_t off_h=rtc_mem_read(RTC_CYCLEOFFSETH_POS);
  599. if (rtc_time_check_magic() && off_h)
  600. {
  601. rtc_mem_write(RTC_CYCLEOFFSETH_POS,off_h+1);
  602. }
  603. xthal_set_ccompare(0,0); // This resets the interrupt condition
  604. }
  605. static inline void rtc_time_install_wrap_handler(void)
  606. {
  607. xthal_set_ccompare(0,0); // Recognise a ccounter wraparound
  608. ets_isr_attach(RTC_TIME_CCOMPARE_INT,rtc_time_ccount_wrap_handler,NULL);
  609. ets_isr_unmask(1<<RTC_TIME_CCOMPARE_INT);
  610. }
  611. #endif
  612. // This switches from MAGIC_SLEEP to MAGIC_CCOUNT, with ccount running at bootup frequency (i.e. 52MHz).
  613. // To be called as early as possible, potententially as the first thing in an overridden entry point.
  614. static void rtc_time_register_bootup(void)
  615. {
  616. RTC_DBG_NOT_ENABLED();
  617. bbram_load();
  618. uint32_t reset_reason=rtc_get_reset_reason();
  619. #ifndef BOOTLOADER_CODE
  620. static const bool erase_calibration=true;
  621. #else
  622. // In the boot loader, any leftover calibration is going to be better than anything we can
  623. // come up with....
  624. static const bool erase_calibration=false;
  625. #endif
  626. if (rtc_time_check_sleep_magic())
  627. {
  628. if (reset_reason!=2) // This was *not* a proper wakeup from a deep sleep. All our time keeping is f*cked!
  629. rtc_time_reset(erase_calibration); // Possibly keep the calibration, it should still be good
  630. rtc_time_select_ccount_source(CPU_BOOTUP_MHZ,true);
  631. rtc_todoffsetus = 0;
  632. rtc_rateadjustedus = rtc_usatlastrate = rtc_time_get_now_us_adjusted();
  633. RTC_DBG_ENABLED();
  634. return;
  635. }
  636. // We did not go to sleep properly. All our time keeping is f*cked!
  637. rtc_time_reset(erase_calibration); // Possibly keep the calibration, it should still be good
  638. RTC_DBG_ENABLED();
  639. }
  640. // Call this from the nodemcu entry point, i.e. just before we switch from 52MHz to 80MHz
  641. static inline void rtc_time_switch_clocks(void)
  642. {
  643. rtc_time_switch_to_ccount_frequency(CPU_DEFAULT_MHZ);
  644. }
  645. // Call this exactly once, from user_init, i.e. once the operating system is up and running
  646. static inline void rtc_time_switch_system(void)
  647. {
  648. rtc_time_install_timer();
  649. rtc_time_switch_to_system_clock();
  650. }
  651. static inline void rtc_time_prepare(void)
  652. {
  653. rtc_time_reset(true);
  654. rtc_time_select_frc2_source();
  655. }
  656. static int32_t rtc_time_adjust_delta_by_rate(int32_t delta) {
  657. return (delta * ((1ull << 32) + (int) rtc_usrate)) >> 32;
  658. }
  659. static uint64_t rtc_time_adjust_us_by_rate(uint64_t us, int force) {
  660. uint64_t usoff = us - rtc_usatlastrate;
  661. uint64_t usadj = (usoff * ((1ull << 32) + (int) rtc_usrate)) >> 32;
  662. usadj = usadj + rtc_rateadjustedus;
  663. if (usoff > 1000000000 || force) {
  664. rtc_usatlastrate = us;
  665. rtc_rateadjustedus = usadj;
  666. }
  667. return usadj;
  668. }
  669. static inline void rtc_time_set_rate(int32_t rate) {
  670. uint64_t now=rtc_time_get_now_us_adjusted();
  671. rtc_time_adjust_us_by_rate(now, 1);
  672. rtc_usrate = rate;
  673. }
  674. static inline int32_t rtc_time_get_rate() {
  675. return rtc_usrate;
  676. }
  677. static inline void rtc_time_tmrfn(void* arg)
  678. {
  679. uint64_t now=rtc_time_get_now_us_adjusted();
  680. rtc_time_adjust_us_by_rate(now, 0);
  681. rtc_time_source_offset();
  682. }
  683. static inline void rtc_time_gettimeofday(struct rtc_timeval* tv)
  684. {
  685. uint64_t now=rtc_time_get_now_us_adjusted();
  686. now = rtc_time_adjust_us_by_rate(now, 0);
  687. uint32_t usec;
  688. uint32_t sec = div1m(&usec, now);
  689. uint32_t to_adjust=rtc_todoffsetus;
  690. if (to_adjust)
  691. {
  692. uint32_t us_passed=rtc_time_us_since_time_reached(sec,usec);
  693. uint32_t adjust=us_passed>>4;
  694. if (adjust)
  695. {
  696. if (adjust>to_adjust)
  697. adjust=to_adjust;
  698. to_adjust-=adjust;
  699. now-=adjust;
  700. sec = div1m(&usec, now);
  701. rtc_todoffsetus = to_adjust;
  702. }
  703. }
  704. tv->tv_sec=sec;
  705. tv->tv_usec=usec;
  706. rtc_time_register_time_reached(sec,usec);
  707. }
  708. static void rtc_time_settimeofday(const struct rtc_timeval* tv)
  709. {
  710. if (!rtc_time_check_magic())
  711. return;
  712. uint32_t sleep_us=rtc_sleeptotalus;
  713. uint32_t sleep_cycles=rtc_sleeptotalcycles;
  714. // At this point, the CPU clock will definitely be at the default rate (nodemcu fully booted)
  715. uint64_t now_esp_us=rtc_time_get_now_us_adjusted();
  716. now_esp_us = rtc_time_adjust_us_by_rate(now_esp_us, 1);
  717. uint64_t now_ntp_us=((uint64_t)tv->tv_sec)*1000000+tv->tv_usec;
  718. int64_t diff_us=now_esp_us-now_ntp_us;
  719. // Store the *actual* time.
  720. uint64_t target_unitcycles=now_ntp_us*UNITCYCLE_MHZ;
  721. uint64_t sourcecycles=rtc_time_source_offset();
  722. rtc_cycleoffset = target_unitcycles-sourcecycles;
  723. // calibrate sleep period based on difference between expected time and actual time
  724. if (sleep_us>0 && sleep_us<0xffffffff &&
  725. sleep_cycles>0 && sleep_cycles<0xffffffff &&
  726. tv->tv_sec)
  727. {
  728. uint64_t actual_sleep_us=sleep_us-diff_us;
  729. uint32_t cali=(actual_sleep_us<<12)/sleep_cycles;
  730. if (rtc_time_calibration_is_sane(cali))
  731. rtc_calibration = cali;
  732. }
  733. rtc_sleeptotalus = 0;
  734. rtc_sleeptotalcycles = 0;
  735. rtc_usatlastrate = now_ntp_us;
  736. rtc_rateadjustedus = now_ntp_us;
  737. rtc_usrate = 0;
  738. // Deal with time adjustment if necessary
  739. if (diff_us>0 && tv->tv_sec) // Time went backwards. Avoid that....
  740. {
  741. if (diff_us>0xffffffffULL)
  742. diff_us=0xffffffffULL;
  743. now_ntp_us+=diff_us;
  744. } else {
  745. diff_us=0;
  746. }
  747. rtc_todoffsetus = diff_us;
  748. uint32_t now_s=now_ntp_us/1000000;
  749. uint32_t now_us=now_ntp_us%1000000;
  750. rtc_time_register_time_reached(now_s,now_us);
  751. }
  752. #endif