aboutsummaryrefslogtreecommitdiff
path: root/src/clock.c
blob: 328ad52152b71fa2aa5517c2e6ca9314417d12d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include "clock.h"
#include "types.h"
#include "peripherals.h"

#define WRITE_CLK_REG(reg, value) (WRITE_REGISTER(CLOCK, reg, value))
#define READ_CLK_REG(reg) (READ_REGISTER(CLOCK, reg))

enum hfclk_src {
	HFINT = 0,
	HFXO = 1,
};

enum lfclk_src {
	LFRC = 0,
	LFXO = 1,
	LFSYNT = 2,
};

/**
 * Memory-mapped registers for the CLOCK peripheral with their offset from its base address,
 * Check the nrf52832's manual for their description.
 */
enum clock_registers {
	TASKS_HFCLKSTART    = 0x000,
	TASKS_HFCLKSTOP     = 0x004,
	TASKS_LFCLKSTART    = 0x008,
	TASKS_LFCLKSTOP     = 0x00c,
	TASKS_CAL           = 0x010,
	TASKS_CTSTART       = 0x014,
	TASKS_CTSTOP        = 0x018,
	EVENTS_HFCLKSTARTED = 0x100,
	EVENTS_LFCLKSTARTED = 0x104,
	EVENTS_DONE         = 0x10c,
	EVENTS_CTTO         = 0x110,
	INTENSET            = 0x304,
	INTENCLR            = 0x308,
	HFCLKRUN            = 0x408,
	HFCLKSTAT           = 0x40c,
	LFCLKRUN            = 0x414,
	LFCLKSTAT           = 0x418,
	LFCLKSRCCOPY        = 0x41c,
	LFCLKSRC            = 0x518,
	CTIV                = 0x538,
	TRACECONFIG         = 0x55c,
};

static int init_hfclk() {
	/* We just assert that the source clock is running with the CPU internal clock
     * as source */
	u32 hfclk_status = READ_CLK_REG(HFCLKSTAT);
	u32 clk_src = hfclk_status & 0x1;
	u32 clk_running = (hfclk_status >> 16) & 0x1;

	return (clk_src == HFINT) && clk_running;
}

static int init_lfclk() {
	int clk_started = 0;
	enum lfclk_src src = LFRC;

	/* LFCLK use the LFRC clock by default, so it should be ready
     * to be started directly */
	WRITE_CLK_REG(TASKS_LFCLKSTART, 0x1);

	/* Wait for the LFCLK to be started */
	/* TODO: We should rely on the IRQ for the LFCLKSTARTED event instead */
	do {
		u32 lfclk_stat = READ_CLK_REG(LFCLKSTAT);

		clk_started = (lfclk_stat >> 16) & 0x1;
		src = lfclk_stat & 0x2;
	} while (!clk_started);

	return src == LFRC;
}

int init_clock() {
	return init_hfclk() && init_lfclk();
}