imix/
main.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022.
4
5//! Board file for Imix development platform.
6//!
7//! - <https://github.com/tock/tock/tree/master/boards/imix>
8//! - <https://github.com/tock/imix>
9
10#![no_std]
11#![no_main]
12#![deny(missing_docs)]
13
14mod imix_components;
15use core::ptr::{addr_of, addr_of_mut};
16
17use capsules_core::alarm::AlarmDriver;
18use capsules_core::console_ordered::ConsoleOrdered;
19use capsules_core::virtualizers::virtual_aes_ccm::MuxAES128CCM;
20use capsules_core::virtualizers::virtual_alarm::VirtualMuxAlarm;
21use capsules_core::virtualizers::virtual_i2c::MuxI2C;
22use capsules_core::virtualizers::virtual_spi::VirtualSpiMasterDevice;
23use capsules_extra::net::ieee802154::MacAddress;
24use capsules_extra::net::ipv6::ip_utils::IPAddr;
25use kernel::capabilities;
26use kernel::component::Component;
27use kernel::deferred_call::DeferredCallClient;
28use kernel::hil::i2c::I2CMaster;
29use kernel::hil::radio;
30#[allow(unused_imports)]
31use kernel::hil::radio::{RadioConfig, RadioData};
32use kernel::hil::symmetric_encryption::AES128;
33use kernel::platform::{KernelResources, SyscallDriverLookup};
34use kernel::scheduler::round_robin::RoundRobinSched;
35
36//use kernel::hil::time::Alarm;
37use kernel::hil::led::LedHigh;
38use kernel::hil::Controller;
39#[allow(unused_imports)]
40use kernel::{create_capability, debug, debug_gpio, static_buf, static_init};
41use sam4l::chip::Sam4lDefaultPeripherals;
42
43use components::alarm::{AlarmDriverComponent, AlarmMuxComponent};
44use components::console::{ConsoleOrderedComponent, UartMuxComponent};
45use components::crc::CrcComponent;
46use components::debug_writer::DebugWriterComponent;
47use components::gpio::GpioComponent;
48use components::isl29035::AmbientLightComponent;
49use components::isl29035::Isl29035Component;
50use components::led::LedsComponent;
51use components::nrf51822::Nrf51822Component;
52use components::process_console::ProcessConsoleComponent;
53use components::rng::RngComponent;
54use components::si7021::SI7021Component;
55use components::spi::{SpiComponent, SpiSyscallComponent};
56
57/// Support routines for debugging I/O.
58///
59/// Note: Use of this module will trample any other USART3 configuration.
60pub mod io;
61
62// Unit Tests for drivers.
63#[allow(dead_code)]
64mod test;
65
66// Helper functions for enabling/disabling power on Imix submodules
67mod power;
68
69#[allow(dead_code)]
70mod alarm_test;
71
72#[allow(dead_code)]
73mod multi_timer_test;
74
75// State for loading apps.
76
77const NUM_PROCS: usize = 4;
78
79// Constants related to the configuration of the 15.4 network stack
80// TODO: Notably, the radio MAC addresses can be configured from userland at the moment
81// We probably want to change this from a security perspective (multiple apps being
82// able to change the MAC address seems problematic), but it is very convenient for
83// development to be able to just flash two corresponding apps onto two devices and
84// have those devices talk to each other without having to modify the kernel flashed
85// onto each device. This makes MAC address configuration a good target for capabilities -
86// only allow one app per board to have control of MAC address configuration?
87const RADIO_CHANNEL: radio::RadioChannel = radio::RadioChannel::Channel26;
88const DST_MAC_ADDR: MacAddress = MacAddress::Short(49138);
89const DEFAULT_CTX_PREFIX_LEN: u8 = 8; //Length of context for 6LoWPAN compression
90const DEFAULT_CTX_PREFIX: [u8; 16] = [0x0_u8; 16]; //Context for 6LoWPAN Compression
91const PAN_ID: u16 = 0xABCD;
92
93// how should the kernel respond when a process faults
94const FAULT_RESPONSE: capsules_system::process_policies::StopFaultPolicy =
95    capsules_system::process_policies::StopFaultPolicy {};
96
97static mut PROCESSES: [Option<&'static dyn kernel::process::Process>; NUM_PROCS] =
98    [None; NUM_PROCS];
99
100static mut CHIP: Option<&'static sam4l::chip::Sam4l<Sam4lDefaultPeripherals>> = None;
101static mut PROCESS_PRINTER: Option<&'static capsules_system::process_printer::ProcessPrinterText> =
102    None;
103
104/// Dummy buffer that causes the linker to reserve enough space for the stack.
105#[no_mangle]
106#[link_section = ".stack_buffer"]
107pub static mut STACK_MEMORY: [u8; 0x2000] = [0; 0x2000];
108
109type SI7021Sensor = components::si7021::SI7021ComponentType<
110    capsules_core::virtualizers::virtual_alarm::VirtualMuxAlarm<'static, sam4l::ast::Ast<'static>>,
111    capsules_core::virtualizers::virtual_i2c::I2CDevice<'static, sam4l::i2c::I2CHw<'static>>,
112>;
113type TemperatureDriver = components::temperature::TemperatureComponentType<SI7021Sensor>;
114type HumidityDriver = components::humidity::HumidityComponentType<SI7021Sensor>;
115type RngDriver = components::rng::RngComponentType<sam4l::trng::Trng<'static>>;
116
117type Rf233 = capsules_extra::rf233::RF233<
118    'static,
119    VirtualSpiMasterDevice<'static, sam4l::spi::SpiHw<'static>>,
120>;
121type Ieee802154MacDevice =
122    components::ieee802154::Ieee802154ComponentMacDeviceType<Rf233, sam4l::aes::Aes<'static>>;
123
124struct Imix {
125    pconsole: &'static capsules_core::process_console::ProcessConsole<
126        'static,
127        { capsules_core::process_console::DEFAULT_COMMAND_HISTORY_LEN },
128        capsules_core::virtualizers::virtual_alarm::VirtualMuxAlarm<
129            'static,
130            sam4l::ast::Ast<'static>,
131        >,
132        components::process_console::Capability,
133    >,
134    console: &'static capsules_core::console_ordered::ConsoleOrdered<
135        'static,
136        VirtualMuxAlarm<'static, sam4l::ast::Ast<'static>>,
137    >,
138    gpio: &'static capsules_core::gpio::GPIO<'static, sam4l::gpio::GPIOPin<'static>>,
139    alarm: &'static AlarmDriver<'static, VirtualMuxAlarm<'static, sam4l::ast::Ast<'static>>>,
140    temp: &'static TemperatureDriver,
141    humidity: &'static HumidityDriver,
142    ambient_light: &'static capsules_extra::ambient_light::AmbientLight<'static>,
143    adc: &'static capsules_core::adc::AdcDedicated<'static, sam4l::adc::Adc<'static>>,
144    led: &'static capsules_core::led::LedDriver<
145        'static,
146        LedHigh<'static, sam4l::gpio::GPIOPin<'static>>,
147        1,
148    >,
149    button: &'static capsules_core::button::Button<'static, sam4l::gpio::GPIOPin<'static>>,
150    rng: &'static RngDriver,
151    analog_comparator: &'static capsules_extra::analog_comparator::AnalogComparator<
152        'static,
153        sam4l::acifc::Acifc<'static>,
154    >,
155    spi: &'static capsules_core::spi_controller::Spi<
156        'static,
157        VirtualSpiMasterDevice<'static, sam4l::spi::SpiHw<'static>>,
158    >,
159    ipc: kernel::ipc::IPC<{ NUM_PROCS as u8 }>,
160    ninedof: &'static capsules_extra::ninedof::NineDof<'static>,
161    udp_driver: &'static capsules_extra::net::udp::UDPDriver<'static>,
162    crc: &'static capsules_extra::crc::CrcDriver<'static, sam4l::crccu::Crccu<'static>>,
163    usb_driver: &'static capsules_extra::usb::usb_user::UsbSyscallDriver<
164        'static,
165        capsules_extra::usb::usbc_client::Client<'static, sam4l::usbc::Usbc<'static>>,
166    >,
167    nrf51822: &'static capsules_extra::nrf51822_serialization::Nrf51822Serialization<'static>,
168    nonvolatile_storage:
169        &'static capsules_extra::nonvolatile_storage_driver::NonvolatileStorage<'static>,
170    scheduler: &'static RoundRobinSched<'static>,
171    systick: cortexm4::systick::SysTick,
172}
173
174impl SyscallDriverLookup for Imix {
175    fn with_driver<F, R>(&self, driver_num: usize, f: F) -> R
176    where
177        F: FnOnce(Option<&dyn kernel::syscall::SyscallDriver>) -> R,
178    {
179        match driver_num {
180            capsules_core::console_ordered::DRIVER_NUM => f(Some(self.console)),
181            capsules_core::gpio::DRIVER_NUM => f(Some(self.gpio)),
182            capsules_core::alarm::DRIVER_NUM => f(Some(self.alarm)),
183            capsules_core::spi_controller::DRIVER_NUM => f(Some(self.spi)),
184            capsules_core::adc::DRIVER_NUM => f(Some(self.adc)),
185            capsules_core::led::DRIVER_NUM => f(Some(self.led)),
186            capsules_core::button::DRIVER_NUM => f(Some(self.button)),
187            capsules_extra::analog_comparator::DRIVER_NUM => f(Some(self.analog_comparator)),
188            capsules_extra::ambient_light::DRIVER_NUM => f(Some(self.ambient_light)),
189            capsules_extra::temperature::DRIVER_NUM => f(Some(self.temp)),
190            capsules_extra::humidity::DRIVER_NUM => f(Some(self.humidity)),
191            capsules_extra::ninedof::DRIVER_NUM => f(Some(self.ninedof)),
192            capsules_extra::crc::DRIVER_NUM => f(Some(self.crc)),
193            capsules_extra::usb::usb_user::DRIVER_NUM => f(Some(self.usb_driver)),
194            capsules_extra::net::udp::DRIVER_NUM => f(Some(self.udp_driver)),
195            capsules_extra::nrf51822_serialization::DRIVER_NUM => f(Some(self.nrf51822)),
196            capsules_extra::nonvolatile_storage_driver::DRIVER_NUM => {
197                f(Some(self.nonvolatile_storage))
198            }
199            capsules_core::rng::DRIVER_NUM => f(Some(self.rng)),
200            kernel::ipc::DRIVER_NUM => f(Some(&self.ipc)),
201            _ => f(None),
202        }
203    }
204}
205
206impl KernelResources<sam4l::chip::Sam4l<Sam4lDefaultPeripherals>> for Imix {
207    type SyscallDriverLookup = Self;
208    type SyscallFilter = ();
209    type ProcessFault = ();
210    type Scheduler = RoundRobinSched<'static>;
211    type SchedulerTimer = cortexm4::systick::SysTick;
212    type WatchDog = ();
213    type ContextSwitchCallback = ();
214
215    fn syscall_driver_lookup(&self) -> &Self::SyscallDriverLookup {
216        self
217    }
218    fn syscall_filter(&self) -> &Self::SyscallFilter {
219        &()
220    }
221    fn process_fault(&self) -> &Self::ProcessFault {
222        &()
223    }
224    fn scheduler(&self) -> &Self::Scheduler {
225        self.scheduler
226    }
227    fn scheduler_timer(&self) -> &Self::SchedulerTimer {
228        &self.systick
229    }
230    fn watchdog(&self) -> &Self::WatchDog {
231        &()
232    }
233    fn context_switch_callback(&self) -> &Self::ContextSwitchCallback {
234        &()
235    }
236}
237
238unsafe fn set_pin_primary_functions(peripherals: &Sam4lDefaultPeripherals) {
239    use sam4l::gpio::PeripheralFunction::{A, B, C, E};
240
241    // Right column: Imix pin name
242    // Left  column: SAM4L peripheral function
243    peripherals.pa[04].configure(Some(A)); // AD0         --  ADCIFE AD0
244    peripherals.pa[05].configure(Some(A)); // AD1         --  ADCIFE AD1
245    peripherals.pa[06].configure(Some(C)); // EXTINT1     --  EIC EXTINT1
246    peripherals.pa[07].configure(Some(A)); // AD1         --  ADCIFE AD2
247    peripherals.pa[08].configure(None); //... RF233 IRQ   --  GPIO pin
248    peripherals.pa[09].configure(None); //... RF233 RST   --  GPIO pin
249    peripherals.pa[10].configure(None); //... RF233 SLP   --  GPIO pin
250    peripherals.pa[13].configure(None); //... TRNG EN     --  GPIO pin
251    peripherals.pa[14].configure(None); //... TRNG_OUT    --  GPIO pin
252    peripherals.pa[17].configure(None); //... NRF INT     -- GPIO pin
253    peripherals.pa[18].configure(Some(A)); // NRF CLK     -- USART2_CLK
254    peripherals.pa[20].configure(None); //... D8          -- GPIO pin
255    peripherals.pa[21].configure(Some(E)); // TWI2 SDA    -- TWIM2_SDA
256    peripherals.pa[22].configure(Some(E)); // TWI2 SCL    --  TWIM2 TWCK
257    peripherals.pa[25].configure(Some(A)); // USB_N       --  USB DM
258    peripherals.pa[26].configure(Some(A)); // USB_P       --  USB DP
259    peripherals.pb[00].configure(Some(A)); // TWI1_SDA    --  TWIMS1 TWD
260    peripherals.pb[01].configure(Some(A)); // TWI1_SCL    --  TWIMS1 TWCK
261    peripherals.pb[02].configure(Some(A)); // AD3         --  ADCIFE AD3
262    peripherals.pb[03].configure(Some(A)); // AD4         --  ADCIFE AD4
263    peripherals.pb[04].configure(Some(A)); // AD5         --  ADCIFE AD5
264    peripherals.pb[05].configure(Some(A)); // VHIGHSAMPLE --  ADCIFE AD6
265    peripherals.pb[06].configure(Some(A)); // RTS3        --  USART3 RTS
266    peripherals.pb[07].configure(None); //... NRF RESET   --  GPIO
267    peripherals.pb[09].configure(Some(A)); // RX3         --  USART3 RX
268    peripherals.pb[10].configure(Some(A)); // TX3         --  USART3 TX
269    peripherals.pb[11].configure(Some(A)); // CTS0        --  USART0 CTS
270    peripherals.pb[12].configure(Some(A)); // RTS0        --  USART0 RTS
271    peripherals.pb[13].configure(Some(A)); // CLK0        --  USART0 CLK
272    peripherals.pb[14].configure(Some(A)); // RX0         --  USART0 RX
273    peripherals.pb[15].configure(Some(A)); // TX0         --  USART0 TX
274    peripherals.pc[00].configure(Some(A)); // CS2         --  SPI Nperipherals.pcS2
275    peripherals.pc[01].configure(Some(A)); // CS3 (RF233) --  SPI Nperipherals.pcS3
276    peripherals.pc[02].configure(Some(A)); // CS1         --  SPI Nperipherals.pcS1
277    peripherals.pc[03].configure(Some(A)); // CS0         --  SPI Nperipherals.pcS0
278    peripherals.pc[04].configure(Some(A)); // MISO        --  SPI MISO
279    peripherals.pc[05].configure(Some(A)); // MOSI        --  SPI MOSI
280    peripherals.pc[06].configure(Some(A)); // SCK         --  SPI CLK
281    peripherals.pc[07].configure(Some(B)); // RTS2 (BLE)  -- USART2_RTS
282    peripherals.pc[08].configure(Some(E)); // CTS2 (BLE)  -- USART2_CTS
283                                           //peripherals.pc[09].configure(None); //... NRF GPIO    -- GPIO
284                                           //peripherals.pc[10].configure(None); //... USER LED    -- GPIO
285    peripherals.pc[09].configure(Some(E)); // ACAN1       -- ACIFC comparator
286    peripherals.pc[10].configure(Some(E)); // ACAP1       -- ACIFC comparator
287    peripherals.pc[11].configure(Some(B)); // RX2 (BLE)   -- USART2_RX
288    peripherals.pc[12].configure(Some(B)); // TX2 (BLE)   -- USART2_TX
289                                           //peripherals.pc[13].configure(None); //... ACC_INT1    -- GPIO
290                                           //peripherals.pc[14].configure(None); //... ACC_INT2    -- GPIO
291    peripherals.pc[13].configure(Some(E)); //... ACBN1    -- ACIFC comparator
292    peripherals.pc[14].configure(Some(E)); //... ACBP1    -- ACIFC comparator
293    peripherals.pc[16].configure(None); //... SENSE_PWR   --  GPIO pin
294    peripherals.pc[17].configure(None); //... NRF_PWR     --  GPIO pin
295    peripherals.pc[18].configure(None); //... RF233_PWR   --  GPIO pin
296    peripherals.pc[19].configure(None); //... TRNG_PWR    -- GPIO Pin
297    peripherals.pc[22].configure(None); //... KERNEL LED  -- GPIO Pin
298    peripherals.pc[24].configure(None); //... USER_BTN    -- GPIO Pin
299    peripherals.pc[25].configure(Some(B)); // LI_INT      --  EIC EXTINT2
300    peripherals.pc[26].configure(None); //... D7          -- GPIO Pin
301    peripherals.pc[27].configure(None); //... D6          -- GPIO Pin
302    peripherals.pc[28].configure(None); //... D5          -- GPIO Pin
303    peripherals.pc[29].configure(None); //... D4          -- GPIO Pin
304    peripherals.pc[30].configure(None); //... D3          -- GPIO Pin
305    peripherals.pc[31].configure(None); //... D2          -- GPIO Pin
306}
307
308/// This is in a separate, inline(never) function so that its stack frame is
309/// removed when this function returns. Otherwise, the stack space used for
310/// these static_inits is wasted.
311#[inline(never)]
312unsafe fn start() -> (
313    &'static kernel::Kernel,
314    Imix,
315    &'static sam4l::chip::Sam4l<Sam4lDefaultPeripherals>,
316) {
317    sam4l::init();
318    let pm = static_init!(sam4l::pm::PowerManager, sam4l::pm::PowerManager::new());
319    let peripherals = static_init!(Sam4lDefaultPeripherals, Sam4lDefaultPeripherals::new(pm));
320
321    pm.setup_system_clock(
322        sam4l::pm::SystemClockSource::PllExternalOscillatorAt48MHz {
323            frequency: sam4l::pm::OscillatorFrequency::Frequency16MHz,
324            startup_mode: sam4l::pm::OscillatorStartup::FastStart,
325        },
326        &peripherals.flash_controller,
327    );
328
329    // Source 32Khz and 1Khz clocks from RC23K (SAM4L Datasheet 11.6.8)
330    sam4l::bpm::set_ck32source(sam4l::bpm::CK32Source::RC32K);
331
332    set_pin_primary_functions(peripherals);
333
334    peripherals.setup_circular_deps();
335    let chip = static_init!(
336        sam4l::chip::Sam4l<Sam4lDefaultPeripherals>,
337        sam4l::chip::Sam4l::new(pm, peripherals)
338    );
339    CHIP = Some(chip);
340
341    // Create capabilities that the board needs to call certain protected kernel
342    // functions.
343    let grant_cap = create_capability!(capabilities::MemoryAllocationCapability);
344
345    power::configure_submodules(
346        &peripherals.pa,
347        &peripherals.pb,
348        &peripherals.pc,
349        power::SubmoduleConfig {
350            rf233: true,
351            nrf51422: true,
352            sensors: true,
353            trng: true,
354        },
355    );
356
357    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(&*addr_of!(PROCESSES)));
358
359    let process_printer = components::process_printer::ProcessPrinterTextComponent::new()
360        .finalize(components::process_printer_text_component_static!());
361    PROCESS_PRINTER = Some(process_printer);
362
363    // # CONSOLE
364    // Create a shared UART channel for the consoles and for kernel debug.
365    peripherals.usart3.set_mode(sam4l::usart::UsartMode::Uart);
366    let uart_mux = UartMuxComponent::new(&peripherals.usart3, 115200)
367        .finalize(components::uart_mux_component_static!());
368
369    // # TIMER
370    let mux_alarm = AlarmMuxComponent::new(&peripherals.ast)
371        .finalize(components::alarm_mux_component_static!(sam4l::ast::Ast));
372    peripherals.ast.configure(mux_alarm);
373
374    let alarm =
375        AlarmDriverComponent::new(board_kernel, capsules_core::alarm::DRIVER_NUM, mux_alarm)
376            .finalize(components::alarm_component_static!(sam4l::ast::Ast));
377
378    let pconsole = ProcessConsoleComponent::new(
379        board_kernel,
380        uart_mux,
381        mux_alarm,
382        process_printer,
383        Some(cortexm4::support::reset),
384    )
385    .finalize(components::process_console_component_static!(
386        sam4l::ast::Ast
387    ));
388
389    let console = ConsoleOrderedComponent::new(
390        board_kernel,
391        capsules_core::console_ordered::DRIVER_NUM,
392        uart_mux,
393        mux_alarm,
394        200,
395        5,
396        5,
397    )
398    .finalize(components::console_ordered_component_static!(
399        sam4l::ast::Ast
400    ));
401    DebugWriterComponent::new(
402        uart_mux,
403        create_capability!(capabilities::SetDebugWriterCapability),
404    )
405    .finalize(components::debug_writer_component_static!());
406
407    // Allow processes to communicate over BLE through the nRF51822
408    peripherals.usart2.set_mode(sam4l::usart::UsartMode::Uart);
409    let nrf_serialization = Nrf51822Component::new(
410        board_kernel,
411        capsules_extra::nrf51822_serialization::DRIVER_NUM,
412        &peripherals.usart2,
413        &peripherals.pb[07],
414    )
415    .finalize(components::nrf51822_component_static!());
416
417    // # I2C and I2C Sensors
418    let mux_i2c = static_init!(
419        MuxI2C<'static, sam4l::i2c::I2CHw<'static>>,
420        MuxI2C::new(&peripherals.i2c2, None)
421    );
422    kernel::deferred_call::DeferredCallClient::register(mux_i2c);
423    peripherals.i2c2.set_master_client(mux_i2c);
424
425    let isl29035 = Isl29035Component::new(mux_i2c, mux_alarm).finalize(
426        components::isl29035_component_static!(sam4l::ast::Ast, sam4l::i2c::I2CHw<'static>),
427    );
428    let ambient_light = AmbientLightComponent::new(
429        board_kernel,
430        capsules_extra::ambient_light::DRIVER_NUM,
431        isl29035,
432    )
433    .finalize(components::ambient_light_component_static!());
434
435    let si7021 = SI7021Component::new(mux_i2c, mux_alarm, 0x40).finalize(
436        components::si7021_component_static!(sam4l::ast::Ast, sam4l::i2c::I2CHw<'static>),
437    );
438    let temp = components::temperature::TemperatureComponent::new(
439        board_kernel,
440        capsules_extra::temperature::DRIVER_NUM,
441        si7021,
442    )
443    .finalize(components::temperature_component_static!(SI7021Sensor));
444    let humidity = components::humidity::HumidityComponent::new(
445        board_kernel,
446        capsules_extra::humidity::DRIVER_NUM,
447        si7021,
448    )
449    .finalize(components::humidity_component_static!(SI7021Sensor));
450
451    let fxos8700 = components::fxos8700::Fxos8700Component::new(mux_i2c, 0x1e, &peripherals.pc[13])
452        .finalize(components::fxos8700_component_static!(
453            sam4l::i2c::I2CHw<'static>
454        ));
455
456    let ninedof = components::ninedof::NineDofComponent::new(
457        board_kernel,
458        capsules_extra::ninedof::DRIVER_NUM,
459    )
460    .finalize(components::ninedof_component_static!(fxos8700));
461
462    // SPI MUX, SPI syscall driver and RF233 radio
463    let mux_spi = components::spi::SpiMuxComponent::new(&peripherals.spi).finalize(
464        components::spi_mux_component_static!(sam4l::spi::SpiHw<'static>),
465    );
466
467    let spi_syscalls = SpiSyscallComponent::new(
468        board_kernel,
469        mux_spi,
470        sam4l::spi::Peripheral::Peripheral2,
471        capsules_core::spi_controller::DRIVER_NUM,
472    )
473    .finalize(components::spi_syscall_component_static!(
474        sam4l::spi::SpiHw<'static>
475    ));
476    let rf233_spi = SpiComponent::new(mux_spi, sam4l::spi::Peripheral::Peripheral3).finalize(
477        components::spi_component_static!(sam4l::spi::SpiHw<'static>),
478    );
479    let rf233 = components::rf233::RF233Component::new(
480        rf233_spi,
481        &peripherals.pa[09], // reset
482        &peripherals.pa[10], // sleep
483        &peripherals.pa[08], // irq
484        &peripherals.pa[08],
485        RADIO_CHANNEL,
486    )
487    .finalize(components::rf233_component_static!(
488        sam4l::spi::SpiHw<'static>
489    ));
490
491    // Setup ADC
492    let adc_channels = static_init!(
493        [sam4l::adc::AdcChannel; 6],
494        [
495            sam4l::adc::AdcChannel::new(sam4l::adc::Channel::AD1), // AD0
496            sam4l::adc::AdcChannel::new(sam4l::adc::Channel::AD2), // AD1
497            sam4l::adc::AdcChannel::new(sam4l::adc::Channel::AD3), // AD2
498            sam4l::adc::AdcChannel::new(sam4l::adc::Channel::AD4), // AD3
499            sam4l::adc::AdcChannel::new(sam4l::adc::Channel::AD5), // AD4
500            sam4l::adc::AdcChannel::new(sam4l::adc::Channel::AD6), // AD5
501        ]
502    );
503    let adc = components::adc::AdcDedicatedComponent::new(
504        &peripherals.adc,
505        adc_channels,
506        board_kernel,
507        capsules_core::adc::DRIVER_NUM,
508    )
509    .finalize(components::adc_dedicated_component_static!(sam4l::adc::Adc));
510
511    let gpio = GpioComponent::new(
512        board_kernel,
513        capsules_core::gpio::DRIVER_NUM,
514        components::gpio_component_helper!(
515            sam4l::gpio::GPIOPin,
516            0 => &peripherals.pc[31],
517            1 => &peripherals.pc[30],
518            2 => &peripherals.pc[29],
519            3 => &peripherals.pc[28],
520            4 => &peripherals.pc[27],
521            5 => &peripherals.pc[26],
522            6 => &peripherals.pa[20]
523        ),
524    )
525    .finalize(components::gpio_component_static!(sam4l::gpio::GPIOPin));
526
527    let led = LedsComponent::new().finalize(components::led_component_static!(
528        LedHigh<'static, sam4l::gpio::GPIOPin>,
529        LedHigh::new(&peripherals.pc[10]),
530    ));
531
532    let button = components::button::ButtonComponent::new(
533        board_kernel,
534        capsules_core::button::DRIVER_NUM,
535        components::button_component_helper!(
536            sam4l::gpio::GPIOPin,
537            (
538                &peripherals.pc[24],
539                kernel::hil::gpio::ActivationMode::ActiveLow,
540                kernel::hil::gpio::FloatingState::PullNone
541            )
542        ),
543    )
544    .finalize(components::button_component_static!(sam4l::gpio::GPIOPin));
545
546    let crc = CrcComponent::new(
547        board_kernel,
548        capsules_extra::crc::DRIVER_NUM,
549        &peripherals.crccu,
550    )
551    .finalize(components::crc_component_static!(sam4l::crccu::Crccu));
552
553    let ac_0 = static_init!(
554        sam4l::acifc::AcChannel,
555        sam4l::acifc::AcChannel::new(sam4l::acifc::Channel::AC0)
556    );
557    let ac_1 = static_init!(
558        sam4l::acifc::AcChannel,
559        sam4l::acifc::AcChannel::new(sam4l::acifc::Channel::AC0)
560    );
561    let ac_2 = static_init!(
562        sam4l::acifc::AcChannel,
563        sam4l::acifc::AcChannel::new(sam4l::acifc::Channel::AC0)
564    );
565    let ac_3 = static_init!(
566        sam4l::acifc::AcChannel,
567        sam4l::acifc::AcChannel::new(sam4l::acifc::Channel::AC0)
568    );
569    let analog_comparator = components::analog_comparator::AnalogComparatorComponent::new(
570        &peripherals.acifc,
571        components::analog_comparator_component_helper!(
572            <sam4l::acifc::Acifc as kernel::hil::analog_comparator::AnalogComparator>::Channel,
573            ac_0,
574            ac_1,
575            ac_2,
576            ac_3
577        ),
578        board_kernel,
579        capsules_extra::analog_comparator::DRIVER_NUM,
580    )
581    .finalize(components::analog_comparator_component_static!(
582        sam4l::acifc::Acifc
583    ));
584    let rng = RngComponent::new(
585        board_kernel,
586        capsules_core::rng::DRIVER_NUM,
587        &peripherals.trng,
588    )
589    .finalize(components::rng_component_static!(sam4l::trng::Trng));
590
591    // For now, assign the 802.15.4 MAC address on the device as
592    // simply a 16-bit short address which represents the last 16 bits
593    // of the serial number of the sam4l for this device.  In the
594    // future, we could generate the DEFAULT_EXT_SRC_MAC address by hashing the full
595    // 120-bit serial number
596    let serial_num: sam4l::serial_num::SerialNum = sam4l::serial_num::SerialNum::new();
597    let serial_num_bottom_16 = (serial_num.get_lower_64() & 0x0000_0000_0000_ffff) as u16;
598    let src_mac_from_serial_num: MacAddress = MacAddress::Short(serial_num_bottom_16);
599    const DEFAULT_EXT_SRC_MAC: [u8; 8] = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77];
600
601    let aes_mux = static_init!(
602        MuxAES128CCM<'static, sam4l::aes::Aes>,
603        MuxAES128CCM::new(&peripherals.aes)
604    );
605    aes_mux.register();
606    peripherals.aes.set_client(aes_mux);
607
608    let (_, mux_mac) = components::ieee802154::Ieee802154Component::new(
609        board_kernel,
610        capsules_extra::ieee802154::DRIVER_NUM,
611        rf233,
612        aes_mux,
613        PAN_ID,
614        serial_num_bottom_16,
615        DEFAULT_EXT_SRC_MAC,
616    )
617    .finalize(components::ieee802154_component_static!(
618        capsules_extra::rf233::RF233<
619            'static,
620            VirtualSpiMasterDevice<'static, sam4l::spi::SpiHw<'static>>,
621        >,
622        sam4l::aes::Aes<'static>
623    ));
624
625    let usb_driver = components::usb::UsbComponent::new(
626        board_kernel,
627        capsules_extra::usb::usb_user::DRIVER_NUM,
628        &peripherals.usbc,
629    )
630    .finalize(components::usb_component_static!(sam4l::usbc::Usbc));
631
632    // Kernel storage region, allocated with the storage_volume!
633    // macro in common/utils.rs
634    extern "C" {
635        /// Beginning on the ROM region containing app images.
636        static _sstorage: u8;
637        static _estorage: u8;
638    }
639
640    let nonvolatile_storage = components::nonvolatile_storage::NonvolatileStorageComponent::new(
641        board_kernel,
642        capsules_extra::nonvolatile_storage_driver::DRIVER_NUM,
643        &peripherals.flash_controller,
644        0x60000, // Start address for userspace accessible region
645        0x20000, // Length of userspace accessible region
646        core::ptr::addr_of!(_sstorage) as usize, //start address of kernel region
647        core::ptr::addr_of!(_estorage) as usize - core::ptr::addr_of!(_sstorage) as usize, // length of kernel region
648    )
649    .finalize(components::nonvolatile_storage_component_static!(
650        sam4l::flashcalw::FLASHCALW
651    ));
652
653    let local_ip_ifaces = static_init!(
654        [IPAddr; 3],
655        [
656            IPAddr([
657                0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
658                0x0e, 0x0f,
659            ]),
660            IPAddr([
661                0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d,
662                0x1e, 0x1f,
663            ]),
664            IPAddr::generate_from_mac(src_mac_from_serial_num),
665        ]
666    );
667
668    let (udp_send_mux, udp_recv_mux, udp_port_table) = components::udp_mux::UDPMuxComponent::new(
669        mux_mac,
670        DEFAULT_CTX_PREFIX_LEN,
671        DEFAULT_CTX_PREFIX,
672        DST_MAC_ADDR,
673        src_mac_from_serial_num, //comment out for dual rx test only
674        //MacAddress::Short(49138), //comment in for dual rx test only
675        local_ip_ifaces,
676        mux_alarm,
677    )
678    .finalize(components::udp_mux_component_static!(
679        sam4l::ast::Ast,
680        Ieee802154MacDevice
681    ));
682
683    // UDP driver initialization happens here
684    let udp_driver = components::udp_driver::UDPDriverComponent::new(
685        board_kernel,
686        capsules_extra::net::udp::driver::DRIVER_NUM,
687        udp_send_mux,
688        udp_recv_mux,
689        udp_port_table,
690        local_ip_ifaces,
691    )
692    .finalize(components::udp_driver_component_static!(sam4l::ast::Ast));
693
694    let scheduler = components::sched::round_robin::RoundRobinComponent::new(&*addr_of!(PROCESSES))
695        .finalize(components::round_robin_component_static!(NUM_PROCS));
696
697    // Create the software-based SHA engine.
698    let sha = components::sha::ShaSoftware256Component::new()
699        .finalize(components::sha_software_256_component_static!());
700
701    // Create the credential checker.
702    let checking_policy = components::appid::checker_sha::AppCheckerSha256Component::new(sha)
703        .finalize(components::app_checker_sha256_component_static!());
704
705    // Create the AppID assigner.
706    let assigner = components::appid::assigner_name::AppIdAssignerNamesComponent::new()
707        .finalize(components::appid_assigner_names_component_static!());
708
709    // Create the process checking machine.
710    let checker = components::appid::checker::ProcessCheckerMachineComponent::new(checking_policy)
711        .finalize(components::process_checker_machine_component_static!());
712
713    //--------------------------------------------------------------------------
714    // STORAGE PERMISSIONS
715    //--------------------------------------------------------------------------
716
717    let storage_permissions_policy =
718        components::storage_permissions::individual::StoragePermissionsIndividualComponent::new()
719            .finalize(
720                components::storage_permissions_individual_component_static!(
721                    sam4l::chip::Sam4l<Sam4lDefaultPeripherals>,
722                    kernel::process::ProcessStandardDebugFull,
723                ),
724            );
725
726    //--------------------------------------------------------------------------
727    // PROCESS LOADING
728    //--------------------------------------------------------------------------
729
730    // These symbols are defined in the standard Tock linker script.
731    extern "C" {
732        /// Beginning of the ROM region containing app images.
733        static _sapps: u8;
734        /// End of the ROM region containing app images.
735        static _eapps: u8;
736        /// Beginning of the RAM region for app memory.
737        static mut _sappmem: u8;
738        /// End of the RAM region for app memory.
739        static _eappmem: u8;
740    }
741
742    let app_flash = core::slice::from_raw_parts(
743        core::ptr::addr_of!(_sapps),
744        core::ptr::addr_of!(_eapps) as usize - core::ptr::addr_of!(_sapps) as usize,
745    );
746    let app_memory = core::slice::from_raw_parts_mut(
747        core::ptr::addr_of_mut!(_sappmem),
748        core::ptr::addr_of!(_eappmem) as usize - core::ptr::addr_of!(_sappmem) as usize,
749    );
750
751    // Create and start the asynchronous process loader.
752    let _loader = components::loader::sequential::ProcessLoaderSequentialComponent::new(
753        checker,
754        &mut *addr_of_mut!(PROCESSES),
755        board_kernel,
756        chip,
757        &FAULT_RESPONSE,
758        assigner,
759        storage_permissions_policy,
760        app_flash,
761        app_memory,
762    )
763    .finalize(components::process_loader_sequential_component_static!(
764        sam4l::chip::Sam4l<Sam4lDefaultPeripherals>,
765        kernel::process::ProcessStandardDebugFull,
766        NUM_PROCS
767    ));
768
769    let imix = Imix {
770        pconsole,
771        console,
772        alarm,
773        gpio,
774        temp,
775        humidity,
776        ambient_light,
777        adc,
778        led,
779        button,
780        rng,
781        analog_comparator,
782        crc,
783        spi: spi_syscalls,
784        ipc: kernel::ipc::IPC::new(board_kernel, kernel::ipc::DRIVER_NUM, &grant_cap),
785        ninedof,
786        udp_driver,
787        usb_driver,
788        nrf51822: nrf_serialization,
789        nonvolatile_storage,
790        scheduler,
791        systick: cortexm4::systick::SysTick::new(),
792    };
793
794    // Need to initialize the UART for the nRF51 serialization.
795    imix.nrf51822.initialize();
796
797    // These two lines need to be below the creation of the chip for
798    // initialization to work.
799    let _ = rf233.reset();
800    let _ = rf233.start();
801
802    let _ = imix.pconsole.start();
803
804    // Optional kernel tests. Note that these might conflict
805    // with normal operation (e.g., steal callbacks from drivers, etc.),
806    // so do not run these and expect all services/applications to work.
807    // Once everything is virtualized in the kernel this won't be a problem.
808    // -pal, 11/20/18
809    //
810    //test::virtual_uart_rx_test::run_virtual_uart_receive(uart_mux);
811    //test::rng_test::run_entropy32(&peripherals.trng);
812    //test::virtual_aes_ccm_test::run(&peripherals.aes);
813    //test::aes_test::run_aes128_ctr(&peripherals.aes);
814    //test::aes_test::run_aes128_cbc(&peripherals.aes);
815    //test::log_test::run(
816    //    mux_alarm,
817    //    &peripherals.flash_controller,
818    //);
819    //test::linear_log_test::run(
820    //    mux_alarm,
821    //    &peripherals.flash_controller,
822    //);
823    //test::icmp_lowpan_test::run(mux_mac, mux_alarm);
824    //let lowpan_frag_test = test::ipv6_lowpan_test::initialize_all(mux_mac, mux_alarm);
825    //lowpan_frag_test.start(); // If flashing the transmitting Imix
826    /*let udp_lowpan_test = test::udp_lowpan_test::initialize_all(
827       udp_send_mux,
828        udp_recv_mux,
829        udp_port_table,
830        mux_alarm,
831    );*/
832    //udp_lowpan_test.start();
833
834    // alarm_test::run_alarm(&peripherals.ast);
835    /*let virtual_alarm_timer = static_init!(
836        VirtualMuxAlarm<'static, sam4l::ast::Ast>,
837        VirtualMuxAlarm::new(mux_alarm)
838    );
839    virtual_alarm_timer.setup();
840
841    let mux_timer = static_init!(
842        MuxTimer<'static, sam4l::ast::Ast>,
843        MuxTimer::new(virtual_alarm_timer)
844    );*/
845    //virtual_alarm_timer.set_alarm_client(mux_timer);
846
847    //test::sha256_test::run_sha256();
848
849    /*components::test::multi_alarm_test::MultiAlarmTestComponent::new(mux_alarm)
850    .finalize(components::multi_alarm_test_component_buf!(sam4l::ast::Ast))
851    .run();*/
852
853    debug!("Initialization complete. Entering main loop");
854
855    (board_kernel, imix, chip)
856}
857
858/// Main function called after RAM initialized.
859#[no_mangle]
860pub unsafe fn main() {
861    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
862
863    let (board_kernel, platform, chip) = start();
864    board_kernel.kernel_loop(&platform, chip, Some(&platform.ipc), &main_loop_capability);
865}