diff options
26 files changed, 1564 insertions, 174 deletions
diff --git a/docs/mimxrt/pinout.rst b/docs/mimxrt/pinout.rst index 9aeb85401..d2b62d56d 100644 --- a/docs/mimxrt/pinout.rst +++ b/docs/mimxrt/pinout.rst @@ -5,7 +5,10 @@ Pinout for the i.MXRT machine modules .. _mimxrt_uart_pinout: -| +The Teensy 4.0 and 4.1 board show pin numbers **nn** at the board's silkscreen. +These are denoted in the tables below as **Dnn**. E.g. a silkscreen number **1** is +shown as **D1**. Whenever a Pin has to be specified in a script, **Dnn** must +be used, not **nn**. UART pin assignment ------------------- @@ -17,8 +20,8 @@ tables below: ================= =========== =========== =========== =========== Board / Pin UART0 UART1 UART2 UART3 ================= =========== =========== =========== =========== -Teensy 4.0 - 0/1 7/8 14/15 -Teensy 4.1 - 0/1 7/8 14/15 +Teensy 4.0 - D0/D1 D7/D8 D14/D15 +Teensy 4.1 - D0/D1 D7/D8 D14/D15 MIMXRT1010-EVK Debug USB D0/D1 D7/D6 - MIMXRT1015-EVK Debug USB D0/D1 D7/A1 - MIMXRT1020-EVK Debug USB D0/D1 D9/D6 D10/D13 @@ -35,11 +38,11 @@ Makerdiary RT1011 - D9/D10 D13/A0 D11/D12 | -================= =========== =========== ======= ======= ===== -Board / Pin UART4 UART5 UART6 UART7 UART8 -================= =========== =========== ======= ======= ===== -Teensy 4.0 16/17 21/20 25/24 28/29 - -Teensy 4.1 16/17 21/20 25/24 28/29 34/35 +================= =========== =========== ======= ======= ======= +Board / Pin UART4 UART5 UART6 UART7 UART8 +================= =========== =========== ======= ======= ======= +Teensy 4.0 D16/D17 D21/D20 D25/D24 D28/D29 - +Teensy 4.1 D16/D17 D21/D20 D25/D24 D28/D29 D34/D35 MIMXRT1010-EVK - - - - - MIMXRT1015-EVK - - - - - MIMXRT1020-EVK D15/D14 A1/A0 - - - @@ -51,7 +54,7 @@ MIMXRT1170-EVK D15/D14 D25/D26 D33/D34 D35/D36 - Olimex RT1010Py - - - - - Seeed ARCH MIX J4_10/J4_11 J5_08/J5_12 - - - Makerdiary RT1011 A1/A2 - - - - -================= =========== =========== ======= ======= ===== +================= =========== =========== ======= ======= ======= .. _mimxrt_pwm_pinout: @@ -102,46 +105,46 @@ Pins denoted with (*) are by default not wired at the board. ==== ========== ==== ========== Pin Teensy 4.0 Pin Teensy 4.1 ==== ========== ==== ========== -0 F1/1/X 0 F1/1/X -1 F1/0/X 1 F1/0/X -2 F4/2/A 2 F4/2/A -3 F4/2/B 3 F4/2/B -4 F2/0/A 4 F2/0/A -5 F2/1/A 5 F2/1/A -6 F2/2/A 6 F2/2/A -7 F1/3/B 7 F1/3/B -8 F1/3/A 8 F1/3/A -9 F2/2/B 9 F2/2/B -10 Q1/0 10 Q1/0 -11 Q1/2 11 Q1/2 -12 Q1/1 12 Q1/1 -13 Q2/0 13 Q2/0 -14 Q3/2 14 Q3/2 -15 Q3/3 15 Q3/3 -18 Q3/1 18 Q3/1 -19 Q3/0 19 Q3/0 -22 F4/0/A 22 F4/0/A -23 F4/1/A 23 F4/1/A -24 F1/2/X 24 F1/2/X -25 F1/3/X 25 F1/3/X -28 F3/1/B 28 F3/1/B -29 F3/1/A 29 F3/1/A -33 F2/0/B 33 F2/0/B -- - 36 F2/3/A -- - 37 F2/3/B -DAT1 F1/1/B 42 F1/1/B -DAT0 F1/1/A 43 F1/1/A -CLK F1/0/B 44 F1/0/B -CMD F1/0/A 45 F1/0/A -DAT2 F1/2/A 46 F1/2/A -DAT3 F1/2/B 47 F1/2/B -- - 48 F1/0/B -- - 49 F1/2/A -- - 50 F1/2/B -- - 51 F3/3/B -- - 52 F1/1/B -- - 53 F1/1/A -- - 54 F3/0/A +D0 F1/1/X D0 F1/1/X +D1 F1/0/X D1 F1/0/X +D2 F4/2/A D2 F4/2/A +D3 F4/2/B D3 F4/2/B +D4 F2/0/A D4 F2/0/A +D5 F2/1/A D5 F2/1/A +D6 F2/2/A D6 F2/2/A +D7 F1/3/B D7 F1/3/B +D8 F1/3/A D8 F1/3/A +D9 F2/2/B D9 F2/2/B +D10 Q1/0 D10 Q1/0 +D11 Q1/2 D11 Q1/2 +D12 Q1/1 D12 Q1/1 +D13 Q2/0 D13 Q2/0 +D14 Q3/2 D14 Q3/2 +D15 Q3/3 D15 Q3/3 +D18 Q3/1 D18 Q3/1 +D19 Q3/0 D19 Q3/0 +D22 F4/0/A D22 F4/0/A +D23 F4/1/A D23 F4/1/A +D24 F1/2/X D24 F1/2/X +D25 F1/3/X D25 F1/3/X +D28 F3/1/B D28 F3/1/B +D29 F3/1/A D29 F3/1/A +D33 F2/0/B D33 F2/0/B +- - D36 F2/3/A +- - D37 F2/3/B +DAT1 F1/1/B D42 F1/1/B +DAT0 F1/1/A D43 F1/1/A +CLK F1/0/B D44 F1/0/B +CMD F1/0/A D45 F1/0/A +DAT2 F1/2/A D46 F1/2/A +DAT3 F1/2/B D47 F1/2/B +- - D48 F1/0/B +- - D49 F1/2/A +- - D50 F1/2/B +- - D51 F3/3/B +- - D52 F1/1/B +- - D53 F1/1/A +- - D54 F3/0/A ==== ========== ==== ========== | @@ -330,11 +333,11 @@ The SPI signals have fixed assignments to GPIO pins. It depends on the board design, which SPI's signals are exposed to the user, as detailed in the table below. The signal order in the table is: CS0, CS1, MOSI, MISO, CLK. -================= ========================= ======================= =============== +================= ========================= ======================= ================= Board / Pin SPI0 SPI1 SPI2 -================= ========================= ======================= =============== -Teensy 4.0 10/-/11/12/13 0/-/26/1/27 - -Teensy 4.1 10/37/11/12/13 0/-/26/1/27 -/29/50/54/49 +================= ========================= ======================= ================= +Teensy 4.0 D10/-/D11/D12/D13 D0/-/D26/D1/D27 - +Teensy 4.1 D10/D37/D11/D12/D13 D0/-/D26/D1/D27 -/D29/D50/D54/D49 MIXMXRT1010-EVK D10/D7/D11/D12/D13 - - MIXMXRT1015-EVK D10/-/D11/D12/D13 - - MIXMXRT1020-EVK D10/-/D11/D12/D13 A3/D0/A5/A4/A0 - @@ -347,7 +350,7 @@ Adafruit Metro M7 -/-/MOSI/MISO/SCK - - Olimex RT1010Py - CS0/-/SDO/SDI/SCK SDCARD with CS1 Seeed ARCH MIX J4_12/-/J4_14/J4_13/J4_15 J3_09/J3_05/J3_08_J3_11 Makerdiary RT1011 A5/A2/A4/A3/A6 A11/A1/A10/A9/CLK -================= ========================= ======================= =============== +================= ========================= ======================= ================= Pins denoted with (*) are by default not wired at the board. The CS0 and CS1 signals are enabled with the keyword option cs=0 or cs=1 of the SPI object constructor. @@ -367,8 +370,8 @@ detailed in the table below. The signal order in the table is: SDA, SCL. ================= =========== =========== =========== ======= ======= Board / Pin I2C 0 I2C 1 I2C 2 I2C 3 I2C 4 ================= =========== =========== =========== ======= ======= -Teensy 4.0 18/19 17/16 25/24 - - -Teensy 4.1 18/19 17/16 25/24 - - +Teensy 4.0 D18/D19 D17/D16 D25/D24 - - +Teensy 4.1 D18/D19 D17/D16 D25/D24 - - MIXMXRT1010-EVK D14/D15 D0/D1 - - - MIXMXRT1015-EVK D14/D15 - - - - MIXMXRT1020-EVK D14/D15 A4/A5 D0/D1 - - @@ -396,10 +399,10 @@ Pin assignments for a few MIMXRT boards: ================= == ===== ======== ======= ======= ======== ======= ======= Board ID MCK SCK_TX WS_TX SD_TX SCK_RX WS_RX SD_RX ================= == ===== ======== ======= ======= ======== ======= ======= -Teensy 4.0 1 23 26 27 7 21 20 8 -Teensy 4.0 2 33 4 3 2 - - 5 -Teensy 4.1 1 23 26 27 7 21 20 8 -Teensy 4.1 2 33 4 3 2 - - 5 +Teensy 4.0 1 D23 D26 D27 D7 D21 D20 D8 +Teensy 4.0 2 D33 D4 D3 D2 - - D5 +Teensy 4.1 1 D23 D26 D27 D7 D21 D20 D8 +Teensy 4.1 2 D33 D4 D3 D2 - - D5 Seeed Arch MIX 1 J4_09 J4_14 J4_15 J14_13 J4_11 J4_10 J4_10 Adafruit Metro M7 1 D8 D10 D9 D12 D14 D15 D13 Olimex RT1010Py 1 D8 D6 D7 D4 D1 D2 D3 diff --git a/ports/alif/tinyusb_port/alif_dcd_reg.h b/ports/alif/tinyusb_port/alif_dcd_reg.h index 84220f6be..c5a707656 100644 --- a/ports/alif/tinyusb_port/alif_dcd_reg.h +++ b/ports/alif/tinyusb_port/alif_dcd_reg.h @@ -1,11 +1,13 @@ // *FORMAT-OFF* -///------------------------------------------------------------------------------------------------- -/// @file alif_dcd_reg.h -/// @author karol.saja@alifsemi.com -/// @version 0.0.1 -/// @date 2023-09-08 -/// @brief Low Level SPI driver -///------------------------------------------------------------------------------------------------- +/* + * Copyright (C) 2024 Alif Semiconductor - All Rights Reserved. + * Use, distribution and modification of this code is permitted under the + * terms stated in the Alif Semiconductor Software License Agreement + * + * You should have received a copy of the Alif Semiconductor Software + * License Agreement with this file. If not, please write to: + * contact@alifsemi.com, or visit: https://alifsemi.com/license + */ #ifndef __ALIF_DCD_REG_H__ #define __ALIF_DCD_REG_H__ diff --git a/ports/stm32/boards/NUCLEO_N657X0/mpconfigboard.h b/ports/stm32/boards/NUCLEO_N657X0/mpconfigboard.h index ccc3fa051..90ea1eae3 100644 --- a/ports/stm32/boards/NUCLEO_N657X0/mpconfigboard.h +++ b/ports/stm32/boards/NUCLEO_N657X0/mpconfigboard.h @@ -74,6 +74,17 @@ #define MICROPY_HW_USB_HS_IN_FS (1) #define MICROPY_HW_USB_MAIN_DEV (USB_PHY_HS_ID) +// Ethernet via RMII +#define MICROPY_HW_ETH_MDC (pin_G11) +#define MICROPY_HW_ETH_MDIO (pin_F4) +#define MICROPY_HW_ETH_RMII_REF_CLK (pin_F7) +#define MICROPY_HW_ETH_RMII_CRS_DV (pin_F10) +#define MICROPY_HW_ETH_RMII_RXD0 (pin_F14) +#define MICROPY_HW_ETH_RMII_RXD1 (pin_F15) +#define MICROPY_HW_ETH_RMII_TX_EN (pin_F11) +#define MICROPY_HW_ETH_RMII_TXD0 (pin_F12) +#define MICROPY_HW_ETH_RMII_TXD1 (pin_F13) + /******************************************************************************/ // Bootloader configuration diff --git a/ports/stm32/boards/NUCLEO_N657X0/mpconfigboard.mk b/ports/stm32/boards/NUCLEO_N657X0/mpconfigboard.mk index fa64cb170..777f22e61 100644 --- a/ports/stm32/boards/NUCLEO_N657X0/mpconfigboard.mk +++ b/ports/stm32/boards/NUCLEO_N657X0/mpconfigboard.mk @@ -24,3 +24,6 @@ endif # MicroPython settings MICROPY_FLOAT_IMPL = double +MICROPY_PY_LWIP = 1 +MICROPY_PY_SSL = 1 +MICROPY_SSL_MBEDTLS = 1 diff --git a/ports/stm32/boards/NUCLEO_N657X0/pins.csv b/ports/stm32/boards/NUCLEO_N657X0/pins.csv index 033f0a552..a8a3f6c5a 100644 --- a/ports/stm32/boards/NUCLEO_N657X0/pins.csv +++ b/ports/stm32/boards/NUCLEO_N657X0/pins.csv @@ -44,6 +44,17 @@ A5,PG15 -SPI5_MISO,PG1 -SPI5_MOSI,PG2 +# ETH1 RMII +,PG11 +,PF4 +,PF7 +,PF10 +,PF11 +,PF12 +,PF13 +,PF14 +,PF15 + -BUTTON,PC13 LED_BLUE,PG8 LED_RED,PG10 diff --git a/ports/stm32/boards/OPENMV_N6/mpconfigboard.h b/ports/stm32/boards/OPENMV_N6/mpconfigboard.h index 6e6bb4357..0d63ff224 100644 --- a/ports/stm32/boards/OPENMV_N6/mpconfigboard.h +++ b/ports/stm32/boards/OPENMV_N6/mpconfigboard.h @@ -126,6 +126,24 @@ #define MICROPY_HW_USB_PID_CDC_HID (MICROPY_HW_USB_PID) #define MICROPY_HW_USB_PID_CDC_MSC_HID (MICROPY_HW_USB_PID) +// Ethernet via RGMII +#define NETWORK_LAN_PHY (ETH_PHY_RTL8211) +#define MICROPY_HW_ETH_MDC (pin_D1) +#define MICROPY_HW_ETH_MDIO (pin_D12) +#define MICROPY_HW_ETH_RGMII_CLK125 (pin_F2) +#define MICROPY_HW_ETH_RGMII_GTX_CLK (pin_F0) +#define MICROPY_HW_ETH_RGMII_TXD0 (pin_F12) +#define MICROPY_HW_ETH_RGMII_TXD1 (pin_F13) +#define MICROPY_HW_ETH_RGMII_TXD2 (pin_G3) +#define MICROPY_HW_ETH_RGMII_TXD3 (pin_G4) +#define MICROPY_HW_ETH_RGMII_TX_CTL (pin_F11) +#define MICROPY_HW_ETH_RGMII_RX_CLK (pin_F7) +#define MICROPY_HW_ETH_RGMII_RXD0 (pin_F14) +#define MICROPY_HW_ETH_RGMII_RXD1 (pin_F15) +#define MICROPY_HW_ETH_RGMII_RXD2 (pin_F8) +#define MICROPY_HW_ETH_RGMII_RXD3 (pin_F9) +#define MICROPY_HW_ETH_RGMII_RX_CTL (pin_F10) + // Murata 1YN configuration #define CYW43_CHIPSET_FIRMWARE_INCLUDE_FILE "lib/cyw43-driver/firmware/w43439_sdio_1yn_7_95_59_combined.h" #define CYW43_WIFI_NVRAM_INCLUDE_FILE "lib/cyw43-driver/firmware/wifi_nvram_1yn.h" diff --git a/ports/stm32/boards/OPENMV_N6/pins.csv b/ports/stm32/boards/OPENMV_N6/pins.csv index 52f6c9249..2ca075a15 100644 --- a/ports/stm32/boards/OPENMV_N6/pins.csv +++ b/ports/stm32/boards/OPENMV_N6/pins.csv @@ -95,7 +95,20 @@ P16,PE12 I2C4_SCL,PE13 I2C4_SDA,PE14 ,PE15 +,PF0 +,PF2 +,PF7 +,PF8 +,PF9 +,PF10 +,PF11 +,PF12 +,PF13 +,PF14 +,PF15 P6,PG0 +,PG3 +,PG4 P9,PG12 P7,PG13 BAT_ADC,PG15 diff --git a/ports/stm32/boards/stm32n657_af.csv b/ports/stm32/boards/stm32n657_af.csv index 220d27b3f..c02c658bd 100644 --- a/ports/stm32/boards/stm32n657_af.csv +++ b/ports/stm32/boards/stm32n657_af.csv @@ -20,6 +20,7 @@ PortC,PC9 , , , , PortC,PC10, , , , , , , , , , ,SDMMC1_D2 , , , , , , PortC,PC11, , , , , , , , , , ,SDMMC1_D3 , , , , , , PortC,PC12, , , , , , , , , , ,SDMMC1_CK , , , , , , +PortD,PD1 , , , , , , , , , , , ,ETH1_MDC , , , , , PortD,PD2 , , , , , , , , , , , ,SDMMC2_CK , , , , , PortD,PD5 , , , , , , , ,USART2_TX , , , , , , , , , PortD,PD6 , , , , ,TIM15_CH2 , , , , , , , , , , , , @@ -27,6 +28,7 @@ PortD,PD7 , , , , PortD,PD8 , , , , , , , ,USART3_TX , , , , , , , , , PortD,PD9 , , , , , , , ,USART3_RX , , , , , , , , , PortD,PD11, , , , , ,SPI2_MISO , , , , , , , , , , , +PortD,PD12, , , , , , , , , , , ,ETH1_MDIO , , , , , PortD,PD13, , ,TIM4_CH2 , , , , , , , , , , , , , , PortE,PE5 , , , , , , , ,USART1_TX , , , , , , , , , PortE,PE6 , , , , , , , ,USART1_RX , , , , , , , , , @@ -37,13 +39,28 @@ PortE,PE12, , , , PortE,PE13, , , , ,I2C4_SCL , , , , , , , , , , , , PortE,PE14, , , , ,I2C4_SDA , , , , , , , , , , , , PortE,PE15, , , , , ,SPI5_SCK , , , , , , , , , , , +PortF,PF0 , , , , , , , , , , , , ,ETH1_RGMII_GTX_CLK , , , , +PortF,PF2 , , , , , , , , , , , ,ETH1_RGMII_CLK125 , , , , , PortF,PF3 , , , , , , , ,USART2_RTS , , , , , , , , ,ADC1_INP16 +PortF,PF4 , , , , , , , , , , , ,ETH1_MDIO , , , , , PortF,PF6 , , , , , , , ,USART2_RX , , , , , , , , , +PortF,PF7 , , , , , , , , , , , ,ETH1_RMII_REF_CLK/ETH1_RGMII_RX_CLK , , , , , +PortF,PF8 , , , , , , , , , , , ,ETH1_RGMII_RXD2 , , , , , +PortF,PF9 , , , , , , , , , , , ,ETH1_RGMII_RXD3 , , , , , +PortF,PF10, , , , , , , , , , , ,ETH1_RMII_CRS_DV/ETH1_RGMII_RX_CTL , , , , , +PortF,PF11, , , , , , , , , , , ,ETH1_RMII_TX_EN/ETH1_RGMII_TX_CTL , , , , , +PortF,PF12, , , , , , , , , , , ,ETH1_RMII_TXD0/ETH1_RGMII_TXD0 , , , , , +PortF,PF13, , , , , , , , , , , ,ETH1_RMII_TXD1/ETH1_RGMII_TXD1 , , , , , +PortF,PF14, , , , , , , , , , , ,ETH1_RMII_RXD0/ETH1_RGMII_RXD0 , , , , , +PortF,PF15, , , , , , , , , , , ,ETH1_RMII_RXD1/ETH1_RGMII_RXD1 , , , , , PortG,PG0 , , ,TIM12_CH1 , , , , , , , , , , , , , , PortG,PG1 , , , , , ,SPI5_MISO , , , , , , , , , , , PortG,PG2 , , , , , ,SPI5_MOSI , , , , , , , , , , , +PortG,PG3 , , , , , , , , , , , ,ETH1_RGMII_TXD2 , , , , , +PortG,PG4 , , , , , , , , , , , ,ETH1_RGMII_TXD3 , , , , , PortG,PG5 , , , , , , , ,USART2_CTS , , , , , , , , , PortG,PG8 , , , , , , , , , , , ,SDMMC2_D1 , , , , , +PortG,PG11, , , , , , , , , , , ,ETH1_MDC , , , , , PortG,PG12, ,TIM17_CH1 , , , , , , , , , , , , , , , PortG,PG13, , ,TIM4_CH1 , , , , ,USART3_RTS , , , , , , , , , PortG,PG15, , , , , , , , , , , , , , , , ,ADC12_INP7/ADC12_INN3 diff --git a/ports/stm32/boards/stm32n6xx_hal_conf_base.h b/ports/stm32/boards/stm32n6xx_hal_conf_base.h index 641a003d8..87556cf15 100644 --- a/ports/stm32/boards/stm32n6xx_hal_conf_base.h +++ b/ports/stm32/boards/stm32n6xx_hal_conf_base.h @@ -160,7 +160,6 @@ #include "stm32n6xx_hal_dcmipp.h" #include "stm32n6xx_hal_dma2d.h" #include "stm32n6xx_hal_dts.h" -#include "stm32n6xx_hal_eth.h" #include "stm32n6xx_hal_exti.h" #include "stm32n6xx_hal_fdcan.h" #include "stm32n6xx_hal_gfxmmu.h" diff --git a/ports/stm32/eth.c b/ports/stm32/eth.c index 9f6553068..60f2a23de 100644 --- a/ports/stm32/eth.c +++ b/ports/stm32/eth.c @@ -41,8 +41,19 @@ #include "lwip/dhcp.h" #include "netif/ethernet.h" +// Register and IRQ compatibility for STM32N6. +#if defined(STM32N6) +#define ETH ETH1 +#define ETH_MACMDIOAR_MB (ETH_MACMDIOAR_GB) +#define ETH_MACMDIOAR_MOC_Msk (ETH_MACMDIOAR_GOC_Msk) +#define ETH_MACMDIOAR_MOC_WR (ETH_MACMDIOAR_GOC_0) +#define ETH_MACMDIOAR_MOC_RD (ETH_MACMDIOAR_GOC_1 | ETH_MACMDIOAR_GOC_0) +#define ETH_IRQn ETH1_IRQn +#define ETH_IRQHandler ETH1_IRQHandler +#endif + // ETH DMA RX and TX descriptor definitions -#if defined(STM32H5) +#if defined(STM32H5) || defined(STM32N6) #define RX_DESCR_3_OWN_Pos (31) #define RX_DESCR_3_IOC_Pos (30) #define RX_DESCR_3_BUF1V_Pos (24) @@ -52,6 +63,7 @@ #define TX_DESCR_3_FD_Pos (29) #define TX_DESCR_3_LD_Pos (28) #define TX_DESCR_3_CIC_Pos (16) +#define TX_DESCR_2_IOC_Pos (31) #define TX_DESCR_2_B1L_Pos (0) #define TX_DESCR_2_B1L_Msk (0x3fff << TX_DESCR_2_B1L_Pos) #elif defined(STM32H7) @@ -85,15 +97,38 @@ #define TX_DESCR_1_TBS1_Pos (0) #endif +// Static alternate function macro. +#if defined(STM32N6) +#define STATIC_AF_ETH(signal) STATIC_AF_ETH1_##signal +#else +#define STATIC_AF_ETH(signal) STATIC_AF_ETH_##signal +#endif + // Configuration values #define PHY_INIT_TIMEOUT_MS (10000) -#define RX_BUF_SIZE (1524) // includes 4-byte CRC at end -#define TX_BUF_SIZE (1524) +// These buffer sizes need to be a multiple of 8 (for STM32N6 at least). +#define RX_BUF_SIZE (1528) // includes 4-byte CRC at end +#define TX_BUF_SIZE (1528) +#if defined(MICROPY_HW_ETH_RMII_REF_CLK) +// RMII in use. #define RX_BUF_NUM (5) #define TX_BUF_NUM (5) +#define USE_PBUF_REF_FOR_TX (0) +#else +// RGMII in use, so increase number of buffers and use pbuf zero copy if possible. +#define RX_BUF_NUM (16) +#define TX_BUF_NUM (16) +#define USE_PBUF_REF_FOR_TX (1) +#endif + +#if defined(STM32N6) +// The N6 has two DMA channels, so use one for RX and one for TX. +#define RX_DMA_CH (0) +#define TX_DMA_CH (1) +#endif typedef struct _eth_dma_rx_descr_t { volatile uint32_t rdes0, rdes1, rdes2, rdes3; @@ -106,11 +141,18 @@ typedef struct _eth_dma_tx_descr_t { typedef struct _eth_dma_t { eth_dma_rx_descr_t rx_descr[RX_BUF_NUM]; eth_dma_tx_descr_t tx_descr[TX_BUF_NUM]; - uint8_t rx_buf[RX_BUF_NUM * RX_BUF_SIZE] __attribute__((aligned(4))); - uint8_t tx_buf[TX_BUF_NUM * TX_BUF_SIZE] __attribute__((aligned(4))); - size_t rx_descr_idx; - size_t tx_descr_idx; - uint8_t padding[16384 - 15408]; + uint8_t rx_buf[RX_BUF_NUM * RX_BUF_SIZE] __attribute__((aligned(8))); + #if !USE_PBUF_REF_FOR_TX + uint8_t tx_buf[TX_BUF_NUM * TX_BUF_SIZE] __attribute__((aligned(8))); + #endif + #if !defined(STM32H5) && !defined(STM32N6) + // Make sure the size of this struct is 16k, for the MPU. + uint8_t padding[16 * 1024 + - sizeof(eth_dma_rx_descr_t) * RX_BUF_NUM + - sizeof(eth_dma_tx_descr_t) * TX_BUF_NUM + - RX_BUF_NUM * RX_BUF_SIZE + - TX_BUF_NUM * TX_BUF_SIZE]; + #endif } eth_dma_t; typedef struct _eth_t { @@ -118,18 +160,30 @@ typedef struct _eth_t { struct netif netif; struct dhcp dhcp_struct; uint32_t phy_addr; + void (*phy_init)(uint32_t phy_addr); int16_t (*phy_get_link_status)(uint32_t phy_addr); } eth_t; +// This struct contains RX and TX buffers shared with the DMA, and they may need +// to go in a special RAM section, or have MPU settings applied. static eth_dma_t eth_dma MICROPY_HW_ETH_DMA_ATTRIBUTE; +#if USE_PBUF_REF_FOR_TX +// This array holds lwIP pbufs that are currently in use by the DMA. +static struct pbuf *eth_dma_pbuf[TX_BUF_NUM]; +#endif + +// These variables index the buffers in eth_dma and are not shared with DMA. +static size_t eth_dma_rx_descr_idx; +static size_t eth_dma_tx_descr_idx; + eth_t eth_instance; static void eth_mac_deinit(eth_t *self); static void eth_process_frame(eth_t *self, size_t len, const uint8_t *buf); void eth_phy_write(uint32_t phy_addr, uint32_t reg, uint32_t val) { - #if defined(STM32H5) || defined(STM32H7) + #if defined(STM32H5) || defined(STM32H7) || defined(STM32N6) while (ETH->MACMDIOAR & ETH_MACMDIOAR_MB) { } uint32_t ar = ETH->MACMDIOAR; @@ -157,7 +211,7 @@ void eth_phy_write(uint32_t phy_addr, uint32_t reg, uint32_t val) { } uint32_t eth_phy_read(uint32_t phy_addr, uint32_t reg) { - #if defined(STM32H5) || defined(STM32H7) + #if defined(STM32H5) || defined(STM32H7) || defined(STM32N6) while (ETH->MACMDIOAR & ETH_MACMDIOAR_MB) { } uint32_t ar = ETH->MACMDIOAR; @@ -188,24 +242,47 @@ int eth_init(eth_t *self, int mac_idx, uint32_t phy_addr, int phy_type) { mp_hal_get_mac(mac_idx, &self->netif.hwaddr[0]); self->netif.hwaddr_len = 6; self->phy_addr = phy_addr; + self->phy_init = eth_phy_generic_init; if (phy_type == ETH_PHY_DP83825 || phy_type == ETH_PHY_DP83848) { self->phy_get_link_status = eth_phy_dp838xx_get_link_status; } else if (phy_type == ETH_PHY_LAN8720 || phy_type == ETH_PHY_LAN8742) { self->phy_get_link_status = eth_phy_lan87xx_get_link_status; + } else if (phy_type == ETH_PHY_RTL8211) { + self->phy_init = eth_phy_rtl8211_init; + self->phy_get_link_status = eth_phy_rtl8211_get_link_status; } else { return -1; } - // Configure GPIO - mp_hal_pin_config_alt_static(MICROPY_HW_ETH_MDC, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH_MDC); - mp_hal_pin_config_alt_static(MICROPY_HW_ETH_MDIO, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH_MDIO); - mp_hal_pin_config_alt_static_speed(MICROPY_HW_ETH_RMII_REF_CLK, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, MP_HAL_PIN_SPEED_MEDIUM, STATIC_AF_ETH_RMII_REF_CLK); - mp_hal_pin_config_alt_static(MICROPY_HW_ETH_RMII_CRS_DV, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH_RMII_CRS_DV); - mp_hal_pin_config_alt_static(MICROPY_HW_ETH_RMII_RXD0, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH_RMII_RXD0); - mp_hal_pin_config_alt_static(MICROPY_HW_ETH_RMII_RXD1, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH_RMII_RXD1); - mp_hal_pin_config_alt_static(MICROPY_HW_ETH_RMII_TX_EN, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH_RMII_TX_EN); - mp_hal_pin_config_alt_static(MICROPY_HW_ETH_RMII_TXD0, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH_RMII_TXD0); - mp_hal_pin_config_alt_static(MICROPY_HW_ETH_RMII_TXD1, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH_RMII_TXD1); + // Configure GPIO for management data. + mp_hal_pin_config_alt_static(MICROPY_HW_ETH_MDC, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH(MDC)); + mp_hal_pin_config_alt_static(MICROPY_HW_ETH_MDIO, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH(MDIO)); + + #if defined(MICROPY_HW_ETH_RMII_REF_CLK) + // Configure GPIO for RMII interface. + mp_hal_pin_config_alt_static_speed(MICROPY_HW_ETH_RMII_REF_CLK, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, MP_HAL_PIN_SPEED_MEDIUM, STATIC_AF_ETH(RMII_REF_CLK)); + mp_hal_pin_config_alt_static(MICROPY_HW_ETH_RMII_CRS_DV, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH(RMII_CRS_DV)); + mp_hal_pin_config_alt_static(MICROPY_HW_ETH_RMII_RXD0, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH(RMII_RXD0)); + mp_hal_pin_config_alt_static(MICROPY_HW_ETH_RMII_RXD1, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH(RMII_RXD1)); + mp_hal_pin_config_alt_static(MICROPY_HW_ETH_RMII_TX_EN, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH(RMII_TX_EN)); + mp_hal_pin_config_alt_static(MICROPY_HW_ETH_RMII_TXD0, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH(RMII_TXD0)); + mp_hal_pin_config_alt_static(MICROPY_HW_ETH_RMII_TXD1, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH(RMII_TXD1)); + #else + // Configure GPIO for RGMII interface. + mp_hal_pin_config_alt_static(MICROPY_HW_ETH_RGMII_CLK125, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH(RGMII_CLK125)); + mp_hal_pin_config_alt_static(MICROPY_HW_ETH_RGMII_GTX_CLK, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH(RGMII_GTX_CLK)); + mp_hal_pin_config_alt_static(MICROPY_HW_ETH_RGMII_TXD0, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH(RGMII_TXD0)); + mp_hal_pin_config_alt_static(MICROPY_HW_ETH_RGMII_TXD1, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH(RGMII_TXD1)); + mp_hal_pin_config_alt_static(MICROPY_HW_ETH_RGMII_TXD2, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH(RGMII_TXD2)); + mp_hal_pin_config_alt_static(MICROPY_HW_ETH_RGMII_TXD3, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH(RGMII_TXD3)); + mp_hal_pin_config_alt_static(MICROPY_HW_ETH_RGMII_TX_CTL, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH(RGMII_TX_CTL)); + mp_hal_pin_config_alt_static(MICROPY_HW_ETH_RGMII_RX_CLK, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH(RGMII_RX_CLK)); + mp_hal_pin_config_alt_static(MICROPY_HW_ETH_RGMII_RXD0, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH(RGMII_RXD0)); + mp_hal_pin_config_alt_static(MICROPY_HW_ETH_RGMII_RXD1, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH(RGMII_RXD1)); + mp_hal_pin_config_alt_static(MICROPY_HW_ETH_RGMII_RXD2, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH(RGMII_RXD2)); + mp_hal_pin_config_alt_static(MICROPY_HW_ETH_RGMII_RXD3, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH(RGMII_RXD3)); + mp_hal_pin_config_alt_static(MICROPY_HW_ETH_RGMII_RX_CTL, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, STATIC_AF_ETH(RGMII_RX_CTL)); + #endif // Enable peripheral clock #if defined(STM32H5) @@ -216,6 +293,11 @@ int eth_init(eth_t *self, int mac_idx, uint32_t phy_addr, int phy_type) { __HAL_RCC_ETH1MAC_CLK_ENABLE(); __HAL_RCC_ETH1TX_CLK_ENABLE(); __HAL_RCC_ETH1RX_CLK_ENABLE(); + #elif defined(STM32N6) + __HAL_RCC_ETH1_CLK_ENABLE(); + __HAL_RCC_ETH1MAC_CLK_ENABLE(); + __HAL_RCC_ETH1TX_CLK_ENABLE(); + __HAL_RCC_ETH1RX_CLK_ENABLE(); #else __HAL_RCC_ETH_CLK_ENABLE(); #endif @@ -229,9 +311,10 @@ void eth_set_trace(eth_t *self, uint32_t value) { static int eth_mac_init(eth_t *self) { // Configure MPU uint32_t irq_state = mpu_config_start(); - #if defined(STM32H5) - mpu_config_region(MPU_REGION_ETH, (uint32_t)ð_dma, MPU_CONFIG_ETH(16 * 1024)); + #if defined(STM32H5) || defined(STM32N6) + mpu_config_region(MPU_REGION_ETH, (uint32_t)ð_dma, MPU_CONFIG_ETH(sizeof(eth_dma_t))); #else + MP_STATIC_ASSERT(sizeof(eth_dma_t) == 16 * 1024); mpu_config_region(MPU_REGION_ETH, (uint32_t)ð_dma, MPU_CONFIG_ETH(MPU_REGION_SIZE_16KB)); #endif mpu_config_end(irq_state); @@ -241,16 +324,33 @@ static int eth_mac_init(eth_t *self) { __HAL_RCC_ETH_FORCE_RESET(); #elif defined(STM32H7) __HAL_RCC_ETH1MAC_FORCE_RESET(); + #elif defined(STM32N6) + __HAL_RCC_ETH1_FORCE_RESET(); #else __HAL_RCC_ETHMAC_FORCE_RESET(); #endif - // Select RMII interface + // Select clock sources. + #if defined(STM32N6) + LL_RCC_SetETHREFTXClockSource(LL_RCC_ETH1REFTX_CLKSOURCE_EXT); // max 25MHz + LL_RCC_SetETHREFRXClockSource(LL_RCC_ETH1REFRX_CLKSOURCE_EXT); // max 125MHz + LL_RCC_SetETHClockSource(LL_RCC_ETH1_CLKSOURCE_IC12); // max 125MHz + LL_RCC_SetETH1PTPDivider(LL_RCC_ETH1PTP_DIV_1); + LL_RCC_SetETHPTPClockSource(LL_RCC_ETH1PTP_CLKSOURCE_HCLK); // max 200MHz + #endif + + // Select RMII or RGMII interface #if defined(STM32H5) __HAL_RCC_SBS_CLK_ENABLE(); SBS->PMCR = (SBS->PMCR & ~SBS_PMCR_ETH_SEL_PHY_Msk) | SBS_PMCR_ETH_SEL_PHY_2; #elif defined(STM32H7) SYSCFG->PMCR = (SYSCFG->PMCR & ~SYSCFG_PMCR_EPIS_SEL_Msk) | SYSCFG_PMCR_EPIS_SEL_2; + #elif defined(STM32N6) + #if defined(MICROPY_HW_ETH_RGMII_CLK125) + LL_RCC_SetETHPHYInterface(LL_RCC_ETH1PHY_IF_RGMII); + #else + LL_RCC_SetETHPHYInterface(LL_RCC_ETH1PHY_IF_RMII); + #endif #else __HAL_RCC_SYSCFG_CLK_ENABLE(); SYSCFG->PMC |= SYSCFG_PMC_MII_RMII_SEL; @@ -268,6 +368,13 @@ static int eth_mac_init(eth_t *self) { __HAL_RCC_ETH1MAC_CLK_SLEEP_ENABLE(); __HAL_RCC_ETH1TX_CLK_SLEEP_ENABLE(); __HAL_RCC_ETH1RX_CLK_SLEEP_ENABLE(); + #elif defined(STM32N6) + __HAL_RCC_ETH1_RELEASE_RESET(); + + __HAL_RCC_ETH1_CLK_SLEEP_ENABLE(); + __HAL_RCC_ETH1MAC_CLK_SLEEP_ENABLE(); + __HAL_RCC_ETH1TX_CLK_SLEEP_ENABLE(); + __HAL_RCC_ETH1RX_CLK_SLEEP_ENABLE(); #else __HAL_RCC_ETHMAC_RELEASE_RESET(); @@ -277,7 +384,7 @@ static int eth_mac_init(eth_t *self) { #endif // Do a soft reset of the MAC core - #if defined(STM32H5) || defined(STM32H7) + #if defined(STM32H5) || defined(STM32H7) || defined(STM32N6) #define ETH_SOFT_RESET(eth) do { eth->DMAMR = ETH_DMAMR_SWR; } while (0) #define ETH_IS_RESET(eth) (eth->DMAMR & ETH_DMAMR_SWR) #else @@ -299,7 +406,7 @@ static int eth_mac_init(eth_t *self) { // Set MII clock range uint32_t hclk = HAL_RCC_GetHCLKFreq(); uint32_t cr_div; - #if defined(STM32H5) + #if defined(STM32H5) || defined(STM32N6) cr_div = ETH->MACMDIOAR & ~ETH_MACMDIOAR_CR; if (hclk < 35000000) { cr_div |= ETH_MACMDIOAR_CR_DIV16; @@ -311,8 +418,17 @@ static int eth_mac_init(eth_t *self) { cr_div |= ETH_MACMDIOAR_CR_DIV62; } else if (hclk < 250000000) { cr_div |= ETH_MACMDIOAR_CR_DIV102; + #if defined(STM32H5) } else { cr_div |= ETH_MACMDIOAR_CR_DIV124; + #else + } else if (hclk < 300000000) { + cr_div |= ETH_MACMDIOAR_CR_DIV124; + } else if (hclk < 500000000) { + cr_div |= ETH_MACMDIOAR_CR_DIV204; + } else { + cr_div |= ETH_MACMDIOAR_CR_DIV324; + #endif } ETH->MACMDIOAR = cr_div; #elif defined(STM32H7) @@ -344,14 +460,21 @@ static int eth_mac_init(eth_t *self) { ETH->MACMIIAR = cr_div; #endif + #if defined(STM32H5) || defined(STM32H7) || defined(STM32N6) + // Configure the MAC 1-us tick counter register. + WRITE_REG(ETH->MAC1USTCR, HAL_RCC_GetHCLKFreq() / 1000000U - 1U); + #endif + #if defined(STM32H5) || defined(STM32H7) // don't skip 32bit words since our descriptors are continuous in memory ETH->DMACCR &= ~(ETH_DMACCR_DSL_Msk); + #elif defined(STM32N6) + ETH->DMA_CH[RX_DMA_CH].DMACCR &= ~(ETH_DMACxCR_DSL_Msk); + ETH->DMA_CH[TX_DMA_CH].DMACCR &= ~(ETH_DMACxCR_DSL_Msk); #endif - // Reset the PHY - eth_phy_write(self->phy_addr, PHY_BCR, PHY_BCR_SOFT_RESET); - mp_hal_delay_ms(50); + // Reset and initialize the PHY. + self->phy_init(self->phy_addr); // Wait for the PHY link to be established int phy_state = 0; @@ -397,7 +520,7 @@ static int eth_mac_init(eth_t *self) { uint16_t phy_scsr = self->phy_get_link_status(self->phy_addr); // Burst mode configuration - #if defined(STM32H5) || defined(STM32H7) + #if defined(STM32H5) || defined(STM32H7) || defined(STM32N6) ETH->DMASBMR = ETH->DMASBMR & ~ETH_DMASBMR_AAL & ~ETH_DMASBMR_FB; #else ETH->DMABMR = 0; @@ -410,6 +533,21 @@ static int eth_mac_init(eth_t *self) { | ETH_DMACIER_NIE // enable normal interrupts | ETH_DMACIER_RIE // enable RX interrupt ; + #elif defined(STM32N6) + ETH->DMA_CH[RX_DMA_CH].DMACIER = + ETH_DMACxIER_NIE // enable normal interrupts + | ETH_DMACxIER_RIE // enable RX interrupt + ; + #if USE_PBUF_REF_FOR_TX + #if RX_DMA_CH == TX_DMA_CH + ETH->DMA_CH[TX_DMA_CH].DMACIER |= ETH_DMACxIER_TIE; // enable TX interrupt + #else + ETH->DMA_CH[TX_DMA_CH].DMACIER = + ETH_DMACxIER_NIE // enable normal interrupts + | ETH_DMACxIER_TIE // enable TX interrupt + ; + #endif + #endif #else ETH->DMAIER = ETH_DMAIER_NISE // enable normal interrupts @@ -419,7 +557,7 @@ static int eth_mac_init(eth_t *self) { // Configure RX descriptor lists for (size_t i = 0; i < RX_BUF_NUM; ++i) { - #if defined(STM32H5) || defined(STM32H7) + #if defined(STM32H5) || defined(STM32H7) || defined(STM32N6) eth_dma.rx_descr[i].rdes3 = 1 << RX_DESCR_3_OWN_Pos | (1 << RX_DESCR_3_BUF1V_Pos) // buf1 address valid @@ -439,17 +577,22 @@ static int eth_mac_init(eth_t *self) { #if defined(STM32H5) || defined(STM32H7) ETH->DMACRDLAR = (uint32_t)ð_dma.rx_descr[0]; + #elif defined(STM32N6) + // Set number of RX descriptors and buffer pointers. + ETH->DMA_CH[RX_DMA_CH].DMACRXRLR = RX_BUF_NUM - 1; + ETH->DMA_CH[RX_DMA_CH].DMACRXDLAR = (uint32_t)ð_dma.rx_descr[0]; + ETH->DMA_CH[RX_DMA_CH].DMACRXDTPR = (uint32_t)ð_dma.rx_descr[RX_BUF_NUM - 1]; #else ETH->DMARDLAR = (uint32_t)ð_dma.rx_descr[0]; #endif - eth_dma.rx_descr_idx = 0; + eth_dma_rx_descr_idx = 0; // Configure TX descriptor lists for (size_t i = 0; i < TX_BUF_NUM; ++i) { - #if defined(STM32H5) || defined(STM32H7) + #if defined(STM32H5) || defined(STM32H7) || defined(STM32N6) eth_dma.tx_descr[i].tdes0 = 0; eth_dma.tx_descr[i].tdes1 = 0; - eth_dma.tx_descr[i].tdes2 = TX_BUF_SIZE & TX_DESCR_2_B1L_Msk; + eth_dma.tx_descr[i].tdes2 = 0; eth_dma.tx_descr[i].tdes3 = 0; #else eth_dma.tx_descr[i].tdes0 = 1 << TX_DESCR_0_TCH_Pos; @@ -465,10 +608,20 @@ static int eth_mac_init(eth_t *self) { ETH->DMACRDRLR = RX_BUF_NUM - 1; ETH->DMACTDLAR = (uint32_t)ð_dma.tx_descr[0]; + #elif defined(STM32N6) + // Set number of TX descriptors and buffer pointers. + ETH->DMA_CH[TX_DMA_CH].DMACTXRLR = TX_BUF_NUM - 1; + ETH->DMA_CH[TX_DMA_CH].DMACTXDLAR = (uint32_t)ð_dma.tx_descr[0]; + ETH->DMA_CH[TX_DMA_CH].DMACTXDTPR = (uint32_t)ð_dma.tx_descr[0]; #else ETH->DMATDLAR = (uint32_t)ð_dma.tx_descr[0]; #endif - eth_dma.tx_descr_idx = 0; + eth_dma_tx_descr_idx = 0; + #if USE_PBUF_REF_FOR_TX + for (int i = 0; i < TX_BUF_NUM; ++i) { + eth_dma_pbuf[i] = NULL; + } + #endif // Configure DMA #if defined(STM32H5) || defined(STM32H7) @@ -476,6 +629,11 @@ static int eth_mac_init(eth_t *self) { ETH->MTLRQOMR = ETH_MTLRQOMR_RSF; // transmission starts when a full packet resides in the Tx queue ETH->MTLTQOMR = ETH_MTLTQOMR_TSF; + #elif defined(STM32N6) + // read from RX FIFO only after a full frame is written + ETH->MTL_QUEUE[0].MTLRXQOMR = ETH_MTLRXQxOMR_RSF; + // transmission starts when a full packet resides in the Tx queue + ETH->MTL_QUEUE[0].MTLTXQOMR = ETH_MTLTXQxOMR_TSF; #else ETH->DMAOMR = ETH_DMAOMR_RSF // read from RX FIFO after a full frame is written @@ -485,7 +643,7 @@ static int eth_mac_init(eth_t *self) { mp_hal_delay_ms(2); // Select MAC filtering options - #if defined(STM32H5) || defined(STM32H7) + #if defined(STM32H5) || defined(STM32H7) || defined(STM32N6) ETH->MACPFR = ETH_MACPFR_RA; // pass all frames up #else ETH->MACFFR = @@ -501,15 +659,50 @@ static int eth_mac_init(eth_t *self) { ETH->MACA0LR = mac[3] << 24 | mac[2] << 16 | mac[1] << 8 | mac[0]; mp_hal_delay_ms(2); + // Work out the line speed configuration for MACCR. + uint32_t maccr = 0; + if (phy_scsr & PHY_SPEED_100HALF) { + maccr |= ETH_MACCR_FES; + } + if (phy_scsr & PHY_DUPLEX) { + maccr |= ETH_MACCR_DM; + } + + #if defined(STM32N6) + + if (!(phy_scsr & PHY_SPEED_1000HALF)) { + maccr |= ETH_MACCR_PS; + } + + maccr |= + ETH_MACCR_IPG_96BIT + | ETH_MACCR_SARC_REPADDR0 + | ETH_MACCR_IPC + | ETH_MACCR_BL_10 + | ETH_MACCR_PRELEN_7; + + ETH->MACCR = maccr; + ETH->MACECR = 0x618U; + ETH->MACWTR = ETH_MACWTR_WTO_2KB; + ETH->MACQ0TXFCR = ETH_MACQ0TXFCR_PLT_MINUS4; + ETH->MACRXFCR = 0; + ETH->MACRXQC0R = ETH_MACRXQC0R_RXQ0EN_GT | ETH_MACRXQC0R_RXQ1EN_NOT; + + ETH->MTLOMR = ETH_MTLOMR_SCHALG_SP | ETH_MTLOMR_RAA_SP; + ETH->MTLRXQDMAMR = ETH_MTLRXQDMAMR_Q0MDMACH_DMACH0 | ETH_MTLRXQDMAMR_Q1MDMACH_DMACH1; + ETH->MTL_QUEUE[0].MTLTXQOMR = ETH_MTLTXQxOMR_TXQEN_EN | ETH_MTLTXQxOMR_TSF | 7 << ETH_MTLTXQxOMR_TQS_Pos; + ETH->MTL_QUEUE[1].MTLTXQOMR = ETH_MTLTXQxOMR_TXQEN_EN | ETH_MTLTXQxOMR_TSF | 7 << ETH_MTLTXQxOMR_TQS_Pos; + ETH->MTL_QUEUE[0].MTLRXQOMR = ETH_MTLRXQxOMR_RSF | 15 << ETH_MTLRXQxOMR_RQS_Pos; + ETH->MTL_QUEUE[1].MTLRXQOMR = ETH_MTLRXQxOMR_RSF | 15 << ETH_MTLRXQxOMR_RQS_Pos; + + #else + // Set main MAC control register - ETH->MACCR = - phy_scsr == PHY_SPEED_10FULL ? ETH_MACCR_DM - : phy_scsr == PHY_SPEED_100HALF ? ETH_MACCR_FES - : phy_scsr == PHY_SPEED_100FULL ? (ETH_MACCR_FES | ETH_MACCR_DM) - : 0 - ; + ETH->MACCR = maccr; mp_hal_delay_ms(2); + #endif + // Start MAC layer ETH->MACCR |= ETH_MACCR_TE // enable TX @@ -521,6 +714,15 @@ static int eth_mac_init(eth_t *self) { #if defined(STM32H5) || defined(STM32H7) ETH->DMACRCR |= ETH_DMACRCR_SR; // start RX ETH->DMACTCR |= ETH_DMACTCR_ST; // start TX + #elif defined(STM32N6) + ETH->MTL_QUEUE[0].MTLTXQOMR |= ETH_MTLTXQxOMR_FTQ; // flush TX FIFO + ETH->MTL_QUEUE[1].MTLTXQOMR |= ETH_MTLTXQxOMR_FTQ; // flush TX FIFO + ETH->DMA_CH[RX_DMA_CH].DMACRXCR = RX_BUF_SIZE << ETH_DMACxRXCR_RBSZ_Pos; + ETH->DMA_CH[RX_DMA_CH].DMACRXCR |= ETH_DMACxRXCR_SR; // start RX + ETH->DMA_CH[TX_DMA_CH].DMACTXCR = 4 << ETH_DMACxTXCR_TXPBL_Pos; + ETH->DMA_CH[TX_DMA_CH].DMACTXCR |= ETH_DMACxTXCR_ST; // start TX + ETH->DMA_CH[RX_DMA_CH].DMACSR |= ETH_DMACxSR_TPS | ETH_DMACxSR_RPS; // clear TX/RX process stopped flags + ETH->DMA_CH[TX_DMA_CH].DMACSR |= ETH_DMACxSR_TPS | ETH_DMACxSR_RPS; // clear TX/RX process stopped flags #else ETH->DMAOMR |= ETH_DMAOMR_ST // start TX @@ -547,6 +749,10 @@ static void eth_mac_deinit(eth_t *self) { __HAL_RCC_ETH1MAC_FORCE_RESET(); __HAL_RCC_ETH1MAC_RELEASE_RESET(); __HAL_RCC_ETH1MAC_CLK_DISABLE(); + #elif defined(STM32N6) + __HAL_RCC_ETH1_FORCE_RESET(); + __HAL_RCC_ETH1_RELEASE_RESET(); + __HAL_RCC_ETH1_CLK_DISABLE(); #else __HAL_RCC_ETHMAC_FORCE_RESET(); __HAL_RCC_ETHMAC_RELEASE_RESET(); @@ -554,16 +760,18 @@ static void eth_mac_deinit(eth_t *self) { #endif } -static int eth_tx_buf_get(size_t len, uint8_t **buf) { +#if !USE_PBUF_REF_FOR_TX + +int eth_tx_buf_get(size_t len, uint8_t **buf) { if (len > TX_BUF_SIZE) { return -MP_EINVAL; } // Wait for DMA to release the current TX descriptor (if it has it) - eth_dma_tx_descr_t *tx_descr = ð_dma.tx_descr[eth_dma.tx_descr_idx]; + eth_dma_tx_descr_t *tx_descr = ð_dma.tx_descr[eth_dma_tx_descr_idx]; uint32_t t0 = mp_hal_ticks_ms(); for (;;) { - #if defined(STM32H5) || defined(STM32H7) + #if defined(STM32H5) || defined(STM32H7) || defined(STM32N6) if (!(tx_descr->tdes3 & (1 << TX_DESCR_3_OWN_Pos))) { break; } @@ -577,44 +785,67 @@ static int eth_tx_buf_get(size_t len, uint8_t **buf) { } } - #if defined(STM32H5) || defined(STM32H7) + #if defined(STM32H5) || defined(STM32H7) || defined(STM32N6) // Update TX descriptor with length and buffer pointer - *buf = ð_dma.tx_buf[eth_dma.tx_descr_idx * TX_BUF_SIZE]; + *buf = ð_dma.tx_buf[eth_dma_tx_descr_idx * TX_BUF_SIZE]; tx_descr->tdes2 = len & TX_DESCR_2_B1L_Msk; tx_descr->tdes0 = (uint32_t)*buf; #else // Update TX descriptor with length, buffer pointer and linked list pointer - *buf = ð_dma.tx_buf[eth_dma.tx_descr_idx * TX_BUF_SIZE]; + *buf = ð_dma.tx_buf[eth_dma_tx_descr_idx * TX_BUF_SIZE]; tx_descr->tdes1 = len << TX_DESCR_1_TBS1_Pos; tx_descr->tdes2 = (uint32_t)*buf; - tx_descr->tdes3 = (uint32_t)ð_dma.tx_descr[(eth_dma.tx_descr_idx + 1) % TX_BUF_NUM]; + tx_descr->tdes3 = (uint32_t)ð_dma.tx_descr[(eth_dma_tx_descr_idx + 1) % TX_BUF_NUM]; #endif return 0; } -static int eth_tx_buf_send(void) { - // Get TX descriptor and move to next one - eth_dma_tx_descr_t *tx_descr = ð_dma.tx_descr[eth_dma.tx_descr_idx]; - eth_dma.tx_descr_idx = (eth_dma.tx_descr_idx + 1) % TX_BUF_NUM; +#else - // Schedule to send next outgoing frame - #if defined(STM32H5) || defined(STM32H7) - tx_descr->tdes3 = - 1 << TX_DESCR_3_OWN_Pos // owned by DMA - | 1 << TX_DESCR_3_LD_Pos // last segment - | 1 << TX_DESCR_3_FD_Pos // first segment - | 3 << TX_DESCR_3_CIC_Pos // enable all checksums inserted by hardware - ; - #else - tx_descr->tdes0 = - 1 << TX_DESCR_0_OWN_Pos // owned by DMA - | 1 << TX_DESCR_0_LS_Pos // last segment - | 1 << TX_DESCR_0_FS_Pos // first segment - | 3 << TX_DESCR_0_CIC_Pos // enable all checksums inserted by hardware - | 1 << TX_DESCR_0_TCH_Pos // TX descriptor is chained - ; - #endif +int eth_tx_buf_get_ref(size_t len, uint8_t *buf, unsigned int idx) { + // Wait for DMA to release the current TX descriptor (if it has it). + eth_dma_tx_descr_t *tx_descr = ð_dma.tx_descr[(eth_dma_tx_descr_idx + idx) % TX_BUF_NUM]; + uint32_t t0 = mp_hal_ticks_ms(); + while (tx_descr->tdes3 & (1 << TX_DESCR_3_OWN_Pos)) { + if (mp_hal_ticks_ms() - t0 > 1000) { + return -MP_ETIMEDOUT; + } + } + + MP_HAL_CLEAN_DCACHE(buf, len); + tx_descr->tdes2 = (len & TX_DESCR_2_B1L_Msk) | (1 << TX_DESCR_2_IOC_Pos); + tx_descr->tdes0 = (uint32_t)buf; + + return 0; +} + +#endif + +static int eth_tx_buf_send(unsigned int num_segments) { + for (unsigned int segment = 0; segment < num_segments; ++segment) { + // Get TX descriptor and move to next one + eth_dma_tx_descr_t *tx_descr = ð_dma.tx_descr[eth_dma_tx_descr_idx]; + eth_dma_tx_descr_idx = (eth_dma_tx_descr_idx + 1) % TX_BUF_NUM; + + // Schedule to send next outgoing frame + #if defined(STM32H5) || defined(STM32H7) || defined(STM32N6) + tx_descr->tdes3 = + 1 << TX_DESCR_3_OWN_Pos // owned by DMA + | (segment == num_segments - 1) << TX_DESCR_3_LD_Pos // last segment + | (segment == 0) << TX_DESCR_3_FD_Pos // first segment + | 3 << TX_DESCR_3_CIC_Pos // enable all checksums inserted by hardware + ; + #else + tx_descr->tdes0 = + 1 << TX_DESCR_0_OWN_Pos // owned by DMA + | (segment == num_segments - 1) << TX_DESCR_0_LS_Pos // last segment + | (segment == 0) << TX_DESCR_0_FS_Pos // first segment + | 3 << TX_DESCR_0_CIC_Pos // enable all checksums inserted by hardware + | 1 << TX_DESCR_0_TCH_Pos // TX descriptor is chained + ; + #endif + } // Notify ETH DMA that there is a new TX descriptor for sending __DMB(); @@ -622,7 +853,12 @@ static int eth_tx_buf_send(void) { if (ETH->DMACSR & ETH_DMACSR_TBU) { ETH->DMACSR = ETH_DMACSR_TBU; } - ETH->DMACTDTPR = (uint32_t)ð_dma.tx_descr[eth_dma.tx_descr_idx]; + ETH->DMACTDTPR = (uint32_t)ð_dma.tx_descr[eth_dma_tx_descr_idx]; + #elif defined(STM32N6) + if (ETH->DMA_CH[TX_DMA_CH].DMACSR & ETH_DMACxSR_TBU) { + ETH->DMA_CH[TX_DMA_CH].DMACSR = ETH_DMACxSR_TBU; + } + ETH->DMA_CH[TX_DMA_CH].DMACTXDTPR = (uint32_t)ð_dma.tx_descr[eth_dma_tx_descr_idx]; #else if (ETH->DMASR & ETH_DMASR_TBUS) { ETH->DMASR = ETH_DMASR_TBUS; @@ -635,12 +871,12 @@ static int eth_tx_buf_send(void) { static void eth_dma_rx_free(void) { // Get RX descriptor, RX buffer and move to next one - eth_dma_rx_descr_t *rx_descr = ð_dma.rx_descr[eth_dma.rx_descr_idx]; - uint8_t *buf = ð_dma.rx_buf[eth_dma.rx_descr_idx * RX_BUF_SIZE]; - eth_dma.rx_descr_idx = (eth_dma.rx_descr_idx + 1) % RX_BUF_NUM; + eth_dma_rx_descr_t *rx_descr = ð_dma.rx_descr[eth_dma_rx_descr_idx]; + uint8_t *buf = ð_dma.rx_buf[eth_dma_rx_descr_idx * RX_BUF_SIZE]; + eth_dma_rx_descr_idx = (eth_dma_rx_descr_idx + 1) % RX_BUF_NUM; // Schedule to get next incoming frame - #if defined(STM32H5) || defined(STM32H7) + #if defined(STM32H5) || defined(STM32H7) || defined(STM32N6) rx_descr->rdes0 = (uint32_t)buf; rx_descr->rdes3 = 1 << RX_DESCR_3_OWN_Pos; // owned by DMA rx_descr->rdes3 |= 1 << RX_DESCR_3_BUF1V_Pos; // buf 1 address valid @@ -651,24 +887,32 @@ static void eth_dma_rx_free(void) { | RX_BUF_SIZE << RX_DESCR_1_RBS1_Pos // maximum buffer length ; rx_descr->rdes2 = (uint32_t)buf; - rx_descr->rdes3 = (uint32_t)ð_dma.rx_descr[eth_dma.rx_descr_idx]; + rx_descr->rdes3 = (uint32_t)ð_dma.rx_descr[eth_dma_rx_descr_idx]; rx_descr->rdes0 = 1 << RX_DESCR_0_OWN_Pos; // owned by DMA #endif // Notify ETH DMA that there is a new RX descriptor available __DMB(); #if defined(STM32H5) || defined(STM32H7) - ETH->DMACRDTPR = (uint32_t)&rx_descr[eth_dma.rx_descr_idx]; + ETH->DMACRDTPR = (uint32_t)&rx_descr[eth_dma_rx_descr_idx]; + #elif defined(STM32N6) + ETH->DMA_CH[RX_DMA_CH].DMACRXDTPR = (uint32_t)&rx_descr[eth_dma_rx_descr_idx]; #else ETH->DMARPDR = 0; #endif } void ETH_IRQHandler(void) { + MP_STATIC_ASSERT(ETH_IRQn > 0); + #if defined(STM32H5) || defined(STM32H7) uint32_t sr = ETH->DMACSR; ETH->DMACSR = ETH_DMACSR_NIS; uint32_t rx_interrupt = sr & ETH_DMACSR_RI; + #elif defined(STM32N6) + uint32_t sr = ETH->DMA_CH[RX_DMA_CH].DMACSR; + ETH->DMA_CH[RX_DMA_CH].DMACSR = ETH_DMACxSR_NIS; + uint32_t rx_interrupt = sr & ETH_DMACxSR_RI; #else uint32_t sr = ETH->DMASR; ETH->DMASR = ETH_DMASR_NIS; @@ -677,18 +921,20 @@ void ETH_IRQHandler(void) { if (rx_interrupt) { #if defined(STM32H5) || defined(STM32H7) ETH->DMACSR = ETH_DMACSR_RI; + #elif defined(STM32N6) + ETH->DMA_CH[RX_DMA_CH].DMACSR = ETH_DMACxSR_RI; #else ETH->DMASR = ETH_DMASR_RS; #endif for (;;) { - #if defined(STM32H5) || defined(STM32H7) - eth_dma_rx_descr_t *rx_descr_l = ð_dma.rx_descr[eth_dma.rx_descr_idx]; + #if defined(STM32H5) || defined(STM32H7) || defined(STM32N6) + eth_dma_rx_descr_t *rx_descr_l = ð_dma.rx_descr[eth_dma_rx_descr_idx]; if (rx_descr_l->rdes3 & (1 << RX_DESCR_3_OWN_Pos)) { // No more RX descriptors ready to read break; } #else - eth_dma_rx_descr_t *rx_descr = ð_dma.rx_descr[eth_dma.rx_descr_idx]; + eth_dma_rx_descr_t *rx_descr = ð_dma.rx_descr[eth_dma_rx_descr_idx]; if (rx_descr->rdes0 & (1 << RX_DESCR_0_OWN_Pos)) { // No more RX descriptors ready to read break; @@ -696,14 +942,14 @@ void ETH_IRQHandler(void) { #endif // Get RX buffer containing new frame - #if defined(STM32H5) || defined(STM32H7) + #if defined(STM32H5) || defined(STM32H7) || defined(STM32N6) size_t len = (rx_descr_l->rdes3 & RX_DESCR_3_PL_Msk); #else size_t len = (rx_descr->rdes0 & RX_DESCR_0_FL_Msk) >> RX_DESCR_0_FL_Pos; #endif len -= 4; // discard CRC at end - #if defined(STM32H5) || defined(STM32H7) - uint8_t *buf = ð_dma.rx_buf[eth_dma.rx_descr_idx * RX_BUF_SIZE]; + #if defined(STM32H5) || defined(STM32H7) || defined(STM32N6) + uint8_t *buf = ð_dma.rx_buf[eth_dma_rx_descr_idx * RX_BUF_SIZE]; #else uint8_t *buf = (uint8_t *)rx_descr->rdes2; #endif @@ -713,6 +959,28 @@ void ETH_IRQHandler(void) { eth_dma_rx_free(); } } + + #if USE_PBUF_REF_FOR_TX + #if RX_DMA_CH != TX_DMA_CH + sr = ETH->DMA_CH[TX_DMA_CH].DMACSR; + ETH->DMA_CH[TX_DMA_CH].DMACSR = ETH_DMACxSR_NIS; + #endif + uint32_t tx_interrupt = sr & ETH_DMACxSR_TI; + if (tx_interrupt) { + ETH->DMA_CH[TX_DMA_CH].DMACSR = ETH_DMACxSR_TI; + for (int i = 0; i < TX_BUF_NUM; ++i) { + eth_dma_tx_descr_t *tx_descr = ð_dma.tx_descr[i]; + if (!(tx_descr->tdes3 & (1 << TX_DESCR_3_OWN_Pos))) { + // DMA does not own it + if (eth_dma_pbuf[i] != NULL) { + // release pbuf + pbuf_free(eth_dma_pbuf[i]); + eth_dma_pbuf[i] = NULL; + } + } + } + } + #endif } /*******************************************************************************/ @@ -749,13 +1017,64 @@ static err_t eth_netif_output(struct netif *netif, struct pbuf *p) { LINK_STATS_INC(link.xmit); eth_trace(netif->state, (size_t)-1, p, NETUTILS_TRACE_IS_TX | NETUTILS_TRACE_NEWLINE); + #if USE_PBUF_REF_FOR_TX + + // Work out how many segments the pbuf has, and if it needs a copy made. + bool made_pbuf_copy = false; + unsigned int num_segments = 0; + for (struct pbuf *pb = p; pb != NULL; pb = pb->next) { + if (PBUF_NEEDS_COPY(pb)) { + // Note: this path is called for large UDP packets that are fragmented, + // because the fragments use PBUF_REF to divide up the original data. + p = pbuf_clone(PBUF_RAW, PBUF_RAM, p); + made_pbuf_copy = true; + num_segments = 1; + break; + } + ++num_segments; + } + + // Allocate TX buffer slots. + unsigned int idx = 0; + for (struct pbuf *pb = p; pb != NULL; pb = pb->next) { + int ret = eth_tx_buf_get_ref(pb->len, pb->payload, idx++); + if (ret != 0) { + if (made_pbuf_copy) { + pbuf_free(p); + } + return ERR_BUF; + } + } + + // Take references to pbufs + idx = 0; + for (struct pbuf *pb = p; pb != NULL; pb = pb->next) { + unsigned int tx_idx = (eth_dma_tx_descr_idx + idx) % TX_BUF_NUM; + if (eth_dma_pbuf[tx_idx] != NULL) { + pbuf_free(eth_dma_pbuf[tx_idx]); + } + if (!made_pbuf_copy) { + pbuf_ref(pb); + } + eth_dma_pbuf[tx_idx] = pb; + ++idx; + } + + // Start the transmission. + int ret = eth_tx_buf_send(num_segments); + + #else + + // Allocate TX slot, copy the pbuf, and start the transmission. uint8_t *buf; int ret = eth_tx_buf_get(p->tot_len, &buf); if (ret == 0) { pbuf_copy_partial(p, buf, p->tot_len, 0); - ret = eth_tx_buf_send(); + ret = eth_tx_buf_send(1); } + #endif + return ret ? ERR_BUF : ERR_OK; } @@ -875,6 +1194,8 @@ void eth_low_power_mode(eth_t *self, bool enable) { // Enable eth clock #if defined(STM32H7) __HAL_RCC_ETH1MAC_CLK_ENABLE(); + #elif defined(STM32N6) + __HAL_RCC_ETH1_CLK_ENABLE(); #else __HAL_RCC_ETH_CLK_ENABLE(); #endif @@ -886,6 +1207,8 @@ void eth_low_power_mode(eth_t *self, bool enable) { // Disable eth clock. #if defined(STM32H7) __HAL_RCC_ETH1MAC_CLK_DISABLE(); + #elif defined(STM32N6) + __HAL_RCC_ETH1_CLK_DISABLE(); #else __HAL_RCC_ETH_CLK_DISABLE(); #endif diff --git a/ports/stm32/eth.h b/ports/stm32/eth.h index 564744969..6556f4a7c 100644 --- a/ports/stm32/eth.h +++ b/ports/stm32/eth.h @@ -30,7 +30,8 @@ enum { ETH_PHY_LAN8742 = 0, ETH_PHY_LAN8720, ETH_PHY_DP83848, - ETH_PHY_DP83825 + ETH_PHY_DP83825, + ETH_PHY_RTL8211 }; typedef struct _eth_t eth_t; diff --git a/ports/stm32/eth_phy.c b/ports/stm32/eth_phy.c index 56cddba9c..cdc632f26 100644 --- a/ports/stm32/eth_phy.c +++ b/ports/stm32/eth_phy.c @@ -31,18 +31,45 @@ #if defined(MICROPY_HW_ETH_MDC) #define PHY_SCSR_LAN87XX (0x001f) -#define PHY_SCSR_LAN87XX_SPEED_Pos (2) -#define PHY_SCSR_LAN87XX_SPEED_Msk (7) +#define PHY_SCSR_LAN87XX_10M_Msk (0x0004) +#define PHY_SCSR_LAN87XX_100M_Msk (0x0008) +#define PHY_SCSR_LAN87XX_DUPLEX_Msk (0x0010) #define PHY_SCSR_DP838XX (0x0010) #define PHY_RECR_DP838XX (0x0015) #define PHY_SCSR_DP838XX_DUPLEX_Msk (4) #define PHY_SCSR_DP838XX_10M_Msk (2) +#define PHY_RTL8211_DEFAULT_PAGE (0xa42) +#define PHY_RTL8211_PAGSR_ADDR (0x1f) +#define PHY_RTL8211_PHYSR_PAGE (0xa43) +#define PHY_RTL8211_PHYSR_ADDR (0x1a) +#define PHY_RTL8211_PHYSR_SPEED_Pos (4) +#define PHY_RTL8211_PHYSR_SPEED_Msk (3 << PHY_RTL8211_PHYSR_SPEED_Pos) +#define PHY_RTL8211_PHYSR_DUPLEX_Msk (0x0008) +#define PHY_RTL8211_LCR_PAGE (0xd04) +#define PHY_RTL8211_LCR_ADDR (0x10) + +void eth_phy_generic_init(uint32_t phy_addr) { + // Reset the PHY. + eth_phy_write(phy_addr, PHY_BCR, PHY_BCR_SOFT_RESET); + mp_hal_delay_ms(50); +} + int16_t eth_phy_lan87xx_get_link_status(uint32_t phy_addr) { // Get the link mode & speed - int16_t scsr = eth_phy_read(phy_addr, PHY_SCSR_LAN87XX); - return (scsr >> PHY_SCSR_LAN87XX_SPEED_Pos) & PHY_SCSR_LAN87XX_SPEED_Msk; + uint16_t scsr = eth_phy_read(phy_addr, PHY_SCSR_LAN87XX); + int16_t status = 0; + if (scsr & PHY_SCSR_LAN87XX_10M_Msk) { + status |= PHY_SPEED_10HALF; + } + if (scsr & PHY_SCSR_LAN87XX_100M_Msk) { + status |= PHY_SPEED_100HALF; + } + if (scsr & PHY_SCSR_LAN87XX_DUPLEX_Msk) { + status |= PHY_DUPLEX; + } + return status; } int16_t eth_phy_dp838xx_get_link_status(uint32_t phy_addr) { @@ -56,4 +83,37 @@ int16_t eth_phy_dp838xx_get_link_status(uint32_t phy_addr) { return scsr; } +void eth_phy_rtl8211_init(uint32_t phy_addr) { + // Perform generic PHY initialization. + eth_phy_generic_init(phy_addr); + + // Configure LED0 output to show 10/100/1000 link speed, and activity. + eth_phy_write(phy_addr, PHY_RTL8211_PAGSR_ADDR, PHY_RTL8211_LCR_PAGE); + eth_phy_write(phy_addr, PHY_RTL8211_LCR_ADDR, 0x001b); + eth_phy_write(phy_addr, PHY_RTL8211_PAGSR_ADDR, PHY_RTL8211_DEFAULT_PAGE); +} + +int16_t eth_phy_rtl8211_get_link_status(uint32_t phy_addr) { + // Get the link mode & speed + eth_phy_write(phy_addr, PHY_RTL8211_PAGSR_ADDR, PHY_RTL8211_PHYSR_PAGE); + int16_t physr = eth_phy_read(phy_addr, PHY_RTL8211_PHYSR_ADDR); + eth_phy_write(phy_addr, PHY_RTL8211_PAGSR_ADDR, PHY_RTL8211_DEFAULT_PAGE); + int16_t status = 0; + switch ((physr & PHY_RTL8211_PHYSR_SPEED_Msk) >> PHY_RTL8211_PHYSR_SPEED_Pos) { + case 0: + status |= PHY_SPEED_10HALF; + break; + case 1: + status |= PHY_SPEED_100HALF; + break; + case 2: + status |= PHY_SPEED_1000HALF; + break; + } + if (physr & PHY_RTL8211_PHYSR_DUPLEX_Msk) { + status |= PHY_DUPLEX; + } + return status; +} + #endif diff --git a/ports/stm32/eth_phy.h b/ports/stm32/eth_phy.h index dccfb7951..7d4bf4c46 100644 --- a/ports/stm32/eth_phy.h +++ b/ports/stm32/eth_phy.h @@ -50,17 +50,22 @@ #define PHY_ANAR_SPEED_100FULL (0x0100) #define PHY_ANAR_IEEE802_3 (0x0001) -#define PHY_SPEED_10HALF (1) -#define PHY_SPEED_10FULL (5) -#define PHY_SPEED_100HALF (2) -#define PHY_SPEED_100FULL (6) -#define PHY_DUPLEX (4) +#define PHY_SPEED_10HALF (0x01) +#define PHY_SPEED_100HALF (0x02) +#define PHY_SPEED_1000HALF (0x04) +#define PHY_DUPLEX (0x08) +#define PHY_SPEED_10FULL (PHY_DUPLEX | PHY_SPEED_10HALF) +#define PHY_SPEED_100FULL (PHY_DUPLEX | PHY_SPEED_100HALF) +#define PHY_SPEED_1000FULL (PHY_DUPLEX | PHY_SPEED_1000HALF) uint32_t eth_phy_read(uint32_t phy_addr, uint32_t reg); void eth_phy_write(uint32_t phy_addr, uint32_t reg, uint32_t val); +void eth_phy_generic_init(uint32_t phy_addr); int16_t eth_phy_lan87xx_get_link_status(uint32_t phy_addr); int16_t eth_phy_dp838xx_get_link_status(uint32_t phy_addr); +void eth_phy_rtl8211_init(uint32_t phy_addr); +int16_t eth_phy_rtl8211_get_link_status(uint32_t phy_addr); #endif diff --git a/ports/stm32/lwip_inc/lwipopts.h b/ports/stm32/lwip_inc/lwipopts.h index ad1143845..5711ba894 100644 --- a/ports/stm32/lwip_inc/lwipopts.h +++ b/ports/stm32/lwip_inc/lwipopts.h @@ -1,6 +1,8 @@ #ifndef MICROPY_INCLUDED_STM32_LWIP_LWIPOPTS_H #define MICROPY_INCLUDED_STM32_LWIP_LWIPOPTS_H +#include STM32_HAL_H + #define LWIP_NETIF_EXT_STATUS_CALLBACK 1 #define LWIP_LOOPIF_MULTICAST 1 @@ -12,11 +14,12 @@ // Increase memory for lwIP to get better performance. #if defined(STM32N6) -#define MEM_SIZE (16 * 1024) +#define MEM_SIZE (64 * 1024) +#define PBUF_POOL_SIZE (32) #define TCP_MSS (1460) -#define TCP_WND (8 * TCP_MSS) -#define TCP_SND_BUF (8 * TCP_MSS) -#define MEMP_NUM_TCP_SEG (32) +#define TCP_WND (16 * TCP_MSS) +#define TCP_SND_BUF (16 * TCP_MSS) +#define MEMP_NUM_TCP_SEG (64) #endif // Include common lwIP configuration. diff --git a/ports/stm32/main.c b/ports/stm32/main.c index 2d97adb1d..6f7413694 100644 --- a/ports/stm32/main.c +++ b/ports/stm32/main.c @@ -318,11 +318,14 @@ static void risaf_init(void) { rimc_master.MasterCID = RIF_CID_1; rimc_master.SecPriv = RIF_ATTRIBUTE_SEC | RIF_ATTRIBUTE_PRIV; - HAL_RIF_RISC_SetSlaveSecureAttributes(RIF_RISC_PERIPH_INDEX_ADC12, RIF_ATTRIBUTE_SEC | RIF_ATTRIBUTE_PRIV); HAL_RIF_RIMC_ConfigMasterAttributes(RIF_MASTER_INDEX_SDMMC1, &rimc_master); - HAL_RIF_RISC_SetSlaveSecureAttributes(RIF_RISC_PERIPH_INDEX_SDMMC1, RIF_ATTRIBUTE_SEC | RIF_ATTRIBUTE_PRIV); HAL_RIF_RIMC_ConfigMasterAttributes(RIF_MASTER_INDEX_SDMMC2, &rimc_master); + HAL_RIF_RIMC_ConfigMasterAttributes(RIF_MASTER_INDEX_ETH1, &rimc_master); + + HAL_RIF_RISC_SetSlaveSecureAttributes(RIF_RISC_PERIPH_INDEX_ADC12, RIF_ATTRIBUTE_SEC | RIF_ATTRIBUTE_PRIV); + HAL_RIF_RISC_SetSlaveSecureAttributes(RIF_RISC_PERIPH_INDEX_SDMMC1, RIF_ATTRIBUTE_SEC | RIF_ATTRIBUTE_PRIV); HAL_RIF_RISC_SetSlaveSecureAttributes(RIF_RISC_PERIPH_INDEX_SDMMC2, RIF_ATTRIBUTE_SEC | RIF_ATTRIBUTE_PRIV); + HAL_RIF_RISC_SetSlaveSecureAttributes(RIF_RISC_PERIPH_INDEX_ETH1, RIF_ATTRIBUTE_SEC | RIF_ATTRIBUTE_PRIV); } #endif diff --git a/ports/stm32/network_lan.c b/ports/stm32/network_lan.c index 0ef33e297..ea03329ad 100644 --- a/ports/stm32/network_lan.c +++ b/ports/stm32/network_lan.c @@ -33,6 +33,11 @@ #include "lwip/netif.h" +// A board can customize the default PHY by defining this setting. +#ifndef NETWORK_LAN_PHY +#define NETWORK_LAN_PHY ETH_PHY_LAN8742 +#endif + typedef struct _network_lan_obj_t { mp_obj_base_t base; eth_t *eth; @@ -57,7 +62,7 @@ static mp_obj_t network_lan_make_new(const mp_obj_type_t *type, size_t n_args, s enum { ARG_phy_addr, ARG_phy_type}; static const mp_arg_t allowed_args[] = { { MP_QSTR_phy_addr, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, - { MP_QSTR_phy_type, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = ETH_PHY_LAN8742} }, + { MP_QSTR_phy_type, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = NETWORK_LAN_PHY} }, }; // Parse args. mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; diff --git a/ports/stm32/powerctrlboot.c b/ports/stm32/powerctrlboot.c index a8ef8c34a..7baaa6773 100644 --- a/ports/stm32/powerctrlboot.c +++ b/ports/stm32/powerctrlboot.c @@ -482,6 +482,11 @@ void SystemClock_Config(void) { LL_RCC_IC11_SetDivider(1); LL_RCC_IC11_Enable(); + // Configure IC12 at 100MHz for ETH1CLKSEL. + LL_RCC_IC12_SetSource(LL_RCC_ICCLKSOURCE_PLL1); + LL_RCC_IC12_SetDivider(8); + LL_RCC_IC12_Enable(); + // Configure IC14 at 100MHz for slower peripherals. LL_RCC_IC14_SetSource(LL_RCC_ICCLKSOURCE_PLL1); LL_RCC_IC14_SetDivider(8); diff --git a/ports/zephyr/CMakeLists.txt b/ports/zephyr/CMakeLists.txt index e7a55d804..9db0a95c6 100644 --- a/ports/zephyr/CMakeLists.txt +++ b/ports/zephyr/CMakeLists.txt @@ -55,6 +55,7 @@ set(MICROPY_SOURCE_PORT uart_core.c zephyr_device.c zephyr_storage.c + zephyr_filesystem.c mpthreadport.c ) list(TRANSFORM MICROPY_SOURCE_PORT PREPEND ${MICROPY_PORT_DIR}/) @@ -81,14 +82,33 @@ set(MICROPY_QSTRDEFS_PORT ${MICROPY_PORT_DIR}/qstrdefsport.h ) -set(MICROPY_SOURCE_LIB +if (CONFIG_MICROPY_VFS_FAT) + +list(APPEND MICROPY_SOURCE_LIB oofatfs/ff.c oofatfs/ffunicode.c +) + +endif() + +if (CONFIG_MICROPY_VFS_LFS1) + +list(APPEND MICROPY_SOURCE_LIB littlefs/lfs1.c littlefs/lfs1_util.c +) + +endif() + +if (CONFIG_MICROPY_VFS_LFS2) + +list(APPEND MICROPY_SOURCE_LIB littlefs/lfs2.c littlefs/lfs2_util.c ) + +endif() + list(TRANSFORM MICROPY_SOURCE_LIB PREPEND ${MICROPY_DIR}/lib/) set(MICROPY_SOURCE_QSTR diff --git a/ports/zephyr/README.md b/ports/zephyr/README.md index eedcdcb58..f3fcd8f70 100644 --- a/ports/zephyr/README.md +++ b/ports/zephyr/README.md @@ -208,3 +208,47 @@ run the following after you built an image with the previous command: $ west build -t run +File Systems +------------ + +The Zephyr Micropython port provides 2 options for handling filesystems on the device: +The first is the Micropython filesystem management, which uses Micropython's filesystem code and +relies on zephyr's FlashArea API, this is enabled by default when +`CONFIG_FLASH` and `CONFIG_FLASH_MAP` are turned on. +The second option is using Zephyr's Filesystem management: +This relies on Zephyr's File System features and enables sharing access between zephyr and +micropython code. Several configuration options must be enabled: + + CONFIG_FLASH_MAP=y # Requirement for the file system subsystem + CONFIG_FILE_SYSTEM=y # Enables the file system subsystem + CONFIG_FILE_SYSTEM_LITTLEFS=y # Enables the littlefs support in zephyr + CONFIG_FILE_SYSTEM_MKFS=y # Enables the ability to create new file systems + +Then, a fstab must be added to the dts overlay, for example: + + + fstab { + compatible = "zephyr,fstab"; + lfs2: lfs2 { + compatible = "zephyr,fstab,littlefs"; + mount-point = "/flash"; + partition = <&storage_partition>; + read-size=<16>; + prog-size=<4096>; + cache-size=<4096>; + lookahead-size=<32>; + block-cycles=<4>; + }; + }; + +It is then possible to use the FS like a normal Micropython filesystem: + + import vfs, zephyr + zfs = zephyr.FileSystem(zephyr.FileSystem.fstab()[0]) + vfs.mount(zfs, "/zephyr") + +You may disable Micropython's File system code to save space: + + CONFIG_MICROPY_VFS_FAT=n + CONFIG_MICROPY_VFS_LFS1=n + CONFIG_MICROPY_VFS_LFS2=n diff --git a/ports/zephyr/boards/rpi_pico.conf b/ports/zephyr/boards/rpi_pico.conf index 683279ddc..6a0be1c37 100644 --- a/ports/zephyr/boards/rpi_pico.conf +++ b/ports/zephyr/boards/rpi_pico.conf @@ -18,3 +18,13 @@ CONFIG_SPI=y # MicroPython config. CONFIG_MICROPY_HEAP_SIZE=196608 + +# File System Configuration +CONFIG_FILE_SYSTEM=y +CONFIG_FILE_SYSTEM_LITTLEFS=y +CONFIG_FILE_SYSTEM_MKFS=y +CONFIG_MICROPY_VFS_FAT=n +CONFIG_MICROPY_VFS_LFS1=n +CONFIG_MICROPY_VFS_LFS2=n +# Default heap for littlefs is too small +CONFIG_FS_LITTLEFS_FC_HEAP_SIZE=8192 diff --git a/ports/zephyr/boards/rpi_pico.overlay b/ports/zephyr/boards/rpi_pico.overlay index d63ed73bd..436e4210a 100644 --- a/ports/zephyr/boards/rpi_pico.overlay +++ b/ports/zephyr/boards/rpi_pico.overlay @@ -9,6 +9,20 @@ /* Use USB CDC ACM as the console. */ zephyr,console = &cdc_acm_uart0; }; + + fstab { + compatible = "zephyr,fstab"; + lfs: lfs { + compatible = "zephyr,fstab,littlefs"; + mount-point = "/flash"; + partition = <&storage_partition>; + read-size=<16>; + prog-size=<256>; + cache-size=<1024>; + lookahead-size=<32>; + block-cycles=<4>; + }; + }; }; /* Delete defined partitions and make a layout matching the rp2 port RPI_PICO configuration. */ diff --git a/ports/zephyr/modules/_boot.py b/ports/zephyr/modules/_boot.py index d0ba21d3f..ab3ed9c63 100644 --- a/ports/zephyr/modules/_boot.py +++ b/ports/zephyr/modules/_boot.py @@ -11,12 +11,39 @@ FlashArea = getattr(zephyr, "FlashArea", None) # DiskAccess depends on CONFIG_DISK_ACCESS DiskAccess = getattr(zephyr, "DiskAccess", None) +# zephyr.FileSystem depends on CONFIG_FILE_SYSTEM and CONFIG_FLASH_MAP +FileSystem = getattr(zephyr, "FileSystem", None) + _FLASH = const("/flash") _FLASH_LIB = const("/flash/lib") _STORAGE_KEY = const("storage") _FLASH_EXISTS = False +def mount_filesystem_flash(): + """Create a filesystem if needed on the FS partition "/flash" + and mount it on /flash. + Return True if successful, False otherwise. + """ + if _FLASH in FileSystem.fstab(): + fs = FileSystem(_FLASH) + retval = True + try: + vfs.mount(fs, _FLASH) + except OSError: + if getattr(fs, "mkfs", None): + try: + fs.mkfs() + vfs.mount(fs, _FLASH) + except OSError: + print("Error formatting flash partition") + retval = False + else: + retval = False + return retval + return False + + def create_flash_partition(): """Create an LFS2 filesystem on the partition labeled storage and mount it on /flash. @@ -54,7 +81,10 @@ def mount_all_disks(): return retval -if FlashArea and create_flash_partition(): +# Prefer FileSystem over FlashArea Access +if FileSystem and mount_filesystem_flash(): + _FLASH_EXISTS = True +elif FlashArea and create_flash_partition(): _FLASH_EXISTS = True # Prefer disks to /flash @@ -67,6 +97,6 @@ if _FLASH_EXISTS: sys.path.append(_FLASH_LIB) # Cleanup globals for boot.py/main.py -del FlashArea, DiskAccess, zephyr +del FlashArea, DiskAccess, FileSystem, zephyr del sys, vfs, os, const -del create_flash_partition, mount_all_disks, _FLASH_EXISTS +del mount_filesystem_flash, create_flash_partition, mount_all_disks, _FLASH_EXISTS diff --git a/ports/zephyr/modzephyr.c b/ports/zephyr/modzephyr.c index 08fdf5c5a..7726737e1 100644 --- a/ports/zephyr/modzephyr.c +++ b/ports/zephyr/modzephyr.c @@ -86,6 +86,9 @@ static const mp_rom_map_elem_t mp_module_time_globals_table[] = { #ifdef CONFIG_FLASH_MAP { MP_ROM_QSTR(MP_QSTR_FlashArea), MP_ROM_PTR(&zephyr_flash_area_type) }, #endif + #ifdef CONFIG_FILE_SYSTEM + { MP_ROM_QSTR(MP_QSTR_FileSystem), MP_ROM_PTR(&zephyr_filesystem_type) }, + #endif }; static MP_DEFINE_CONST_DICT(mp_module_time_globals, mp_module_time_globals_table); diff --git a/ports/zephyr/modzephyr.h b/ports/zephyr/modzephyr.h index f9b7e8eea..834ec4a31 100644 --- a/ports/zephyr/modzephyr.h +++ b/ports/zephyr/modzephyr.h @@ -37,4 +37,8 @@ extern const mp_obj_type_t zephyr_disk_access_type; extern const mp_obj_type_t zephyr_flash_area_type; #endif +#ifdef CONFIG_FILE_SYSTEM +extern const mp_obj_type_t zephyr_filesystem_type; +#endif + #endif // MICROPY_INCLUDED_ZEPHYR_MODZEPHYR_H diff --git a/ports/zephyr/mpconfigport.h b/ports/zephyr/mpconfigport.h index 8d5d60ed2..7f8497348 100644 --- a/ports/zephyr/mpconfigport.h +++ b/ports/zephyr/mpconfigport.h @@ -84,9 +84,10 @@ #endif #define MICROPY_PY_MACHINE_PWM (1) #define MICROPY_PY_MACHINE_PWM_INCLUDEFILE "ports/zephyr/machine_pwm.c" -#ifdef CONFIG_NETWORKING -// If we have networking, we likely want errno comfort +#if defined(CONFIG_NETWORKING) || defined(CONFIG_FILE_SYSTEM) #define MICROPY_PY_ERRNO (1) +#endif +#ifdef CONFIG_NETWORKING #define MICROPY_PY_SOCKET (1) #endif #ifdef CONFIG_BT diff --git a/ports/zephyr/zephyr_filesystem.c b/ports/zephyr/zephyr_filesystem.c new file mode 100644 index 000000000..2ca726253 --- /dev/null +++ b/ports/zephyr/zephyr_filesystem.c @@ -0,0 +1,782 @@ +/* +* This file is part of the MicroPython project, http://micropython.org/ +* +* The MIT License (MIT) +* +* Copyright (c) 2025 MASSDRIVER EI (massdriver.space) +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in +* all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +* THE SOFTWARE. +*/ + +#include "py/mpconfig.h" + +#if CONFIG_FILE_SYSTEM + +#if !MICROPY_VFS +#error "with CONFIG_FILE_SYSTEM enabled, must also enable MICROPY_VFS" +#endif + +#include <zephyr/fs/fs.h> +#include <zephyr/fs/fs_sys.h> + +#include <string.h> +#include "py/obj.h" +#include "py/objstr.h" +#include "py/runtime.h" +#include "py/stream.h" +#include "py/mperrno.h" +#include "extmod/vfs.h" +#include "shared/timeutils/timeutils.h" + +// Declare each FSTAB entry +#define FOREACH_FS_DEFINE(fs) FS_FSTAB_DECLARE_ENTRY(fs); + +#define FOREACH_FSTAB_DEFINE(n) DT_FOREACH_CHILD(n, FOREACH_FS_DEFINE) + +DT_FOREACH_STATUS_OKAY(zephyr_fstab, FOREACH_FSTAB_DEFINE) + +// Add all FSTAB entries to a table for us to use dynamically +#define FOREACH_FS(fs) FS_FSTAB_ENTRY(fs) + +#define FOREACH_FSTAB(n) DT_FOREACH_CHILD(n, FOREACH_FS) + +static struct fs_mount_t *const zephyr_fs_mounts[] = { + &DT_FOREACH_STATUS_OKAY(zephyr_fstab, FOREACH_FSTAB), +}; + +#define zephyr_fs_mounts_size sizeof(zephyr_fs_mounts) / sizeof(struct fs_mount_t *) + +typedef struct _zephyr_fs_obj_t { + mp_obj_base_t base; + struct fs_mount_t *mount; + vstr_t cur_dir; + vstr_t root_dir; +} zephyr_fs_obj_t; + +const char *zephyr_fs_make_path(zephyr_fs_obj_t *self, mp_obj_t path_in) { + const char *path = mp_obj_str_get_str(path_in); + + if (path[0] != '/') { + size_t l = vstr_len(&self->root_dir); + size_t lc = vstr_len(&self->cur_dir); + vstr_add_str(&self->root_dir, "/"); + vstr_add_strn(&self->root_dir, self->cur_dir.buf, lc); + vstr_add_str(&self->root_dir, path); + path = vstr_null_terminated_str(&self->root_dir); + self->root_dir.len = l; + } else { + size_t l = vstr_len(&self->root_dir); + vstr_add_str(&self->root_dir, path); + path = vstr_null_terminated_str(&self->root_dir); + self->root_dir.len = l; + } + return path; +} + +typedef struct _zephyr_file_obj_t { + mp_obj_base_t base; + struct fs_file_t fp; +} zephyr_file_obj_t; + +static void file_obj_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { + (void)kind; + mp_printf(print, "<io.%s %p>", mp_obj_get_type_str(self_in), MP_OBJ_TO_PTR(self_in)); +} + +static mp_uint_t file_obj_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) { + zephyr_file_obj_t *self = MP_OBJ_TO_PTR(self_in); + ssize_t err; + + err = fs_read(&self->fp, buf, size); + if (err < 0) { + *errcode = -err; + return MP_STREAM_ERROR; + } + return err; +} + +static mp_uint_t file_obj_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) { + zephyr_file_obj_t *self = MP_OBJ_TO_PTR(self_in); + ssize_t err; + + err = fs_write(&self->fp, buf, size); + if (err < 0) { + *errcode = -err; + return MP_STREAM_ERROR; + } + return err; +} + +static mp_uint_t file_obj_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) { + zephyr_file_obj_t *self = MP_OBJ_TO_PTR(o_in); + int err = -EINVAL; + + if (request == MP_STREAM_SEEK) { + struct mp_stream_seek_t *s = (struct mp_stream_seek_t *)(uintptr_t)arg; + + MP_STATIC_ASSERT(FS_SEEK_SET == MP_SEEK_SET); + MP_STATIC_ASSERT(FS_SEEK_CUR == MP_SEEK_CUR); + MP_STATIC_ASSERT(FS_SEEK_END == MP_SEEK_END); + + err = fs_seek(&self->fp, s->offset, s->whence); + + if (err < 0) { + *errcode = -err; + return MP_STREAM_ERROR; + } + + off_t tell = fs_tell(&self->fp); + if (tell < 0) { + *errcode = -err; + return MP_STREAM_ERROR; + } + s->offset = tell; + return 0; + + } else if (request == MP_STREAM_FLUSH) { + err = fs_sync(&self->fp); + if (err < 0) { + *errcode = -err; + return MP_STREAM_ERROR; + } + return 0; + + } else if (request == MP_STREAM_CLOSE) { + err = fs_close(&self->fp); + if (err < 0) { + *errcode = -err; + return MP_STREAM_ERROR; + } + return 0; + + } else { + *errcode = MP_EINVAL; + return MP_STREAM_ERROR; + } +} + +static const mp_rom_map_elem_t zephyr_fs_rawfile_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) }, + { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) }, + { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) }, + { MP_ROM_QSTR(MP_QSTR_readlines), MP_ROM_PTR(&mp_stream_unbuffered_readlines_obj) }, + { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, + { MP_ROM_QSTR(MP_QSTR_flush), MP_ROM_PTR(&mp_stream_flush_obj) }, + { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) }, + { MP_ROM_QSTR(MP_QSTR_seek), MP_ROM_PTR(&mp_stream_seek_obj) }, + { MP_ROM_QSTR(MP_QSTR_tell), MP_ROM_PTR(&mp_stream_tell_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mp_stream_close_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&mp_identity_obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&mp_stream___exit___obj) }, +}; + +static MP_DEFINE_CONST_DICT(zephyr_fs_rawfile_locals_dict, zephyr_fs_rawfile_locals_dict_table); + +static const mp_stream_p_t zephyr_fs_fileio_stream_p = { + .read = file_obj_read, + .write = file_obj_write, + .ioctl = file_obj_ioctl, +}; + +MP_DEFINE_CONST_OBJ_TYPE( + mp_type_zephyr_fs_fileio, + MP_QSTR_FileIO, + MP_TYPE_FLAG_ITER_IS_STREAM, + print, file_obj_print, + protocol, &zephyr_fs_fileio_stream_p, + locals_dict, &zephyr_fs_rawfile_locals_dict + ); + +static const mp_stream_p_t zephyr_fs_textio_stream_p = { + .read = file_obj_read, + .write = file_obj_write, + .ioctl = file_obj_ioctl, + .is_text = true, +}; + +MP_DEFINE_CONST_OBJ_TYPE( + mp_type_zephyr_fs_textio, + MP_QSTR_TextIOWrapper, + MP_TYPE_FLAG_ITER_IS_STREAM, + print, file_obj_print, + protocol, &zephyr_fs_textio_stream_p, + locals_dict, &zephyr_fs_rawfile_locals_dict + ); + +// Factory function for I/O stream classes +static mp_obj_t zephyr_fs_open(mp_obj_t self_in, mp_obj_t path_in, mp_obj_t mode_in) { + zephyr_fs_obj_t *self = MP_OBJ_TO_PTR(self_in); + const mp_obj_type_t *type = &mp_type_zephyr_fs_textio; + int flags = 0; + int err; + bool x_mode = false; + const char *mode_str = mp_obj_str_get_str(mode_in); + const char *path = zephyr_fs_make_path(self, path_in); + + for (; *mode_str; ++mode_str) { + int new_flags = 0; + switch (*mode_str) { + case 'r': + new_flags = FS_O_READ; + break; + case 'w': + new_flags = FS_O_WRITE | FS_O_CREATE | FS_O_TRUNC; + break; + case 'x': + new_flags = FS_O_WRITE; + x_mode = true; + break; + case 'a': + new_flags = FS_O_WRITE | FS_O_CREATE | FS_O_APPEND; + break; + case '+': + flags |= FS_O_RDWR; + break; + case 'b': + type = &mp_type_zephyr_fs_fileio; + break; + case 't': + type = &mp_type_zephyr_fs_textio; + break; + } + if (new_flags) { + if (flags) { + mp_raise_ValueError(NULL); + } + flags = new_flags; + } + } + + zephyr_file_obj_t *o = mp_obj_malloc_with_finaliser(zephyr_file_obj_t, type); + + err = fs_open(&o->fp, path, flags); + if (x_mode && err < 0) { + err = fs_open(&o->fp, path, flags | FS_O_CREATE); + } else if (x_mode) { + fs_close(&o->fp); + mp_raise_msg_varg(&mp_type_OSError, + MP_ERROR_TEXT("file %s Already exists: %q"), path, mp_errno_to_str(MP_OBJ_NEW_SMALL_INT(-err))); + return mp_const_none; + } + if (err < 0) { + m_del_obj(zephyr_file_obj_t, o); + mp_raise_msg_varg(&mp_type_OSError, + MP_ERROR_TEXT("error opening file %s: %q"), path, mp_errno_to_str(MP_OBJ_NEW_SMALL_INT(-err))); + return mp_const_none; + } + + return MP_OBJ_FROM_PTR(o); +} +MP_DEFINE_CONST_FUN_OBJ_3(zephyr_fs_open_obj, zephyr_fs_open); + +typedef struct _mp_zephyr_fs_ilistdir_it_t { + mp_obj_base_t base; + mp_fun_1_t iternext; + mp_fun_1_t finaliser; + bool is_str; + struct fs_dir_t dir; +} mp_zephyr_fs_ilistdir_it_t; + +static mp_obj_t mp_zephyr_fs_ilistdir_it_iternext(mp_obj_t self_in) { + mp_zephyr_fs_ilistdir_it_t *self = MP_OBJ_TO_PTR(self_in); + int err; + + for (;;) { + struct fs_dirent stats; + err = fs_readdir(&self->dir, &stats); + char *fn = stats.name; + if (err < 0 || stats.name[0] == 0) { + // stop on error or end of dir + break; + } + + // Note that Zephyr FS also already filters . and .., so we don't need to + + // make 4-tuple with info about this entry + mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(4, NULL)); + if (self->is_str) { + t->items[0] = mp_obj_new_str_from_cstr(fn); + } else { + t->items[0] = mp_obj_new_bytes((const byte *)fn, strlen(fn)); + } + if (stats.type == FS_DIR_ENTRY_DIR) { + // dir + t->items[1] = MP_OBJ_NEW_SMALL_INT(MP_S_IFDIR); + } else { + // file + t->items[1] = MP_OBJ_NEW_SMALL_INT(MP_S_IFREG); + } + t->items[2] = MP_OBJ_NEW_SMALL_INT(0); // no inode number + t->items[3] = mp_obj_new_int_from_uint(stats.size); + + return MP_OBJ_FROM_PTR(t); + } + + // ignore error because we may be closing a second time + fs_closedir(&self->dir); + + return MP_OBJ_STOP_ITERATION; +} + +static mp_obj_t mp_zephyr_fs_ilistdir_it_del(mp_obj_t self_in) { + mp_zephyr_fs_ilistdir_it_t *self = MP_OBJ_TO_PTR(self_in); + // ignore result / error because we may be closing a second time. + fs_closedir(&self->dir); + return mp_const_none; +} + +static mp_obj_t zephyr_fs_ilistdir_func(size_t n_args, const mp_obj_t *args) { + zephyr_fs_obj_t *self = MP_OBJ_TO_PTR(args[0]); + bool is_str_type = true; + const char *path; + int err; + + if (n_args == 2) { + if (mp_obj_get_type(args[1]) == &mp_type_bytes) { + is_str_type = false; + } + path = zephyr_fs_make_path(self, args[1]); + } else { + path = ""; + } + + // Create a new iterator object to list the dir + mp_zephyr_fs_ilistdir_it_t *iter = mp_obj_malloc_with_finaliser(mp_zephyr_fs_ilistdir_it_t, &mp_type_polymorph_iter_with_finaliser); + iter->iternext = mp_zephyr_fs_ilistdir_it_iternext; + iter->finaliser = mp_zephyr_fs_ilistdir_it_del; + iter->is_str = is_str_type; + + err = fs_opendir(&iter->dir, path); + if (err < 0) { + mp_raise_msg_varg(&mp_type_OSError, + MP_ERROR_TEXT("could not open directory %s: %q"), path, mp_errno_to_str(MP_OBJ_NEW_SMALL_INT(-err))); + return mp_const_none; + } + + return MP_OBJ_FROM_PTR(iter); +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(zephyr_fs_ilistdir_obj, 1, 2, zephyr_fs_ilistdir_func); + +static mp_obj_t zephyr_fs_mkdir(mp_obj_t vfs_in, mp_obj_t path_o) { + zephyr_fs_obj_t *self = MP_OBJ_TO_PTR(vfs_in); + const char *path = zephyr_fs_make_path(self, path_o); + int err; + + err = fs_mkdir(path); + if (err < 0) { + mp_raise_msg_varg(&mp_type_OSError, + MP_ERROR_TEXT("could not mkdir %s: %q"), path, mp_errno_to_str(MP_OBJ_NEW_SMALL_INT(-err))); + return mp_const_none; + } + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(zephyr_fs_mkdir_obj, zephyr_fs_mkdir); + + +static mp_obj_t zephyr_fs_chdir(mp_obj_t vfs_in, mp_obj_t path_in) { + zephyr_fs_obj_t *self = MP_OBJ_TO_PTR(vfs_in); + const char *path = mp_obj_str_get_str(path_in); + size_t lc = vstr_len(&self->cur_dir); + size_t l = vstr_len(&self->root_dir); + vstr_t chdir; + struct fs_dirent stats; + int err; + + + vstr_init(&chdir, 32); + vstr_add_strn(&chdir, self->root_dir.buf, l); + if (path[0] != '/') { + vstr_add_byte(&chdir, '/'); + vstr_add_strn(&chdir, self->cur_dir.buf, lc); + } + vstr_add_str(&chdir, path); + vstr_add_byte(&chdir, '/'); + + #define CWD_LEN (vstr_len(&chdir)) + size_t to = 1; + size_t from = 1; + char *cwd = vstr_str(&chdir); + while (from < CWD_LEN) { + for (; from < CWD_LEN && cwd[from] == '/'; ++from) { + // Scan for the start + } + if (from > to) { + // Found excessive slash chars, squeeze them out + vstr_cut_out_bytes(&chdir, to, from - to); + from = to; + } + for (; from < CWD_LEN && cwd[from] != '/'; ++from) { + // Scan for the next / + } + if ((from - to) == 1 && cwd[to] == '.') { + // './', ignore + vstr_cut_out_bytes(&chdir, to, ++from - to); + from = to; + } else if ((from - to) == 2 && cwd[to] == '.' && cwd[to + 1] == '.') { + // '../', skip back + if (to > 1) { + // Only skip back if not at the tip + for (--to; to > 1 && cwd[to - 1] != '/'; --to) { + // Skip back + } + } + vstr_cut_out_bytes(&chdir, to, ++from - to); + from = to; + } else { + // Normal element, keep it and just move the offset + to = ++from; + } + } + + err = fs_stat(vstr_null_terminated_str(&chdir), &stats); + vstr_cut_out_bytes(&chdir, 0, l + 1); + lc = vstr_len(&chdir); + if (err < 0) { + mp_raise_msg_varg(&mp_type_OSError, + MP_ERROR_TEXT("could not chdir to %s: %q"), path, mp_errno_to_str(MP_OBJ_NEW_SMALL_INT(-err))); + return mp_const_none; + } + + vstr_reset(&self->cur_dir); + vstr_add_strn(&self->cur_dir, chdir.buf, lc); + + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(zephyr_fs_chdir_obj, zephyr_fs_chdir); + +static mp_obj_t zephyr_fs_getcwd(mp_obj_t vfs_in) { + zephyr_fs_obj_t *self = MP_OBJ_TO_PTR(vfs_in); + char *path; + + if (vstr_len(&self->cur_dir) == 0) { + return MP_OBJ_NEW_QSTR(MP_QSTR__slash_); + } else { + size_t l = vstr_len(&self->root_dir); + size_t lc = vstr_len(&self->cur_dir); + vstr_add_str(&self->root_dir, "/"); + vstr_add_strn(&self->root_dir, self->cur_dir.buf, lc); + path = vstr_null_terminated_str(&self->root_dir); + self->root_dir.len = l; + return mp_obj_new_str_from_cstr(path + l); + } +} +static MP_DEFINE_CONST_FUN_OBJ_1(zephyr_fs_getcwd_obj, zephyr_fs_getcwd); + +static mp_obj_t zephyr_fs_rmdir(mp_obj_t vfs_in, mp_obj_t path_in) { + zephyr_fs_obj_t *self = MP_OBJ_TO_PTR(vfs_in); + const char *path = zephyr_fs_make_path(self, path_in); + struct fs_dirent stats; + int err; + + err = fs_stat(path, &stats); + if (err < 0) { + mp_raise_msg_varg(&mp_type_OSError, + MP_ERROR_TEXT("error getting stats of Zephyr File System at %s: %q"), path, mp_errno_to_str(MP_OBJ_NEW_SMALL_INT(-err))); + return mp_const_none; + } + if (stats.type == FS_DIR_ENTRY_FILE) { + mp_raise_msg_varg(&mp_type_OSError, MP_ERROR_TEXT("not for removing files")); + return mp_const_none; + } + err = fs_unlink(path); + if (err < 0) { + mp_raise_msg_varg(&mp_type_OSError, + MP_ERROR_TEXT("error removing directory at %s: %q"), path, mp_errno_to_str(MP_OBJ_NEW_SMALL_INT(-err))); + } + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(zephyr_fs_rmdir_obj, zephyr_fs_rmdir); + +static mp_obj_t zephyr_fs_remove(mp_obj_t vfs_in, mp_obj_t path_in) { + zephyr_fs_obj_t *self = MP_OBJ_TO_PTR(vfs_in); + const char *path = zephyr_fs_make_path(self, path_in); + struct fs_dirent stats; + int err; + + err = fs_stat(path, &stats); + if (err < 0) { + mp_raise_msg_varg(&mp_type_OSError, + MP_ERROR_TEXT("error getting stats of Zephyr File System at %s: %q"), path, mp_errno_to_str(MP_OBJ_NEW_SMALL_INT(-err))); + return mp_const_none; + } + if (stats.type == FS_DIR_ENTRY_DIR) { + mp_raise_msg_varg(&mp_type_OSError, MP_ERROR_TEXT("not for removing directories")); + return mp_const_none; + } + err = fs_unlink(path); + if (err < 0) { + mp_raise_msg_varg(&mp_type_OSError, + MP_ERROR_TEXT("error removing file at %s: %q"), path, mp_errno_to_str(MP_OBJ_NEW_SMALL_INT(-err))); + } + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(zephyr_fs_remove_obj, zephyr_fs_remove); + +static mp_obj_t zephyr_fs_rename(mp_obj_t vfs_in, mp_obj_t path_in, mp_obj_t path_out) { + zephyr_fs_obj_t *self = MP_OBJ_TO_PTR(vfs_in); + const char *old_path = zephyr_fs_make_path(self, path_in); + const char *new_path = zephyr_fs_make_path(self, path_out); + int err; + + err = fs_rename(old_path, new_path); + if (err < 0) { + mp_raise_msg_varg(&mp_type_OSError, + MP_ERROR_TEXT("error renaming file from %s to %s: %q"), old_path, new_path, mp_errno_to_str(MP_OBJ_NEW_SMALL_INT(-err))); + } + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_3(zephyr_fs_rename_obj, zephyr_fs_rename); + +static mp_import_stat_t zephyr_fs_import_stat(void *vfs_in, const char *path) { + zephyr_fs_obj_t *self = vfs_in; + struct fs_dirent stats; + assert(self != NULL); + const char *ppath = zephyr_fs_make_path(self, mp_obj_new_str_from_cstr(path)); + int err; + + err = fs_stat(ppath, &stats); + if (err == 0) { + if (stats.type == FS_DIR_ENTRY_DIR) { + return MP_IMPORT_STAT_DIR; + } else { + return MP_IMPORT_STAT_FILE; + } + } + return MP_IMPORT_STAT_NO_EXIST; +} + +static mp_obj_t zephyr_fs_stat(mp_obj_t vfs_in, mp_obj_t path_in) { + zephyr_fs_obj_t *self = MP_OBJ_TO_PTR(vfs_in); + int err; + struct fs_dirent stats; + const char *path = zephyr_fs_make_path(self, path_in); + + err = fs_stat(path, &stats); + if (err < 0) { + mp_raise_msg_varg(&mp_type_OSError, + MP_ERROR_TEXT("error getting stats of Zephyr File System at %s: %q"), path, mp_errno_to_str(MP_OBJ_NEW_SMALL_INT(-err))); + return mp_const_none; + } + + mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(10, NULL)); + mp_int_t mode = 0; + if (stats.type == FS_DIR_ENTRY_DIR) { + mode |= MP_S_IFDIR; + } else { + mode |= MP_S_IFREG; + } + t->items[0] = MP_OBJ_NEW_SMALL_INT(mode); // st_mode + t->items[1] = MP_OBJ_NEW_SMALL_INT(0); // st_ino + t->items[2] = MP_OBJ_NEW_SMALL_INT(0); // st_dev + t->items[3] = MP_OBJ_NEW_SMALL_INT(0); // st_nlink + t->items[4] = MP_OBJ_NEW_SMALL_INT(0); // st_uid + t->items[5] = MP_OBJ_NEW_SMALL_INT(0); // st_gid + t->items[6] = mp_obj_new_int_from_uint(stats.size); // st_size + t->items[7] = mp_obj_new_int_from_uint(0); // st_atime + t->items[8] = mp_obj_new_int_from_uint(0); // st_mtime + t->items[9] = mp_obj_new_int_from_uint(0); // st_ctime + + return MP_OBJ_FROM_PTR(t); +} +static MP_DEFINE_CONST_FUN_OBJ_2(zephyr_fs_stat_obj, zephyr_fs_stat); + +static mp_obj_t zephyr_fs_statvfs(mp_obj_t vfs_in, mp_obj_t path_in) { + zephyr_fs_obj_t *self = MP_OBJ_TO_PTR(vfs_in); + (void)path_in; + int err; + struct fs_statvfs stats; + unsigned long bsize; + + err = fs_statvfs(self->mount->mnt_point, &stats); + if (err < 0) { + mp_raise_msg_varg(&mp_type_OSError, + MP_ERROR_TEXT("error getting stats of Zephyr File System: %q"), mp_errno_to_str(MP_OBJ_NEW_SMALL_INT(-err))); + return mp_const_none; + } + + if (stats.f_frsize > stats.f_bsize) { + bsize = stats.f_frsize; + } else { + bsize = stats.f_bsize; + } + + mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(10, NULL)); + + t->items[0] = MP_OBJ_NEW_SMALL_INT(bsize); // f_bsize + t->items[1] = MP_OBJ_NEW_SMALL_INT(stats.f_frsize); // f_frsize + t->items[2] = MP_OBJ_NEW_SMALL_INT(stats.f_blocks); // f_blocks + t->items[3] = MP_OBJ_NEW_SMALL_INT(stats.f_bfree); // f_bfree + t->items[4] = t->items[3]; // f_bavail + t->items[5] = MP_OBJ_NEW_SMALL_INT(0); // f_files + t->items[6] = MP_OBJ_NEW_SMALL_INT(0); // f_ffree + t->items[7] = MP_OBJ_NEW_SMALL_INT(0); // f_favail + t->items[8] = MP_OBJ_NEW_SMALL_INT(0); // f_flags + t->items[9] = MP_OBJ_NEW_SMALL_INT(MAX_FILE_NAME); // f_namemax. + + return MP_OBJ_FROM_PTR(t); +} +static MP_DEFINE_CONST_FUN_OBJ_2(zephyr_fs_statvfs_obj, zephyr_fs_statvfs); + +static mp_obj_t zephyr_fs_umount(mp_obj_t self_in) { + zephyr_fs_obj_t *self = MP_OBJ_TO_PTR(self_in); + int err; + + err = fs_unmount(self->mount); + if (err < 0) { + mp_raise_msg_varg(&mp_type_OSError, + MP_ERROR_TEXT("error un-mounting Zephyr File System: %q"), mp_errno_to_str(MP_OBJ_NEW_SMALL_INT(-err))); + return mp_const_none; + } + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(zephyr_fs_umount_obj, zephyr_fs_umount); + +static mp_obj_t zephyr_fs_mount(mp_obj_t self_in, mp_obj_t readonly, mp_obj_t mkfs) { + zephyr_fs_obj_t *self = MP_OBJ_TO_PTR(self_in); + int err; + (void)readonly; + (void)mkfs; + + err = fs_mount(self->mount); + if (err == -EBUSY) { + err = fs_unmount(self->mount); + if (err < 0) { + mp_raise_msg_varg(&mp_type_OSError, + MP_ERROR_TEXT("error un-mounting Zephyr File System: %q"), mp_errno_to_str(MP_OBJ_NEW_SMALL_INT(-err))); + return mp_const_none; + } + err = fs_mount(self->mount); + } + + if (err == -EROFS) { + mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("read only filesystem that requires formatting")); + return mp_const_none; + } else if (err < 0) { + mp_raise_msg_varg(&mp_type_OSError, + MP_ERROR_TEXT("error mounting Zephyr File System: %q"), mp_errno_to_str(MP_OBJ_NEW_SMALL_INT(-err))); + return mp_const_none; + } + + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_3(zephyr_fs_mount_obj, zephyr_fs_mount); + +#if CONFIG_FILE_SYSTEM_MKFS +static mp_obj_t zephyr_fs_mkfs(mp_obj_t self_in) { + zephyr_fs_obj_t *self = MP_OBJ_TO_PTR(self_in); + + // Yes, they correspond indirectly + if (self->mount->fs->mkfs((int)self->mount->storage_dev, self->mount->fs_data, self->mount->flags) < 0) { + mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("error formatting Zephyr File System")); + } + + return mp_const_none; +} + +static MP_DEFINE_CONST_FUN_OBJ_1(zephyr_fs_mkfs_obj, zephyr_fs_mkfs); +#endif + +static mp_obj_t zephyr_fs_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { + mp_arg_check_num(n_args, n_kw, 1, 1, false); + + if (!mp_obj_is_str(args[0])) { + mp_raise_ValueError(MP_ERROR_TEXT("argument must be a zephyr FSTAB mountpoint string")); + return mp_const_none; + } + + const char *_mountpoint = mp_obj_str_get_str(args[0]); + int i = 0; + + for (; i < zephyr_fs_mounts_size; i++) { + if (strcmp(_mountpoint, zephyr_fs_mounts[i]->mnt_point) == 0) { + break; + } + } + + if (i == zephyr_fs_mounts_size) { + mp_raise_ValueError(MP_ERROR_TEXT("couldn't find zephyr mountpoint")); + return mp_const_none; + } + + if (zephyr_fs_mounts[i]->fs == 0) { + if (fs_mount(zephyr_fs_mounts[i]) != 0) { + mp_raise_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("FS is invalid, try adding automount to fstab")); + return mp_const_none; + } + } + + // create new object + zephyr_fs_obj_t *fs = mp_obj_malloc(zephyr_fs_obj_t, type); + fs->mount = zephyr_fs_mounts[i]; + vstr_init(&fs->cur_dir, 32); + vstr_init(&fs->root_dir, 128); + vstr_add_str(&fs->root_dir, zephyr_fs_mounts[i]->mnt_point); + + return MP_OBJ_FROM_PTR(fs); +} + +static mp_obj_t zephyr_fs_fstab(void) { + mp_obj_t list = mp_obj_new_list(0, NULL); + + for (int i = 0; i < zephyr_fs_mounts_size; i++) { + mp_obj_list_append(list, mp_obj_new_str_from_cstr(zephyr_fs_mounts[i]->mnt_point)); + } + + return list; +} +static MP_DEFINE_CONST_FUN_OBJ_0(zephyr_fs_fstab_fun_obj, zephyr_fs_fstab); +static MP_DEFINE_CONST_STATICMETHOD_OBJ(zephyr_fs_fstab_obj, MP_ROM_PTR(&zephyr_fs_fstab_fun_obj)); + +static const mp_rom_map_elem_t zephyr_fs_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_mount), MP_ROM_PTR(&zephyr_fs_mount_obj) }, + { MP_ROM_QSTR(MP_QSTR_umount), MP_ROM_PTR(&zephyr_fs_umount_obj) }, + { MP_ROM_QSTR(MP_QSTR_statvfs), MP_ROM_PTR(&zephyr_fs_statvfs_obj) }, + { MP_ROM_QSTR(MP_QSTR_stat), MP_ROM_PTR(&zephyr_fs_stat_obj) }, + { MP_ROM_QSTR(MP_QSTR_rename), MP_ROM_PTR(&zephyr_fs_rename_obj) }, + { MP_ROM_QSTR(MP_QSTR_remove), MP_ROM_PTR(&zephyr_fs_remove_obj) }, + { MP_ROM_QSTR(MP_QSTR_rmdir), MP_ROM_PTR(&zephyr_fs_rmdir_obj) }, + { MP_ROM_QSTR(MP_QSTR_getcwd), MP_ROM_PTR(&zephyr_fs_getcwd_obj) }, + { MP_ROM_QSTR(MP_QSTR_chdir), MP_ROM_PTR(&zephyr_fs_chdir_obj) }, + { MP_ROM_QSTR(MP_QSTR_mkdir), MP_ROM_PTR(&zephyr_fs_mkdir_obj) }, + { MP_ROM_QSTR(MP_QSTR_open), MP_ROM_PTR(&zephyr_fs_open_obj) }, + { MP_ROM_QSTR(MP_QSTR_ilistdir), MP_ROM_PTR(&zephyr_fs_ilistdir_obj) }, + #if CONFIG_FILE_SYSTEM_MKFS + { MP_ROM_QSTR(MP_QSTR_mkfs), MP_ROM_PTR(&zephyr_fs_mkfs_obj) }, + #endif + // Not part of the VFS API, used to list available File Systems + { MP_ROM_QSTR(MP_QSTR_fstab), MP_ROM_PTR(&zephyr_fs_fstab_obj) }, +}; +static MP_DEFINE_CONST_DICT(zephyr_fs_locals_dict, zephyr_fs_locals_dict_table); + +static const mp_vfs_proto_t zephyr_fs_proto = { + .import_stat = zephyr_fs_import_stat, +}; + +const mp_obj_type_t zephyr_filesystem_type; + +MP_DEFINE_CONST_OBJ_TYPE( + zephyr_filesystem_type, + MP_QSTR_FileSystem, + MP_TYPE_FLAG_NONE, + make_new, zephyr_fs_make_new, + protocol, &zephyr_fs_proto, + locals_dict, &zephyr_fs_locals_dict + ); + +#endif // CONFIG_FILE_SYSTEM |
