Skip to content

sched/wqueue: Add work_queue_init() and work_queue_run() - #22268

Open
chengkai15 wants to merge 1 commit into
apache:masterfrom
chengkai15:wqueue-pthread
Open

chengkai15 wants to merge 1 commit into
apache:masterfrom
chengkai15:wqueue-pthread

Conversation

@chengkai15

@chengkai15 chengkai15 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

In the flat build, the workers of a custom queue created with work_queue_create() are kernel threads, which do not share the file descriptors or the other resources of the task that created the queue. A callback cannot use the files that the task opened: write() fails with EBADF, or reaches another file that has the same number in the kernel thread group.

This shows up when an application moves its deferred work to a NuttX work queue: the Zephyr Bluetooth host of nuttx-apps#3977 runs its work queues on work_queue_create(), and on current master bt_enable() hangs on sim:zblue (see apache/nuttx-apps#4129).

As suggested in the review, the caller now creates the threads and the work queue only provides the loop:

  • work_queue_init(nthreads) creates a custom queue with nthreads worker slots and no thread. Work can be queued at once.
  • work_queue_run(wqueue), called from a thread that the caller created, makes that thread a worker and runs the work loop until the queue is freed.

The caller chooses the kind of thread, its name, priority and stack; in the flat build the workers can be pthreads of the task. The same interfaces are in the libc user-mode implementation (protected and kernel builds).

A thread may not have reached work_queue_run() when the queue is freed, so work_queue_free() now waits only for the workers that run the loop, counted under the queue lock. work_queue_run() returns -EBUSY when all the slots are taken and -ESHUTDOWN when the queue is being freed. The threads must call work_queue_run() before the queue is freed, and if they end with their task, the queue must be freed before the task exits. work_queue_setpriority_wq() skips the slots that no thread took.

Impact

  • New API. work_queue_create() and HPWORK/LPWORK are unchanged; work_queue_create() shares the allocation and the loop with the new interfaces.
  • Code size, mps3-an547:nsh (flat, arm-none-eabi-gcc 10.3.1), text: 359903 -> 360023 (+120 bytes).
  • Documentation: include/nuttx/wqueue.h and Documentation/os/scheduling/wqueue.rst.
  • The regression test is testing/ostest: Test work_queue_init() and work_queue_run() nuttx-apps#4140 (testing/ostest/wqueue.c).

Testing

The new ostest case creates a queue with work_queue_init(2), opens /dev/null in the test task, queues a callback, and only then starts two pthreads of the task that call work_queue_run(). The callback checks that getpid() is the pid of the task and that write() on the fd succeeds. Then the sync cancel, parallel cancel (both threads serve the queue at the same time) and priority tests run on the queue, a third work_queue_run() must return -EBUSY, and both threads must return 0 from work_queue_run() after work_queue_free(). Last, work_queue_free() of a queue with a slot that no thread took must return.

master (b5db91f), sim:ostest, the same check with work_queue_create() (the problem):

wqueue_test: pthread workers
wqueue_test: worker pid = 0, expect = 5, write = -1
dump_assert_info: Current Version: NuttX  13.1.1-RC0 b5db91fe0d Nov 24 2026 19:51:44 sim
dump_assert_info: Assertion failed : at file: wqueue.c:1180 task: ostest process: ostest 0x4005045d

This PR, sim:ostest (flat), full ostest (4 loops, no errors):

wqueue_test: work_queue_run
wqueue_test: worker pid = 5, expect = 5, write = 1
wqueue_test: sync cancel finished = 1, expect = 1
wqueue_test: parallel callbacks = 2, expect = 2
wqueue_test: work_queue_run() = 0, expect = 0
wqueue_test: work_queue_run() = 0, expect = 0
wqueue_test: work_queue_run done

mps2-an500:citest_protected (protected) + CONFIG_LIBC_USRWORK, qemu-system-arm, ostest wqueue:

wqueue_test: work_queue_run
wqueue_test: worker pid = 5, expect = 5, write = 1
wqueue_test: sync cancel finished = 1, expect = 1
wqueue_test: parallel sync cancel
wqueue_test: parallel callbacks = 2, expect = 2
wqueue_test: priority = 100, expect = 100
...
wqueue_test: work_queue_run() = 0, expect = 0
wqueue_test: work_queue_run() = 0, expect = 0
wqueue_test: work_queue_run done

qemu-armv7a:citest_knsh (kernel) + CONFIG_LIBC_USRWORK, qemu-system-arm, ostest wqueue:

wqueue_test: work_queue_run
wqueue_test: worker pid = 4, expect = 4, write = 1
wqueue_test: work_queue_run() = 0, expect = 0
wqueue_test: work_queue_run() = 0, expect = 0
wqueue_test: work_queue_run done

On protected and kernel, ostest wqueue fails on master before it reaches this case, in code that this PR does not change. For these two runs those checks were disabled locally:

  • protected and kernel: on a libc custom queue, cancelling idle work does not return -ENOENT (api_validation_test()). Master fails at the same assertion.
  • kernel: the callbacks of the predefined USRWORK queue do not run (usrwork_test() reports -110). Master fails the same way.

With apache/nuttx-apps#4129, sim:zblue with a CSR controller passes discovery, MTU exchange, write, 200 reads on one connection and 10 reads on new connections; all host threads are pthreads of the application.

Builds: sim:ostest and sim:zblue (Make), mps2-an500:citest_protected, qemu-armv7a:citest_knsh, mps3-an547:nsh. Not tested: CMake, SMP, real hardware.

@github-actions github-actions Bot added Area: Documentation Improvements or additions to documentation Size: M The size of the change in this PR is medium labels Nov 24, 2026
@chengkai15

Copy link
Copy Markdown
Contributor Author

apache/nuttx-apps#4129 depends on this PR.

zblue (merged in apache/nuttx-apps#3977) creates its Zephyr work queues with work_queue_create(). In the flat build the workers are kernel threads, while the HCI receive thread and the application threads are pthreads of the application, so the host is split over two task groups. On current master this makes bt_enable() hang on sim:zblue:

  • The thread-specific key of the zblue porting layer is created by the first work queue, so it belongs to the kernel thread group. Since 0bc013b, pthread_setspecific() returns EINVAL in the application's receive thread. That thread then keeps the cooperative lock while it blocks in read(), and the host TX work queue waits on that lock forever, so HCI_Reset is never sent.
  • File descriptors are not shared either, which is why zblue needed a separate TX work queue that opens /dev/ttyHCI0 a second time.

apache/nuttx-apps#4129 switches zblue to work_queue_create_pthread(), removes that TX work queue, and writes in send() again. With this PR and #4129 on master, sim:zblue with a CSR controller passes discovery, MTU exchange, write, 200 reads on one connection, and 10 reads on new connections. All host threads are pthreads of the application. #4129 stays in draft until this PR is merged.

@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

MemBrowse Memory Report · Explore what changed →

mps2-an500-citest

  • flash: .text +48 B (+0.0%, 248,400 B / 4,194,304 B, total: 6% used)

mps2-an500-citest-protected

  • flash: .text +16 B (+0.0%, 116,936 B / 4,194,304 B, total: 3% used)

qemu-armv7a-citest

  • ROM: .data +16 B, .init_section -80 B, .text +80 B (+0.0%, 554,120 B / 1,048,576 B, total: 53% used)

qemu-armv8a

  • Code: .text.work_queue_create -96 B, .text.work_thread -436 B (+0.0%, 379,228 B)

stm32-nucleo-f103rb

  • flash: .text +16 B (+0.0%, 34,000 B / 131,072 B, total: 26% used)

No memory changes detected for:


Catch memory regressions in CI with MemBrowse. Free for open source.

GUIDINGLI
GUIDINGLI previously approved these changes Nov 25, 2026
Comment thread include/nuttx/wqueue.h Outdated

#if !defined(CONFIG_DISABLE_PTHREAD) && \
(defined(CONFIG_BUILD_FLAT) || !defined(__KERNEL__))
FAR struct kwork_wqueue_s *work_queue_create_pthread(FAR const char *name,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's provide a new work_queue_init which is called from the caller created thread context and run the work loop in this context directly

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I'll rework it that way. One question on the API shape first.

(a) Two steps:

/* Any thread; allocates the queue, creates no worker */

FAR struct kwork_wqueue_s *work_queue_init(int nthreads);

/* From a thread the caller created: becomes one of the workers and runs
 * the loop; returns after work_queue_free()
 */

int work_queue_run(FAR struct kwork_wqueue_s *wqueue);

The handle exists before the thread runs, so the caller can queue work right after it creates the thread, and up to nthreads threads can serve one queue.

(b) work_queue_init() is called inside the new thread, which then runs the loop. The creator has to wait for the thread to hand back the handle, and only that thread can serve the queue.

I plan to do (a). work_queue_create() then becomes work_queue_init() plus kernel threads that run the same loop, and work_queue_create_pthread() is dropped. Please tell me if you prefer (b).

work_queue_free() needs a change with (a). Today it posts the semaphore nthreads times and waits for nthreads exits. With (a), some threads may not have reached work_queue_run() yet, or never will (for example when pthread_create() failed), so work_queue_free() would hang. I'll count the workers under the queue lock instead:

  • work_queue_run() registers the calling thread (its tid goes into a free worker slot) and increments the count. It returns -EBUSY when all nthreads slots are taken, and -ESHUTDOWN when the queue is already being freed.
  • work_queue_free() sets exit under the same lock, then waits only for the registered workers.
  • Since the queue memory is released when work_queue_free() returns, a thread must not call work_queue_run() after that. I'll document that the caller frees the queue only after its threads have started serving it, or have been joined.

As before, a worker that is killed when the task exits never reports back, so the queue must be freed before the task exits.

acassis
acassis previously approved these changes Nov 25, 2026

@xiaoxiang781216 xiaoxiang781216 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please don't merge this patch before fixing the problem.

@chengkai15
chengkai15 dismissed stale reviews from acassis and GUIDINGLI via 4c73208 November 25, 2026 13:28
@chengkai15 chengkai15 changed the title sched/wqueue: Add work_queue_create_pthread() sched/wqueue: Add work_queue_init() and work_queue_run() Nov 25, 2026
@cederom

cederom commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

Thanks, the two-step work_queue_init() / work_queue_run() shape reads well (and matches Zephyr's k_work_queue_run()). Comments on 4c73208:

1. work_queue_free() vs. a thread that has not reached work_queue_run() yet (use-after-free)

work_queue_free() waits only for the nworkers snapshot, then kmm_free()s the queue. A caller thread that was created but has not yet taken the lock in work_queue_run() will then call it on freed memory. -ESHUTDOWN can only be seen in the short window between exit = true and kmm_free(), so callers can't rely on it, and the caller has no race-free way to know "my thread is now inside work_queue_run()": anything it signals before the call can be preempted before the lock is taken.

The doc says the threads "must call work_queue_run() before the queue is freed", but no API lets the caller check that. Options:

  • Make the contract "exactly nthreads threads call work_queue_run()": work_queue_free() waits for nthreads posts, and a late work_queue_run() that sees exit posts exsem and returns -ESHUTDOWN. Then -ESHUTDOWN is reliable and nothing touches freed memory. The cost is that free() blocks until every thread has arrived.
  • Or keep the current behaviour, but drop -ESHUTDOWN from the documented return values and state plainly that calling work_queue_run() concurrently with or after work_queue_free() is undefined.

The same applies to the libc implementation.

2. Workers that die inside the loop

If a work_queue_run() thread ends while it is registered (its task exits, or a callback calls pthread_exit() / hits a cancellation point), exsem is never posted, the slot stays taken, and a later work_queue_free() blocks forever. The rst covers the task-exit case. Please also mention it in the header comment of work_queue_run(), since kthread workers could not die this way.

3. work_queue_priority_wq() before the first worker arrives

Both implementations read worker[0].pid/tid. For a work_queue_init() queue with no worker yet, that is INVALID_PROCESS_ID, so you get -ESRCH (kernel) or a sched_getparam(-1) error (libc). Please document or handle this. Similarly, work_queue_setpriority_wq() now skips empty slots and returns OK, so threads that join later keep their own priority. That's probably fine, but worth a line in the docs.

4. Minor

  • Kernel and libc disagree on work_queue_run() for a queue made by work_queue_create(): the kernel returns -EBUSY (all slots taken), libc returns -EINVAL (!run). The header documents -EINVAL for "does not identify a custom queue". Please pick one.
  • Coverage: nothing in sim:ostest exercises the new path. Is apps xtensa/esp32: Make UART TX DMA depends on EXPERIMENTAL. #4140 meant to become part of ostest? A case where work_queue_free() runs while one of the nthreads threads has not started would cover (1).
  • CMake, SMP, and real hardware are untested per the description. SMP matters most here, because of the lock/registration ordering.

Apart from that, the refactor (work_queue_alloc() / work_loop() / work_queue_release()) keeps work_queue_create() behaviour unchanged as far as I can see: nworkers = created on the create path, and libc still joins all nthreads.

In the flat build, the workers of a custom queue created with
work_queue_create() are kernel threads.  They do not share the file
descriptors or the other resources of the task that created the queue,
so a callback cannot use the files that the task opened: write() fails
with EBADF, or reaches another file that has the same number in the
kernel thread group.

Add work_queue_init(), which creates a custom queue with nthreads worker
slots and no thread, and work_queue_run(), which makes the calling
thread a worker and runs the work loop until the queue is freed.  The
caller creates the threads, so it chooses their kind, name, priority
and stack; in the flat build they can be pthreads of the task.  Work can
be queued before the threads run.

Exactly nthreads threads must call work_queue_run(), and
work_queue_free() waits for all of them.  A thread may reach
work_queue_run() after work_queue_free() was called: it then posts the
exit semaphore as its last access to the queue and returns -ESHUTDOWN,
so the queue is not released while a thread still uses it.
work_queue_run() returns -EBUSY when all the slots are taken, and
-EINVAL for a queue that work_queue_init() did not create.  A worker
must stay in work_queue_run() until it returns; if it ends with its
task, work_queue_free() blocks.

work_queue_create() is unchanged; it shares the allocation and the loop
with the new interfaces.  The user-mode implementation in libc gets the
same interfaces.

Assisted-by: Kiro:claude-opus-5-5
Signed-off-by: Kai Cheng <chengkai@xiaomi.com>
@github-actions github-actions Bot added Size: L The size of the change in this PR is large and removed Size: M The size of the change in this PR is medium labels Nov 27, 2026
@chengkai15

Copy link
Copy Markdown
Contributor Author

@cederom thanks for the careful review. Updated in the new push (rebased on the current master):

  1. work_queue_free() vs. a late work_queue_run(): you were right, and the -ESHUTDOWN path itself was not safe either: a late thread still touched the queue lock after work_queue_free() had stopped waiting for workers, and could run into kmm_free() / free(). Now exactly nthreads threads must call work_queue_run(), work_queue_free() waits for all nthreads, and a late caller posts exsem as its last access to the queue before it returns -ESHUTDOWN. Same change in the kernel and in libc. nworkers is gone, so the kernel free path is back to the original wait loop.
  2. A worker that leaves the loop: documented in work_queue_run(). If the task exits, or a callback calls pthread_exit() or is cancelled, work_queue_free() blocks forever.
  3. work_queue_priority_wq() before any worker: it returns -ESRCH in both the kernel and libc, and that is now documented. Slots are taken from index 0 and never released, so worker[0] is valid as soon as one thread runs. work_queue_setpriority_wq() only changes the threads already in work_queue_run(); threads that join later keep their own priority. This is documented too.
  4. Return values: the kernel now has a run flag like libc, so work_queue_run() on a work_queue_create() queue returns -EINVAL in both builds. There are no new source files, so CMake needed no change.

Tested:

@xiaoxiang781216 point 1 changes the API contract: exactly nthreads threads must call work_queue_run(). Could you take another look and confirm that this works for you, and whether it resolves your earlier change request?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Area: Documentation Improvements or additions to documentation Size: L The size of the change in this PR is large

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants