90 driver main functions repeated the same three strcmp() checks and
calls. I2CSPIDriver<T>::module_main() does it once; drivers with extra
verbs keep their own dispatch.
Assisted-by: Claude:claude-opus-5-5
Add the PX4 arch layer for the i.MX9 family: ADC, HRT on LPTMR with
LPIT deadlines, TPM io timers, pin interrupts, LPSPI with chip selects
for all eight instances, critmon on the DWT cycle counter, a tone alarm
on a TPM channel, version reporting with the 128-bit ECID read from the
Fuse Status Block as the UUID, the board reset entry point, plus the
i.MX95 chip include set, the chip mapping in px4_impl_os.cmake and the
PX4_SOC_ARCH_ID_IMX95 id. DShot uses the shared NXP FlexIO driver with
the i.MX9 FlexIO base, offsets, IRQ, clock root and pad hooks.
Not implemented yet: reset of the M7 through the System Manager, LED
PWM and PWM input capture.
i.MX9 timer configs name their timers Timer::TPMn and mark DShot
capable ones with initIOTimerDshot(), so teach
output_groups_from_timer_config.py both forms.
Co-authored-by: Andre Heinemans <andre.heinemans@nxp.com>
About 1700 call sites loaded the log level as the first argument of
px4_log_modulename(). Per-level functions drop that load and leave one
more register for the format arguments.
Assisted-by: Claude:claude-opus-5-5
CONSTRAINED_FLASH_NO_HELP only emptied the PRINT_MODULE_USAGE_* bodies,
so every call site and its strings stayed in flash. Make the helpers
no-op inlines there, as PRINT_MODULE_DESCRIPTION already is on NuttX;
only the usage line with the docs link is still printed.
Assisted-by: Claude:claude-opus-5-5
The constructor was defined in the header, so every one of the ~150
module and library classes deriving from ModuleParams expanded it into
its own constructor: the ListNode and child-list initialisation plus
the setParent() call, repeated per class.
Moving the body next to setParent() in module_params.cpp leaves a single
call at each site. px4_fmu-v6x_default: 1934288 -> 1932520 bytes of
text, -1768 B.
Assisted-by: Claude:claude-fable-5-1
Co-authored-by: Balduin <balduin@auterion.com>
The constructor was defined in the header, so each of the ~75 I2C/SPI
drivers expanded the ScheduledWorkItem and I2CSPIInstance initialisation
into its own constructor.
Moving the body to i2c_spi_buses.cpp leaves one call per driver.
px4_fmu-v6x_default: 1932520 -> 1930616 bytes of text, -1904 B.
Assisted-by: Claude:claude-fable-5-1
Co-authored-by: Balduin <balduin@auterion.com>
The base implementation, which walks the child list and then calls
updateParamsImpl(), was defined in the class body. Every module that
calls updateParams() on a parameter update therefore inlined the list
walk. Define it in module_params.cpp next to setParent().
px4_fmu-v6x_default: 1917160 -> 1915056 bytes of text, -2104 B.
Assisted-by: Claude:claude-fable-5-1
Co-authored-by: Balduin <balduin@auterion.com>
* fix(vectornav): limit init based on retries, set max thread prio
Signed-off-by: dirksavage88 <dirksavage88@gmail.com>
* fix(vnav): set lower priority than max
Signed-off-by: dirksavage88 <dirksavage88@gmail.com>
* chore(vnav): remove unused variable
Signed-off-by: dirksavage88 <dirksavage88@gmail.com>
* fix(vnav): set scheduler priority definition in tasks header, base off of PX4_WQ_HP_BASE
Signed-off-by: dirksavage88 <dirksavage88@gmail.com>
---------
Signed-off-by: dirksavage88 <dirksavage88@gmail.com>
Erbium is a RISC-V RV64IMFC chip whose NuttX port is in PX4/NuttX. Add
the PX4 platform layer for it: HRT, board reset, critmon time base and
board identity, the riscv-none-elf toolchain file and the rv64imfc
compiler flags, which include -mno-fdiv because the ET-Minion core has
no hardware for FDIV.S and FSQRT.S.
The HRT reads the machine timer and runs its callouts in a task, since
the NuttX RISC-V trap path does not save the FP registers that callouts
may use.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Afonso Oliveira <afonso.oliveira707@gmail.com>
px4_at24c_initialize() takes a struct i2c_master_s pointer. Without a
declaration in scope the struct is local to the prototype, which is an
error with -Werror on a target that does not include the NuttX I2C
headers before px4_mtd.h.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Afonso Oliveira <afonso.oliveira707@gmail.com>
events::send(id, log_levels, message) was an inline function, so every
module using it got either a private clone or the body inlined at each
call site. The message is never part of the sent event: it only feeds
the build-time event generator and the optional console print.
Keep a thin inline wrapper so the compiler still drops the unused
message string, and build the event in one out-of-line function that
takes the two log levels as scalars to keep the call sites small. This
saves 1760 bytes of FLASH on px4_fmu-v6x and 1184 bytes on px4_fmu-v2.
Assisted-by: Claude:claude-fable-5-1
Signed-off-by: Michael Rogov Papernov <michael@membrowse.com>
Modules that stop through ModuleBase::exit_and_cleanup() delete themselves
inside Run(), and since 9b62a1701d WorkQueue::Run() then clears
_run_in_progress in the freed object. ASAN aborts SITL on
`battery_simulator stop` and the stop of most other work queue modules.
Track the in-flight item in the WorkQueue instead, which lives until its
own Run() exits on the worker thread.
Assisted-by: Claude:claude-opus-5-5
* fix(platforms/common): sleep with nanosleep() in px4_usleep()
Outside of the SITL lockstep build, px4_usleep() was usleep(). POSIX only requires usleep() to accept less than 1000000 microseconds and lets it fail with EINVAL from there; POSIX.1-2001 marked it obsolescent and POSIX.1-2008 removed it in favour of nanosleep(). glibc, NuttX and macOS sleep for longer anyway, but other implementations return EINVAL at once, and as no caller checks the result, the sleep would silently not happen. More than twenty call sites ask for a second or more, such as uorb top, mavlink, the ESC calibration or voxl2_io, and some durations are computed at run time, such as the one-second idle period of the POSIX HRT thread.
Outside of the lockstep build, px4_usleep() is now a px4_platform function that converts the microseconds to the timespec of nanosleep(), so the call sites keep passing microseconds of any duration. It is not inline: expanding the conversion at every call site grew px4_fmu-v6xrt_default by 4 kB of flash. QURT has no nanosleep(), which PX4 only stubs there, but its usleep() accepts a second or more, so px4_usleep() remains usleep() there. system_usleep() remains usleep(), for the wall-clock sleeps that bypass the lockstep scheduler.
A signal still ends the sleep early, with -1 and EINTR, rather than restarting it for the remaining time: on POSIX, the HRT and work queue threads sleep in px4_usleep(), and hrt_work_queue() and work_queue() wake them with SIGCONT, so a restarted sleep would delay hrt_call_*() callouts by up to a second. On NuttX, no PX4 code signals its tasks, and px4_task_delete() does not depend on the sleep returning: without cancellation points, which no board enables, task_delete() terminates the task wherever it is.
Failures are now -1 with errno, where the usleep() of NuttX returned the error number. No call site checks the result, so none changes. The sleep test now also sleeps for 1.2 s.
Assisted-by: Claude:opus-5.5
* perf(boards): keep the sleep path in ITCM on i.MX RT boards
The ITCM lists of these boards hold the sleep path of NuttX: usleep(), clock_nanosleep() and nxsig_nanosleep(). px4_usleep() now enters it through its own function and nanosleep(), which take the place of usleep(), so the path stays in ITCM. usleep() remains linked for the code that still calls it directly, such as the start-up code of the boards and NSH.
Assisted-by: Claude:opus-5.5
* fix(drivers): sleep for a second or more with px4_usleep()
bmi088_i2c, microstrain, frsky_telemetry and the bit rate detection of the kinetis, stm32 and stm32h7 UAVCAN drivers asked usleep() for a second or more, which POSIX doesn't require it to accept. The usleep() of NuttX accepts it, but px4_usleep() now does on every platform.
Assisted-by: Claude:opus-5.5
The fmu-v6xrt boards can be fitted with either of two octal flash parts, and
nothing told the user which one is on the board. The identity is already
known: the bootloader stage reads the JEDEC ID to pick a config, and the app
stage recognises the config from the installed read sequence, so no extra
flash access is needed to report it.
Keep the part name behind a weak board_get_flash_type_name() and append it to
the chip tag when the board provides one, so `ver mcu` and the logged chip
name read e.g. "i.MX RT1170 rA0 IS25WX512M". Boards that do not implement it
are unaffected and their tag is unchanged.
Signed-off-by: Peter van der Perk <peter.vanderperk@nxp.com>
Each default driver instantiation emits the same allocation and initialization failure handling. Share that code outside the template while keeping init() resolved on the concrete driver. Allocation failures are now logged under SPI_I2C.
Extracted from Balduin (mbjd) in PX4/PX4-Autopilot#27816, commit 8a2391730f.
Assisted-by: Codex
Signed-off-by: Jacob Dahl <dahl.jakejacob@gmail.com>
Co-authored-by: Balduin <balduin@auterion.com>
On NuttX these are two things: / is the filesystem root, and /fs/microsd is the
SD card mounted under it. MAVLink FTP serves the root and confines writes to the
SD card, so the read-only ROMFS at /etc is visible but cannot be written.
On POSIX they were the same directory. PX4_ROOTFSDIR and PX4_STORAGEDIR both
resolved to CONFIG_BOARD_ROOT_PATH, which on SITL is ".", so the working
directory was simultaneously the FTP root and the only writable area. The
consequences were that the ROMFS symlink sat inside the FTP root, and that
_validatePathIsWritable() had nothing meaningful to check against and so was
compiled out on POSIX entirely, leaving no write restriction at all.
Give POSIX the same split. CONFIG_BOARD_ROOT_PATH keeps its meaning as the
storage directory, and a new CONFIG_BOARD_FS_ROOT_PATH names the root FTP
serves, defaulting to the storage path so every existing board is unchanged.
SITL sets the root to "." and storage to "./fs", which mirrors NuttX: logs,
parameters, dataman and eeprom move under ./fs, and etc/ stays in the root as
read-only data.
With storage distinct from the root, the write restriction now applies on every
platform rather than NuttX only, and no longer compares against a hardcoded
prefix length that was wrong for any board not using /fs/microsd.
Assisted-by: Claude:claude-opus-5[1m]
Signed-off-by: Julian Oes <julian@oes.ch>
* feat(sensors): decouple sensor internal/external classification from the bus
A sensor's internal/external classification was derived from its bus
(px4_i2c_bus_external / px4_spi_bus_external), but a bus is a wire: one bus
routinely serves both chips soldered on the FC and a pinned-out connector, and
any onboard sensor on such a shared bus was classified external. That hands an
onboard mag an operator-settable rotation instead of the board rotation, feeds
an onboard baro's self-heated die temperature into air density as if it were
ambient, and inverts the 75/50 default priority. FMU-v6C and AirBrainH743
worked around it with hand-rolled device_id whitelists behind
BOARD_OVERRIDE_I2C_DEVICE_EXTERNAL; FMU-v6XRT's second onboard baro was simply
misclassified.
Classify the device instead of the bus: drivers publish is_external in
sensor_accel/gyro/mag/baro, derived from the device id by default and
overridden by the new -O start flag ("onboard") for onboard sensors that share
a bus with an external connector. -I/-X stay pure bus probe filters.
The question "is this sensor external" had four answers. It now has one, with
a single override point:
-O -> I2CSPIDriverConfig::external -> Device::set_external() and the
PX4* wrappers -> is_external in the sensor topic
px4_i2c_device_external() was px4_i2c_bus_external() with a device id decode in
front, and calibration::DeviceExternal() forwarded to device_is_external();
both are gone. Device::external() stops being a bus query: it is non-virtual,
defaults to device_is_external(), and takes the declared value through
set_external(), so the five I2C/SPI overrides that used to answer it from the
bus are deleted and cannot diverge again. device::I2C and device::SPI set it
from the config, so every driver built on the bus framework follows -O without
doing anything. px4_i2c_bus_external() and px4_spi_bus_external() survive as
what they honestly are - bus predicates - reachable only through the fallback.
-O is opt-in per driver (BusCLIArguments::support_onboard), the same way -k is:
a flag that every driver advertised but only a handful honoured would be a
silent no-op on the rest. This also drops the special case for the mcp23009 and
mcp23017 GPIO expanders, which use -O for their output state and simply do not
opt in.
sensor_gyro_fifo carries is_external too. VehicleAngularVelocity prefers the
FIFO topic for any IMU that publishes one, so without it the rate controller
would take its rotation from the bus while VehicleIMU took it from the topic -
the same chip, two classifications.
The BOARD_OVERRIDE_I2C_DEVICE_EXTERNAL hook is removed along with both board
implementations, replaced by -O on the affected rc.board_sensors lines.
FMU-v5x, MR-CANHUBK3, KakuteF7, NXT-Dual and MicoAir H743-Lite each start an
onboard barometer on an external bus and get the flag as well.
Assisted-by: Claude:claude-fable-5, Claude:claude-opus-5[1m]
Signed-off-by: Jacob Dahl <dahl.jakejacob@gmail.com>
* feat(sensors): treat shared buses as first-class topology
A boolean internal/external flag cannot describe a bus that carries both
hard-mounted chips and a connector. -O was an opt-in override for that
case, so most drivers silently ignored it and classification still
followed the bus.
Declare Internal / External / Shared on the bus, probe External and
Shared, and classify each sensor from -I/-s vs -X/-S.
Signed-off-by: Jacob Dahl <dahl.jakejacob@gmail.com>
* fix(ci): drop stale ITCM symbols and clang-tidy errors
ITCM lists still named calibration::DeviceExternal and
px4_spi_bus_external after both were removed. The host test stubs
forwarded varargs in a way the analyzer rejected, and stripped I2C
headers kept extra trailing newlines.
Signed-off-by: Jacob Dahl <dahl.jakejacob@gmail.com>
* fix(sensors): inline device_is_external into the header
Reaching it through drivers__device pulled the kernel-only library into
the userspace image of a protected build; giving it a library of its own
put an archive referencing px4_i2c_buses/px4_spi_buses after the board
library that defines them. Inlining sidesteps both.
* fix(sensors): compile tcbp001ta and probe canhubk3 GPS mag
tcbp001ta is not an I2CSPIDriver, so config.external does not exist; it
only ever starts on internal SPI. -X on canhubk3 I2C2 never ran because
that bus is Internal.
Signed-off-by: Jacob Dahl <dahl.jakejacob@gmail.com>
---------
Signed-off-by: Jacob Dahl <dahl.jakejacob@gmail.com>
* refactor(px4_work_queue): out-line ScheduledWorkItem constructor to save flash
The header-inline constructor zero-initialises the hrt_call member at
every derived work-item constructor across ~150 classes. Move the
definition (verbatim) into ScheduledWorkItem.cpp next to the
destructor; the derived constructors already pay a call into the base
constructor chain, so this only removes the duplicated inline stores.
Saves 1376 B of .text on px4_fmu-v6x_default.
Signed-off-by: Balduin <balduin@auterion.com>
* refactor(px4_work_queue): out-line WorkItem::ScheduleNow to save flash
The body was inlined at ~240 call sites; a plain call is smaller at
every one of them.
Saves 672 B FLASH on px4_fmu-v6x_default.
Signed-off-by: Balduin <balduin@auterion.com>
---------
Signed-off-by: Balduin <balduin@auterion.com>
Co-authored-by: Balduin <balduin@auterion.com>
The constructor is inlined into every I2C/SPI driver's command-line
entry point, and with it the ~15 default member initializers and the
32-byte _options zero-fill, costing ~50-70 B per driver. Move the
definition (verbatim) into i2c_spi_buses.cpp, which already holds the
rest of the CLI parsing code. Purely cold-path (driver start/CLI).
Saves 2456 B of .text on px4_fmu-v6x_default.
Signed-off-by: Balduin <balduin@auterion.com>
Co-authored-by: Balduin <balduin@auterion.com>
Every Param<> constructor inlines param_set_used(handle()) followed by
param_get(handle(), &_val), materialising the handle constant twice at
each of the ~2000 instantiation sites. Fold both into a single
out-of-line param_get_mark_used() so each constructor emits one call.
The failsafe_web build stubs the param API itself, so it gets a matching
stub. The smaller constructors let the compiler fully inline the
defaulted FlightTaskDescend constructor on the ITCM boards, so its entry
is dropped from their linker scripts.
Saves 7232 B of .text on px4_fmu-v6x_default.
Assisted-by: Claude:claude-fable-5
Signed-off-by: Jacob Dahl <dahl.jakejacob@gmail.com>
Co-authored-by: Balduin <balduin@auterion.com>
Both were defined inline in the header, so the List add/remove bodies
were duplicated into the constructor and destructor of every one of the
150+ ModuleParams-derived classes. Construction and destruction are cold
paths; a call is smaller at each site.
Two consumers reach ModuleParams without px4_platform on the link line
and now need the definitions explicitly: health_and_arming_checks (the
functional-ModeManagement test only pulls it in transitively through
modules__commander, after px4_platform) and the failsafe_web emscripten
build, which compiles module_params.cpp directly.
The smaller constructors let the compiler fully inline the defaulted
FlightTaskDescend constructor on the ITCM boards, so its entry is
dropped from their linker scripts.
Saves 3968 B of .text on px4_fmu-v6x_default.
Assisted-by: Claude:claude-fable-5
Signed-off-by: Jacob Dahl <dahl.jakejacob@gmail.com>
Co-authored-by: Balduin <balduin@auterion.com>
Make px4::atomic's value constructor and ModuleBase::Descriptor
constexpr so the ~40 per-module 'desc' statics are constant-initialised
instead of each emitting static-init code, and apply the same to the
mixer_module FunctionProvider table.
Signed-off-by: Balduin <balduin@auterion.com>
Two related fixes for HRT callout queue corruption under lockstep SIH:
1. WorkQueue::Run() popped a WorkItem, released the work-queue lock,
then called work->Run(). If another thread called Deinit on the
item in that window, wq->Remove was a no-op (item already popped)
and Deinit returned while Run() was still executing. Run() could
then call ScheduleDelayed → hrt_call_after on an object that the
caller of Deinit has since destructed and reused via placement new
— the hrt_call metadata ends up living inside another object's
fields, which later overwrite the flink pointer and tear the hrt
callout queue.
Fix: WorkItem carries a _run_in_progress atomic flag set by
WorkQueue::Run around work->Run(). Deinit spins on that flag after
wq->Remove so it cannot return while a Run() is still executing.
WorkQueue captures its worker tid in the constructor (the ctor
runs on the worker thread) so Deinit can skip the self-wait when
called from inside Run() itself (e.g. should_exit() paths that
invoke ScheduleClear).
2. _hrt_lock was a px4_sem_t and hrt_call_invoke unlocked around the
callback so callbacks could re-enter hrt_call_*. That also exposed
the queue to other threads mid-invocation. Switch _hrt_lock to a
PTHREAD_MUTEX_RECURSIVE pthread_mutex and hold it across the
callback — matches NuttX's enter_critical_section() nesting
semantics, lets callbacks reschedule themselves safely, and
prevents concurrent queue manipulation.
Together these eliminate the HRT queue tearing observed in the
SIH-at-20x MAVSDK integration soak (torn flink chains with the tail
unreachable from the head; orphan nodes pointing into reused
memory).
Move the helper from the header into WorkQueue.cpp. Drop the
SignalWorkerThread() call from request_stop() — request_stop sets
_should_exit but the worker is woken up via the existing exit path
in Detach already, so the extra signal here is redundant.
A seq_cst px4::atomic emits a hardware `dmb` on ARM. That barrier only orders
accesses as seen by a second observer (another CPU core or DMA); for inter-thread
synchronisation on a single-core (uniprocessor) target there is no second core, so
the `dmb` is dead weight - only the compiler ordering is required.
On a NuttX build without CONFIG_SMP, keep full seq_cst semantics but emit a
compiler-only fence (__atomic_signal_fence, zero instructions) instead of the
`dmb`. This mirrors Linux, where smp_mb()/smp_rmb()/smp_wmb() collapse to a
compiler barrier on uniprocessor builds. SMP NuttX and POSIX are unchanged (real
barriers, so SITL under ThreadSanitizer keeps full ordering). 64-bit types (not
lock-free on a 32-bit core) keep the existing interrupts-off critical section,
which already provides both atomicity and ordering.
The public API is unchanged - no per-call ordering knob. Verified on
arm-none-eabi Cortex-M7 that the single-core path emits no `dmb` while keeping
atomicity, and that SMP/POSIX is unchanged:
load (single-core): ldr (signal_fence: 0 instr)
store (single-core): str
fadd (single-core): ldrex/strex loop, no dmb
load (seq_cst/SMP): dmb ish; ldr; dmb ish
store (seq_cst/SMP): dmb ish; str; dmb ish
fadd (seq_cst/SMP): dmb ish; ldrex/strex; dmb ish
Shrinks fmu-v6x by ~2.8 KB (dead barriers removed from atomics already in use),
with no behaviour change. Note: inter-thread ordering only - DMA/device sync
still needs explicit barriers.
* fix(i2c_spi): prevent use-after-free when stopping driver instances
module_stop() deleted each instance before unlinking it from the global
i2c_spi_module_instances list. The instance *is* the intrusive list node,
so removeInstance()/List::remove() then dereferenced the freed node to fix
up the links. If another thread reused that heap block in the window, the
list got corrupted, sporadically leaving instances linked (a later start
reports "already running") or hard-faulting. This regressed in the 2020
array->linked-list refactor: the old array version only nulled an array
slot after delete, which was safe.
Unlink each instance before freeing it. Also only delete/unlink when the
task actually exited: if request_stop_and_wait() times out the work queue
may still reference the object, so leave it allocated and listed rather
than freeing it. module_stop() now returns -1 when an instance failed to
stop.
Signed-off-by: Jacob Dahl <dahl.jakejacob@gmail.com>
* Update platforms/common/i2c_spi_buses.cpp
* Update platforms/common/i2c_spi_buses.cpp
---------
Signed-off-by: Jacob Dahl <dahl.jakejacob@gmail.com>
I2CBusIterator::external() was returning px4_i2c_bus_external(_bus),
where _bus is the constructor filter argument (the user's -b value,
which defaults to -1 when no bus is specified). When a driver was
started with -I and no -b (e.g. iis2mdc -I start, bmp388 -I start),
_bus stayed -1, px4_i2c_bus_external(-1) fell through to its "not
found" fallback that returns true, and the boot log printed
"on I2C bus 4 (external)" for sensors sitting on an internal bus.
Pass bus().bus instead so the result reflects the bus the iterator
is currently positioned on. This mirrors SPIBusIterator::external()
and restores the pre-8080ca966a8 semantics.
Device::external() (the override used by sensors status and
calibration) already used the device id's bus number, so only the
boot-time print was wrong.
Signed-off-by: Jacob Dahl <dahl.jakejacob@gmail.com>
* rt106x: Use platform SPI hal layer
* rt106x: Add romapi support and reboot to isp/bootloader
* bootloader: imxrt_common: Add rt106x support
* NXP MR-Tropic initial commit
* Add missing file for mr-tropic bootloader
* nxp-mr-tropic:Bootloader Alow Assertion debugging & Keep Ram Vectors
* nxp-mr-tropic: Firmware Boot from bootloader
* nxp-mr-tropic:Add Bootloader bin file
* mr-tropic: Update config and linker
Fixes enet issues with write-back and some code cleanup.
Furthermore increase NOR LittleFS to 256kB to reflect on linker
* Update NuttX
* mr-tropic: fix itcm apping and add mr-tropic to itcm check
---------
Co-authored-by: David Sidrane <David.Sidrane@NscDg.com>
* platforms: Serial new dedicated writeBlocking method
* finish writeBlocking()
* add back fsync
* updated posix, added string constant for port not open error
* format
* fix build
* remove fsync
* actually remove fsync
* remove fsync from write
* review feedback
---------
Co-authored-by: Jacob Dahl <dahl.jakejacob@gmail.com>
Co-authored-by: Jacob Dahl <37091262+dakejahl@users.noreply.github.com>