The USB device controller drivers invoke CLASS_DISCONNECT() on every
USB bus reset, and a bus reset is the first step of normal host
enumeration. Every other class driver (cdcacm, usbmsc, rndis)
re-asserts DEV_CONNECT() at the end of its disconnect() handler so
that the device remains attached; cdcecm and cdcncm did not, so on
controllers that soft-disconnect around bus reset (e.g. rp2040, which
drops the pull-up in its bus-reset handler) a standalone CDC-ECM or
CDC-NCM device is left soft-disconnected by the first bus reset and
never enumerates on the host.
Mirror the cdcacm behavior and perform the soft connect in the
disconnect() methods, unless part of a composite device (composite.c
already re-connects in its own disconnect handler).
Fixes the standalone CDC-ECM case of issue #15880.
Validated on raspberrypi-pico (RP2040): with this change a standalone
CONFIG_NET_CDCECM device that previously never appeared on the host
enumerates via cdc_ether and pings with 0% loss. cdcncm has the
identical defect and receives the identical fix.
Signed-off-by: Ricard Rosson <ricard@groundbits.com>
Co-authored-by: Xiang Xiao <xiaoxiang781216@gmail.com>
Assisted-by: Claude (Anthropic Claude Code)
cdcncm_send() defers each transmit with MSEC2TICK(CDCNCM_DGRAM_COMBINE_PERIOD)
(1 ms). MSEC2TICK() rounds up to the system tick, so at the default 100 Hz tick
the "1 ms" coalescing window becomes a full 10 ms tick (10-20 ms with phase),
adding that latency to every single-datagram reply (ICMP echo, TCP ACK, one-MSS
HTTP segment) and dominating the CDC-NCM round-trip time.
The window only coalesces datagrams appended within the same synchronous TX
burst (already queued before the worker runs), so an inter-burst delay adds
latency without batching benefit in the common case. Fire the transmit worker
immediately (delay 0); within-burst coalescing is preserved.
On RP2350 (Pico 2 W) USB-NIC at 100 Hz tick: ping RTT 21.7 -> 2.8 ms, a 257 KB
HTTP download 5.79 -> 0.92 s (44.5 -> 279 KB/s).
Signed-off-by: Ricard Rosson <ricard@groundbits.com>
Assisted-by: Claude (Anthropic Claude Code)
Signed-off-by: Ricard Rosson <ricard@groundbits.com>
Two related defects corrupt CDC-NCM transmit once TCP write buffers make TX
bursty (a single txavail poll drains many queued segments back-to-back through
cdcncm_send):
1. Buffer-reuse race. cdcncm coalesces datagrams into the single pre-allocated
wrreq->buf that the USB controller transmits directly from, but cdcncm_send
formatted a new NTB batch into it (cdcncm_transmit_format) without first
waiting for the previous transfer to complete -- the wrreq_idle wait happened
only later, in cdcncm_transmit_work. A new batch started while the previous
NTB was still in flight overwrote the in-flight buffer, so the host dropped
the corrupted NTB and TX could wedge (wrreq_idle never reposted).
Fix: acquire wrreq_idle in cdcncm_send when starting a new batch
(dgramcount == 0), before formatting; drop the now-redundant wait in
cdcncm_transmit_work (a second wait on the init-to-1 semaphore would deadlock).
2. Concurrent transmit_work. cdcncm_send runs under the recursive netdev_lock and
calls cdcncm_transmit_work() synchronously in the buffer-full branch, while a
scheduled delaywork instance runs cdcncm_transmit_work() on ETHWORK -- two
different threads. Two EP_SUBMITs of the one wrreq corrupt the IN request
queue and leave the IN buffer prepared-but-unarmed (controller idle,
wrreq_idle never reposted).
Fix: wrap cdcncm_transmit_work in netdev_lock (the synchronous caller already
holds this recursive nxrmutex; a delaywork instance blocks until the drain
releases it), and add an empty-batch guard (dgramcount == 0 -> return) so a
delaywork that runs after a synchronous flush emptied the batch does not seal
an empty NTB and double-submit the in-flight wrreq.
Validated on RP2350 (Pico 2 W) with CONFIG_NET_TCP_WRITE_BUFFERS=y as part of the
complete fix set: 144 dense/concurrent HTTP downloads, zero wedges, ~486 KB/s
(previously transmit hung within a few requests). On RP2350 full stability under
maximal TX density additionally requires a memory barrier between the BUFF_STATUS
clear and the AVAILABLE re-arm in the Cortex-M33 USB device driver (a separate
change); these cdcncm defects are real and the fixes correct independent of it.
Signed-off-by: Ricard Rosson <ricard@groundbits.com>
Assisted-by: Claude (Anthropic Claude Code)
Signed-off-by: Ricard Rosson <ricard@groundbits.com>
Summary
Permissions (Part 3)
Description:
In kernel builds, any unprivileged process running on the NuttX device can
open /dev/efuse and attempt to read/write fuse content. Reading the fuses
may provide valuable information to an attacker controlling the user process.
The write operation, in extreme cases where the fuse blocks are not locked,
may brick the device.
DISCLAIMER: I tried to be strict with the settings, better to relax them
later if it's needed.
This is part of https://github.com/apache/nuttx/issues/19410
Impact
See https://github.com/apache/nuttx/issues/19410
Testing
Compiles ok.
Signed-off-by: Catalin Visinescu <catalin_visinescu@yahoo.com>
Three defects that together prevented macOS from ever mounting a
composite USBMSC function (Linux was mostly unaffected because its
probe sequence and recovery timing never exercised these paths):
1. usbmsc_setup() compared the class-request wIndex against the
compile-time constant USBMSC_INTERFACEID (= CONFIG_USBMSC_IFNOBASE,
i.e. 0) instead of the composite-assigned priv->devinfo.ifnobase.
In composite mode the MSC interface number is nonzero, so
GET MAX LUN, Bulk-Only Mass Storage Reset, and GET/SET INTERFACE
all failed the index check and stalled EP0. Standalone MSC is
unaffected (ifnobase == 0), which is why this went unnoticed.
2. usbmsc_deferredresponse() has its entire body inside
#ifndef CONFIG_USBMSC_COMPOSITE, so the deferred EP0 status stage
for MSRESET/SETINTERFACE was never sent in composite mode and the
host's Bulk-Only reset timed out. (Unreachable before fix 1 --
MSRESET used to stall at the wrong-interface check.) Compile the
body in composite mode too, but suppress the worker's deferred
response for SETCONFIGURATION there: the composite driver answers
that request itself, and a duplicate zero-length packet corrupts
the EP0 state.
3. usbmsc_cmdfinishstate() stalled the bulk IN endpoint whenever a
device-to-host command left a residue, even when the response had
already been sent and terminated by a short packet (or ZLP). The
stall is BOT-legal (USB MSC BOT 6.7.2) but gratuitous: the short
packet already ended the data phase and the residue is reported in
dCSWDataResidue. Hosts such as macOS answer any bulk-IN halt during
device probing with a full Bulk-Only reset sequence, which costs
seconds per command or aborts the probe entirely (macOS probes
MODE SENSE(6) with allocation lengths that exceed the response;
Linux's probe does not). Only halt the endpoint when nothing
terminated the data phase.
Root-cause analysis and host traces in apache/nuttx#19435.
Validated on RP2350 silicon (Raspberry Pi Pico 2 W, composite
CDC-ACM + CDC-NCM + USBMSC): GET MAX LUN answers 1 LUN (previously
EP0 stall and a garbage LUN count on macOS), MSRESET completes 10/10
(previously ETIMEDOUT), MODE SENSE(6) alloc=0xC0 returns short data
plus a CSW with dCSWDataResidue and zero bulk-IN stalls across the
exact-length suite, and macOS now mounts the volume (together with the
companion DCD fixes).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Signed-off-by: Ricard Rosson <ricard@groundbits.com>
Permissions (Part 2)
Description:
In kernel builds, any unprivileged process running on the NuttX
device can open /dev/efuse and attempt to read/write fuse content.
Reading the fuses may provide valuable information to an attacker
controlling the user process. The write operation, in extreme cases
where the fuse blocks are not locked, may brick the device.
DISCLAIMER: I tried to be strict with the settings, better to relax them
later if it's needed.
This is part of https://github.com/apache/nuttx/issues/19410
See https://github.com/apache/nuttx/issues/19410
Compiles ok.
Signed-off-by: Catalin Visinescu <catalin_visinescu@yahoo.com>
When several RNDIS responses are queued, the control request handler sends one complete response if the host wLength is smaller than the whole queue. If the first queued response is also larger than wLength, copying hdr->msglen bytes would overrun the requested transfer and the completion path would consume a partial message.
Return EMSGSIZE before copying in that case so the queued response remains intact for a retry with a large enough wLength.
Signed-off-by: Old-Ding <35417409+Old-Ding@users.noreply.github.com>
debug.h is a NuttX-specific, non-POSIX header. Placing it in the
top-level include/ directory creates naming conflicts with external
projects that define their own debug.h.
This commit moves the canonical header to include/nuttx/debug.h,
following the NuttX convention for non-POSIX/non-standard headers,
and updates all in-tree references.
A backward-compatibility shim is left at include/debug.h that
emits a deprecation #warning and re-includes <nuttx/debug.h>,
allowing out-of-tree code to continue building while migrating.
Signed-off-by: Piyush Patle <piyushpatle228@gmail.com>
Add USB Video Class 1.1 gadget driver supporting Bulk transport
with uncompressed YUY2 video streaming. Resolution and frame
interval are negotiated dynamically via PROBE/COMMIT control.
- uvc.h: protocol constants, streaming control struct, public API
- uvc.c: class driver with PROBE/COMMIT, bulk EP, /dev/uvc0 chardev
- Kconfig/Make.defs: USBUVC config and build rules
- boardctl.c: BOARDIOC_USBDEV_UVC standalone init path
Hardened against host disconnect:
- Removed nxmutex_lock from USB interrupt context paths
- Added 30s semaphore timeout in uvc_write with EP_CANCEL fallback
- Drain stale wrsem counts in VS_COMMIT before new stream
- Guard uvc_streaming_stop() against double EP_CANCEL race
- Handle EP_SUBMIT returning -ESHUTDOWN gracefully
Signed-off-by: wangjianyu3 <wangjianyu3@xiaomi.com>
Correct duplicate "is is" word found in 181 files throughout the
codebase.
In most cases "is is" was changed to "is", but in contexts like
"MCU is is sleep mode" it was corrected to "MCU in sleep mode".
Also fixes a "the the" typo in net/inet/inet_sockif.c.
This is a pure style/documentation fix that improves code readability.
Signed-off-by: Huang Qi <huangqi3@xiaomi.com>
Fix 269 occurrences of duplicate "the" word typo found in 209 files
across source code, header files, and configuration.
Signed-off-by: Huang Qi <huangqi3@xiaomi.com>
Move network interface up operation (ifup) to work queue in RNDIS USB
device driver to avoid calling netdev_carrier_on API in interrupt context.
Signed-off-by: zhanghongyu <zhanghongyu@xiaomi.com>
1. Move DEBUGASSERT to correct place
2. Leave it out if composite device
3. Move working thread stop to separate function
4. Call it from unbind function for composite device
Signed-off-by: Ari Kimari <ari.kimari@tii.ae>
since the judgment for network card selection was changed from IS_UP to
IS_RUNNING, drivers that lack carrier_on need to add the carrier_on
operation; otherwise, network access issues will occur.
Signed-off-by: zhanghongyu <zhanghongyu@xiaomi.com>
drivers/usbdev/rndis: after client send notication, host can't read msg timely
rndis use intr ep to notify host to read RNDIS message from client, it should
read all the messages cached. Need notify host to read again if there is msg left.
Signed-off-by: Jerry Ma <shichunma@bestechnic.com>
modify the code of the adapted protocol stack to avoid deadlocks and the
logic that cannot be protected by locks after modification.
Signed-off-by: zhanghongyu <zhanghongyu@xiaomi.com>
When the setinterface interface is called, it indicates that the underlying
USB link has been successfully established. At this point, the status of the
network card needs to be updated to RUNNING by calling the netdev_carrier_on
interface. It is similar to the logic after a Wi-Fi network card is
connected to a hotspot. Otherwise, an incorrect network card status may
cause packets to fail to be successfully sent.
Signed-off-by: zhanghongyu <zhanghongyu@xiaomi.com>
When using the serial framework buffer, if the buffer is full, excess
data is cached in the usb req buffer. The CDCACM driver doesn't know
when the upper layer will read data from the serial buffer, so it
needs to periodically check if the cached data can be put into the
serial buffer. However, when using zero-copy, each usb req buffer
needs to be completely read before actively switching to the next
req buffer, so the timer is not needed to assist to query.
Signed-off-by: yangsong8 <yangsong8@xiaomi.com>
in cdcacm_sndpacket, If `if (priv->wrcontainer)` is true, then
`priv->wrcontainer` is set to NULL. If an interrupt occurs before
`priv->wrcontainer` is reassigned after being NULL,
`priv->wrcontainer` will be reassigned once during the interrupt,
and `nwrq--` will be called, but no data will be sent at this time.
Only when data is sent by calling `txint` will `priv->wrcontainer`
be reassigned and `nwrq--` called again. This causes the issue.
Signed-off-by: yangsong8 <yangsong8@xiaomi.com>
When CONFIG_CDCACM_DISABLE_TXBUF is enabled, if the USB is
unplugged during serial data transmission, it is possible
that cdcacm will enter the unbind process, and reqbuf will
be released, causing a crash during serial write.
Signed-off-by: yangsong8 <yangsong8@xiaomi.com>
When enable CONFIG_CDCACM_DISABLE_TXBUF, dev->xmit.buffer always
take one req, so just compare CONFIG_CDCACM_NWRREQS - 1.
Signed-off-by: yangsong8 <yangsong8@xiaomi.com>
usbdev/cdcacm.c:2974:3: runtime error: null pointer passed as argument 2, which is declared to never be null
#0 0x44716307 in cdcuart_dmasend usbdev/cdcacm.c:2974
Signed-off-by: yangsong8 <yangsong8@xiaomi.com>
When close the serial tool in PC, only the persent bit is cleared
on Windows but all bits are cleared on linux.
Signed-off-by: yangsong8 <yangsong8@xiaomi.com>
Nuttx currently has 2 types of sleep interfaces:
1. Signal-scheduled sleep: nxsig_sleep() / nxsig_usleep() / nxsig_nanosleep()
Weaknesses:
a. Signal-dependent: The signal-scheduled sleep method is bound to the signal framework, while some driver sleep operations do not depend on signals.
b. Timespec conversion: Signal-scheduled sleep involves timespec conversion, which has a significant impact on performance.
2. Busy sleep: up_mdelay() / up_udelay()
Weaknesses:
a. Does not actively trigger scheduling, occupy the CPU loading.
3. New interfaces: Scheduled sleep: nxsched_sleep() / nxsched_usleep() / nxsched_msleep() / nxsched_ticksleep()
Strengths:
a. Does not depend on the signal framework.
b. Tick-based, without additional computational overhead.
Currently, the Nuttx driver framework extensively uses nxsig_* interfaces. However, the driver does not need to rely on signals or timespec conversion.
Therefore, a new set of APIs is added to reduce dependencies on other modules.
(This PR also aims to make signals optional, further reducing the code size of Nuttx.)
Signed-off-by: chao an <anchao.archer@bytedance.com>
This protects the driver in case multiple threads are trying to initialize
or uninitialize the cdcacm concurrently.
Note that this only protects the case when the private pointer is not managed
outside the kernel. If someone has acquired the pointer to the driver and uses
that, it also needs to manage the protection itself if needed.
Signed-off-by: Jukka Laitinen <jukka.laitinen@tii.ae>
Option COMPOSITE_VENDORSTR should be described as composite vendor
string, not vendor id. This is consistent with other USB devices.
Also fixes a typo in USBDEV_EPBUFFER_ALIGNMENT.
Signed-off-by: Michal Lenc <michallenc@seznam.cz>
To be compatible with the previous method, add a buf between cdcacm
and serial. Because when using usbreqbuf directly as the buf of serial,
the amount of data sent may be insufficient due to the limit of the
number of reqs. For example, when the number of reqs is 4, the number
of data send through cdcacm is 5, and each data is a separate USB
packet, if the host does not read in time, resulting in blocking send.
Signed-off-by: yangsong8 <yangsong8@xiaomi.com>
To be compatible with the previous method, add a buf between cdcacm
and serial. Because when using usbreqbuf directly as the buf of serial,
the amount of data received may be insufficient due to the limit of the
number of reqs. For example, when the number of reqs is 4, the number
of data received through cdcacm is 5, and each data is a separate USB
packet, which should require 5 reqs, resulting in the last number not
being received. If the application always waits for 5 numbers before
performing an operation, this will cause problems.
Signed-off-by: yangsong8 <yangsong8@xiaomi.com>
In cdcacm, USB req buf is directly used as serial buf, so the getting
buf status operation in ioctl is different from the original serial.
Signed-off-by: yangsong8 <yangsong8@xiaomi.com>
Use the CDCACM as a SYSLOG output device, send message to remote proc.
If there are more than one CDCACM devices, then a device minor number
may also need to be provided. Default: 0
Signed-off-by: yangsong8 <yangsong8@xiaomi.com>
Data form serial framework will be written to usb reqbuf directly,
and data form cdcacm will be read form reqbuf directly.
Signed-off-by: yangsong8 <yangsong8@xiaomi.com>
Make sure that the cdcacm is disconnected before the usbdev gets unregistered.
Also, check if the device is connected or not in cdcuart_txempty (uart_txempty). Otherwise there may be a crash during uart_tcdrain, called in tty close path, if the usbdev unregistration happens during the loop.
This issue can be triggered by monitoring the cable connection status in one thread, sending BOARDIOC_USBDEV_DISCONNECT if the usb cable is detached. In another thread close the ttyACM.
Signed-off-by: Jukka Laitinen <jukkax@ssrc.tii.ae>
Most tools used for compliance and SBOM generation use SPDX identifiers
This change brings us a step closer to an easy SBOM generation.
Signed-off-by: Alin Jerpelea <alin.jerpelea@sony.com>
This patch fixed userspace headers conflict. Architecture-related definition and API should not be exposed to users.
Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>