+#include <io/sam3_pmc.h>
+#include <io/sam3_sysctl.h>
+#include <cfg/compiler.h>
+#include <cfg/macros.h>
+
+
+/* Frequency of board main oscillator */
+#define BOARDOSC_FREQ 12000000
+
+/* Main crystal oscillator startup time, optimal value for CPU_FREQ == 48 MHz */
+#define BOARD_OSC_COUNT (CKGR_MOR_MOSCXTST(0x8))
+
+/* Timer countdown timeout for clock initialization operations */
+#define CLOCK_TIMEOUT 0xFFFFFFFF
+
+
+/*
+ * Try to evaluate the correct divider and multiplier value depending
+ * on the desired CPU frequency.
+ *
+ * We try all combinations in a certain range of divider and multiplier
+ * values. The range can change, with better match with "strange"
+ * frequencies, but boot time will be longer.
+ *
+ * Limits for SAM3N: divider [1,255], multiplier [1,2047].
+ */
+INLINE uint32_t evaluate_pll(void)
+{
+ int mul, div, best_mul, best_div;
+ int best_delta = CPU_FREQ;
+ int freq = 0;
+
+ for (mul = 1; mul <= 8; mul++)
+ {
+ for (div = 1; div <= 24; div++)
+ {
+ freq = BOARDOSC_FREQ / div * (1 + mul);
+ if (ABS((int)CPU_FREQ - freq) < best_delta) {
+ best_delta = ABS((int)CPU_FREQ - freq);
+ best_mul = mul;
+ best_div = div;
+ }
+ }
+ }
+
+ // Bit 29 must always be set to 1
+ return CKGR_PLLR_DIV(best_div) | CKGR_PLLR_MUL(best_mul) | BV(29);
+}
+