2.8. Bootrom

The Bootrom size is limited to 16kB. It contains:

Bootrom Source Code

The full source for the RP2040 bootrom can be found at https://github.com/raspberrypi/pico-bootrom .

This includes versions 1, 2 and 3 of the bootrom, which correspond to the B0, B1 and B2 silicon revisions, respectively.

2.8.1. Processor Controlled Boot Sequence

A flow diagram of the boot sequence is given in Figure 15 .

Figure 15. RP2040 Boot Sequence

Flow diagram of the RP2040 Boot Sequence. The sequence starts with 'Both cores enter bootrom'. A decision 'Which core am I?' leads to 'Sleep until given entry point' for core 1 and continues for core 0. Core 0 checks 'PoR rescue flag set?'. If 'Y', it 'Clears flag and halt'. If 'N', it checks 'Watchdog boot-to-SRAM set?'. If 'Y', it 'Set SP and jump to entry point'. If 'N', it performs a '100us delay (pullup on flash CSn)', then 'Read flash CSn'. If 'High (flash boot)', it proceeds to 'Configure SSI and connect to pads'. If 'Low (USB device)', it proceeds to 'Start crystal oscillator'. The 'Start crystal oscillator' step leads to a 'Crystal present?' decision. If 'N', it 'Halt'. If 'Y', it 'Start PLLs, Sys, USB clocked at 48 MHz' and 'Enter USB device mode bootcode'. The 'Enter USB device mode bootcode' step leads to 'Load 256 bytes from flash', then a 'Checksum pass?' decision. If 'Y', it 'Enter flash second stage'. If 'N', it checks 'Longer than 0.5 s since boot?'. If 'Y', it 'Enter flash second stage'. If 'N', it 'Increment CPOL, CPHA and delay 100us' and loops back to 'Load 256 bytes from flash'.
graph TD
    Start([Both cores enter bootrom]) --> CoreID{Which core am I?}
    CoreID -- 1 --> Sleep([Sleep until given entry point])
    CoreID -- 0 --> PoR{PoR rescue flag set?}
    PoR -- Y --> ClearFlag([Clear flag and halt])
    PoR -- N --> Watchdog{Watchdog boot-to-SRAM set?}
    Watchdog -- Y --> SetSP([Set SP and jump to entry point])
    Watchdog -- N --> Delay[100us delay
(pullup on flash CSn)] Delay --> ReadCSn{Read flash CSn} ReadCSn -- High (flash boot) --> ConfigSSI[Configure SSI and connect to pads] ReadCSn -- Low (USB device) --> StartOsc[Start crystal oscillator] StartOsc --> CrystalPresent{Crystal present?} CrystalPresent -- N --> Halt([Halt]) CrystalPresent -- Y --> StartPLL[Start PLLs, Sys, USB clocked at 48 MHz] StartPLL --> EnterUSB[Enter USB device mode bootcode] EnterUSB --> LoadFlash[Load 256 bytes from flash] LoadFlash --> Checksum{Checksum pass?} Checksum -- Y --> EnterFlash2[Enter flash second stage] Checksum -- N --> TimeOut{Longer than 0.5 s since boot?} TimeOut -- Y --> EnterFlash2 TimeOut -- N --> Increment[Increment CPOL, CPHA and delay 100us] Increment --> LoadFlash
Flow diagram of the RP2040 Boot Sequence. The sequence starts with 'Both cores enter bootrom'. A decision 'Which core am I?' leads to 'Sleep until given entry point' for core 1 and continues for core 0. Core 0 checks 'PoR rescue flag set?'. If 'Y', it 'Clears flag and halt'. If 'N', it checks 'Watchdog boot-to-SRAM set?'. If 'Y', it 'Set SP and jump to entry point'. If 'N', it performs a '100us delay (pullup on flash CSn)', then 'Read flash CSn'. If 'High (flash boot)', it proceeds to 'Configure SSI and connect to pads'. If 'Low (USB device)', it proceeds to 'Start crystal oscillator'. The 'Start crystal oscillator' step leads to a 'Crystal present?' decision. If 'N', it 'Halt'. If 'Y', it 'Start PLLs, Sys, USB clocked at 48 MHz' and 'Enter USB device mode bootcode'. The 'Enter USB device mode bootcode' step leads to 'Load 256 bytes from flash', then a 'Checksum pass?' decision. If 'Y', it 'Enter flash second stage'. If 'N', it checks 'Longer than 0.5 s since boot?'. If 'Y', it 'Enter flash second stage'. If 'N', it 'Increment CPOL, CPHA and delay 100us' and loops back to 'Load 256 bytes from flash'.

After the hardware controlled boot sequence described in Section 2.7 , the processor controlled boot sequence starts:

2.8.1.1. Watchdog Boot

Watchdog boot allows users to install their own boot handler, and divert control away from the main boot sequence on non-POR/BOR resets. It also simplifies running code over the JTAG test interface. It recognises the following values written to the watchdog's upper scratch registers:

If either of the magic numbers mismatch, watchdog boot does not take place. If the numbers match, the Bootrom zeroes scratch 4 before transferring control, so that the behaviour does not persist over subsequent reboots.

2.8.1.2. Flash Boot Sequence

One of the main challenges of a warm flash boot is forcing the external flash from XIP mode to a mode where it will accept standard SPI commands. There is no standard method to discontinue XIP on an unknown flash. The Bootrom provides a best-effort sequence with broad compatibility, which is as follows:

This is designed to miss the XIP continuation codes on Cypress, Micron and Winbond parts. If the device is already in SPI mode, it interprets this sequence as two FFh NOP instructions, which should be ignored.

As this is best effort only, there may be some devices which obstinately remain in XIP mode. There are then two options:

After issuing the XIP exit sequence, the Bootrom attempts to read in the second stage from flash using standard 03h serial read commands, which are near-universally supported. Since the Bootrom is immutable, it aims for compatibility

rather than performance.

2.8.1.3. Flash Second Stage

The flash second stage must configure the SSI and the external flash for the best possible execute-in-place performance. This includes interface width, SCK frequency, SPI instruction prefix and an XIP continuation code for address-data only modes. Generally some operation can be performed on the external flash so that it does not require an instruction prefix on each access, and will simply respond to addresses with data.

Until the SSI is correctly configured for the attached flash device, it is not possible to access flash via the XIP address window. Additionally, the Synopsys SSI can not be reconfigured at all without first disabling it. Therefore the second stage must be copied from flash to SRAM by the bootrom, and executed in SRAM.

Alternatively, the second stage can simply shadow an image from external flash into SRAM, and not configure execute-in-place.

This is the only job of the second stage. All other chip setup (e.g. PLLs, Voltage Regulator) can be performed by platform initialisation code executed over the XIP interface, once the second stage has run.

2.8.1.3.1. Checksum

The last four bytes of the image loaded from flash (which we hope is a valid flash second stage) are a CRC32 checksum of the first 252 bytes. The parameters of the checksum are:

The Bootrom makes 128 attempts of approximately 4ms each for a total of approximately 0.5 seconds before giving up and dropping into USB code to load and checksum the second stage with varying SPI parameters. If it sees a checksum pass it will immediately jump into the 252-byte payload which contains the flash second stage.

2.8.2. Launching Code On Processor Core 1

As described in the introduction to Section 2.8.1 , after reset, processor core 1 "sleeps (WFE with SCR.SLEEPDEEP enabled) and remains asleep until woken by user code, via the mailbox".

If you are using the SDK then you can simply use the multicore_launch_core1 function to launch code on processor core 1. However this section describes the procedure to launch code on processor core 1 yourself.

The procedure to start running on processor core 1 involves both cores moving in lockstep through a state machine coordinated by passing messages over the inter-processor FIFOs. This state machine is designed to be robust enough to cope with a recently reset processor core 1 which may be anywhere in its boot code, up to and including going to sleep. As result, the procedure may be performed at any point after processor core 1 has been reset (either by system reset, or explicitly resetting just processor core 1).

The following C code is the simplest way to describe the procedure:

// values to be sent in order over the FIFO from core 0 to core 1
//
// vector_table is value for VTOR register
// sp is initial stack pointer (SP)
// entry is the initial program counter (PC) (don't forget to set the thumb bit!)
const uint32_t cmd_sequence[] =
    {0, 0, 1, (uintptr_t) vector_table, (uintptr_t) sp, (uintptr_t) entry};

uint seq = 0;
do {
    uint cmd = cmd_sequence[seq];
    // always drain the READ FIFO (from core 1) before sending a 0
    if (!cmd) {
        // discard data from read FIFO until empty
        multicore_fifo_drain();
        // execute a SEV as core 1 may be waiting for FIFO space
        __sev();
    }
    // write 32 bit value to write FIFO
    multicore_fifo_push_blocking(cmd);
    // read 32 bit value from read FIFO once available
    uint32_t response = multicore_fifo_pop_blocking();
    // move to next state on correct response (echo-d value) otherwise start over
    seq = cmd == response ? seq + 1 : 0;
} while (seq < count_of(cmd_sequence));

2.8.3. Bootrom Contents

Some of the bootrom is dedicated to the implementation of the boot sequence and USB boot interfaces. There is also code in the bootrom useful to user programs. Table 163 shows the fixed memory layout of the first handful of words in the Bootrom which are instrumental in locating other content within the bootrom.

Table 163. Bootrom contents at fixed (well known) addresses

AddressContentsDescription
0x0000000032-bit pointerInitial boot stack pointer
0x0000000432-bit pointerPointer to boot reset handler function
0x0000000832-bit pointerPointer to boot NMI handler function
0x0000000c32-bit pointerPointer to boot Hard fault handler function
0x00000010'M', 'u', 0x01Magic
0x00000013byteBootrom version
0x0000001416-bit pointerPointer to a public function lookup table (rom_func_table)
0x0000001616-bit pointerPointer to a public data lookup table (rom_data_table)
0x0000001816-bit pointerPointer to a helper function (rom_table_lookup())

2.8.3.1. Bootrom Functions

The Bootrom contains a number of public functions that provide useful RP2040 functionality that might be needed in the absence of any other code on the device, as well as highly optimized versions of certain key functionality that would otherwise have to take up space in most user binaries.

These functions are normally made available to the user by the SDK, however a lower level method is provided to locate them (their locations may change with each Bootrom release) and call them directly.

Assuming the three bytes starting at address 0x00000010 are ('M', 'u', 0x01) then the three halfwords starting at offset 0x00000014 are valid.

These three values can be used to dynamically locate other functions or data within the Bootrom. The version byte at offset 0x00000013 is informational and should not be used to infer the exact location of any functions.

The following code from the SDK shows how the three 16-bit pointers are used to lookup other functions or data.

SDK: https://github.com/raspberrypi/pico-sdk/blob/master/src/rp2_common/pico_bootrom/bootrom.c Lines 12 - 19

12 void *rom_func_lookup(uint32_t code) {
13     return rom_func_lookup_inline(code);
14 }
15
16 void *rom_data_lookup(uint32_t code) {
17     return rom_data_lookup_inline(code);
18 }

The code parameter correspond to the CODE values in the tables below, and is calculated as follows:

uint32_t rom_table_code(char c1, char c2) {
    return (c2 << 8) | c1;
}

2.8.3.1.1. Fast Bit Counting / Manipulation Functions

These are optimized versions of common bit counting / manipulation functions.

In general you do not need to call these methods directly as the SDK pico_bit_ops library replaces the corresponding standard compiler library functions by default so that the standard functions such as __builtin_popcount or __clzdi2 uses the corresponding Bootrom implementations automatically (see pico_bit_ops for more details).

These functions have changed in speed slightly between version 1 (V1) of the bootrom and version 2 (V2).

Table 164. Fast Bit Counting / Manipulation Functions.

CODECycles Avg V1Cycles Avg V2/V3Description
'P', '3'1820uint32_t _popcount32(uint32_t value)
Return a count of the number of 1 bits in value.
'R', '3'2122uint32_t _reverse32(uint32_t value)
Return the bits of value in the reverse order.
'L', '3'139.6uint32_t _clz32(uint32_t value)
Return the number of consecutive high order 0 bits of value. If value is zero, returns 32.
'T', '3'1211uint32_t _ctz32(uint32_t value)
Return the number of consecutive low order 0 bits of value. If value is zero, returns 32.

2.8.3.1.2. Fast Bulk Memory Fill / Copy Functions

These are highly optimized bulk memory fill and copy functions commonly provided by most language runtimes.

In general you do not need to call these methods directly as the SDK pico_mem_ops library replaces the corresponding standard ARM EABI functions by default so that the standard C library functions e.g. memcpy or memset use the Bootrom implementations automatically (see pico_mem_ops for more details).

Table 165. Optimized Bulk Memory Fill / Copy Functions

CODEDescription
'M', 'S'uint8_t *_memset(uint8_t *ptr, uint8_t c, uint32_t n)
Sets n bytes start at ptr to the value c and returns ptr.
'S', '4'uint32_t *_memset4(uint32_t *ptr, uint8_t c, uint32_t n)
Sets n bytes start at ptr to the value c and returns ptr. Note this is a slightly more efficient variant of _memset that may only be used if ptr is word aligned.
'M', 'C'uint8_t *_memcpy(uint8_t *dest, uint8_t *src, uint32_t n)
Copies n bytes starting at src to dest and returns dest. The results are undefined if the regions overlap.
'C', '4'uint8_t *_memcpy44(uint32_t *dest, uint32_t *src, uint32_t n)
Copies n bytes starting at src to dest and returns dest. The results are undefined if the regions overlap. Note this is a slightly more efficient variant of _memcpy that may only be used if dest and src are word aligned.

2.8.3.1.3. Flash Access Functions

These are low level flash helper functions.

Table 166. Flash Access Functions

CODEDescription
'I', 'F'void _connect_internal_flash(void)
Restore all QSPI pad controls to their default state, and connect the SSI to the QSPI pads
'E', 'X'void _flash_exit_xip(void)
First set up the SSI for serial-mode operations, then issue the fixed XIP exit sequence described in Section 2.8.1.2 . Note that the bootrom code uses the IO forcing logic to drive the CS pin, which must be cleared before returning the SSI to XIP mode (e.g. by a call to _flash_flush_cache). This function configures the SSI with a fixed SCK clock divisor of /6.
'R', 'E'void _flash_range_erase(uint32_t addr, size_t count, uint32_t block_size, uint8_t block_cmd)
Erase a count bytes, starting at addr(offset from start of flash). Optionally, pass a block erase command e.g. 08h block_erase, and the size of the block erased by this command — this function will use the larger block erase where possible, for much higher erase speed. addr must be aligned to a 4096-byte sector, and count must be a multiple of 4096 bytes.
'R', 'P'void flash_range_program(uint32_t addr, const uint8_t *data, size_t count)
Program data to a range of flash addresses starting at addr(offset from the start of flash) and count bytes in size. addr must be aligned to a 256-byte boundary, and count must be a multiple of 256.
'F', 'C'void _flash_flush_cache(void)
Flush and enable the XIP cache. Also clears the IO forcing on QSPI CSn, so that the SSI can drive the flash chip select as normal.
'C', 'X'void _flash_enter_cmd_xip(void)
Configure the SSI to generate a standard 03h serial read command, with 24 address bits, upon each XIP access. This is a very slow XIP configuration, but is very widely supported. The debugger calls this function after performing a flash erase/programming operation, so that the freshly-programmed code and data is visible to the debug host, without having to know exactly what kind of flash device is connected.

A typical call sequence for erasing a flash sector from user code would be:

Note that, in between the first and last calls in this sequence, the SSI is not in a state where it can handle XIP accesses, so the code that calls the intervening functions must be located in SRAM. The SDK hardware_flash library hides these details.

2.8.3.1.4. Debugging Support Functions

These two methods simplify the task of calling code on the device and then returning control to the debugger.

Table 167. Debugging Support Functions

CODEDescription
'D', 'T'_debug_trampoline
Simple debugger trampoline for break-on-return.
This methods helps the debugger call ROM routines without setting hardware breakpoints. The function address is passed in r7 and args are passed through r0 ... r3 as per ABI.

This method does not return but executes a BKPT #0 at the end.
'D', 'E'_debug_trampoline_end
This is the address of the final BKPT #0 instruction of debug_trampoline. This can be compared with the program counter to detect completion of the debug_trampoline call.

2.8.3.1.5. Miscellaneous Functions

These remaining functions don't fit in other categories and are exposed in the SDK via the pico_bootrom library (see pico_bootrom ).

Table 168. Miscellaneous Functions

CODEDescription
'U', 'B'void _reset_to_usb_boot(uint32_t gpio_activity_pin_mask, uint32_t disable_interface_mask)
Resets the RP2040 and uses the watchdog facility to re-start in BOOTSEL mode:
  • • gpio_activity_pin_mask is provided to enable an "activity light" via GPIO attached LED for the USB Mass Storage Device:
    • ◦ 0 No pins are used as per a cold boot.
    • ◦ Otherwise a single bit set indicating which GPIO pin should be set to output and raised whenever there is mass storage activity from the host.
  • • disable_interface_mask may be used to control the exposed USB interfaces:
    • ◦ 0 To enable both interfaces (as per a cold boot)
    • ◦ 1 To disable the USB Mass Storage Interface (see Section 2.8.4 )
    • ◦ 2 To disable the USB PICOBOT Interface (see Section 2.8.5 )
'W', 'V'_wait_for_vector
This is the method that is entered by core 1 on reset to wait to be launched by core 0. There are few cases where you should call this method (resetting core 1 is much better). This method does not return and should only ever be called on core 1.
'E', 'C'deprecated
Do not use this function which may not be present.

2.8.3.2. Fast Floating Point Library

The Bootrom contains an optimized single-precision floating point implementation. Additionally V2 onwards also contain an optimized double-precision float point implementation. The function pointers for each precision are kept in a table structure found via the rom_data_lookup table (see Section 2.8.3.3 ).

2.8.3.2.1. Implementation Details

There is always a trade-off between speed and size. Whilst the overall goal for the floating-point routines is to achieve good performance within a small footprint, the emphasis is more on improved performance for the basic operations (add, subtract, multiply, divide and square root) and more on reduced footprint for the scientific functions (trigonometric functions, logarithms and exponentials).

The IEEE single- and double-precision data formats are used throughout, but in the interests of reducing code size, input denormals are treated as zero, input NaNs are treated as infinities, output denormals are flushed to zero, and output NaNs are rendered as infinities. Only the round-to-nearest, even-on-tie rounding mode is supported. Traps are not supported.

The five basic operations return results that are always correctly rounded.

The scientific functions always return results within 1 ULP (unit in last place) of the exact result. In many cases results are better.

The scientific functions are calculated using internal fixed-point representations so accuracy (as measured in ULP error rather than in absolute terms) is poorer in situations where converting the result back to floating point entails a large normalising shift. This occurs, for example, when calculating the sine of a value near a multiple of pi, the cosine of a value near an odd multiple of pi/2, or the logarithm of a value near 1. Accuracy of the tangent function is also poorer when the result is very large. Although covering these cases is possible, it would add considerably to the code footprint, and there are few types of program where accuracy in these situations is essential.

The sine, cosine and tangent functions also only operate correctly over a limited range: \( -128 < x < +128 \) for single-precision arguments x and \( -1024 < x < +1024 \) for double-precision x. This is to avoid the need to (at least in effect) store the value of pi to high precision within the code, and hence saves code space. Accurate range reduction over a wider range of arguments can be done externally to the library if required, but again there are few situations where this would be needed.

NOTE

The SDK cos/sin functions perform this range reduction, so accept the full range of arguments, though are slower for inputs outside of these ranges.

2.8.3.2.2. Functions

These functions follow the standard ARM EABI for passing floating point values.

You do not need to call these methods directly as the SDK pico_float and pico_double libraries used by default replace the ARM EABI Float functions such that C/C++ level code (or indirectly code in languages such as MicroPython that are implemented in C) use these Bootrom functions automatically for the corresponding floating point operations.

Some of these functions do not behave exactly the same as some of the corresponding C library functions. For that reason if you are using the SDK it is strongly advised that you simply use the regular math.h functions or those in pico/float.h or pico/double.h and not try to call into the bootrom directly.

Note that double-precision floating point support is not present in version 1 (V1) of the bootrom, but the above mentioned pico_double library in the SDK will take care of pulling in any extra code needed for V1.

i NOTE

For more information on using floating point in the SDK, and real world timings (noting also that some conversion functions are re-implemented in the SDK to be faster) see floating point support .

Table 169. Single-precision Floating Point Function Table. Timings are average time in us over random (worst case) input. Functions with timing of N/A are not present in that ROM version, and the function pointer should be considered invalid. The functions (and table entries) from offset 0x54 onwards are only present in the V2 ROM.

OffsetV1 Cycles (Avg)V2/V3 Cycles (Avg)Description
Functions common to all versions of the bootrom
0x007171float _fadd(float a, float b)
Return \( a + b \)
0x047474float _fsub(float a, float b)
Return \( a - b \)
0x086958float _fmul(float a, float b)
Return \( a * b \)
0x0c7171float _fdiv(float a, float b)
Return \( a / b \)
0x10N/AN/Adeprecated
Do not use this function
0x14N/AN/Adeprecated
Do not use this function
0x186363float _fsqrt(float v)
Return \( \sqrt{v} \) or -Infinity if \( v \) is negative. (Note V1 returns +Infinity in this case)
0x1c3740int _float2int(float v)
Convert a float to a signed integer, rounding towards -Infinity , and clamping the result to lie within the range -0x80000000 to 0x7FFFFFFF
0x203639int _float2fix(float v, int n)
Convert a float to a signed fixed point integer representation where \( n \) specifies the position of the binary point in the resulting fixed point representation - e.g. _float2fix(0.5f, 16) == 0x8000. This method rounds towards -Infinity , and clamps the resulting integer to lie within the range -0x80000000 to 0x7FFFFFFF
0x243839uint _float2uint(float v)
Convert a float to an unsigned integer, rounding towards -Infinity , and clamping the result to lie within the range 0x00000000 to 0xFFFFFFFF
0x283838uint_float2ufix(float v, int n)
Convert a float to an unsigned fixed point integer representation where \( n \) specifies the position of the binary point in the resulting fixed point representation, e.g. _float2ufix(0.5f, 16) == 0x8000. This method rounds towards -Infinity , and clamps the resulting integer to lie within the range 0x00000000 to 0xFFFFFFFF
0x2c5555float_int2float(int v)
Convert a signed integer to the nearest float value, rounding to even on tie
0x305353float_fix2float(int32_t v, int n)
Convert a signed fixed point integer representation to the nearest float value, rounding to even on tie. \( n \) specifies the position of the binary point in fixed point, so \( f = nearest(v / 2^n) \)
0x345454float_uint2float(uint32_t v)
Convert an unsigned integer to the nearest float value, rounding to even on tie
0x385252float_ufix2float(uint32_t v, int n)
Convert an unsigned fixed point integer representation to the nearest float value, rounding to even on tie. \( n \) specifies the position of the binary point in fixed point, so \( f = nearest(v / 2^n) \)
0x3c603587float_fcos(float angle)
Return the cosine of angle . angle is in radians, and must be in the range -128 to 128
0x40593577float_fsin(float angle)
Return the sine of angle . angle is in radians, and must be in the range -128 to 128
0x44669653float_ftan(float angle)
Return the tangent of angle . angle is in radians, and must be in the range -128 to 128
0x48N/AN/Adeprecated
Do not use this function
0x4c542524float_fexp(float v)
Return the exponential value of \( v \) , i.e. so \( e^v \)
0x50810789float_fln( float v)
Return the natural logarithm of \( v \) . If \( v < 0 \) return -Infinity
Functions (and table entries) present in the V2/V3 bootrom only
0x54N/A25int_fcmp(float a, float b)
Compares two floating point numbers, returning:
  • • 0 if \( a == b \)
  • • -1 if \( a < b \)
  • • 1 if \( a > b \)
0x58N/A667float_fatan2(float y, float x)
Computes the arc tangent of \( y/x \) using the signs of arguments to determine the correct quadrant
0x5cN/A62float _int642float(int64_t v)
Convert a signed 64-bit integer to the nearest float value, rounding to even on tie
0x60N/A60float _fix642float(int64_t v, int n)
Convert a signed fixed point 64-bit integer representation to the nearest float value, rounding to even on tie. \( n \) specifies the position of the binary point in fixed point, so \( f = nearest(v / 2^n) \)
0x64N/A58float _uint642float(uint64_t v)
Convert an unsigned 64-bit integer to the nearest float value, rounding to even on tie
0x68N/A57float _ufix642float(uint64_t v, int n)
Convert an unsigned fixed point 64-bit integer representation to the nearest float value, rounding to even on tie. \( n \) specifies the position of the binary point in fixed point, so \( f = nearest(v / 2^n) \)
0x6cN/A54_float2int64
Convert a float to a signed 64-bit integer, rounding towards -Infinity , and clamping the result to lie within the range -0x8000000000000000 to 0x7FFFFFFFFFFFFFFF
0x70N/A53_float2fix64
Convert a float to a signed fixed point 64-bit integer representation where \( n \) specifies the position of the binary point in the resulting fixed point representation - e.g. _float2fix(0.5f, 16) == 0x8000. This method rounds towards -Infinity , and clamps the resulting integer to lie within the range -0x8000000000000000 to 0x7FFFFFFFFFFFFFFF
0x74N/A42_float2uint64
Convert a float to an unsigned 64-bit integer, rounding towards -Infinity , and clamping the result to lie within the range 0x0000000000000000 to 0xFFFFFFFFFFFFFFF
0x78N/A41_float2ufix64
Convert a float to an unsigned fixed point 64-bit integer representation where \( n \) specifies the position of the binary point in the resulting fixed point representation, e.g. _float2ufix(0.5f, 16) == 0x8000. This method rounds towards -Infinity , and clamps the resulting integer to lie within the range 0x0000000000000000 to 0xFFFFFFFFFFFFFFF
0x7cN/A15double _float2double(float v)
Converts a float to a double
Function present in the V3 bootrom only
0x48

(uses
previously
deprecated
slot)
577 (V3
only)
float (float) _fsincos(float angle)
Calculates the sine and cosine of angle . angle is in radians, and must be in the range -128 to 128. The sine value is returned in register r0 (and is thus the official function return value), the cosine value is returned in register r1 . This method is considerably faster than calling _fsin and _fcos separately.

Note that the V2/V3 bootroms contains an equivalent table of functions for double-precision floating point operations. The offsets are the same, however where there was now float there is double (and vice versa for the float<>double conversion)

Table 170. Double-precision Floating Point Function Table. Timings are average time in us over random (worst case) input. Functions with timing of N/A are not present in that ROM version, and the function pointer should be considered invalid. The functions (and table entries) from offset 0x54 onwards are only present in the V2 and V3 ROMs.

OffsetCycles (Avg)*Description
0x0091double _dadd(double a, double b)
Return a + b
0x0495double _dsub(double a, double b)
Return a - b
0x08155double _dmul(double a, double b)
Return a * b
0x0c183double _ddiv(double a, double b)
Return a / b
0x10N/Adeprecated
Do not use this function
0x14N/Adeprecated
Do not use this function
0x18169double _dsqrt(double v)
Return \( \sqrt{v} \) or -Infinity if v is negative.
0x1c75int _double2int(double v)
Convert a double to a signed integer, rounding towards -Infinity , and clamping the result to lie within the range -0x80000000 to 0x7FFFFFFF
0x2074int _double2fix(double v, int n)
Convert a double to a signed fixed point integer representation where n specifies the position of the binary point in the resulting fixed point representation - e.g. _double2fix(0.5f, 16) == 0x8000. This method rounds towards -Infinity , and clamps the resulting integer to lie within the range -0x80000000 to 0x7FFFFFFF
0x2463uint _double2uint(double v)
Convert a double to an unsigned integer, rounding towards -Infinity , and clamping the result to lie within the range 0x00000000 to 0xFFFFFFFF
0x2862uint _double2ufix(double v, int n)
Convert a double to an unsigned fixed point integer representation where n specifies the position of the binary point in the resulting fixed point representation, e.g. _double2ufix(0.5f, 16) == 0x8000. This method rounds towards -Infinity , and clamps the resulting integer to lie within the range 0x00000000 to 0xFFFFFFFF
0x2c69double _int2double(int v)
Convert a signed integer to the nearest double value, rounding to even on tie
0x3068double _fix2double(int32_t v, int n)
Convert a signed fixed point integer representation to the nearest double value, rounding to even on tie. n specifies the position of the binary point in fixed point, so \( f = nearest(v / 2^n) \)
0x3464double _uint2double(uint32_t v)
Convert an unsigned integer to the nearest double value, rounding to even on tie
OffsetCycles (Avg)*Description
0x3862double _ufix2double(uint32_t v, int n)
Convert an unsigned fixed point integer representation to the nearest double value, rounding to even on tie. \( n \) specifies the position of the binary point in fixed point, so \( f = nearest(v / 2^n) \)
0x3c1617double _dcos(double angle)
Return the cosine of angle . angle is in radians, and must be in the range -1024 to 1024
0x401618double _dsin(double angle)
Return the sine of angle . angle is in radians, and must be in the range -1024 to 1024
0x441891double _dtan(double angle)
Return the tangent of angle . angle is in radians, and must be in the range -1024 to 1024
0x48N/Adeprecated
Do not use this function
0x4c804double _dexp(double v)
Return the exponential value of \( v \) , i.e. so \( e^v \)
0x50428double _dln( double v)
Return the natural logarithm of \( v \) . If \( v < 0 \) return -Infinity
0x5439int _dcmp(double a, double b)
Compares two floating point numbers, returning:
  • • 0 if \( a == b \)
  • • -1 if \( a < b \)
  • • 1 if \( a > b \)
0x582168double _datan2(double y, double x)
Computes the arc tangent of \( y/x \) using the signs of arguments to determine the correct quadrant
0x5c55double _int642double(int64_t v)
Convert a signed 64-bit integer to the nearest double value, rounding to even on tie
0x6056double _dix642double(int64_t v, int n)
Convert a signed fixed point 64-bit integer representation to the nearest double value, rounding to even on tie. \( n \) specifies the position of the binary point in fixed point, so \( f = nearest(v / 2^n) \)
0x6450double _uint642double(uint64_t v)
Convert an unsigned 64-bit integer to the nearest double value, rounding to even on tie
0x6849double _ufix642double(uint64_t v, int n)
Convert an unsigned fixed point 64-bit integer representation to the nearest double value, rounding to even on tie. \( n \) specifies the position of the binary point in fixed point, so \( f = nearest(v / 2^n) \)
0x6c64_double2int64
Convert a double to a signed 64-bit integer, rounding towards -Infinity , and clamping the result to lie within the range -0x8000000000000000 to 0x7FFFFFFFFFFFFFFF
OffsetCycles (Avg)*Description
0x7063_double2fix64
Convert a double to a signed fixed point 64-bit integer representation where n specifies the position of the binary point in the resulting fixed point representation - e.g. _double2fix(0.5f, 16) == 0x8000. This method rounds towards -Infinity , and clamps the resulting integer to lie within the range -0x8000000000000000 to 0x7FFFFFFFFFFFFFFF
0x7453_double2uint64
Convert a double to an unsigned 64-bit integer, rounding towards -Infinity , and clamping the result to lie within the range 0x0000000000000000 to 0xFFFFFFFFFFFFFFF
0x7852_double2ufix64
Convert a double to an unsigned fixed point 64-bit integer representation where n specifies the position of the binary point in the resulting fixed point representation, e.g. _double2ufix(0.5f, 16) == 0x8000. This method rounds towards -Infinity , and clamps the resulting integer to lie within the range 0x0000000000000000 to 0xFFFFFFFFFFFFFFF
0x7c23float _double2float(double v)
Converts a double to a float
Function present in the V3 bootrom only
0x48

(uses previously deprecated slot)
1718

(V3 only)
double (,double) _sincos(double angle)
Calculates the sine and cosine of angle . angle is in radians, and must be in the range -1024 to 1024. The sine value is returned in registers r0/r1 (and is thus the official return value), the cosine value is returned in registers r2/r3 . This method is considerably faster than calling _sin and _cos separately.

2.8.3.3. Bootrom Data

The Bootrom data table ( rom_data_table) contains the following pointers.

Table 171. Bootrom data pointers

CODEValue (16-bit pointer)Description
'C', 'R'const char *copyright_string
The Raspberry Pi Trading Ltd copyright string.
'G', 'R'const uint32_t *git_revision
The 8 most significant hex digits of the Bootrom git revision.
'F', 'S'fplib_start
The start address of the floating point library code and data. This and fplib_end along with the individual function pointers in soft_float_table can be used to copy the floating point implementation into RAM if desired.
'S', 'F'soft_float_table
See Table 169 for the contents of this table.
'F', 'E'fplib_end
The end address of the floating point library code and data.
'S', 'D'soft_double_table
This entry is only present in the V2 bootrom. See Table 170 for the contents of this table.
'P', '8'deprecated . This entry is not present in the V2 bootrom; do not use it.
'R', '8'deprecated . This entry is not present in the V2 bootrom; do not use it.
'L', '8'deprecated . This entry is not present in the V2 bootrom; do not use it.
'T', '8'deprecated . This entry is not present in the V2 bootrom; do not use it.

2.8.4. USB Mass Storage Interface

The Bootrom provides a standard USB bootloader that makes a writeable drive available for copying code to the RP2040 using UF2 files (see Section 2.8.4.2 ).

A UF2 file copied to the drive is downloaded and written to Flash or RAM, and the device is automatically rebooted, making it trivial to download and run code on the RP2040 using only a USB connection.

2.8.4.1. The RPI-RP2 Drive

The RP2040 appears as a standard 128MB flash drive named RPI-RP2 formatted as a single partition with FAT16. There are only ever two actual files visible on the drive specified.

Any type of files may be written to the USB drive from the host, however in general these are not stored, and only appear to be so because of caching on the host side.

When a UF2 file is written to the device however, the special contents are recognized and data is written to specified locations in RAM or Flash. On the completed download of an entire valid UF2 file, the RP2040 automatically reboots to run the newly downloaded code.

info icon NOTE

The INDEX.HTM file is currently redirected to https://www.raspberrypi.com/documentation/microcontrollers/

2.8.4.2. UF2 Format Details

lightbulb icon TIP

To generate UF2 files, use the UF2 convert functionality in picotool .

info icon NOTE

Invalid UF2 files may not write at all or only write partially to RP2040 before failing. Not all operating systems notify you of disk write errors after a failed write. You can use picotool to verify that a UF2 file wrote correctly to RP2040.

a. A regular flash binary

b. A RAM only binary

Image: Note icon

NOTE

Traditionally UF2 has only been used to write to Flash, but this is more a limitation of using the metadata-free .BIN file as the source to generate the UF2 file. RP2040 takes full advantage of the inherent flexibility of UF2 to support the full range of binaries in the richer .ELF format produced by the build to be used as the source for the UF2 file.

The flash is always erased a 4kB sector at a time, so including data for only a subset of the 256-byte pages within a sector in a flash-binary UF2 will leave the remaining 256-byte pages of the sector erased but undefined. The RP2040 bootrom will accept UF2 binaries with such partially-filled sectors, however due to a bug ( RP2040-E14 ) such binaries may not be written correctly if there is any partially-filled sector other than at the end. Most flash binaries are 4kB aligned and contiguous, and therefore it is usually only the last sector that is partially-filled. If you need to write non-aligned or non-contiguous UF2 s to flash, then you should make sure to include a full 4kB worth of data for every sector in flash that will be written other than the last. This is handled for you automatically by the elf2uf2 tool in the SDK version 1.3.1 onwards, which explicitly adds zero-filled pages to the appropriate partially-filled sectors.

A binary is considered "downloaded" when each of the numBlocks blocks has been seen at least once in the course of a single valid transfer. The data for a block is only written the first time in case of the host resending duplicate blocks.

After downloading a regular flash binary, a reset is performed after which the flash binary second stage (at address 0x10000000- the start of flash) will be entered (if valid) via the bootrom.

A downloaded RAM only binary is entered by watchdog reset into the start of the binary, which is calculated as the lowest address of a downloaded block (with Main RAM considered lower than Flash Cache if both are present).

Finally it is possible for host software to temporarily disable UF2 writes via the PICOB00T interface to prevent interference with operations being performed via that interface (see below), in which case any UF2 file write in progress will be aborted.

2.8.5. USB PICOB00T Interface

The PICOB00T interface is a low level USB protocol for interacting with the RP2040 while it is in BOOTSEL mode. This interface may be used concurrently with the USB Mass Storage Interface.

It provides for flexible reading from and writing to RAM or Flash, rebooting, executing code on the device and a handful of other management functions.

Constants and structures related to the interface can be found in the SDK header https://github.com/raspberrypi/pico-sdk/blob/master/src/common/boot_picoboot_headers/include/boot_picoboot.h

2.8.5.1. Identifying The Device

A RP2040 device is recognized by the Vendor ID and Product ID in its device descriptor (shown in Table 172 ).

Table 172. RP2040
Boot Device
Descriptor

FieldValue
bLength18
bDescriptorType1
bcdUSB1.10
bDeviceClass0
bDeviceSubClass0
bDeviceProtocol0
bMaxPacketSize064
idVendor0x2e8a
idProduct0x0003
bcdDevice1.00
iManufacturer1
iProduct2
iSerial3
bNumConfigurations1

2.8.5.2. Identifying The Interface

The PICOBOOT interface is recognized by the "Vendor Specific" Interface Class and the zero Interface Sub Class and Interface Protocol (shown in Table 173 ). Note that you should not rely on the interface number, as that is dependent on whether the device is also exposing the Mass Storage Interface. Note also that the device equally may not be exposing the PICOBOOT interface at all, so you should not assume it is present.

Table 173. PICOBOOT
Interface Descriptor

FieldValue
bLength9
bDescriptorType4
bInterfaceNumbervaries
bAlternateSetting0
bNumEndpoints2
bInterfaceClass0xff (vendor specific)
bInterfaceSubClass0
bInterfaceProtocol0
iInterface0

2.8.5.3. Identifying The Endpoints

The PICOBOOT interface provides a single BULK OUT and a single BULK IN endpoint. These can be identified by their direction and type. You should not rely on endpoint numbers.

2.8.5.4. PICOBOOT Commands

The two bulk endpoints are used for sending commands and retrieved successful command results. All commands are exactly 32 bytes (see Table 174 ) and sent to the BULK OUT endpoint.

Table 174. PICOBOOT Command Definition

line_numbercodecomment
exactly 32 bytes (seeTable 174)and sent to the BULK OUT endpoint.
Table 174. PICOBOOT OffsetNameDescription
Command Definition 0x00dMagicThe value 0x431fd10b
0x04dTokenA user provided token to identify this request by
0x08bCmdIdThe ID of the command. Note that the top bit indicates data transfer direction
0x09bCmdSize(0x80 = IN) Number of bytes of valid data in the args field
0x0areserved0x0000
0x0cdTransferLengthThe number of bytes the host expects to send or receive over the bulk channel
0x10args16 bytes of command specific data padded with zeros
via the GET_COMMAND_STATUSrequest (see Section 2.8.5.5.2 ).
Following the initial 32 byte packet, ifdTranferLength is non-zero, then that many bytes are transferred over the bulk
pipe and the command is completed with an empty packet in the opposite direction. IfdTransferLength is zero then
The following commands are supported (note common fieldsdMagic, dToken, reserved are omitted for clarity)
Table 175. PICOBOOT OffsetNameValue / Description
Exclusive access command structure 0x08bCmdId0x01 (EXCLUSIVE_ACCESS)
0x09bCmdSize0x01
0x0cdTransferLength0x00000000
0x10bExclusiveNOT_EXCLUSIVE (0) No restriction on USB Mass Storage operation EXCLUSIVE (1)
see them as write protect failures, but in any case any active UF2 download will be aborted) EXCLUSIVE_AND_EJECT Lock the USB Mass Storage Interface out by
Table 176. PICOBOOT OffsetName Value / Description
command structure Reboot access 0x08bCmdId 0x02 (REBOOT)
0x09bCmdSize 0x0c

If a command sent is invalid or not recognized, the bulk endpoints will be stalled. Further information will be available via the GET_COMMAND_STATUS request (see Section 2.8.5.5.2 ).

Following the initial 32 byte packet, if dTransferLength is non-zero, then that many bytes are transferred over the bulk pipe and the command is completed with an empty packet in the opposite direction. If dTransferLength is zero then command success is indicated by an empty IN packet.

The following commands are supported (note common fields dMagic , dToken , reserved are omitted for clarity)

2.8.5.4.1. EXCLUSIVE_ACCESS (0x01)

Claim or release exclusive access for writing to the RP2040 over USB (versus the Mass Storage Interface)

Table 175. PICOBOOT Exclusive access command structure

2.8.5.4.2. REBOOT (0x02)

Reboots the RP2040 out of BOOTSEL mode. Note that BOOTSEL mode might be re-entered if rebooting to flash and no valid second stage bootloader is found.

Table 176. PICOBOOT Reboot access command structure

0x0cdTransferLength0x00000000
0x10dPCThe address to start executing from. Valid values are:
0x00000000 Reboot via the standard Flash boot mechanism
RAM address Reboot via watchdog and start executing at the specified address in RAM
0x14dSPInitial stack pointer post reboot (only used if booting into RAM)
0x18dDelayMSNumber of milliseconds to delay prior to reboot

2.8.5.4.3. FLASH_ERASE (0x03)

Erases a contiguous range of flash sectors.

Table 177. PICOB00T
Flash erase command structure

OffsetNameValue / Description
0x08bCmdId0x03 (FLASH_ERASE)
0x09bCmdSize0x08
0x0cdTransferLength0x00000000
0x10dAddrThe address in flash to erase, starting at this location. This must be sector (4kB) aligned
0x14dSizeThe number of bytes to erase. This must be an exact multiple number of sectors (4kB)

2.8.5.4.4. READ (0x84)

Read a contiguous memory (Flash or RAM or ROM) range from the RP2040

Table 178. PICOB00T
Read memory command (Flash, RAM, ROM) structure

OffsetNameValue / Description
0x08bCmdId0x84 (READ)
0x09bCmdSize0x08
0x0cdTransferLengthMust be the same as dSize
0x10dAddrThe address to read from. May be in Flash or RAM or ROM
0x14dSizeThe number of bytes to read

2.8.5.4.5. WRITE (0x05)

Writes a contiguous memory range of memory (Flash or RAM) on the RP2040.

Table 179. PICOB00T
Write memory command (Flash, RAM) structure

OffsetNameValue / Description
0x08bCmdId0x05 (WRITE)
0x09bCmdSize0x08
0x0cdTransferLengthMust be the same as dSize
OffsetNameValue / Description
0x10dAddrThe address to write from. May be in Flash or RAM, however must be page (256 byte) aligned if in Flash. Note the flash must be erased first or the results are undefined.
0x14dSizeThe number of bytes to write. If writing to flash and the size is not an exact multiple of pages (256 bytes) then the last page is zero-filled to the end.

2.8.5.4.6. EXIT_XIP (0x06)

Exit Flash XIP mode. This first initialises the SSI for serial transfers, and then issues the XIP exit sequence given in Section 2.8.1.2 , to attempt to make the flash responsive to standard serial SPI commands. The SSI is configured with a fixed clock divisor of /6, so the USB bootloader will drive SCLK at 8MHz.

Table 180. PIC0BOOT
Exit Execute in place
(XIP) command
structure

OffsetNameValue / Description
0x08bCmdId0x06 (EXIT_XIP)
0x09bCmdSize0x00
0x0cdTransferLength0x00000000

2.8.5.4.7. ENTER_XIP (0x07)

Enter Flash XIP mode. This configures the SSI to issue a standard 03h serial read command, with 24 address clocks and 32 data clocks, for every XIP access. This is a slow but very widely supported way to read flash. The intent of this function is to make flash easily accessible (i.e. just access addresses in the 0x10..... segment) without having to know the details of exactly what kind of flash is connected. This mode is suitable for executing code from flash, but is much slower than e.g. QSPI XIP access.

Table 181. PIC0BOOT
Enter Execute in place
(XIP) command

OffsetNameValue / Description
0x08bCmdId0x07 (ENTER_XIP)
0x09bCmdSize0x00
0x0cdTransferLength0x00000000

2.8.5.4.8. EXEC (0x08)

Executes a function on the device. This function takes no arguments and returns no results, so it must communicate via RAM. Execution of this method will block any other commands as well as Mass Storage Interface UF2 writes, so should only be used in exclusive mode and with extreme care (and it should save and restore registers as per the ARM EABI). This method is called from a regular (non-IRQ) context, and has a very limited stack, so the function should use its own.

Table 182. PIC0BOOT
Execute function on
device command
structure

OffsetNameValue / Description
0x08bCmdId0x08 (EXEC)
0x09bCmdSize0x04
0x0cdTransferLength0x00000000
0x10dAddrFunction address to execute at (a thumb bit will be added for you since you will have forgotten).

2.8.5.4.9. VECTORIZE_FLASH (0x09)

Requests that the vector table of flash access functions used internally by the Mass Storage and PICOBOOT interfaces be copied into RAM, such that the method implementations can be replaced with custom versions (For example, if the board uses flash that does not support standard commands)

Table 183. PICOBOOT
Vectorise flash
command structure

OffsetNameValue / Description
0x08bCmdId0x09 (VECTORIZE_FLASH)
0x09bCmdSize0x04
0x0cdTransferLength0x00000000
0x10dAddrPointer to where to place vector table in RAM

Flash function vector table

struct {
    uint32_t size; // 28
    uint32_t (*do_flash_enter_cmd_xip)();
    uint32_t (*do_flash_exit_xip)();
    uint32_t (*do_flash_erase_sector)();
    uint32_t (*do_flash_erase_range)(uint32_t addr, uint32_t size);
    uint32_t (*do_flash_page_program)(uint32_t addr, uint8_t *data);
    uint32_t (*do_flash_page_read)(uint32_t addr, uint8_t *data);
};

These methods have the same signature and arguments as the corresponding flash access functions in the bootrom (see Section 2.8.3.1.3 ).

Note that the host must subsequently update the RAM copy of this table via an EXEC command running on the RP2040 as any write to RAM from the host via a PICOBOOT WRITE that overlaps this (now active in RAM) vector table will cause a reset to the use of the default ROM Flash function vector table.

2.8.5.5. Control Requests

The following requests are sent to the interface via the default control pipe.

2.8.5.5.1. INTERFACE_RESET (0x41)

The host sends this control request to reset the PICOBOOT interface. This command:

Table 184. PICOBOOT
Reset PICOBOOT
interface control

bmRequestTypebRequestwValuewIndexwLengthData
01000001b01000001b0000hInterface0000hnone

This command responds with an empty packet on success.

2.8.5.5.2. GET_COMMAND_STATUS (0x42)

Retrieve the status of the last command (which may be a command still in progress). Successful completion of a PICOBOOT Protocol Command is acknowledged over the bulk pipe, however if the operation is still in progress or has failed (stalling the bulk pipe), then this method can be used to determine the operation’s status.

Table 185. PICOBOOT
Get last command
status control

bmRequestTypebRequestwValuewIndexwLengthData
11000001b01000010b0000hInterface0000hnone

The command responds with the following 16 byte response

Table 186. PICOBOOT
Get last command
status control
response

OffsetNameDescription
0x00dTokenThe user token specified with the command
0x04dStatusCodeOK (0)The command completed successfully (or is in still in progress)
UNKNOWN_CMD (1)The ID of the command was not recognized
INVALID_CMD_LENGTH (2)The length of the command request was incorrect
INVALID_TRANSFER_LENGTH (3)The data transfer length was incorrect given the command
INVALID_ADDRESS (4)The address specified was invalid for the command type; i.e. did not match the type Flash/RAM that the command was expecting
BAD_ALIGNMENT (5)The address specified was not correctly aligned according to the requirements of the command
INTERLEAVED_WRITE (6)A Mass Storage Interface UF2 write has interfered with the current operation. The command was abandoned with unknown status. Note this will not happen if you have exclusive access.
REBOOTING (7)The device is in the process of rebooting, so the command has been ignored.
UNKNOWN_ERROR (8)Some other error occurred.
0x08bCmdIdThe ID of the command
0x09bInProgress1 if the command is still in progress0 otherwise
0x0areserved(6 zero bytes)