//! Clock tree initialization for {{ ir.board.name }}.
//!
//! Peripheral clock gating and reset on {{ ir.chip.name }} are controlled via
//! per-peripheral gate registers. To bring up a peripheral this file:
//!
//! 1. Asserts reset,
//! 2. Enables the clock gate,
//! 3. Releases reset.
//!
//! CPU frequency selection against the PLL is handled by the bootrom; this
//! code does not currently reprogram the CPU clock. See `pac.rs` for the
//! constants.

use super::pac;

/// Enable and reset every peripheral used by this board.
///
/// Called by [`crate::pac::init`] as the first bring-up step, before IO MUX
/// configuration so that peripheral registers are writable.
pub fn init() {
    let p = unsafe { pac::Peripherals::steal() };
    {% for name in peripherals_used %}
    {% set gate = ir.chip.clock_tree.system_gates[name] %}
    {% if gate %}
    // {{ name }} — clock enable {{ gate.clk_en_field }}, reset {{ gate.rst_field }}
    p.{{ gate.rst_reg | pac_path }}.modify(|_, w| w.{{ gate.rst_field }}().set_bit());
    p.{{ gate.clk_en_reg | pac_path }}.modify(|_, w| w.{{ gate.clk_en_field }}().set_bit());
    p.{{ gate.rst_reg | pac_path }}.modify(|_, w| w.{{ gate.rst_field }}().clear_bit());
    {% if gate.clk_sel_reg and gate.clk_sel_field %}
    {%- set _width = gate.clk_sel_width or 2 %}
    {%- set _value = gate.clk_sel_value if gate.clk_sel_value is not none else 1 %}
    {%- if _width == 1 %}
    // {{ name }} — kernel clock source select (single-bit field)
    {%- if _value == 0 %}
    p.{{ gate.clk_sel_reg | pac_path }}.modify(|_, w| w.{{ gate.clk_sel_field }}().clear_bit());
    {%- else %}
    p.{{ gate.clk_sel_reg | pac_path }}.modify(|_, w| w.{{ gate.clk_sel_field }}().set_bit());
    {%- endif %}
    {%- else %}
    // {{ name }} — select APB as kernel clock source
    p.{{ gate.clk_sel_reg | pac_path }}.modify(|_, w| unsafe { w.{{ gate.clk_sel_field }}().bits({{ _value }}) });
    {%- endif %}
    {% endif %}
    {% else %}
    // {{ name }}: no system gate entry in chip IR (TODO)
    {% endif %}
    {% endfor %}
}
