Commit graph

9334 commits

Author SHA1 Message Date
Daniel P. Carvalho
c78e4d69ea netutils/ptpd: Add egress latency compensation for TX timestamps.
The frame leaves the MAC later than the moment its hardware transmit
timestamp is latched, because of the clock domain crossing and the PHY.
This fixed delay is the egressLatency port parameter of IEEE 1588.

Add the configured latency to every hardware transmit timestamp
obtained through MSG_ERRQUEUE, the counterpart of the ingress
compensation.

- Add CONFIG_NETUTILS_PTPD_EGRESS_LATENCY_NS (default 0, which applies
  no compensation).
- Add the -O option to override it at run time.
- Add egress_latency_ns to struct ptpd_config_s.

Software timestamps are not affected.

Assisted-by: Claude:claude-sonnet-5
Signed-off-by: Daniel P. Carvalho <danieloak@gmail.com>
2026-09-24 11:07:31 +08:00
Daniel P. Carvalho
dd35d76edd netutils/ptpd: Retrieve hardware TX timestamps via MSG_ERRQUEUE.
Timestamp transmitted event messages with the hardware clock instead of
reading the clock after sendmsg() returns.

When hardware timestamping is selected on an AF_PACKET socket, request
SOF_TIMESTAMPING_TX_HARDWARE for each event message, wait for the
looped-back packet on the error queue with MSG_ERRQUEUE, and take the
timestamp from its SO_TIMESTAMPING control message, as on Linux. Sync,
Delay_Req and Pdelay_Req get their real departure time.

- Use a transmit socket of its own, separate from the event socket, so
  the error queue is not shared with received packets.
- Handle POLLERR separately from POLLIN in the main loop and drain all
  pending packets on each wakeup.
- If the timestamp does not arrive, fall back to a software timestamp
  taken before the frame is sent. After three consecutive failures the
  driver is assumed not to provide hardware transmit timestamps, a
  warning is printed once and only software timestamps are used, so a
  driver without support does not stall the daemon.
- Take the software timestamp before sending in every mode. It used to
  be taken after sendmsg() returned, so a fast peer's reply could appear
  to arrive before the request had left and give a negative delay.
- Accept a measured path delay down to -100 microseconds and clamp it to
  zero, since hardware timestamps on both ends can make a short link
  measure slightly negative.

Assisted-by: Claude:claude-sonnet-5
Signed-off-by: Daniel P. Carvalho <danieloak@gmail.com>
2026-09-24 11:07:31 +08:00
Daniel P. Carvalho
3727812c22 netutils/ptpd: Discard outlier Sync phase error samples.
A single Sync sample whose receive timestamp was taken late, for
example because the task was scheduled late with software
timestamping, was fed straight into the phase correction and the
drift estimate, and could pull the clock away from the master.

- Add CONFIG_NETUTILS_PTPD_OUTLIER_THRESHOLD_NS (default 0, which
  disables the check). A phase error that differs by more than this
  many nanoseconds from the median of the last five accepted samples
  is discarded, with a warning.
- Accept the sample after eight consecutive rejections and restart
  the history from it, so that a real step of the master is still
  followed while a short burst of disturbed samples is ridden out.
- Restart the history whenever the clock is stepped, since the old
  samples no longer describe the new time base.
- With the default of 0 the behaviour is unchanged.

Signed-off-by: Daniel P. Carvalho <danieloak@gmail.com>
Assisted-by: Claude:claude-sonnet-5
2026-09-24 11:07:31 +08:00
Daniel P. Carvalho
8940f6b0d4 netutils/ptpd: retain in-memory IPC for CONFIG_BUILD_FLAT in ptpd_status()
PR #3789 replaced the in-memory sigqueue + shared memory IPC in ptpd_status()
with file-based IPC to support Protected and Kernel modes across address
spaces. However, on microcontrollers running CONFIG_BUILD_FLAT, a filesystem
or /tmp (TMPFS) is rarely mounted or available, causing ptpd_status() to fail
with -ETIMEDOUT (errno 110) because the status file cannot be created.

Retain the file-based IPC for !CONFIG_BUILD_FLAT (Protected and Kernel modes)
while restoring the zero-overhead in-memory sigqueue + semaphore IPC for
CONFIG_BUILD_FLAT. Both modes share the status serialization logic via
ptp_populate_status() and support all fields including P2P.

Assisted-by: Gemini:gemini-3.8-flash-medium
Signed-off-by: Daniel P. Carvalho <danieloak@gmail.com>
2026-09-24 11:07:31 +08:00
Daniel P. Carvalho
585db4b657 netutils/ptpd: Add ingress latency compensation for RX timestamps.
The MAC latches a hardware receive timestamp later than the frame
reaches the wire, because of the PHY and the clock domain crossing.
This fixed delay is the ingressLatency port parameter of IEEE 1588 and
shows up as a constant phase error between the local and the master
clock.

Subtract the configured latency from every hardware receive timestamp
in ptp_getrxtime(), the single place where they enter the daemon, so
Sync, Delay_Resp and the peer delay messages are all corrected.

- Add CONFIG_NETUTILS_PTPD_INGRESS_LATENCY_NS (default 0, which applies
  no compensation).
- Add the -I option to override it at run time.
- Add ingress_latency_ns to struct ptpd_config_s.

Software timestamps are not affected.

Assisted-by: Claude:claude-sonnet-5
Signed-off-by: Daniel P. Carvalho <danieloak@gmail.com>
2026-09-24 11:07:31 +08:00
Daniel P. Carvalho
6d10b44bc1 netutils/ptpd: phase-lock hardware clock via POSIX clock_adjtime.
When state->clockid is configured to a hardware PTP clock device
(e.g., /dev/ptp0) instead of CLOCK_REALTIME, ptp_adjtime() previously
passed only the measured frequency drift (-ppb) to clock_adjtime(),
ignoring the residual phase offset (delta_ns / adjustment_ns).
As a result, while the hardware counter tracked frequency, its phase
was never pulled into alignment with the master clock.

Convert delta_ns (which combines frequency drift and current phase error
clamped to max_adjust_ns) to ppb over CONFIG_CLOCK_ADJTIME_PERIOD_MS,
acting as a proportional-integral (PI) phase servo. This drives the
hardware clock to phase lock with the master via POSIX clock_adjtime()
using ADJ_FREQUENCY without requiring proprietary ioctl calls.

Assisted-by: Claude:claude-sonnet-5
Assisted-by: Gemini:gemini-3.8-flash-medium
Signed-off-by: Daniel P. Carvalho <danieloak@gmail.com>
2026-09-24 11:07:31 +08:00
Daniel P. Carvalho
e8fa49dc72 netutils/ptpd: discard implausible drift-rate samples before averaging
A single drift-rate sample computed between two consecutive sync
updates was clamped against CLOCK_ADJTIME_SLEWLIMIT_PPM - the
hardware's slew-rate safety limit, not a bound on how large a real
crystal-oscillator drift measurement can plausibly be. An abnormally
short or long measurement interval (e.g. right after a clock
source outage/reconnect, or a burst of closely spaced sync packets
following packet loss) could therefore produce a wildly implausible
sample that still passed the check and corrupted the long-term
drift_ppb average.

Add CONFIG_NETUTILS_PTPD_MAX_DRIFT_PPB (default 500000, well above
any real crystal's few-hundred-ppm drift) as a dedicated plausibility
bound, intentionally much tighter than CLOCK_ADJTIME_SLEWLIMIT_PPM.
A sample outside this bound is discarded and the previous averaged
drift_ppb is kept unchanged instead of being corrupted.

Assisted-by: Claude:claude-sonnet-5
Signed-off-by: Daniel P. Carvalho <danieloak@gmail.com>
2026-09-24 11:07:31 +08:00
Daniel P. Carvalho
6d6ab39939 netutils/ptpd: Implement IEEE 1588 peer-to-peer (P2P) delay mechanism.
Implements the Peer-to-Peer (P2P) transparent clock delay measurement
mechanism (IEEE 1588-2008 §11.4 / IEEE 802.1AS / IEC/IEEE 61850-9-3)
in apps/netutils/ptpd:

- Add PTP_MSGTYPE_PDELAY_REQ, PTP_MSGTYPE_PDELAY_RESP, and
  PTP_MSGTYPE_PDELAY_RESP_FOLLOW_UP definitions and structs in ptpv2.h.
- Define IEEE 1588-2008 Annex F peer delay multicast MAC address
  01:80:c2:00:00:0e and Annex D peer delay IP address 224.0.0.107.
- Replace bool delay_e2e with enum ptp_delay_mechanism_e (PTP_DELAY_NONE,
  PTP_DELAY_E2E, PTP_DELAY_P2P) in include/netutils/ptpd.h.
- Add -P CLI option in system/ptpd/ptpd_main.c with mutual exclusion
  check against -E, and display last_transmitted_pdelayreq in status.
- Implement responder logic in ptp_process_pdelay_req() sending
  Pdelay_Resp (t2) and Pdelay_Resp_Follow_Up (t3) regardless of master
  or slave state.
- Implement requester logic in ptp_send_pdelay_req() gated on the
  physical link without requiring prior BMCA master selection.
- Implement ptp_process_pdelay_resp() and
  ptp_process_pdelay_resp_followup() using canonical mean path delay
  formula ((t4 - t1) - (t3 - t2)) / 2.
- Refactor path delay bounds checking and moving average filter into
  ptp_record_path_delay() shared across E2E and P2P mechanisms.
- Set PTP version 2.0 and controlField 0x05 in Pdelay_Req, Pdelay_Resp
  and Pdelay_Resp_Follow_Up, and in the own-identity header, so that
  peers such as linuxptp accept the messages.
- Clear pdelay_waiting_followup when a new Pdelay_Req is sent, so an
  orphaned Pdelay_Resp_Follow_Up from an abandoned cycle is not paired
  with stale timestamps.
- Warn at startup when P2P is selected without CONFIG_SCHED_TICKLESS,
  since a tick-driven clock cannot resolve the peer delay.
- Skip IP multicast join/leave handling for AF_PACKET.

Assisted-by: Claude:claude-sonnet-5
Assisted-by: Gemini:gemini-3.8-flash-medium
Signed-off-by: Daniel P. Carvalho <danieloak@gmail.com>
2026-09-24 11:07:31 +08:00
Daniel P. Carvalho
7c4ea1dbff netutils/ptpd: Fix Delay_Resp consumption by sendmsg.
ptp_sendmsg() called a blocking recvmsg(state->tx_socket, ...) right
after sending a Delay_Req whenever hardware_ts was set, assuming a
Linux-style MSG_ERRQUEUE/loopback semantics NuttX does not have.
Since tx_socket and event_socket share the same underlying
connection, this call instead blocked on and consumed whatever PTP
packet arrived next on the wire — almost always the Delay_Resp,
which typically arrives within milliseconds of the request. Its
payload was read into a local buffer that went out of scope on
return, so the packet never reached ptp_process_rx_packet() and
path_delay_ns stayed at 0 in -H mode. t3 is now captured locally
via ptp_gettime(), the same way -S mode already did, until
hardware TX timestamping is supported.

Also replaces the path delay heuristic in ptp_process_delay_resp()
(which derived an approximation of (t2-t1) from path_delay_ns and
last_delta_ns, only valid once the clock had already converged) with
the canonical IEEE 1588-2008 §11.3 formula: store (t2-t1) directly
from Sync/Follow_Up as sync_diff_ns, then average it with (t4-t3)
from the Delay_Req/Delay_Resp exchange. Relaxes the path delay
ceiling to 10ms unconditionally, since Delay_Req's t3 is software-
timestamped in both modes until hardware TX timestamping is supported.

Assisted-by: Claude:claude-sonnet-5
Assisted-by: Gemini:gemini-3.8-flash-medium
Signed-off-by: Daniel P. Carvalho <danieloak@gmail.com>
2026-09-24 11:07:31 +08:00
hanzhijian
46e148db09 testing/ostest: add strto base tests
Add regression coverage for integer conversions with explicit bases from 2 through 36.  Exercise lower- and upper-case digits, positional values, all six strto* interfaces, end pointers, errno, and the invalid range boundaries.

The tests fail at base 27 without apache/nuttx#19594 and pass with the corresponding libc fix.

Signed-off-by: hanzhijian <hanzhijian@zepp.com>
2026-09-23 15:37:09 +08:00
aviralgarg05
922cf59799 games/NXDoom: support RGB565 and loadable modules
Add RGB565 framebuffer output and module builds. Harden configuration parsing and renderer bounds, support supervised SIGTERM shutdown, and notify framebuffer drivers after drawing.

Assisted-by: Codex:gpt-5
Signed-off-by: aviralgarg05 <gargaviral99@gmail.com>
2026-09-22 14:17:01 -03:00
Felipe Moura
34ca2a5ed8 system/uorb: bump listener stack when float print extension is on
uorb_listener's %pB debug printing (orb_info() -> lib_bsprintf()) does
real floating-point-to-string conversion synchronously, in the
listener's own task -- not a lightweight pointer dump. With
CONFIG_LIBC_PRINT_EXTENSION off, %pB just prints a raw pointer and the
default CONFIG_UORB_STACKSIZE (DEFAULT_TASK_STACKSIZE, 2048 on most
configs) is plenty. With it on, decoding a topic's float fields through
this path silently overflows a 2048-byte stack -- confirmed on real
hardware (ESP32-S3, one push every ~10-20ms from two subscribed
topics): uorb_listener hangs completely after printing only a partial
topic name, no panic, no stack dump, nothing -- because
CONFIG_SCHED_STACKGUARD/CONFIG_STACK_COLORATION aren't on by default
either, so there's no guard to catch the overflow before it corrupts
adjacent memory.

Raising the default only when CONFIG_LIBC_PRINT_EXTENSION is set (not
unconditionally, and not keyed off CONFIG_DEBUG_UORB specifically,
since anything else that selects the same libc extension hits the same
path) keeps the common case -- raw pointer output, small stack --
exactly as before, and only pays for the extra stack when the feature
that needs it is actually enabled.

4096 was verified sufficient (tested against 2048, which reproduces
the hang, and 8192, which also works but wastes RAM); reproduced
cleanly across multiple fresh boots.

Note: this default only applies when CONFIG_UORB_STACKSIZE has never
been explicitly recorded in .config. Like any Kconfig int default,
flipping CONFIG_LIBC_PRINT_EXTENSION on in an existing .config that
already has an explicit CONFIG_UORB_STACKSIZE value won't retroactively
raise it; the value has to be re-picked (e.g. via a fresh olddefconfig
after removing the stale line, or manually).

Signed-off-by: Felipe Moura <moura.fmo@gmail.com>
2026-09-22 14:44:19 +08:00
Abhishek Mishra
546bbd21d7 mlearning/tflite-micro: use the same compile flags in Make and CMake
Define TF_LITE_STATIC_MEMORY and TFLITE_EMULATE_FLOAT in both build
systems. Drop the CMake-only -O3 so optimization follows NuttX
Kconfig, and remove the duplicate CMSIS_NN define, KissFFT include,
and non-English comment.

Signed-off-by: Abhishek Mishra <mishra.abhishek2808@gmail.com>
2026-09-22 14:43:45 +08:00
Matteo Golin
83955c8dbe examples/nimble: Use ble_hs_adv_fields instead
This removes the less readable way of setting advertising parameters and
replaces it with the more readable `ble_gap_adv_set_fields` struct. This
also resolves the bug where the value in `g_gap_name` appeared truncated
on devices discovering the advertisement. Now the full string appears in
discovery.

Signed-off-by: Matteo Golin <matteo.golin@gmail.com>
2026-09-22 13:27:05 +08:00
Matteo Golin
d7fa4d1d5b bluetooth/nimble: Allow DIS service options to be changed
This allows NuttX users to configure the NimBLE built-in DIS service
options that are only available at compile-time. Now all the
characteristics can be used if desired. The default Kconfig values match
the original definitions, so there is no change in behaviour.

Signed-off-by: Matteo Golin <matteo.golin@gmail.com>
2026-09-22 13:27:05 +08:00
Jorge Guzman
ee20ddd0ba system/zbus: Port the Zephyr zbus message bus to NuttX
Port of the Zephyr RTOS zbus (many-to-many message bus with typed
channels and decoupled observers), built entirely on native NuttX
primitives and preserving the original declarative API
(ZBUS_CHAN_DEFINE, ZBUS_LISTENER_DEFINE, ZBUS_SUBSCRIBER_DEFINE, ...).

Features: listeners (synchronous callbacks), subscribers (queue of
channel references), message subscribers (ordered message copies),
async listeners (callback on a dedicated task), runtime observers,
per-observation notification masks, observer enable/disable, message
validators, channel user data, publish statistics, lookup by
name/numeric id and channel/observer iteration.

Mapping to NuttX primitives:
- Channel/observer registration: link-time iterable sections
  (include/nuttx/iterable_sections.h); the observers of a channel are
  named after their position in the definition, so the linker sorts the
  notification order, and the declarative macros are built on
  nuttx/macro.h (CONCATENATE, FOREACH_ARG and the FOREACH_IDX_ARG added
  in a companion nuttx commit) rather than on a private macro engine.
  Notification masks live in .bss with their initial value preserved in
  ROM and applied on lazy init.
- Channel lock: sem_t (enable CONFIG_PRIORITY_INHERITANCE instead of
  the Zephyr priority-boost/HLP); timeouts are computed with the
  clock_timespec_* helpers from nuttx/clock.h.
- Subscriber queues: kernel message queues (file_mq_*) opened lazily
  via pthread_once, usable from any task; mq payload copying replaces
  the Zephyr net_buf machinery entirely.
- Async listeners: one task per listener (task_create, priority and
  stack size configurable) blocking on the listener queue; a task
  rather than a pthread so it outlives the first API caller.
- Timeouts: milliseconds with CLOCK_MONOTONIC deadlines
  (ZBUS_NO_WAIT/ZBUS_FOREVER).

Includes a runnable example (examples/zbus, CONFIG_EXAMPLES_ZBUS) and a
cmocka test suite (testing/zbus, CONFIG_TESTING_ZBUS) covering the full
API: 17/17 tests passing on linum-stm32h753bi hardware, including
multi-channel index grouping, mask semantics, runtime observer error
paths, notification order (the observers of a channel run in the order
they are listed, and an observation bound with ZBUS_CHAN_ADD_OBS() runs
after all of them), queue overflow/timeout semantics, async listener
bursts,
bit-exact float/double payload delivery across every observer type
(sensor-style messages with a float-math validator) and an
interrupt-driven publisher (kernel timer interrupt -> signal -> sampling
thread -> zbus_chan_pub, the recommended pattern for interrupt sources).

Requirements: FLAT build; CONFIG_MQ_MAXMSGSIZE >= pointer size +
CONFIG_ZBUS_MSG_SUBSCRIBER_MAX_MSG_SIZE for message subscribers; board
linker script including <nuttx/linker/common-rom.ld> or the generic
CONFIG_ITERABLE_SECTIONS_LINKER_INSERT mode.

Not ported: multi-domain proxy agent (experimental upstream); publishing
from interrupt handlers (userspace library: hand the data to a thread).

Documentation lives in the nuttx repository
(Documentation/applications/system/zbus).

Assisted-by: Claude Code
Signed-off-by: Jorge Guzman <jorge.gzm@gmail.com>
2026-09-21 18:46:31 -03:00
wenquan1
11124141cb testing/nettest: add SO_TIMESTAMPING cmocka test
Add cmocka-based test program for SO_TIMESTAMPING socket option
under testing/nettest/timestamp/. Covers all five test scenarios
from the SO_TIMESTAMPING PR (apache/nuttx#20161):

1. SO_TIMESTAMPING setsockopt/getsockopt
2. SO_TIMESTAMP/SO_TIMESTAMPNS backward compatibility
3. TX timestamping + MSG_ERRQUEUE delivery
4. RX timestamp via SO_TIMESTAMP
5. TX timestamping with poll(POLLPRI) notification

Enable with CONFIG_TESTING_NET_TIMESTAMP=y (requires
CONFIG_NET_TIMESTAMP, CONFIG_NET_PKT, CONFIG_TESTING_CMOCKA).

Tested on sim:dynconns — all 5 tests pass.

Signed-off-by: wenquan1 <wenquan1@xiaomi.com>
2026-09-21 16:26:06 +08:00
Justin Hammond
41a2c9d982 system/uorb: Select the printf extension the format strings need.
Every topic's format string is printed through orb_info() or
orb_fprintf(), and both reach the data through "%pB", which is a NuttX
extension rather than a standard conversion.  UORB_FORMAT turns that
code on without turning the extension on, so a configuration that
enables the listener but not the debug output builds cleanly, runs, and
prints a pointer where the reading should be:

  sensor_voltage(now:4294968998000):0xc0203c98B

The address is the va_format the extension was supposed to expand, and
the trailing B is the conversion character being taken as ordinary
text.  Nothing warns, because to the compiler and to printf this is a
valid format string that means something else.

DEBUG_UORB already selects the extension, so the fault is invisible to
anyone who turned that on.  The two are independent options and only
one of them declared what it needed.  Move the select onto UORB_FORMAT,
which is the option that decides whether the format strings are
compiled in at all.

Signed-off-by: Justin Hammond <justin@dynam.ac>
2026-09-20 22:30:19 +08:00
Justin Hammond
3cfb129dbf system/sensortest: Put a blank line after the declarations.
Each of the ten print helpers opens with a declaration followed
immediately by its printf, which nxstyle reports as an error on every
one of them.  The file cannot be checked cleanly until they are fixed,
so a later change to it starts from a failing run and has to sort its
own errors from the existing ones.

Whitespace only.  git diff -w is empty.

Signed-off-by: Justin Hammond <justin@dynam.ac>
2026-09-20 09:24:47 -04:00
Justin Hammond
6d45e5404d system/sensortest: Add rows for the voltage, current and power topics.
The three electrical topics exist and publish, but sensortest rejects
their node names before opening them: its table is matched by name and
carries each structure's size, so a type without a row is one the tool
cannot read at all.

All three are a timestamp and a single value, the shape print_valf
already handles.

Signed-off-by: Justin Hammond <justin@dynam.ac>
2026-09-20 09:24:47 -04:00
Felipe Moura
0e2e851f50 fsutils/libtinycbor: fix build on picolibc/newlib
CONFIG_FSUTILS_TINYCBOR_LIB fails to build on toolchains with their own
<memory.h> (picolibc, newlib): cbortojson.c does "#include <memory.h>"
meaning TinyCBOR's own (where cbor_malloc/cbor_realloc/cbor_free are
declared), but only the parent directory was on the include path, so
the toolchain's own <memory.h> wins instead, leaving those symbols
implicitly declared.

Fix: also put the unpacked tinycbor/ subdirectory (Make.defs' own
TINYCBOR_UNPACKNAME) on the include path.

Signed-off-by: Felipe Moura <moura.fmo@gmail.com>
Assisted-by: Claude:claude-sonnet-5
2026-09-18 21:24:16 +08:00
Arnav Sharma
b6bb99c951 testing/drivertest: add sensor watchdog regression test.
Issue apache/nuttx#20145 reported a sensor fetch-watchdog lifetime
regression: sensor_poll() arms a per-subscriber watchdog for
fetch-only sensors with a finite interval, but sensor_close()
freed the subscriber without cancelling it, letting
sensor_fetch_expired() run after free.

Fixed by apache/nuttx#20146, which cancels the watchdog on close.
Add regression coverage in drivertest as suggested by the maintainer:
open a sensor device, set a finite fetch interval, enter the poll
path so the watchdog can be armed, then close while the watchdog
state is relevant. Sleep past the interval so any stray timer would
fire, and reopen to prove teardown was clean. The test skips
gracefully when no sensor device is present, so it is safe on sim
without hardware.

The test does not deterministically reproduce the UAF; it verifies
the observable invariant that repeated poll/close/reopen cycles
complete cleanly and the device remains usable. Under KASAN or
stress, a missing wd_cancel in close would be caught here.

Impact:
* Is new feature added? YES (new regression test coverage in
  testing/drivers/drivertest, no existing functionality changed).
* Impact on user, build, hardware, documentation, security,
  compatibility? NO, test-only change.

Testing:
* Full build and runtime logs are provided in the PR description.

Assisted-by: Muse Spark:muse-spark-1.3
Assisted-by: Claude:claude-opus
Signed-off-by: Arnav Sharma <2006arnavsharma@gmail.com>
2026-09-18 21:10:56 +08:00
wenquan1
6e12c3de75 canutils/candump: guard SOF_TIMESTAMPING macros with ifndef
candump.c locally defines SOF_TIMESTAMPING_SOFTWARE,
SOF_TIMESTAMPING_RX_SOFTWARE and SOF_TIMESTAMPING_RAW_HARDWARE.
After nuttx added these macros to sys/socket.h, the build fails
with -Werror=redefine. Wrap the local defines with #ifndef guards
so they are only used when the system header does not provide them.

Signed-off-by: wenquan1 <wenquan1@xiaomi.com>
2026-09-18 21:09:13 +08:00
wenquan1
e3e3933138 netutils/ptpd: use status file for ptpd_status IPC
Replace the sigqueue + shared-memory IPC mechanism in ptpd_status()
with a file-based approach:

  - Daemon side: on SIGUSR1, write a binary ptpd_status_s struct to
    a temp file and atomically rename it to the status path.
  - Client side: send kill(SIGUSR1), poll for the file to appear,
    then read the struct back.

This removes the CONFIG_BUILD_FLAT restriction (the old code returned
-ENOTSUP for Protected and Kernel builds) and avoids passing pointers
across address spaces via sigqueue.  The status file path is
configurable via NETUTILS_PTPD_STATUSFILE (default /tmp/ptpd.status).

The atomic temp + rename pattern ensures readers never see a partial
write.

Signed-off-by: wenquan1 <wenquan1@xiaomi.com>
2026-09-18 17:00:03 +08:00
wenquan1
4210b2226e netutils/ptpd: move multicast join after interface address query
The IGMP multicast join (ipmsfilter) was previously called before
the interface address (interface_addr) was populated via SIOCGIFADDR.
This meant the IGMP join had to locate the network device without
a valid local address, which could fail or join on the wrong interface.

Move the multicast group subscription to after the interface address
is queried, and guard it with an AF_INET check since IGMP only applies
to IPv4. This ensures the IGMP join can always locate the correct
network device.

Signed-off-by: wenquan1 <wenquan1@xiaomi.com>
2026-09-18 17:00:03 +08:00
Arnav Sharma
642720e9b4 examples/configdata: exercise unregister/register lifetime
Add a regression test for apache/nuttx#20166 to the configdata
example, which runs automatically in every sim:configdata build.
After the normal configdata test loops, close the long-lived
descriptor and run a full lifetime cycle on /dev/config:

- mtdconfig_unregister() must succeed,
- the unregistered device must no longer be openable (ENOENT),
- the same MTD device must be registerable again and usable,
- a final unregister must succeed, leaving the device unregistered.

Before the driver fix this crashes deterministically: the old
mtdconfig_unregister_by_path() freed the private device structure
before closing its temporary file, so the subsequent open() faults
in mm_malloc on the corrupted heap (SIGSEGV observed on sim right
after unregister returns).  With the fix the whole example,
934706/934706 checks included, completes cleanly.

The test uses only generic configdata APIs, so it also passes
unchanged under CONFIG_MTD_CONFIG_NVS, whose open/close callbacks
are no-ops.

Assisted-by: Claude:claude-opus
Signed-off-by: Arnav Sharma <2006arnavsharma@gmail.com>
2026-09-18 16:35:34 +08:00
raiden00pl
73a9c9a697 testing/ostest: accept -ENOENT from work_cancel() for unqueued work
Since nuttx commit 5a209a853e ("sched/wqueue: restore -ENOENT from
work_cancel() for unqueued work") work_cancel() and work_cancel_wq()
return -ENOENT when the work is not queued. The tester thread queues
work with zero delay, so the worker may already have consumed it by the
time it is cancelled and the ASSERT(ret == OK) fires;

Accept -ENOENT there and expect it when cancelling idle work in
the API validation test.

Signed-off-by: raiden00pl <raiden00@railab.me>
2026-09-17 09:40:21 -03:00
fangpeina
2f76986584 system/fastboot: fix pre-existing nxstyle warnings
Add missing blank lines after variable declarations and fix
alignment in preprocessor conditionals. These are pre-existing
style issues exposed by the latest nxstyle version.

Signed-off-by: fangpeina <fangpeina@xiaomi.com>
2026-09-16 00:09:34 +08:00
fangpeina
3b993dfbb6 system/fastboot: Add serial (UART) transport backend.
Add a serial transport alongside the existing USB and TCP backends.
The serial backend reuses the TCP v1 wire framing (FB01 handshake
plus an 8-byte big-endian length prefix) so the host side needs no
new tool: socat bridges the UART to a TCP socket and the standard
fastboot tool connects via tcp:.

The serial port path is configured at build time through Kconfig
SYSTEM_FASTBOOTD_SERIAL_PORT.

Signed-off-by: fangpeina <fangpeina@xiaomi.com>
2026-09-16 00:09:34 +08:00
fangpeina
43dcb51087 system/fastboot: extract framed_read helper and simplify tcp_read
Extract fastboot_framed_read() that handles TCP v1 wire framing:
handshake detection (FB01 exchange) and 8-byte big-endian length
prefix parsing.  Simplify fastboot_tcp_read() to reuse this helper
for both initial handshake and subsequent data frames.

This prepares for adding a serial transport that shares the same
framed protocol.

Signed-off-by: fangpeina <fangpeina@xiaomi.com>
2026-09-16 00:09:34 +08:00
fangpeina
bac662c215 system/fastboot: add per-transport Kconfig options for USB and TCP
Add SYSTEM_FASTBOOTD_USB (default y) and SYSTEM_FASTBOOTD_TCP
(default y) to allow disabling individual transports independently.

Replace direct CONFIG_USBFASTBOOT / CONFIG_NET_TCP guards in the
transport code with the new fastbootd-level Kconfig symbols.

Signed-off-by: fangpeina <fangpeina@xiaomi.com>
2026-09-16 00:09:34 +08:00
fangpeina
06ceed1afb system/fastboot: fix buffer pointer and length in fastboot_read_all
The read loop was passing the original buf pointer and full length on
every iteration, causing subsequent reads to overwrite previous data
and potentially request more bytes than the remaining buffer space.

Update buf and len after each successful read to advance through the
buffer correctly.

Signed-off-by: fangpeina <fangpeina@xiaomi.com>
2026-09-16 00:09:34 +08:00
wangjianyu3
2085e1ca96 system/nxinit: add fallback option to resolve preset service conflict
The preset kvdb service defined in parser.c conflicts with user-defined
kvdb service in board-level init.rc, causing:

  Error redefined service 'kvdb'

Add SVC_FALLBACK flag and fallback service option. When a service
is marked as fallback, it will be silently ignored if another
service with the same name already exists. This is the semantic
opposite of override:

- override: new definition replaces old
- fallback: new definition yields to old
- old has fallback + new arrives: old yields to new

If neither flag is set, duplicate service names still produce
EEXIST error as before.

Mark the preset kvdb service as fallback so that board-specific
init.rc can freely define its own kvdb service without conflict.

Signed-off-by: wangjianyu3 <wangjianyu3@xiaomi.com>
2026-09-16 00:08:45 +08:00
wangjianyu3
5f7db152b2 system/nxinit: fix rptun builtin blocking the action queue
RPTUNIOC_START returns the (positive) pid of the rptun kernel thread
in async mode (CONFIG_RPTUN_START_SYNC unset). The action engine
treats any positive builtin return value as the pid of a spawned
child and waitpid()s on it (action.c: "if (ret > 0) pid_running =
ret"). The rptun thread is a detached kthread, never a child of init,
so that wait blocks the whole action queue forever and "on init" /
console never run. Normalize a successful start to 0.

Assisted-by: OpenCode:claude-sonnet-5
Signed-off-by: wangjianyu3 <wangjianyu3@xiaomi.com>
2026-09-16 00:08:45 +08:00
wangyongrong
64f65dbf3d system/nxinit: add rptun and unlink builtin commands
BL uses init framework (not NSH), so the NSH rptun command is not
available. Add rptun as an init builtin command that supports
start and stop subcommands. Also add a generic unlink builtin
command for removing device nodes.

Usage in init.bl.rc:
  rptun stop /dev/rptun/corecs
  unlink /dev/rptun/corecs
  rptun start /dev/rptun/corecs

- rptun start/stop: open device, ioctl(RPTUNIOC_START/STOP), close
- unlink: generic command to unlink any file/device node

Signed-off-by: wangyongrong <wangyongrong@xiaomi.com>
2026-09-16 00:08:45 +08:00
wangjianyu3
04ee0d45ef system/nxinit: use TRACE_DEVERROR_BIT|TRACE_CLSERROR_BIT, not TRACE_BITSET
usbtrace_enable(TRACE_BITSET) was copied from nsh's CONFIG_USBDEV_TRACE
block without also copying nsh's local #define TRACE_BITSET or the
<nuttx/usb/usbdev_trace.h> include it needs. TRACE_BITSET has no
built-in definition; every other CONFIG_USBDEV_TRACE caller in the
tree (nsh, composite, cdcacm, usbmsc) defines its own. This compiled
fine as long as CONFIG_SYSTEM_NXINIT and CONFIG_USBDEV_TRACE were never
both on for the same board; the two combined for the first time and
init.c failed to build with 'TRACE_BITSET' undeclared.

Add the missing include and inline the same error-only bitset those
other callers fall back to when none of their granular trace options
are enabled, since this file has no such granular Kconfig of its own.

Assisted-by: OpenCode:claude-sonnet-5
Signed-off-by: wangjianyu3 <wangjianyu3@xiaomi.com>
2026-09-16 00:08:22 +08:00
DuoYuWang
1c0a812377 testing/ostest: exercise custom work queues
Add a focused wqueue entry that exercises predefined and dynamically
created work queues without changing the no-argument ostest flow.

Share the semaphore wait and basic worker helpers across configurations.
Flat builds exercise scheduler queues, Protected builds exercise USRWORK,
and pthread-enabled builds additionally cover configurable custom worker
pools. When pthread support is disabled, only predefined USRWORK cases are
compiled.

Cover invalid arguments, priority lookup, immediate and delayed work,
pending replacement and cancellation, periodic requeue, synchronous and
parallel cancellation, concurrent queues, callback self-destruction, and
queue teardown.

Assisted-by: Codex:GPT-5
Signed-off-by: DuoYuWang <thirteenking.wang@gmail.com>
2026-09-16 00:07:51 +08:00
Felix-LJY
61143782d4 benchmarks/sd_bench: Fix sd_bench in CMake build system.
Fix sd_bench in CMake build system.

Signed-off-by: JingYue LIAO <felix-liao@my.swjtu.edu.cn>
2026-09-15 21:43:29 +08:00
wangjianyu3
c8ffe2a5e1 system/nxinit: add CONFIG_SYSTEM_NXINIT_STDOUT for printf-based log output
Syslog may be output via services such as DFX. When debugging the init
component (e.g., service startup failures, including DFX-related
exceptions), syslog may not be output properly.

Add a debug Kconfig option SYSTEM_NXINIT_STDOUT that redirects all init
log macros (init_debug/info/warn/err) to printf instead of syslog.
This is useful for early boot debugging when syslog is not yet
available or serial console shows no output.

Introduce init_log_output() macro as the common log backend, selected
at compile time between printf (with appended newline) and syslog.

Signed-off-by: wangjianyu3 <wangjianyu3@xiaomi.com>
2026-09-15 09:17:06 -03:00
Junbo Zheng
2968b2c587 monkey: add missing blank lines after declarations
The nxstyle check on CI flagged three spots in monkey_main.c where a
declaration block runs directly into the following statement. Insert a
blank line after the declarations at each location; no logic change.

Fixes the Check job failure on PR #3784:
https://github.com/apache/nuttx-apps/actions/runs/34935981535/job/104273851956?pr=3784

Before:
```
graphics/input/monkey/monkey_main.c:223:2: error: Missing blank line after declarations
graphics/input/monkey/monkey_main.c:363:2: error: Missing blank line after declarations
graphics/input/monkey/monkey_main.c:526:6: error: Missing blank line after declarations
```

After:
```
nxstyle monkey_main.c -> exit 0
```

Assisted-by: Claude Code (GLM-5.3) <claude@anthropic.com>
Signed-off-by: Junbo Zheng <zhengjunbo1@xiaomi.com>
2026-09-15 09:16:23 -03:00
Junbo Zheng
6e79ea2d85 monkey: block SIGTERM and consume it in sigtimedwait() for a clean exit
Block SIGTERM at startup and add it to the sigtimedwait() set in
monkey_wait(): a blocked signal is never swallowed by the handler, it
either wakes the in-progress wait or stays pending on the task until
the next sigtimedwait() returns it immediately, so the exit through
the regular monkey_delete() cleanup path is deterministic. Because
the kernel keeps the signal mask and pending queue per task, sibling
monkey instances (e.g. multiple instances started for different
input devices) each stop independently, and no shared state is
involved.

Also add a signal_handler() that logs the received signal and
register it for SIGTSTP/SIGCONT/SIGTERM, so these signals never fall
back to their default actions and stay consumable by sigtimedwait()
/ sigwaitinfo().

Before:
kill -15 <pid> terminates the task via the default SIGTERM action
with no cleanup: no "monkey_delete: OK" is ever printed.

After:
kill -15 <pid> exits within one loop iteration (<= one event period,
100-500ms by default) via monkey_delete(), independently for each
running instance, and restarting monkey works.

Testing:

Built and verified on the NuttX simulator (host: Ubuntu 22.04):

  cmake -B build -DBOARD_CONFIG=sim:nsh -GNinja
  # enable in build/.config:
  #   CONFIG_INPUT=y
  #   CONFIG_GRAPHICS_INPUT_MONKEY=y
  #   CONFIG_NSH_MAXARGUMENTS=16
  ninja -C build olddefconfig && ninja -C build
  ./build/nuttx

Run in the nsh prompt (uinput injection mode):

  nsh> monkey -t 0x11 -p 100-300 -s 454x454 &   (uinput touch)
  nsh> monkey -t 0x12 -p 100-300 -s 454x454 -b 0 &  (uinput button)
  nsh> ps
  nsh> kill -15 <pid>

ps with both instances running (each monkey task shows "Waiting
Signal" with SIGMASK 0x8000, i.e. SIGTERM blocked while sitting in
sigtimedwait):

  TID   PID  PPID PRI POLICY   TYPE    NPX STATE    EVENT     SIGMASK            STACK COMMAND
    0     0     0   0 FIFO     Kthread   - Ready              0000000000000000 0069584 Idle_Task
    1     0     0 224 FIFO     Kthread   - Waiting  Semaphore 0000000000000000 0067456 sim_loop_wq 0x71204b2003f0 0x71204b200478
    2     0     0 224 FIFO     Kthread   - Waiting  Semaphore 0000000000000000 0067464 hpwork 0x40188860 0x401888e8
    4     4     0 100 FIFO     Task      - Waiting  Semaphore 0000000000000000 0067496 init_main
    9     9     4 100 FIFO     Task      - Running            0000000000000000 0067504 sh
   10    10     9 110 FIFO     Task      - Waiting  Signal    0000000000008000 0069472 monkey -t 0x11 -p 100-300 -s 454x454
   11    11     9 110 FIFO     Task      - Waiting  Signal    0000000000008000 0069448 monkey -t 0x12 -p 100-300 -s 454x454 -b 0

After "kill -15 10" (touch instance exits, button instance
unaffected):

  nsh> kill -15 10
  [monkey] monkey_wait: Recv sig: SIGTERM
  [monkey] monkey_delete: OK
  nsh> ps
  TID   PID  PPID PRI POLICY   TYPE    NPX STATE    EVENT     SIGMASK            STACK COMMAND
    0     0     0   0 FIFO     Kthread   - Ready              0000000000000000 0069584 Idle_Task
    1     0     0 224 FIFO     Kthread   - Waiting  Semaphore 0000000000000000 0067456 sim_loop_wq 0x71204b2003f0 0x71204b200478
    2     0     0 224 FIFO     Kthread   - Waiting  Semaphore 0000000000000000 0067464 hpwork 0x40188860 0x401888e8
    4     4     0 100 FIFO     Task      - Waiting  Semaphore 0000000000000000 0067496 init_main
    9     9     4 100 FIFO     Task      - Running            0000000000000000 0067504 sh
   11    11     9 110 FIFO     Task      - Waiting  Signal    0000000000008000 0069448 monkey -t 0x12 -p 100-300 -s 454x454 -b 0

After "kill -15 11" (second instance exits the same way, no monkey
task left):

  nsh> kill -15 11
  [monkey] monkey_wait: Recv sig: SIGTERM
  [monkey] monkey_delete: OK
  nsh> ps
  TID   PID  PPID PRI POLICY   TYPE    NPX STATE    EVENT     SIGMASK            STACK COMMAND
    0     0     0   0 FIFO     Kthread   - Ready              0000000000000000 0069584 Idle_Task
    1     0     0 224 FIFO     Kthread   - Waiting  Semaphore 0000000000000000 0067456 sim_loop_wq 0x71204b2003f0 0x71204b200478
    2     0     0 224 FIFO     Kthread   - Waiting  Semaphore 0000000000000000 0067464 hpwork 0x40188860 0x401888e8
    4     4     0 100 FIFO     Task      - Waiting  Semaphore 0000000000000000 0067496 init_main
    9     9     4 100 FIFO     Task      - Running            0000000000000000 0067504 sh

A new instance started after both kills (PID 12) runs normally and
is again stopped cleanly by kill -15.

Note: on the simulator the uinput devices register as /dev/utouch
and /dev/ubutton, while monkey opens /dev/input0 and /dev/buttons;
the run above used a local (uncommitted) path patch to work around
this. On a board where the device paths match, no patch is needed.

Assisted-by: Claude Code (glm-5.3) <claude@anthropic.com>
Signed-off-by: Junbo Zheng <zhengjunbo1@xiaomi.com>
2026-09-15 09:16:23 -03:00
lljwork2021
6284bdc50e system/xrcedds: add eProsima Micro XRCE-DDS
Add a lightweight Micro XRCE-DDS Client integration with UDP transport support and a publisher example.

Signed-off-by: lljwork2021 <lljwork2021@163.com>
2026-09-15 09:14:39 -03:00
Daniel P. Carvalho
9fdf62935b netutils/ptpd: add diagnostic logging for RX and Delay_Resp checks
Add ptpinfo()/ptpwarn() calls, gated by the existing
CONFIG_DEBUG_PTP_INFO/_WARN symbols (zero cost when disabled), at
points that previously failed silently: an unrecognized L2 protocol,
a domain mismatch, and a Delay_Resp rejected by the source/requester
identity check. These were essential to diagnosing the drift and
Delay_Req bugs fixed in the two preceding commits on real hardware,
and are kept for future maintainers debugging this path.

Assisted-by: Claude:claude-sonnet-5
Assisted-by: Gemini:gemini-3.8-flash-medium
Signed-off-by: Daniel P. Carvalho <danieloak@gmail.com>
2026-09-15 09:09:00 -03:00
Daniel P. Carvalho
32411a54ae netutils/ptpd: fix Delay_Req transmission over AF_PACKET
1. On AF_PACKET SOCK_RAW sockets in NuttX, msg_name must be NULL because
   the destination MAC address is already contained in the Ethernet header.
   Previously, passing sockaddr_in caused sendmsg() to fail immediately
   with -EAFNOSUPPORT, completely blocking transmission of Delay_Req.
2. Correct PTP primary multicast MAC address to 01:1b:19:00:00:00
   (IEEE 1588 Annex F) and ensure ether_type is in network byte order.
3. Initialize delayreq_interval to 1 second default and guard against 0.
4. Set logmessageinterval to 0x7f (IEEE 1588-2008 Table 23 sentinel for
   Delay_Req) instead of inheriting 0 from the announce header template.
5. Update PTP version to 0x12 (2.1, minorVersionPTP=1) to match the
   value used by mature implementations such as linuxptp.

Assisted-by: Claude:claude-sonnet-5
Assisted-by: Gemini:gemini-3.8-flash-medium
Signed-off-by: Daniel P. Carvalho <danieloak@gmail.com>
2026-09-15 09:09:00 -03:00
Daniel P. Carvalho
d9cb21d909 netutils/ptpd: fix drift divergence and post-jump bootstrap
1. Post-jump drift bootstrap: on the first Sync packet following a step
   jump, do not compute frequency drift against a synthesized zero delta,
   which previously caused the entire residual phase offset (~ms) to be
   mistaken for frequency drift (~million ppb) and immediately absorbed.
2. Drift rate formula: normalize the adjustment contribution by the actual
   measurement interval instead of the adjtime slew period, and compute
   natural delta rate as (delta - last_delta + last_adjtime) / interval.
3. Remove broken last_delta > delta comparison that prevented offsets from
   converging and applied inverted corrections on negative overshoots.
4. Correct ptp_adjtime() invocation to always pass adjustment_ns for
   CLOCK_REALTIME slewing rather than dropping drift compensation when
   delta exceeds threshold. Clamp adjustment_ns to the hardware slew limit
   so last_adjtime_ns accurately mirrors the true slew applied.
5. Enable Delay_Req in E2E mode once clock is tracking (not jumping) and
   allow software timestamping latency in ptp_process_delay_resp().
6. Propagate initialization return code from ptpd_start() and avoid
   unconditional failure print in do_ptpd_start().

Assisted-by: Claude:claude-sonnet-5
Assisted-by: Gemini:gemini-3.8-flash-medium
Signed-off-by: Daniel P. Carvalho <danieloak@gmail.com>
2026-09-15 09:09:00 -03:00
Daniel P. Carvalho
071074247b netutils/ptpd: fix BMCA compilation typos and define ETHERTYPE_PTP
- Fix typo state->conifg -> state->config in BMCA announce check.
- Fix typo state->n_identity -> state->own_identity in BMCA announce check.
- Define ETHERTYPE_PTP as 0x88f7 for IEEE 802.3 Layer 2 transport.

Assisted-by: Claude:claude-sonnet-5
Assisted-by: Gemini:gemini-3.8-flash-medium
Signed-off-by: Daniel P. Carvalho <danieloak@gmail.com>
2026-09-15 09:09:00 -03:00
Daniel P. Carvalho
72cf59b647 examples/comp: add comparator example tool
Add a dedicated NSH tool for testing and interacting with analog
comparator devices (/dev/comp*). Supports reading comparator output
state, enabling/disabling via IOCTL, and performing an automated voltage
ramp sweep using a DAC device when available.

Assisted-by: Gemini:gemini-2.5-pro
Signed-off-by: Daniel P. Carvalho <danieloak@gmail.com>
2026-09-15 16:09:24 +08:00
likun17
d1b15db361 system/uorb: add resistance, conductivity, energy and charge topics.
Declare and define the uORB metadata for the resistance, conductivity,
energy and charge types, and register them in g_sensor_list[] so that
orb_get_meta() and uorb_listener can resolve them by name.

Signed-off-by: likun17 <likun17@xiaomi.com>
2026-09-14 23:56:06 +08:00
likun17
b93c947608 system/uorb: add voltage, current and power topics
Declare and define the uORB metadata for the voltage, current and power
types, and register them in g_sensor_list[] so that orb_get_meta() and
uorb_listener can resolve them by name.

Signed-off-by: likun17 <likun17@xiaomi.com>
2026-09-14 23:56:06 +08:00
likun17
00d9af873d system/uorb: add missing metadata for velocity and ambient_temp
SENSOR_TYPE_VELOCITY and SENSOR_TYPE_AMBIENT_TEMPERATURE have an
entry in the kernel g_sensor_meta[] table but no ORB_DECLARE/ORB_DEFINE
in user space, so ORB_ID() fails to link, callers must fall back to
orb_open() by name and lose the o_size check, and uorb_listener cannot
monitor them.
Add the missing metadata and register both in g_sensor_list[];
ambient_temp reuses struct sensor_temp the same way sensor_light_uncal
already reuses struct sensor_light.

Signed-off-by: likun17 <likun17@xiaomi.com>
2026-09-14 23:56:06 +08:00