Render Brian Paul's classic OpenGL "gears" demo with TinyGL on a NuttX
framebuffer device. TinyGL draws each frame into its own ZBuffer, which
is then copied to the mmap()ed framebuffer (plus FBIO_UPDATE when
CONFIG_FB_UPDATE is enabled), so partially drawn frames are never shown.
The frame rate is printed every five seconds.
Usage: tinygl [frames] [fbdev]
Tested on sim:tinygl (640x480, 32 bpp): about 1400 FPS with
CONFIG_DEBUG_FULLOPT on an x86_64 host, with both make and CMake.
Assisted-By: Claude Opus 5.5 (1M context)
Signed-off-by: Alan Carvalho de Assis <acassis@gmail.com>
Add TinyGL (https://github.com/C-Chads/tinygl), a small software-only
implementation of a subset of OpenGL 1.1 written in portable C99, by
Fabrice Bellard, Gek and C-Chads, under a zlib-style license.
Like graphics/lvgl, the sources are not kept in the repository: the
build downloads a pinned git revision from GitHub
(CONFIG_TINYGL_VERSION) and applies the NuttX patches that live next to
the Makefile:
0001 zfeatures: allow overriding the feature switches at build time
0002 Fix -Wstrict-prototypes warnings
0003 zbuffer: do not over-read the source in ZB_copyFrameBuffer()
0004 zbuffer.h: make the default allocator wrappers static inline
The TinyGL compile time features (pixel depth, GL_SELECT, GL_POLYGON,
blending, texture size, ...) are exposed as CONFIG_TINYGL_* Kconfig
options. They change public structures, so Make.defs / CMakeLists.txt
export them to every application that includes <GL/gl.h> or
<zbuffer.h>.
Both the make and the CMake builds are supported. An unpack stamp file
makes sure an object directory created inside the source tree is never
mistaken for downloaded sources.
Assisted-by: Claude Opus 5.5 (1M context)
Signed-off-by: Alan Carvalho de Assis <acassis@gmail.com>
When ptpd runs over IEEE 802.3 (-2) with hardware timestamping and
ETHTOOL_GET_TS_INFO does not report SOF_TIMESTAMPING_TX_HARDWARE,
SOF_TIMESTAMPING_RX_HARDWARE and SOF_TIMESTAMPING_RAW_HARDWARE for the
interface, refuse to start instead of logging a warning and running in
software - the same way linuxptp/ptp4l refuses to start when hardware
timestamping is configured but not reported as supported by ethtool,
rather than silently degrading. The error message names the missing
capability and points to -S, and the usage text documents the
requirement.
Hardware RX timestamps are required as well: without them the receive
timestamps come from the system clock while the transmit ones come from
the MAC, and the two cannot be combined into a meaningful delay.
The check is limited to the 802.3 transport, the only one on which ptpd
retrieves hardware TX timestamps. -H is the default with
CONFIG_NET_TIMESTAMP, so applying it to the UDP transports would make a
plain "ptpd" refuse to start on any interface whose driver does not
report hardware timestamping, although it never needs that capability.
Assisted-by: Claude:claude-sonnet-5
Signed-off-by: Daniel P. Carvalho <danieloak@gmail.com>
Query interface hardware timestamping capabilities with the SIOCETHTOOL
ETHTOOL_GET_TS_INFO ioctl during initialization, the same way
linuxptp/ptp4l does on Linux, instead of detecting support through
runtime trial and error. If the query itself fails, refuse to start.
Remove the consecutive failure counter (hwts_tx_failures,
PTP_HWTS_TX_MAX_FAILURES, hwts_tx_disabled). When hardware TX
timestamping is supported and requested, report genuine runtime timeouts
as errors (ptperr) instead of silently downgrading to software
timestamping. Invalidate clock_source_valid in ptpd status while a
hardware TX timestamp failure persists.
Assisted-by: Gemini:gemini-3.8-pro
Assisted-by: Claude:claude-sonnet-5
Signed-off-by: Daniel P. Carvalho <danieloak@gmail.com>
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>
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>
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
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
Add a lightweight Micro XRCE-DDS Client integration with UDP transport support and a publisher example.
Signed-off-by: lljwork2021 <lljwork2021@163.com>
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>
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>
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>