UF2 Loader release

You will probably end up having to write it from scratch, assembly is one of the things where there isn’t such a large corppus of data to pull from.
Depending on the complexity of the ai model it may cheat and generate C code and run a compiler on it to produce valid asm, but compilers don’t have ideal register allocation compared to assembly programmers either. In particular on cortex m0 architectures there are extra registers only assembly programmers have access to, and assembly programmers can ignore arm calling convention where appropriate for calls into ASM you have control over.
The code you posted looks like something a compiler might generate.
In particular for this code it’d be entirely legal to push and pop nearly all registers to have more flexibility even though this would normally be bad idea for performance reasons.

Edit: I think this assembly isn’t calling convention-legal btw, you should probably save/restore r4-r7 if you use them.

I don’t think it runs a compiler because there are obvious bugs:

// Functions
tx: ldr r0, =0x4003c000
    str r1, [r0, #8]
5:  ldr r0, [r0, #12]
    lsls r0, #27
    bmi 5b
    bx lr

rx: movs r1, #255
    b tx

Should be:

// void tx(byte: r1)
//  local SPI0_BASE: r0
tx: ldr r0, =SPI0_BASE
    str r1, [r0, #SPI_SSPDR_OFFSET] // store tx buffer
5:  ldr r1, [r0, #SPI_SSPSR_OFFSET]
    lsls r1, #27                    // Busy flag is 0x10 (bit 4), shift 27 to bit 31 (sign)
    bmi 5b
    str r1, [r0, #SPI_SSPDR_OFFSET] // load rx buffer
    bx lr

// r1 tx(byte: r1)
//  local SPI0_BASE: r0
//  returns rx buffer
rx: movs r1, #255
    b tx

The wrong ldr r0, [r0, #12] instruction would be very obvious in C:

  x = *(x+12); // what kind of linked list traversal should be here?

Also, this is a cool trick:

5:  ldr r1, [r0, #SPI_SSPSR_OFFSET]
    lsls r1, #27                    // Busy flag is 0x10 (bit 4), shift 27 to bit 31 (sign)
    bmi 5b

Initially it wrote:

ldr r1, ...
tst r1, #0x10 // poor thumb only has 3 bit imm for test

I agree that this piece of AI-generated assembly is full of bugs. But given that I don’t know THUMB (nor am I familiar with ARM assembly in general), it gave me a good enough starting point and I’m getting hang of it now :slight_smile:

1 Like

Thumb-1 has weird restrictions on what instructions it has access to compared to arm that make it a lot less flexible.
Thumb-2 is a lot better in this regard, writing for rp2350 is more fun.

Probably download the cortex M0+ technical reference manual, it has an overview of what instructions are legal.

1 Like

Edit: I think this assembly isn’t calling convention-legal btw, you should probably save/restore r4-r7 if you use them.

Given only 256 bytes, let’s not talk about calling conventions…
Did this a lot with legacy DSPs and that’s just a way of life

AI is terrible of generating arm assembly.

I found it only useful to guide me but much of the generated code needed rework. In my Hobby Project: ANS Forth, the forth engine is written in arm assembly, and I gave up being lazy using AI, and just coded it myself.

Here’s my corrected version:

// ----------------------------------------------------------------------------
// Ultra-minimal SD boot2 - reads 8K (16 sectors)
// ----------------------------------------------------------------------------

#include "pico/asm_helper.S"
#include "hardware/regs/resets.h"
#include "hardware/regs/io_bank0.h"
#include "hardware/regs/sio.h"
#include "hardware/regs/spi.h"

pico_default_asm_setup
.section .text

// locals (volatile stuff)
//   func param: r1
//   iterator: r2 (always reset to zero after use!)
// variables
#define REG_ADDR r0
#define REG_SD_SECTOR r4
#define REG_SD_BLOCK r5
// constants
#define REG_ZERO r2
#define REG_SPI_BASE r3
#define REG_512 r6
#define REG_SIO_BASE r7


regular_func _stage2_boot
    // load constant values
    ldr REG_SIO_BASE, =SIO_BASE
    ldr REG_512, =512 // 1<<9
    ldr REG_SPI_BASE, =SPI0_BASE

    // Reset SPI0 only
    ldr REG_ADDR, =(RESETS_BASE + RESETS_RESET_OFFSET)
    ldr r1, [REG_ADDR]
    lsls REG_512, r2, #7         // RESETS_RESET_SPI0_BITS (1u << 16) too large for immediate, use (1<<9)<<7
    bics r1, r2
    str r1, [REG_ADDR]
1:  ldr r1, [REG_ADDR, #(RESETS_RESET_DONE_OFFSET - RESETS_RESET_OFFSET)]
    tst r1, r2
    beq 1b

    // GPIO setup - SPI0 function
    ldr r2, =(IO_BANK0_BASE + IO_BANK0_GPIO16_CTRL_OFFSET)
    ldr r1, =IO_BANK0_GPIO16_CTRL_FUNCSEL_VALUE_SPI0_RX
    str r1, [r2]
    str r1, [r2, #(IO_BANK0_GPIO17_CTRL_OFFSET - IO_BANK0_GPIO16_CTRL_OFFSET)]
    str r1, [r2, #(IO_BANK0_GPIO18_CTRL_OFFSET - IO_BANK0_GPIO16_CTRL_OFFSET)]
    str r1, [r2, #(IO_BANK0_GPIO19_CTRL_OFFSET - IO_BANK0_GPIO16_CTRL_OFFSET)]
    
    // GPIO17 output
    lsls REG_512, r1, #8         // (1u << 17) too large for immediate, use (1<<9)<<8
    str r1, [REG_SIO_BASE, #SIO_GPIO_OE_SET_OFFSET]
    str r1, [REG_SIO_BASE, #SIO_GPIO_OUT_SET_OFFSET]

    // SPI0 setup
    movs r1, #0
    str r1, [REG_SIO_BASE, #SPI_SSPCR1_OFFSET]
    movs r1, #250
    str r1, [REG_SIO_BASE, #SPI_SSPCPSR_OFFSET]
    movs r1, #7             // 0111 for 8-bit data
    str r1, [REG_SIO_BASE, #SPI_SSPCR0_OFFSET]
    movs r1, SPI_SSPCR1_SSE_BITS
    str r1, [REG_SIO_BASE, #SPI_SSPCR1_OFFSET]

    // Init clocks
    movs r2, #6
2:  movs r1, #255
    bl tx
    subs r2, #1
    bne 2b

    // r2 is now REG_ZERO

    // CS low
    str REG_ZERO, [REG_SIO_BASE, #SIO_GPIO_OUT_CLR_OFFSET]

    // CMD0: 0x40 0x00 0x00 0x00 0x00 0x95
    movs r1, #0x40
    bl tx
    movs r1, #0x00
    bl tx
    bl tx
    bl tx
    bl tx
    movs r1, #0x95
    bl tx
    bl wait

    // Read multiple sectors starting at 8K (512 * 16)
    ldr REG_ADDR, =SRAM_BASE        // Load address
    movs REG_SD_SECTOR, #16         // Sector count (8K)
    movs REG_SD_BLOCK, #16          // Starting block

read_sector:
    // CMD17 with current block number
    // 0x51 0x00 0x00 BLOCK 0x00
    movs r1, #0x51
    bl tx
    movs r1, #0x00
    bl tx
    bl tx
    mov r1, REG_SD_BLOCK            // Block number  
    bl tx
    movs r1, #0
    bl tx
    bl rx
    bl wait

    // Wait for data token
3:  bl rx
    cmp r1, #254
    bne 3b

    // Read 512 bytes
4:  bl rx
    strb r1, [REG_ADDR, r2]
    adds r2, #1
    cmp r2, REG_512
    bne 4b
    movs r2, #0
    // r2 back to zero now

    // Skip CRC (2 bytes)
    bl rx
    bl rx

    // Next sector
    adds REG_ADDR, REG_512         // Advance pointer by 512
    adds REG_SD_BLOCK, #1         // Next block
    subs REG_SD_SECTOR, #1         // Decrement sector count
    bne read_sector

    // CS high & jump
    str REG_ZERO, [REG_SIO_BASE, #SIO_GPIO_OUT_SET_OFFSET]
    ldr REG_ADDR, =SRAM_BASE
    bx REG_ADDR

// void tx(byte: r1)
tx: 
    str r1, [REG_SPI_BASE, #SPI_SSPDR_OFFSET] // store tx buffer
5:  ldr r1, [REG_SPI_BASE, #SPI_SSPSR_OFFSET]
    lsls r1, #27                    // Busy flag is 0x10 (bit 4), shift 27 to bit 31 (sign)
    bmi 5b
    str r1, [REG_SPI_BASE, #SPI_SSPDR_OFFSET] // load rx buffer
    bx lr

// r1 tx(byte: r1)
//  returns rx buffer
rx: movs r1, #255
    b tx

// void wait()
//  local wait_count: r2
wait: movs r2, #5
6:  subs r2, #1
    beq 7f // r2 == 0 ? goto 7
    bl rx
    cmp r1, #255
    beq 6b // r1 == 0xFF ? goto 6
    movs r2, #0 // r2 is back to REG_ZERO
7:  bx lr

.end

Space occupied: 0xFC
Fixed all the register misuses (overwrites, wrong aliasing, …)
Half of the registers are fixed to specific constants due to THUMB issues.
r2 has interesting behaviors
r6 serves as single cycle for 3 different constants: 0x200, 0x10000 and 0x20000

2 Likes

Just finished testing v1.1 and it works great for me so far. Thanks @pelrun for your work on this!

1 Like

Another idea: bootstrap by loading stage3 from stm32 instead.

Thank you for creating this very useful program. Took me forever to even find out about it.

A question to moderators of this forum: why aren’t threads like this (and adcockm’s version of mmbasic, multiboot, micropython, michikania compiled basic, frotz, the custom firmware, etc.) stickied so we newbs can easily find out about this great stuff?

2 Likes

With only 4 KB of stage 3, this can fit without too much issue in the stm32 flash.
Need a I2C way to “fetch” from memory too!

1 Like

I’ve got the flash resident part of the bootloader down to 9k now (so 12k given the flash sector size), I don’t think there’s a lot of scope (or benefit) in shrinking it much further without making it harder on the user in various ways.

There’s been a lot of yak-shaving involved, annoyingly, but I’m getting close to having the pieces come back together.

2 Likes

V2.0 of UF2 Loader is now available. Pico 2 is now natively supported! See the first post for updated links.

The bootloader now only takes up 2 flash sectors on both platforms, and all the UI code is loaded from SD card as needed, so changes to the UI only require copying a new BOOT*.UF2 file to the SD card. Pico 1 and 2 uf2 files are kept in separate directories now (pico1-apps and pico2-apps) instead of the old firmware directory, so you can swap boards without needing to change the SD card. There’s a bunch of performance improvements as well.

(I did say it was only a couple of days away :smiley: )

7 Likes

Mate, I’ve been playing with your UF2 since receiving my Picocalc yesterday. What a lovely piece of software that I didn’t know I needed!

I am a noob so please excuse my silly questions. With the original pico in the picocalc, I found that your UF2 loader (original version) worked like a charm! I was able to boot and load firmwares and use the different programs like picomite, vuzix, mp3player, mycropython and lua and lisp.

I also have a Pimoroni pico plus 2 W that I popped into the picocalc, so when I saw your update I was very happy! I followed the instructions by putting the BOOT*.UF2 files on the sdcard and did a flashnuke on the picoplus2W just to be sure it’s clean. Then flashed it with bootloader_pico2.uf2 with good effect! I can boot up (holding up button) with the loader screen visible and select all the options (different uf2 files that are in the pico2-apps folder on the sdcard). The problem that I now have is that when I select a uf2 file it appears to load (loading app, followed by counting to 4303 then launching app) then it goes to a black screen. I’m able to reboot and access the loader menu again by holding the up button. When I reboot normally it just stays a black screen. I’m not sure if i’m doing something wrong. I tried with a freshly formatted sd card and new downloads of all the files but same black screen. (Edit: Of note, the Vuzix uf2 works but it says no valid app for the lisp, lua and mp3 player uf2) I tried leaving it for 10 minutes with no change. Could it be because it is a pimoroni pico plus 2W and not a raspberrypi pico 2?

Any help or advice would be greatly appreciated!

I have a similar problem. I also have a Pimoroni Pico Plus 2 W, I believe I followed the instructions, but I only get a blank screen no matter which buttons I hold down.

1 Like

Aren’t those Pico 1 builds? You need different builds for the pico 1 and pico 2, they’re not cross compatible (you can’t just copy the same files into the two apps folders!).

That information is embedded in the UF2 and is checked by the loader. “No valid app” means it’s scanned the entire file and not found any blocks with an appropriate family ID.

You should end up in the menu no matter what after the initial installation, as there won’t be a valid app present in flash. If you only get a black screen, it’s because the bootloader isn’t able to load the BOOT2350.UF2 file from the SD card for some reason. (Make sure you put it in the root of the sd card, not in the apps directory!) I don’t yet have a good way to report errors from this step, but I’ll work on it.

I don’t have the Pico Plus board, so is is untested (I’ll probably get one shortly). At the very least using the standard Pico 2 build on it will restrict you to 4MB of flash like the Pico 2, because it’s hardcoded in a few places.

1 Like

I have this problem too with certain UF2 files - it appears to be based on the number of files the loader is loading as anything below 1000 files will work (micro-python, Phyllosoma etc.) anything above that number the files appear to load but the picocalc reverts to a blank black screen which needs a force close to restart the launcher. It looks to be a really useful application though! :slight_smile:

I forgot to mention I’m running a Pico 2…

1 Like

I tried a different SD card and copied the files from my other SD card and now get the menu! I am using the SD card that came with the PicoCalc instead of a new SanDisk 32GB card I was using.

Now I am seeing exactly what @Peekaboo is experiencing.

The apps that I wrote do start and but appears that the timers are not running, so that add_repeating_timer_ms does not work. This is probably my fault, not initialising correctly assuming a default power on state. I will take a look, but any suggestions would be appreciated!

1 Like

I did notice the timer issue with Frotz, but hadn’t dug into it very far yet. If it works fine without the bootloader then it’ll be a problem on my end. It’s my job on the bootloader side to be as invisible as possible, after all!

I’ll also go track down some other SD cards and see about improving my tiny sd driver.

That’s really weird, and I don’t know how it can be affected just by length, but while looking at it I’ve found at least one bug in the loader that should be preventing any UF2 from being loaded! (edit: actually it looks like there’s some subtle changes in how picotool has created UF2 files over time, and one of those variations trips over a check. I just hadn’t had any of those UF2’s before!) (double edit: nope, Picotool has always done the right thing. Whoever created these uf2s blindly renumbered the blocks internally without understanding the abs-block workaround and created something wrong)

So there’ll be a v2.1 coming out as soon as I’ve resolved these issues.

3 Likes

I must be doing something incorrectly.

I was able to take a quick look during lunch, but I cannot see anything that stands out.

I went to first principles and I built the pico-examples hello_timer and timer_lowlevel. Both work as expected when using uf2loader.

I will make a deeper dive this evening to see if I can find out what is going on with my code.

1 Like

I found the cause. I don’t really like it and you might not either.

  • If I build with SDK v2.1.1, my apps do not work.
  • If I build with SDK v2.2.0, my apps work.

I was planning to create an updated release of my work in the next few days using the new SDK. This, of course, won’t help other projects that are somehow failing for the same reason that my work does.

The only documented change that might be involved (long shot) is:

hardware_clocks

  • Corrected documentation and implementation of clock_configure() supporting the full range of clock dividers.
  • Added PICO_USE_FASTEST_SUPPORTED_CLOCK and PLL configuration for 200 MHz on RP2040.
1 Like