Commit Graph
151 Commits
Author SHA1 Message Date
LibretroAdmin 54e6ef1869 task_queue: a wait sees a task between finishing and the finished stack
A finishing task's settle counts it finished, stops counting it as
running and then pushes it onto the finished stack. The threaded
task_queue_wait() asked whether anything was left by the running count
against the scheduled count, the finished stack and the retire list -
so in the moment between the running count dropping and the push it
saw nothing, and returned before the task was retired or its callback
run. Where a handler's last pass ends just as the waiter looks, the
wait gave up on a task it was waiting for.

macOS's TSan run of task_queue_park_test hit it: 'task_queue_wait()
returned with a parked task still running', then the next lane's task
found the last one's state still on the stack (a race report in
horizon_handler, and 'the horizon handler did not run three times').
The finished count is raised before the running count drops and
lowered only once the gather has the task on the retire list, so the
busy test reads it too.

With a 30 ms sleep put between the two steps of the settle, the old
test fails exactly as on macOS and the new one passes. Every
task_queue sample passes plain, under ASan and UBSan, and under TSan.
2026-11-13 00:02:56 +01:00
LibretroAdmin f3c3c579c2 task_queue: survive wait and reset before init
A failed command-line argument jumps to the init failure path, which
waits on the task queue before it is created, and segfaults.
2026-11-09 03:03:38 +01:00
LibretroAdmin bca0f6cde4 Widgets: send a running task's progress without copying its text
Every frame each running task with a title went to the widgets with a
fresh copy of its title (and error) and a new command, only for the
widgets' owner to compare the title with the one it already had and
free it: a few allocations a frame per task, on the main thread,
during gameplay.

The task system now counts publications of a task's title and error
(task_get_text_gen()). The widgets record on the task what they last
sent it: the key, that count, and progress, flags, style and category
packed into one word. While the text is unchanged it is not copied,
and an update that changes nothing is not sent at all. A finished
task is always sent whole.

When the widgets' owner loses what a task sent it - a task widget
freed, an update dropped for lack of room, widgets cut loose for a
reinit - it bumps a static epoch, and every task sends its title
again. A widget handed on to another task is under a key that task
never sent, so its first update carries its title too. Where the
strings are read without the setters' publication (the runner without
lock-free atomics) the count never repeats and every update copies,
as before.

An unchanged push drops from about 30 ns to 11 ns, with no allocation.
The task bar sample checks that nothing is sent for an unchanged
task, that a progress step is sent once, and that a new title reaches
the widget; its title churn test now republishes the titles it
rewrites in place.
2026-11-02 23:24:10 +01:00
LibretroAdmin 376110ae9b task_queue: GCD runs on the threaded runner without locks
GCD builds take the lock-free runner, with GCD's queues in place of its
workers. Each push of a task due now makes a call that takes tasks
from its ring until it finds none: plain tasks on a serial queue, so
they never overlap, parallel ones on a concurrent queue. A serial
keeper queue holds the tasks waiting for their time, with one timer
source, and every timed push and wake nudges it. Each init is a
generation its calls hold; deinit waits only for the calls past their
check, and leaves a detachable handler behind after the bound as the
threaded runner does. The locked GCD runner and task->sched are gone.

task_queue_deinit() waits for every thread still inside the wake gate
before the runner goes.

The GCD-capable samples also build against a libdispatch stand-in on
pthreads (GCD=standin), and task_queue_overlap_test checks which tasks
run at once on either runner, with pushes stopped halfway into the ring
through a test hook.
2026-10-30 19:08:45 +01:00
LibretroAdmin 27967e0b52 task_queue: titles and errors without property_lock
With the lock-free runner a task's title and error are also published
as atomic pointers beside the handler's own fields. Progress reports
and snapshots read the published copies inside a read epoch, and a
string replaced while a reader is inside goes through the epoch's
limbo instead of being freed at once, so a worker replacing its title
never waits on the frame that is formatting it. The getters return the
published copies; a title or error assigned to the field directly is
published when the task is pushed.

The locked runner keeps property_lock.
2026-10-30 16:17:00 +01:00
LibretroAdmin 5ba7f8c8cb task_queue: a threaded runner without locks
Where the atomics have compare-and-swap and pointer operations, the
threaded runner takes no lock and waits on no condition variable.

Every task is on a live list from its push until it is retired: any
thread links it at the head, only the checking thread unlinks it, and
find(), retrieve() and the lookups behind wake, cancel and reset walk
it from any thread inside a read epoch. A retired task is cleaned up
and freed once no finder can still hold it, at once when none is
inside, since finders read task->state.

Workers take ready tasks from two bounded MPMC rings: the plain one,
which only the one worker takes from, and the parallel one, which
every worker does; what overflows waits behind them in order. A task
with a 'when' to wait for goes to the timer keeper, whichever idle
worker holds the token, which sleeps until the earliest is due and
hands the token on before it runs anything. Main-thread tasks and
finished ones reach the checking thread through lock-free stacks.
Workers, task_queue_wait() and deinit's bounded wait for the workers
park on eventcounts. Each gather with work in flight and each pass's
end advance one counter that both read, so a handler still sees what
the frame loop wrote before a check, as the frame count a load waits
on, and has read it before the loop writes again.

The volatile and PS2 backends keep the locked runner, as does GCD.
task_queue.c now uses retro_eventcount.c, which the sample builds
compiling it with threads now link.

task_queue_parallel_test floods both rings past what they hold with
every worker held; task_queue_switch_test holds a waker in
retro_eventcount_notify() where the runner takes no lock.
2026-10-30 13:59:17 +01:00
Davey HughesandLibretroAdmin ad2e9e05d8 scan: parallel readers, 3DS product codes, CRCs and index builds over steps (#19920)
* samples/database: include compat/strl.h in the scan test

The test calls strlcpy(), which mingw-w64 does not declare, so it did
not build for Windows.

* PS1 scan: PSX.EXE means no serial only as the BOOT target

A root directory can list a PSX.EXE ahead of the executable SYSTEM.CNF
boots: Tomb Raider (USA) lists one before SLUS_001.52. Stopping at the
first PSX.EXE in the probe window sent such discs to a whole-track CRC,
eight seconds for a CHD. Look for the BOOT target first, matched without
regard to case so cdrom:\psx.exe counts. A disc that boots PSX.EXE, or
has no SYSTEM.CNF so the BIOS boots PSX.EXE, has no serial and still
falls back to its CRC (#15241); any other disc is searched for its
serial with PSX.EXE directory records ignored.

* 3DS scan: identify .3ds, .cci and .cxi by the NCCH product code

These images took the default whole-file CRC, 0.5-4 GB a game. The
product code in the NCCH header (partition 0 of a cart image, or the
start of a bare NCCH) is the serial the 3DS database is keyed on, and
the header is plaintext in encrypted dumps too. A code held by one
record matches it outright. Revisions and regions that share a code fall
back to the file's CRC to choose, and to the first record when no CRC
matches; with scan_serial_and_crc on every match is confirmed by CRC, as
for PSP and Dreamcast, and a file none of whose records carry its CRC
goes on to the plain CRC lookup with the CRC already computed. A code no
record carries, or a header without valid magic such as a CIA, keeps the
CRC path, in first-match mode too. Like the CRC lookup, the serial pass
visits only databases an installed core claims the extension for, unless
Scan Without Core Match is on.

* scan: run ITERATE steps while the shared I/O window lasts

A file takes about twenty ITERATE steps, and the handler ran one per
call. On the regular task queue that is one step per frame: 1000 NES
zips took 335 s of pacing, 400 arcade sets 1639 s. The ITERATE states
now run in a loop under the same window the BEGIN states use, which
times the steps rather than counting them and grants every call at least
one. The scan test's unclaimed-database lane spends the window before
each check, so that it still counts steps.

* scan: hash file CRCs a quantum at a time across steps

A step that needed a CRC computed all of it in one handler call: a whole
CHD track with LZMA decode, or a multi-gigabyte 3DS image. On the
regular queue that froze a frame, and on the threaded queue it held the
worker for seconds. Each CRC site now opens its span and returns, and
later steps hash 256 KiB quanta while the shared I/O window lasts, at
least one per call. The lookup that wanted the CRC runs when it is in,
at the same entry. The one-shot CRC helpers, which nothing else called,
are gone.

* scan: walk each database once for its crc and serial indexes

The first file to reach the serial lookup built a crc index and then a
serial index for every database, a full walk each: 47 MB of Mobile -
J2ME twice in one handler call, the second for an index that came out
empty. The crc walk now reads serials as well. It notes whether a
database has any, so the serial lookup passes over one with none, and
for the serial lookup it builds the serial index in the same pass. Index
contents, matches and the split of the index budget are unchanged.

* scan: let a database's indexes be built a run of records at a time

A database's crc and serial indexes were built by one walk and a qsort
in a single call: 50-70 ms for Mobile - J2ME. libretrodb_scan_begin(),
_step() and _end() walk a run of records per call, and
database_info_index_job_*() builds both indexes over as many calls as it
takes, each walking a run of records or merging a run of entries in a
resumable merge sort. libretrodb_scan_field2() and
database_info_index_new() are built on them and answer as before.

* scan: build each database's indexes over steps

The first file to reach a database built its indexes in one handler
call: 52-68 ms on the regular queue for Mobile - J2ME, 13-17 frames'
worth of the 4 ms window. The build now runs over the steps that follow
the lookup that began it, a run of records walked or entries merged at a
time while the window lasts, and the lookup takes the indexes when they
are done. A database counts as size-checked only then. Cancelling frees
a build in flight. The one-shot builders, database_info_crc_index_new(),
database_info_serial_index_new(), database_info_index_new() and
libretrodb_scan_field() and _field2(), lose their last caller here and
go; the tests build through the job and the stepped scan.

* task_queue samples: build on macOS, run on GCD in a macOS job

No sample ran the GCD runner and nothing in CI built HAVE_GCD. Apple's
ld has no --wrap, so on Darwin the switch and init-failure tests
redirect the wrapped calls from task_queue.c by macro instead, and
libdispatch comes from libSystem there. The switch test gets a GCD=1
build, and a macOS job runs every task_queue sample plain, under
ASan+UBSan and TSan, threaded and, where it has a GCD=1 build, on GCD.

* task_queue: a switch waits out a wake from another thread

task_queue_wake() is documented as safe from any thread, but a switch
between the threaded and the unthreaded queue frees the threaded
runner's lock and condition variable while a waker on another thread can
still be inside it. Toggling Threaded Video makes that switch at the
next frame. Two seq_cst counters now keep them apart without a lock: a
switch that finds a waker inside is put off to the next
task_queue_check(), and a waker that finds a switch under way leaves its
task to it. A wake on the thread that drives the queue cannot meet a
switch and skips the counters.

A switch now ends every park, and the new runner takes wakes again
before it runs any task, so a parked task loses nothing to a wake
dropped during the switch. A wake dropped while a switch is put off and
then taken back, or for a task whose park a switch keeps because it
leaves a stuck handler behind, waits for that park's horizon.

The switch test holds a waker inside the queue across a switch, wakes
from four threads through 1000 switches, and holds the main thread where
the new runner first runs a task while that task's first pass wakes it.

GCD builds leave out the threaded runner's own code, which they never
used and which warned there. The switch test also checks that its
realloc() wrapper ran, since on macOS that wrap is a macro rather than a
link option.

* scan: a scan of one file only adds to its playlist

A Content Location that is a file is scanned as one file, which the Scan
button, --scan=FILE and iOS "open in" already rely on. Such a scan
cleared the playlist when Overwrite was on, and recorded the file, and
its core, as what the playlist refreshes with, so Refresh Playlist later
rescanned that file alone. Overwrite is now ignored for a file, and the
playlist's scan record and default core are left as they were. Validate
Existing Entries is skipped too: a file scan's extensions can differ
from its folder's, so validating with them could drop entries the folder
scan added. A later folder scan or Refresh still prunes. With no
database and an automatic target playlist, a file is filed under its
folder's name, as a scan of that folder files it, rather than in a
playlist named after the file. A Content Location that is missing, as on
a drive that is offline, counts as a file, so Overwrite no longer
empties its playlist while the drive is away.

* menu: Content Location takes a file or a folder

Content Scan's Content Location now opens one browser that lists folders
and files in every scan method: OK on a file picks it, <Use This
Directory> picks the folder. In Automatic it lists every file, as an
Automatic scan reads every file; Custom keeps listing the scan's
extensions. The Scan Single File toggle, which switched the browser to
files and was shown only in Custom with Search Recursively off, goes
with its setting and strings, and a scan of a file no longer turns
Search Recursively off behind the user's back. Import Content drops Scan
Directory and Scan File, as the Scan Directory list already had, leaving
Content Scan as the one way in; Scan File no longer started a scan. On
Apple, File > Open and the iOS document picker opened from Content
Location set the location as OK on a file does.

* task_queue: hold pushes from other threads for the main thread

task_queue_push() from another thread could meet a switch between the
threaded and the unthreaded queue, which frees the lock and condition
variable the push takes. On the unthreaded queue, with no switch at all,
it put the task on a list the main thread walks without a lock. Windows
pushes from the video thread under threaded video, and HID builds from
libusb's thread. Such a push now goes through the switch's gate: when
the gate is shut, or the unthreaded queue is up, the task goes onto a
lock-free list that the next gather pushes on the main thread, and the
push returns true. A push is also held while earlier ones still wait, so
a thread's pushes start in the order it made them. A BLOCKING task
refused there is cancelled, and its callback still runs. The switch test
pushes from four threads on the unthreaded queue and through 1000
switches, checks a held BLOCKING push, and holds the main thread inside
the gather that reopens the queue to show that a thread's next push does
not pass its held one.

* task_queue: cancel by ident and find safely from other threads

task_queue_cancel_task() and task_queue_find() from another thread met
the same switch and the same unlocked lists as a push did.
task_queue_cancel_ident() cancels by ident from any thread: a locked
walk when the threaded queue is up with nothing held, otherwise an ident
left for the next gather, which applies it after its pushes, to a held
push as well. A held push cancelled so retires cancelled without
running, and its callback runs. A find from another thread goes through
the switch's gate and reports false when it cannot walk the lists. The
queue's own workers and GCD threads skip the gate, and a find on the
main thread also sees held pushes. Each worker keeps its thread id in a
slot of its own and clears it before it reports that it left, so a
thread that reuses a joined worker's id is not taken for one. The switch
test cancels and finds from other threads on both queues and across a
put-off switch, and holds the main thread in the gather to show that a
thread's cancel of its own held push is not lost. Once extra workers
start, finds from handlers on the one worker and on an extra still skip
the gate, and a find with a joined extra worker's id from inside deinit
is refused.

* autoconfig: make connects reported on other threads on the main thread

libusb's hotplug thread and the Wii's HID poll thread report pads from
their own threads, where task_queue_find() can no longer answer exactly:
at a switch, or on the unthreaded queue, it reports false. Off the main
thread, input_autoconfigure_connect_ex() and
input_autoconfigure_disconnect() now copy the request into a main-thread
task and return true. Its callback makes the call on the main thread, in
the order the requests were made, so the duplicate check, the port's
sequence number and the settings it reads are the main thread's. A new
sample drives task_autodetect.c on the task queue with the rest stubbed,
reports pads from another thread, and checks that every find runs on the
main thread, that a pad reported twice queues one connect, that a
disconnect handed off is made and that a cancelled request is not.

* task_queue: wait, reset and deinit see pushes held for the main thread

On the unthreaded queue every push from another thread is held for the
next gather. A wait with nothing running returned without running it,
and a reset, the exit drain's included, left it to run normally
afterwards. Cancels held for the gather were never freed at deinit.

The unthreaded wait now drains held pushes first, and a reset drains
them into the runner before it cancels, so a held task meets a queued
one's fate. Deinit applies and frees held cancels; held pushes stay held
for the next runner's first gather, so no callback runs inside deinit.

* task_queue: make the Threaded Tasks flag atomic

Task handlers on the worker read it through task_queue_is_threaded(),
and the main thread writes it when the setting changes, so changing the
setting while a task ran was a data race.  ThreadSanitizer shows it on a
database scan whose queue is switched under it.

* task_queue: a parallel task names the extra workers it needs

retro_task_t gains parallel_workers, which task_init() clears. A
parallel push starts the extra workers it finds missing, up to the
larger of task_queue_set_parallel_workers() and the task's number, at
most 8. They serve every parallel task and stay until deinit, as before,
so the pool only grows; 0 keeps the frontend's number. The started count
is atomic, so a push that finds enough takes no lock, and one that needs
more claims the next entries under running_lock.

The parallel test has a task asking for three, a later one asking for
fewer, one asking for more than eight, a plain task whose number is
ignored, the frontend's number holding for a task asking for fewer, and
a task that leaves the number alone.

* task_queue: let deinit leave extra workers behind in detachable handlers

A parallel task may now also be detachable, and then runs on the extra
workers like any other parallel task. Deinit gives every worker the one
bound it gave the one worker, the extra workers first. One still inside
a detachable handler past it is left behind to finish alone, as the one
worker was, and one inside any other handler is still waited for. The
primitives of an init are held by deinit and by each worker it leaves
behind, and the last of them to let go frees them, so the one worker and
several extras can be left behind together.

A worker left behind, the one or an extra, now runs the task's cleanup
once the handler returns, then frees the task, so a detachable task
releases what it holds however it ends. Its callback still never runs;
its cleanup, like its handler, may touch only what the task owns.

The parallel test runs a detachable parallel task on an extra worker,
leaves one stuck past the bound, waits for a slow one that is not
detachable, and leaves the one worker and two extras behind together
with a new queue running beside them. Each task left behind is cleaned
up once, by its own worker, after its handler returns, and one not left
behind at its retirement as before. The switch test switches to the
unthreaded queue and back with extra workers live.

* task_queue: on Emscripten, sleep after a pass on the one worker only

On Emscripten every worker sleeps 1 ms after each handler call, a
pthreads workaround from when the one worker ran every task.  The extra
workers run parallel tasks, which work in many short passes, and the
sleep cost each of those passes 1 ms, more than the pass itself. The
extra workers no longer sleep; the one worker still does.

* emscripten: ask for at most 4 extra workers, and start 5 threads

In the browser a pthread the pool has not started is made on demand by
the main thread, and with the JS file system, where every thread's file
calls go through the main thread, 8 extra workers made each of those
calls about 40% dearer than 4 did.  The frontend asked for cores - 3
extra workers, up to 8; on Emscripten it now asks for at most 4, and the
build starts 5 pthreads up front, enough for the one worker and those 4.

* scan: read small plain files on parallel reader tasks, in list order

A database scan on the threaded queue pushes min(4, cores) reader tasks,
none below 2, as parallel tasks that ask for that many extra workers, in
HAVE_THREADS builds with lock-free atomics, except on Wii U, whose C
library and FAT layer take no locks, and on Vita, where Vita3K's sceIo
tables take none.  With Threaded Tasks off none starts and the scan
reads every file itself, stepped as before.

The scan hands the plain files and archives it would CRC whole to the
readers, up to 64 per reader ahead of it, each with its own copy of the
path.  A reader claims them in list order, opens and sizes each, leaves
one over 128 MiB to the scan unread and CRCs the rest a quantum per
call.  The scan takes each result at its own place in the content list,
so the databases see files in the same order as before, parks while the
next one is still being read, and reads itself whatever a reader could
not.

The scan never waits for its readers.  At its end, on cancel and once
the queue is unthreaded, each reader leaves at its next call and hands
back the file in hand.  Each reader drops its reference to what they
share in its cleanup, and the last reference frees it.  A queue deinit
leaves a reader stuck in a read behind after its 1 s bound and never
calls it again; the worker left with it runs its cleanup once the read
returns, which hands back the file in hand and drops the reference.

The scan test covers list order, files over the cutoff, failed pushes,
cancels and quits with a reader stuck in a read, and queue switches
under a scan; CI runs it under TSan, without threads and with no
readers.

* scan: run the command-line scan with no menu on the threaded queue

A command-line scan with no menu waits for the task queue to run dry,
and only a scan on the threaded queue gets readers.  In threaded builds
that run now uses the threaded queue whatever Threaded Tasks says; the
setting is not changed.

* menu: Import Content offers Scan Directory and Scan File

Both entries sit beside Content Scan when the database is built in.
OK on a file in Scan File's browser scans that file, as the Scan
action does.  The load_content_filter harness checks that the
entries are listed and that OK on a file starts its scan.

* manual scan: Content Location holds a full file path

The location can now be a file, so it is kept in a PATH_MAX_LENGTH
buffer, as is the scan task's copy.  A file whose path does not fit
is refused in the browser instead of being joined short.  The
load_content_filter harness sets a location deeper than a folder
buffer and checks that it is kept whole.

---------

Co-authored-by: LibretroAdmin <[email protected]>
2026-10-26 13:28:42 +01:00
LibretroAdmin 8d1dd59093 task_queue: parallel tasks on extra workers; shader stages use them
RETRO_TASK_FLG_PARALLEL lets a task run beside any other on extra
workers that take only tasks marked so; every other task keeps to the
one worker, one at a time as before, and no task is in two handlers at
once. The frontend sets how many extra workers start (cores less
three, from retroarch.c); none by default. Detachable and main-thread
tasks ignore the flag, and the GCD runner, whose tasks already run on
the system's concurrent queue, is unchanged.

A deferred shader load pushes up to four parallel compile tasks, each
taking the next pass and compiling a file once however many passes
name it; the stepper lists what they finished before each step and
parks until the pass it needs lands. The blob table's claim moves with
the stepper, whose calls may each run on a different worker or GCD
thread. task_queue_parallel_test covers the runner.
2026-10-24 04:12:55 +02:00
LibretroAdmin 63ead85ba7 task_queue: on Switch, run the worker below the main thread
Horizon never time-slices, and on Switch the task worker shares the
process's default core with the main thread.  Level with it, a handler
that returns without waiting - polling for a callback the main thread
runs - holds the core, the callback never runs, and the frontend
freezes with the transfer at 0%.  The worker now lowers itself one step
below its creator there, as it does on 3DS, so tasks run whenever the
main thread waits.

samples/queues/task_queue_fifo_prio_test runs the queue's Switch code
on a host under SCHED_FIFO pinned to one CPU, the priority calls stood
in.  A handler polling for a main-thread callback finishes in two
frames, and frames keep coming at 5 ms while a task works; with the
worker level with the main thread the first lane livelocks and the
second sees a 519 ms gap.  The lanes need CAP_SYS_NICE and skip
without it.

Fixes #19591 together with the handlers parking on their sub-tasks.
2026-10-14 23:34:01 +02:00
LibretroAdmin d5c92b5314 task_queue: on 3DS, run the worker below the main thread
The 3DS kernel never time-slices: of two ready threads on a core, the
higher priority one keeps it until it waits.  rthreads starts a worker
one step above its creator, and on Old 3DS the task worker shares a
core with the main thread, so a handler that keeps working held the
core for as long as its task ran.  A millisecond's sleep after every
pass handed the core back, a frame at a time at best: with passes of
25 ms the main thread drew 22 frames a second.

The worker now lowers itself one step below the thread that started
the queue.  Tasks run whenever the main thread waits - for the vblank,
for audio, in task_queue_wait - and the sleep goes.  The Emscripten
half of it stays.

samples/queues/task_queue_ctr_prio_test is a 3DS homebrew that has
the main thread draw frames while a task works, and wait on one.  On
Old 3DS, before: 78 ms between frames, 22 of them over the task's
second; without the sleep and with the old priority, one frame in
1019 ms.  Now 17 ms, 62 frames, and the task takes as long as before.
New 3DS, where the worker has a core of its own, passes either way.
2026-10-14 22:29:26 +02:00
LibretroAdmin 4791072084 task_queue: on GCD, run a due task with dispatch_async; time only a wait
The GCD runner hands a task that is due now to the global queue with
dispatch_async(), and gives it a timer source only once it parks or is
scheduled for later; a wake turns a wait on the timer into a
dispatch_async().  A per-task record, under running_lock, keeps one run
pending or in progress, and the timer's handlers hold the record rather
than the task, so a fire after the task stopped finds nothing to run.
A pass that makes progress costs what dispatch_async() costs.

A finishing task moves from the running queue to the finished one under
both locks, so a wait on the queue never finds it in neither.

task_queue_park_test: deinit with a task parked, which the next init
runs; a wait lane that widens the gap between the runner's two locks;
the child-callback lane sets its handler before the push.
2026-10-14 22:08:01 +02:00
LibretroAdmin f2349bd3d5 task_queue: let a waiting handler park until it is woken
A handler that returns unfinished because it waits on something now
calls task_queue_park() with a watchdog horizon, and whatever ends the
wait calls task_queue_wake() with the task's ident.  Both meet under the
running lock, so a wake that lands during the pass cancels the park it
asks for.  A cancel or a reset wakes a parked task too, and
task_queue_wait() counts a parked task as running.  The unthreaded
queue runs a handler once per check and ignores parks.

On GCD each task runs from one timer source, which a park, a wake or a
cancel retargets; a start time is passed to it in nanoseconds.

task_queue_park_test covers a wake from another thread, from a child's
callback and from inside the pass, cancel, reset, the wait, the horizon
and the unthreaded queue; GCD=1 builds it against the GCD runner.
2026-10-14 21:39:51 +02:00
davey a1f50fab58 task_queue: a switch to the threaded queue counts the tasks it takes over
task_queue_check() switches implementations when the threaded flag
changes, as Threaded Data Runloop does at runtime. The regular queue
leaves its tasks on the shared lists and the threaded one takes them
over, but its running count started at zero and counted only tasks
pushed to it: each inherited task took the count one below zero when
it finished. The gather sizes its report list from that count plus
eight, so with nine or more inherited tasks the unsigned size wrapped
and every check asked realloc() for about 32 GiB. A release build
gets NULL back and carries on, never again taking the idle early-out;
ASan and TSan abort. The threaded_video harness's hardware-core mode
hits it on the CI runners, where an input autoconfig task is queued at
the switch. The GCD queue took the tasks over the same way.

Both now start their counts from the lists, before a worker can touch
them. task_queue_switch_test queues sixteen tasks on the regular queue,
switches, and fails on any report list sized past a megabyte.
2026-10-06 08:39:54 +02:00
LibretroAdmin f539ccd3d6 task_queue: flags and progress are atomics, off property_lock
task_get_flags(), task_set_flags(), task_get_progress() and
task_set_progress() each took the process-wide property_lock, so every
handler polling for cancellation and every progress update queued
behind every other task's, and behind the progress report formatting a
title under the same lock. The queue itself took it again to cancel,
to settle a task and to test for a main-thread or detachable one.

retro_task_t::flags and ::progress are retro_atomic_int_t now. Reads
are an acquire load, progress a release store, and flag updates an
atomic fetch-or / fetch-and, so concurrent updates of different bits
cannot lose one another. Only a backend whose read-modify-write is not
atomic (RETRO_ATOMIC_LOCK_FREE undefined) still takes property_lock,
and only around the flag update.

Title and error stay under property_lock: their buffers are freed and
replaced, which an atomic pointer would not make safe. The snapshot
and the progress report read the flags before the strings, so a task
seen finished is seen with the error it set before finishing.

Code that touched the two fields on a task already pushed goes through
the accessors: the progress callbacks, the cloud sync handler, the
emscripten HTTP handler and the cheevos badge tasks. Setting them on a
task not yet pushed is unchanged.

task_queue_snapshot_test covers both properties: bits flipped from two
threads with a third held, and a finished task always snapshotting
with its error. retro_task_threaded_gather drops from 8 lock
acquisitions to 6 and the budget reference moves with it.
2026-10-04 11:20:19 +02:00
LibretroAdmin 71318ef1ec Fix build warnings on old GCC, uClibc and old wayland-scanner
Statics rely on implicit zero initialisation instead of {0}, and local
aggregates whose first member is an array get the matching braces, so
GCC 4.x -Wmissing-braces stays quiet. Locals the compiler cannot prove
written are initialised (rh265 keep[], rflac block header, query.c
lengths), loops older VRP misreads are reshaped, the unused SDL2
geometry forward declaration is gone, and task_queue no longer names a
variable main.

rzstd probes BMI2 with __get_cpuid_max/__cpuid_count, which every
cpuid.h the branch accepts provides. Hole punching needs uClibc-ng 1.0
with its Linux-specific API on uClibc. The sinc resampler's pop_options
does not warn on GCC 4.x MIPS. generate_wayland_protos.sh strips the
event type and deprecated-since attributes for scanners whose DTD
predates them, which ignore them anyway.
2026-10-04 04:23:50 +02:00
LibretroAdmin ac1b9c3dfa task_queue: a finished task always makes its retirement push
Whether a widget is attached is read by the widgets, under their state
lock: frontend_userdata is their link, and under the threaded video
wrapper the video thread clears it as it frees a widget. The gather
pushes every finished task, and the widgets spawn nothing for an empty
push with nothing attached.

gfx_widgets_task_gate_test retires tasks through the widgets' push
while another thread frees the widgets bound to them, under TSan and
ASan, and checks a muted task's retirement puts nothing up.
2026-10-02 10:20:47 +02:00
LibretroAdmin 2e10a65f98 task_queue: progress is reported after running_lock is dropped
The gather's pass under running_lock counts the due main-thread tasks
and takes down the running ones; the progress reports - formatting,
and the push into the frontend's message path - are made after it, so
a worker picking up or settling a task, or a thread queueing one,
never waits on the frontend. The list the tasks are taken down in
grows on the main thread to the number running.

task_queue_snapshot_test queues a task from a second thread inside a
progress report, and checks every one of 80 running tasks is reported.
2026-10-02 07:25:43 +02:00
libretroadmin 22571cbe42 task_queue: hand the fast-cores preference to the worker atomically
The preference is stored with release ordering on the main thread and loaded with acquire ordering by the worker as it starts, so a worker started while the setting is applied reads it without a data race.
2026-10-02 02:11:00 +02:00
LibretroAdmin 4e9bff8d64 task_queue: a main-thread handler that waits does not run them again
The threaded gather a wait runs from inside a main-thread handler
leaves the main-thread tasks to the pass further up the stack.  They
ran twice and were freed twice: a load that failed with Threaded Tasks
on crashed falling back to the dummy core.
2026-09-30 19:20:56 +02:00
LibretroAdmin 3db41c4d27 task_queue: count due main-thread tasks in the progress walk
The gather already holds running_lock to publish progress; counting
the due main-thread tasks there saves the frame a second acquisition.
2026-09-30 06:16:46 +02:00
LibretroAdmin d3149eb217 task_queue: time main-thread handlers on the threaded runner
The slow-handler watchdog now also measures RETRO_TASK_FLG_MAIN_THREAD
handlers when Threaded Tasks is on: they run on the frame thread there
too, so an overrun is the same visible stall.
2026-09-30 06:16:35 +02:00
LibretroAdmin af2997c9d2 task_queue: RETRO_TASK_FLG_MAIN_THREAD runs a handler on the checking thread
A task pushed with the flag has its handler run by task_queue_check()
- the main thread - under every runner: the threaded worker and the
GCD dispatch pass such tasks by, and the gather runs the due ones once
each within the handler budget, settling them as the worker settles
its own.  Work that must stay on the main thread (calls into the
core, the drivers, the menu) gets a task's lifetime: pushed, found,
cancelled, retired through callback and cleanup.

Sample task_queue_main_thread_test covers both runners: where the
handler runs, one call per check while unfinished, a future 'when',
task_queue_wait(), and plain tasks interleaved with main-thread ones.
tools/platform_stubs/gcd carries a dispatch.h stand-in so the HAVE_GCD
arm syntax-checks with clang -fblocks off Apple.
2026-09-30 02:23:13 +02:00
Codex 108642a968 Publish progress from the regular task runner
The regular runner executes on the pumping thread but skipped running-task progress pushes as though a separate threaded gather would deliver them. Publish updates for unfinished tasks after their handler, while leaving final delivery to retirement. This restores notifications and progress callbacks when threaded tasks are disabled.

Test intermediate updates and exactly one final update; clarify prefetch's existing callback deduplication.
2026-09-28 05:41:53 +02:00
Codex 140a30ea9f Publish suppressed task completion to attached widgets
A muted task or failed final title allocation can suppress its last progress push, leaving a widget linked to a freed task. Send an empty completion message when frontend data is attached. The runloop updates widget lifetime state without forwarding empty text to notifications or speech.

Cover muted and missing-title completions, callbacks outside the property lock, and real task retirement with an attached widget.
2026-09-28 05:12:20 +02:00
Codex 9d8228ebb1 Snapshot task display properties before updating widgets
Copy title, error, flags and progress together under the task property lock. Widgets consume the owned copy after that lock is released, preserving the existing task association and widget-state locking. Keep terminal flags available on allocation failure so retiring tasks do not leave live widget references.

Add regression coverage for concurrent string replacement, retained snapshots, allocation failures and an unthreaded runner.
2026-09-28 03:35:32 +02:00
LibretroAdmin 82c06f7d17 task_queue: init(false) clears the threaded flag
task_queue_init() set task_threaded_enable only when asked for a
threaded queue and never cleared it, so init(false) after a threaded
session left the flag on and the next task_queue_check(), seeing the
flag and an unthreaded queue disagree, re-initialised the threaded
one behind the caller's back. RetroArch never hit it because its
settings path clears the flag through task_queue_unset_threaded()
first; any other user of the queue did.

The flag now follows the argument both ways. task_queue_budget_test
drops its workaround and checks that init(false) after a threaded
session stays unthreaded across a check; that lane fails on the old
queue, and the two unthreaded lanes after it fail with it.
2026-09-26 22:35:25 +02:00
LibretroAdmin e8c5c813ef task_queue: budget retirement and unthreaded handlers per check
Two audit P1s, both about task_queue_check() taking as much of the
frame as it likes on the thread that drives the frame loop:

- Retirement had no bound. Finished tasks retire (progress push,
  callback, cleanup, free) on the checking thread, and a burst of
  completions - a thumbnail scan, a bulk download - retired in one
  check however long the callbacks took.
- On the unthreaded queue every running task's handler ran once per
  check, so the frame cost grew with the running list.

task_queue_set_budget(retire_usec, retire_max, handler_usec) bounds
one check. Retirement stops once retire_max tasks or retire_usec have
gone by, after at least one; what is left stays on the retiring list,
findable, for the next check (the threaded early-out is told there is
work pending). Handlers stop once handler_usec has gone by, after at
least one due handler; the tasks not run go back to the front of the
running list, the ones that ran behind them, so the list rotates
instead of starving its tail. The unthreaded gather now keeps FIFO
order rather than reversing the list each pass, which the rotation
needs. Zero means unbounded and is the default, so nothing changes
for a caller that does not opt in.

RetroArch sets 2 ms or 32 callbacks for retirement and 4 ms of
handler time per check, leaving most of a 16.7 ms frame to the core.
task_queue_wait() loops on the check, so a blocking wait is slowed,
never changed.

task_queue_budget_test covers the count and time retire budgets and
the unbounded case on the threaded queue, and the handler budget,
rotation fairness and the unbounded case on the unthreaded one. Four
of its seven lanes fail against the old queue. Wired into
Linux-libretro-common-samples.
2026-09-26 22:33:49 +02:00
LibretroAdmin 050d0a92c2 Place the video thread and task worker on the fast cores too
"Prefer Performance Cores" (thread_prefer_fast_cores) pinned only the
main and audio threads. The two other frame-critical threads never
asked: the threaded video worker (video_thread_wrapper.c) and the task
queue worker (task_queue.c), which runs the completion handlers the
frame loop retires.

Both now take the same sthread_prefer_fast_cores() placement when the
setting is on:

- video_thread_set_prefer_fast_cores() is set from video_driver.c
  before video_init_thread() and applied at the top of
  video_thread_loop().
- task_queue_set_prefer_fast_cores() is set in retroarch.c before
  task_queue_init() and applied at the top of threaded_worker(). It
  is a setter rather than a task_queue_init() argument so the samples
  and stubs that call task_queue_init() are untouched. No effect on
  GCD, which has no worker thread.

The setting's sublabel now names all four threads.
2026-09-26 21:20:09 +02:00
LibretroAdmin 3d0e133db1 task_queue: push a task's message with property_lock released
The message is built from the task's title, progress and flags under the
lock that guards them, and the push that carries it to the frontend runs
with that lock released. msg_push() inserts into the widget queue and, on
a build with accessibility enabled, reaches a speak backend that forks;
a worker's task_set_progress() has no business waiting behind that.

The push therefore carries the formatted string and nothing the lock
guards, which makes the title and mute tests in
runloop_task_msg_queue_push() the caller's to make: re-reading the title
there would be reading a pointer a worker is free to free, so they go.
The widgets' one remaining read, ALTERNATIVE_LOOK, is set while the task
is built and never changed after, and says so where it is read.
progress_cb() stays under the lock - it reads the task's progress and
finished flag, and pokes the display server rather than going through the
message path.

samples/tasks/progress_push holds the contract. msg_push() there calls
task_get_progress(), which takes that same non-recursive lock, so a push
made under it deadlocks and a watchdog names the phase; the worker churns
the title free-then-set throughout, so a push reading task->title is a
race TSan reports against task_free_title(). Both halves were checked by
injecting each defect. Clean under ASan, ASan+UBSan and TSan; the thread
read audit stays at 0 findings.
2026-09-21 12:11:30 +02:00
LibretroAdmin d0cb8317dd Take four locks off fast paths
android_display_has_focus() returns one acquire load of an atomic the
focus commands publish with a release store, which is all the ordering
there is to carry; the input poll reaches it every frame. A dispmanx
page carries its used flag as an atomic, claimed by the frame thread and
released in the vsync callback - the form the free-page scan already
reads it in - so a page needs no mutex of its own.

task_queue keeps one lock over the running queue: running_lock guards
every walk and every splice of it, task_queue_remove() included, and
task_queue_push()'s blocking-task scan takes it like the push_running()
that follows. librsound calls the client's audio callback directly;
rsd_callback_lock() and rsd_callback_unlock() go with the lock they
were the only users of.
2026-09-21 10:28:13 +02:00
LibretroAdmin ece2bb3824 task_queue: bound the worker join, and let a detachable handler be left behind
task_queue_deinit() joined the worker with no limit. The exit path
already drains tasks with a bound (retroarch_drain_tasks_for_exit),
but a handler that is blocked inside an OS call outlives that drain,
and then held the join in task_queue_deinit() - and with it quit, and
every reinit of the queue on content load - for as long as it stayed
blocked. A DirectInput device walk held by a Bluetooth stack still
coming up after boot is one such handler.

Deinit now waits for the worker with a bound (one second). A worker
that is idle or doing the queue's own bookkeeping sees worker_continue
and leaves long before that, and says so on worker_cond, so the common
case wakes exactly when it exits rather than polling. Only a handler
that has not returned can run the bound out, and then:

- If the task was pushed with the new RETRO_TASK_FLG_DETACHABLE, deinit
  stops waiting. The task is taken off the running queue, the worker
  thread is detached, and the queue's globals are cleared for the next
  init. The worker, as soon as its handler returns, finds itself
  orphaned, takes its own generation's running_lock once - which deinit
  releases as its last step, so that is an exact wait, not a poll -
  then frees that generation's primitives and the task and exits
  without touching any global. The task's callback and cleanup never
  run.

- Otherwise deinit keeps waiting, as before: a handler that did not
  promise otherwise may be using something teardown frees next
  (net_http's pool is released right after task_queue_deinit() on
  exit, for one).

Detachable is a promise by the pusher that the handler touches only its
own task: its state, and the task_set_* / task_get_* accessors. No
logging, no pushing other tasks, nothing the frontend tears down. The
accessors take property_lock, so once a worker has been left behind
that lock is kept and reused by every later init instead of being freed.

Where the worker is, and which primitives are its own, now live in a
per-worker record passed as the thread's userdata instead of in
globals: a worker left behind must not read the state of the one the
next init starts.

samples/queues/task_queue_detach_test pins it: an idle worker stops at
once; a detachable handler stuck past the bound is left behind, a new
queue runs tasks meanwhile, the handler finishing later touches nothing
of it and its callback never fires; a handler that is not detachable
is still waited for past the bound. Clean under ASan, UBSan and TSan,
and added to the libretro-common samples job.
2026-09-18 15:41:18 +02:00
LibretroAdmin 85f8fd310e retroarch: the exit path drains the task queue before teardown
The discovery pass's shutdown-ordering thread, opened by the mixer
retirement fix: main_exit() tore drivers down and freed global state
before task_queue_deinit(), and deinit abandons whatever is still
queued - the worker breaks out mid-queue (its own comment asked
whether it should), so remaining handlers never run, finish
callbacks never fire, and cleanup callbacks never release their
owners. A mixer load, a screenshot, a database scan chunk in flight
at quit just leaked, and anything that did retire in that stretch
retired into torn subsystems - the class the MIXER_INITED latch
guards one door of.

main_exit() now runs retroarch_drain_tasks_for_exit() first:
task_queue_reset() cancels everything so cancellation-aware handlers
wind down instead of completing their work, and a bounded
task_queue_wait_timeout() retires the queue - handlers, finish
callbacks and cleanups all run on the exiting thread while every
subsystem they can reach is still alive. The bound (three seconds)
keeps a stuck handler from hanging quit; whatever survives it meets
the old abandonment, demoted from rule to fallback. Tasks scheduled
for later (a set 'when') do not hold the wait and are dropped as
designed. The worker's questioning comment now states the contract.

samples/tasks/exit_drain links the shipping objects with only main()
replaced, boots headless with the threaded task runner, and puts the
exit-time population in flight: a cancellation-aware handler
mid-run, a task completing on its own, and one scheduled thirty
seconds out. The drain must retire the first two - handler wound
down, finish and cleanup callbacks run - in well under the bound
(432 microseconds measured) without the deferred task holding it.
The MODE=old lane runs the pre-change order, straight to
task_queue_deinit(): the aware task's callbacks never run, which is
the abandonment this change demotes.

Verified: both harness lanes green as stated, playlist_nav green,
thread-read audit 0 findings / 0 allowlisted pairs, C89 gate clean
on task_queue.c, full build scanned clean for the warning classes,
hot-function budgets and the 74-lane compile matrix.
2026-09-16 10:00:18 +02:00
LibretroAdmin 0119f1991d runloop: a worker's message crosses to the main thread once
runloop_msg_queue_push() renders widgets, measures text, speaks the
accessibility line and reads the settings - the main thread's work,
and six of the threaded task handlers were doing it on the worker.
An off-main caller now queues the message, whole, under the message
queue lock, and the iterate's drain replays it on the main thread a
frame late at most - the cadence messages show at anyway. The
threaded task worker also stops pushing progress after a handler:
the gather pushes for every running task each check and retirement
pushes the final state, both on the main thread, so the worker-side
push was a duplicate doing widget work from the wrong thread through
the queue's message callback - a function pointer the audit cannot
see, which is worth remembering.

The audit learns what this fix is: a boundary - a function that
defers off-main callers before touching anything - declared as
@boundary in tools/thread_read_allow.list and held by review, where
the walk stops. runloop_msg_queue_push is the first.

tools/thread_read_audit.py --binary retroarch: 23 findings become
11, across every handler that showed messages; the remaining 11 are
direct reads. All twenty-one task sample suites pass.
2026-09-15 15:42:49 +02:00
libretroadmin 0b19092315 task_queue: a threaded queue that cannot start is not left in place
task_queue_init() selects the threaded implementation before running its
init hook, so an init that produced no worker left the queue accepting
tasks nobody would service. slock_new() and scond_new() return NULL when
the allocation or the platform primitive fails and sthread_create()
returns NULL when a thread cannot be started, none of which was checked;
slock_lock() tolerates a NULL lock but scond_signal() does not.

The threaded and GCD hooks now build their synchronisation primitives
through one helper that takes the whole set back if any of it is
missing, and the threaded hook releases them again when the worker
cannot be created. A failed init reports it, and task_queue_init() falls
back to the regular implementation so tasks run on the caller's thread
instead of queueing forever. Callers read the outcome through
task_queue_is_threaded(), which is where the frontend logs it.

task_queue_init_failure_test forces sthread_create() to fail and checks
that the queue reports itself unthreaded, that a task pushed to it still
runs, and that a later init starts a worker again.
2026-09-14 14:43:54 +02:00
libretroadmin bb80db9bfc task_queue: an idle gather takes no lock
retro_task_threaded_gather() runs every frame. The sizes of
tasks_running and tasks_finished are also kept in two atomics, changed
where a task enters or leaves those queues under the queue's lock, and
the gather returns before taking any lock while both are zero - no task
running and none to retire, as on nearly every frame. A finishing task
counts as finished before it stops counting as running, so both are
never zero while one is in flight; a task that finishes just after the
test retires on the next call.

That is three lock and unlock pairs fewer per frame for the threaded
task queue, with threaded video or without.
2026-09-11 07:56:18 +02:00
LibretroAdmin 75d79f9009 task_queue: sleep in the blocking waiters instead of spinning
retro_task_threaded_wait() and retro_task_gcd_wait() looped on
gather() with nothing in between until the task they were waiting on
retired.  That pinned a core for the whole wait: profiling a CLI
--scan showed the main thread at 50% of the process, all of it taking
and releasing running_lock and finished_lock in the loop.  The same
loop serves the blocking save/load-state paths in task_save.c.

Add finished_cond, signalled by both workers when a task moves onto
the finished queue, and park the waiter on it between passes.  The
wait is bounded at 1 ms so the states the signal does not cover - the
caller's own condition flipping, a task that keeps yielding without
finishing - still resolve promptly; a task already sitting on the
finished queue is not waited for at all, gather() retires it on the
next pass.

--scan of the PC Engine set against all 147 rdbs: 78 ms task-clock
for 79 ms elapsed (0.99 CPUs); the second core is idle.  Wall time is
unchanged.  Playlist output byte-identical.  TSan clean on the scan,
ASan+UBSan+LSan clean.

Same change belongs in the standalone libretro-common repository.
2026-09-10 23:06:34 +02:00
LibretroAdmin b646d5af77 task_queue: threaded cancel sets the cancelled flag under property_lock
task->flags is guarded by property_lock - the worker's handler reads
it through task_get_flags mid-task - and the threaded reset already
takes it for exactly this reason. Cancel was the one site left
setting the flag under running_lock alone, which both races that
read and, being a read-modify-write, can lose a concurrent
task_set_flags update in either direction. The GCD backend shares
this cancel, so it is covered by the same change.
2026-09-04 20:39:41 +02:00
LibretroAdmin 76c3d4817e Label the frontend's long-lived threads
sthread_setname applies a short label to the calling thread, so the
frame loop, video, audio and task worker threads identify themselves in
debuggers, tombstones and ANR reports. Threads that go unlabelled
inherit the name of whichever thread created them, which on Android
leaves an ANR report holding several identically-named entries and a
tombstone naming no thread at all.

Linux and Android go through prctl, which takes the name as a buffer
and so truncates at the kernel's 16-byte limit rather than rejecting an
over-long label; Apple and the BSDs use their respective
pthread_setname_np spellings. Platforms with no naming interface get a
no-op.
2026-08-20 11:13:30 +02:00
LibretroAdmin 6ed120d12e task_content: fix the deferred menu load's remaining #19426 defects
The deferral gate mirrors the load's BLCK_NEED_FULLPATH decision
and declines content the load will not read into memory: a
need_fullpath core (ppsspp + chd, the reported repro) is handed the
path, so a prefetch fills an allocation nothing consumes.  The
decision reads the live system info and override list - LOAD_CORE
has run by the gate; the caller's content_ctx is built before it,
without sys info.  The progress callback is delivered on the
thread that pumps the queue under either queue mode - a
task->progress_cb trampoline dedups per change on the pumping
thread, the unthreaded handler delivers directly, and
task_queue_push_progress() fires the callback for any non-mute
task while messages keep the title gate.  The parked continuation
is stamped with the content and core paths it belongs to and
stands down on a mismatch, since in-flight tasks survive a
competing load's queue reinit.

The oracle gains a threaded progress-callback lane pinning
delivery to the pumping thread; the pre-fix code fails it.  Sweep:
ASan+UBSan+LSan pass (9 lanes), TSan 35/35 clean, oracle also run
on aarch64/bionic (NDK r29, static, qemu-user), NDK arm64-v8a
griffin.o compiles clean, desktop griffin error set unchanged.
End-to-end differential (headless build, real ppsspp core, 400 MB
chd via the from-menu entry point): peak RSS 415 MB before, 25 MB
after.

Fixes https://github.com/libretro/RetroArch/issues/19426
2026-08-18 11:29:42 +02:00
LibretroAdminandLibretroAdmin 334e8b7baf UI non-blocking, part 3: netplay host init and content close (#19417)
* netplay: bound the wait for tunnel information

Stage 1 of making netplay host init non-blocking: the hang becomes an
error, with no new states and no restructuring.

Hosting through a relay waits for the lobby server to answer with a
tunnel address.  The wait was already narrowed to that one query, but
it was still unbounded - and it is a round trip to a machine we do
not control.  A lobby server that is down, blackholed or merely slow
left the frontend hung with no way out but killing it.  It now gives
up after ten seconds and reports failure like any other query, so the
caller falls back to direct mode with the warning it already has.
Generous on purpose: timing out a query that would have succeeded
costs the user their session, while waiting a few seconds longer
costs only patience.

task_queue_wait_timeout() is the bound.  It wraps the caller's
condition in one that also goes false at a deadline and hands that to
the existing wait, so every queue implementation - regular, threaded
and GCD - keeps its own waiting behaviour and no platform-specific
code is touched.  Adding a variant to the implementation vtable would
have meant editing the GCD path blind, which is the shape of a recent
break and not worth repeating for this.

A timeout alone would have been a bug, not a fix.  The query is still
in flight when we give up, and its callback writes
host_room->mitm_address and mitm_port unconditionally - so it would
land after the fallback and publish a tunnel address for a session
running direct.  Each query now carries a generation token and the
callback ignores results that are no longer current; abandoning a
query bumps the generation.  That also closes the pre-existing case
of two queries overlapping.

The oracle covers the primitive rather than netplay's HTTP, because
that is where the risk is: the netplay side is a few lines routing
into an else branch that already existed.  Five lanes over both queue
implementations assert that a satisfiable wait returns as soon as it
is satisfied - not after sitting out the timeout, which would pass a
naive check - and that an unsatisfiable one gives up near the
deadline rather than early or never.  Removing the deadline hangs the
lane until CI kills it, which is the behaviour being removed.

Verified: builds with networking ENABLED and DISABLED, the latter
being the configuration class that broke recently; task_queue.c links
for ARM32 without NEON; all nine task oracles still pass, since that
file is shared; the new lanes pass plain, under ASan+UBSan+LSan and
twice under TSan.

Not verified: behaviour against a real unresponsive lobby server.

* netplay: split the tunnel query into begin / await / result

Stage 2 of making netplay host init non-blocking: a refactor that
changes no behaviour, so it can be reviewed on its own before
anything moves.

netplay_mitm_query() welded "ask the lobby server" to "wait for the
answer".  Those are now netplay_mitm_query_begin(),
netplay_mitm_query_ready(), netplay_mitm_query_await() and
netplay_mitm_query_result(), with netplay_mitm_query() calling them
back to back at the same call site.  Nothing is deferred and nothing
moves; the point is that the next step - issuing the query when the
user opens the host UI, so the answer is already there when host
setup runs - becomes a change of WHERE begin() is called rather than
a restructuring of host init.

Every path was walked against the original:

  handle NULL/empty       false                 begin() false
  custom, decode fails    false                 begin() false
  custom, decode ok       address set, result   begin(), await(), result()
  http push fails         pending cleared,false begin() false
  http ok, reply in time  wait, then result     await() waits, result()
  http ok, timeout        warn, bump gen, false await() identical

One deliberate difference, because the split exposed an edge the old
shape hid.  The custom-relay path answers synchronously and the old
code returned without ever consulting the pending flag - so an
earlier query left outstanding could not make it wait.  Routed
through await() it would have, so the custom path now supersedes any
query in flight: it bumps the generation and clears the flag.  That
also stops a late callback from overwriting the address it just set,
which the old code would have allowed.

Verified: builds with networking enabled AND disabled; the
wait_timeout CI step replayed verbatim; the netplay NAT, task
ordering and watchdog oracles still pass.

Not verified: behaviour against a real lobby server.

* netplay: start the tunnel query when the user commits to hosting

Stage 3, and the one that removes the stall the user actually feels.

Host setup needs the relay address, and the query for it was issued
at the moment of need - so the wait was the full round trip, every
time.  It is now issued at CMD_EVENT_NETPLAY_ENABLE_HOST, where the
user commits to hosting, which is well before the address is wanted:
on the content-reload path, before content has even started loading.
The round trip overlaps work that was going to happen anyway, so by
the time host setup asks, the answer is usually already there and the
wait costs nothing.

Nothing is deferred and host init is not restructured.  The wait
stays exactly where it was, as the backstop for the case where the
answer has not arrived yet - which is what makes this cheap to
reason about and cheap to revert.

Prefetching only matters if asking twice is avoided, so the query
records the handle it was issued for, and host setup reuses an
answer that is already in hand or on its way.  It deliberately does
NOT reuse a prefetch that came back empty: a transient lobby failure
at prefetch time would otherwise doom a session that asking again
would have got, and one extra request is the better trade.  Every
state was walked:

  no prefetch                query issued as before
  prefetch in flight, same   reused, one query, overlapped
  prefetch answered          reused, no wait at all
  prefetch came back empty   re-issued
  relay changed since        re-issued, picks the new server
  custom relay               answered synchronously, reused

The prefetch is best effort in the strictest sense: skipped when the
relay is off or unconfigured, and if it fails for any reason host
setup asks exactly as it did before.  It is not speculative - the
user has already chosen to host, so no request is made for anyone who
merely opens a menu.

Verified: the call site sits inside #ifdef HAVE_NETWORKING, computed
from the preprocessor nesting rather than eyeballed, and both builds
were made - networking enabled AND disabled, the configuration class
that broke recently.  The wait_timeout CI step was replayed verbatim
from the workflow, and the netplay NAT and task ordering oracles
pass.

Not verified: behaviour against a real lobby server, including
whether the overlap is long enough in practice to hide the round
trip on the content-reload path.

* content close: pin the save wait, and say what it is waiting for

Stages 0 and 1 of unblocking content close.  Nothing about the wait
changes; this establishes what it guarantees and stops it looking
like a hang.

Stage 0, the oracle lane.  Closing content waits for in-flight save
and load tasks because their handlers call into core function
pointers - retro_serialize via content_get_serialized_data,
retro_unserialize via core_unserialize - while
runloop_event_deinit_core() unloads the dylib underneath them.  A
worker mid-call when the library goes away dispatches into freed
code.  That is why this wait, unlike the others removed in this
series, cannot simply be deleted.

The lane pins the property the unload depends on: the file is
checked incomplete before content_wait_for_save_state_task() and
complete after, so a wait that returned early - on a budget
boundary, say - fails here rather than becoming a crash on a device.
Neutering the wait fails it, as it should.

Stage 1, legibility.  The wait cannot be shortened without deferring
the teardown itself, which is later work, but an unexplained frozen
frame and a frame that says "saving state" are very different
experiences - and on slow storage this is seconds, not milliseconds.
The message is pushed and one frame forced out before blocking,
since nothing draws once the wait starts.

It fires only when there is something to wait for, using the same
condition the wait itself uses, so an ordinary close with no save in
flight is untouched and shows nothing.  That predicate had to become
public to be asked from here; its load counterpart already was.

Verified: builds with networking enabled and disabled; the
save_state oracle passes, including the new lane, and fails when the
wait is neutered.

Not verified on a device: whether the message reads well in the case
that matters, which is the slow-storage close it exists for.

* runloop: introduce the content-closing state, observed by nothing

Stage 2 of unblocking content close.  A no-op by construction: the
state is set and cleared around the teardown that already exists, so
while it is true the main thread is inside that teardown and no
frame runs to ask about it.

It is introduced on its own precisely because the work that makes it
observable - returning to the frame loop instead of blocking on the
save wait - is a lifecycle change, and this is the piece the rest
will key off.  Reviewing the two separately means a problem with the
lifecycle change is one revert, not an unpicking.

A plain bool in runloop_state_t rather than a RUNLOOP_FLAG bit.
Bits 0-30 of that word are taken and bit 31 was deliberately vacated
to avoid a cross-thread race with the AppIntents entity query;
reusing it would undo that reasoning for no gain, and this is
main-thread only.

The clear is placed at the block's single exit, which was checked
rather than assumed: there is no early return or goto between the
set and the break, so one clear covers every path.  A leaked true
would be harmless today and would wedge the frame loop at stage 3,
which is exactly the kind of thing worth getting right while it
still cannot bite.

Verified: nothing reads the state except its own accessor, which
nothing calls - grepped rather than asserted, since "no-op" is the
entire claim here; builds with networking enabled and disabled; the
save_state oracle passes and the wait_timeout CI step was replayed
verbatim from the workflow.

* task_queue: fix two data races TSan found in CI

Two separate races, one mine and one older.

Mine, in the oracle: work_pending was cleared by the task HANDLER,
which runs on the worker thread, and read by the waiting main
thread.  A plain bool across two threads - a race on inspection,
with no tooling needed to see it.  It was also a misrepresentation
of the thing under test: the code being modelled,
netplay_mitm_query_cb(), clears its flag in the CALLBACK, which runs
on the thread pumping the queue.  Clearing it there fixes the race
and makes the test match what it claims to model.

The older one is in the queue itself.  retro_task_threaded_reset()
set RETRO_TASK_FLG_CANCELLED under running_lock, while the worker
reads task->flags under property_lock - two locks for one field.
It needed a reset to land while a worker was mid-task, which is why
it sat undisturbed until a lane that cancels an unfinished task
turned up.  The flags are now set under property_lock as well.
Nesting is safe: property_lock is never held while any other lock is
taken anywhere in this file, checked by walking every lock/unlock
pair, so it can only be an inner lock and no cycle exists.

Both are load-bearing, measured rather than assumed: 40 TSan runs
report 0 races with both fixes, and reverting the queue fix alone
brings it back at 6/40.

On the reporting of this: the commit that introduced the oracle said
it passed twice under TSan.  That was true - I ran it, three times
including the CI replay, and it passed each time.  The race
reproduces about once in twelve runs here, so three clean runs were
about a 78% chance of missing it.  The claim was accurate and the
verification was not adequate, which is the more useful way to say
it.  Repeat counts for anything threaded are now sized against how
rare the failure can be, not against how many runs feel like
enough - and a shared mutable flag written from a handler should
have been caught by reading it, which is where this should have
stopped.

Verified: 40 TSan runs clean on the changed lane; 8 each on the
other threaded oracles, since task_queue.c is shared by all of them;
every task oracle passes on a plain build; desktop build clean; the
CI step replayed verbatim from the workflow.

* runloop: don't run the core while content is closing

Stage 3 of unblocking content close.  Still inert, and deliberately
so: it establishes what the frame loop must do while the closing
state is set, before anything can set it with frames running.

retro_run() must not be entered once closing has begun, because the
teardown unloads the library that function lives in.  The guard
therefore has to exist before the wait moves out of the close path,
not with it - otherwise the change that lets frames run would be
introducing both the opportunity and the protection at once.

That it cannot fire today was checked rather than assumed: both
core_run() call sites are inside runloop_iterate(), and the content
close block in CMD_EVENT_CORE_DEINIT reaches neither - it calls no
iterate, no core_run and no run_ahead, so the main thread cannot be
in the frame loop while the flag is set.

It polls input and presents a cached frame rather than returning
bare, matching the netplay-paused case immediately below, and for
the same reason: a frame that simply stops being produced reads as a
hang, which is the whole complaint being worked on here.

Verified: builds with networking enabled and disabled; the
save_state oracle passes, including the lane that pins the close
wait; the wait_timeout CI step replayed verbatim from the workflow.

Worth stating before stage 4: at that point this guard stops being
inert, and video_driver_cached_frame() will be running while a core
is being torn down.  That is the first thing to look at if the frame
loop misbehaves during a close, and it is why the harness lane for
content close belongs before that change rather than after it.

* runloop: fix C89 violation in core_run

The content-closing guard was placed before netplay_preframe's
declaration, so that declaration followed a statement:

  runloop.c:8808: error: ISO C90 forbids mixed declarations and code

netplay_preframe is now declared with the other locals and assigned
where it was, so the guard still returns before netplay's pre-frame
call and the declarations stay at the top of the block.

My own standing rule is that every C file gets the strict C89 gate
before commit, and I did not run it on this one - the ordinary
desktop build does not use those flags, so it compiled clean and I
took that as sufficient.  It is not, and the gate exists precisely
because it is not.

Verified with the flags the C89 build actually uses, on runloop.c
with networking both enabled and disabled, and with a full
C89_BUILD=1 compile of the tree; reinstating the original ordering
reproduces the reported error, so the check is real rather than
vacuous.

* samples: drive the content-closing guard against the real frame loop

Stage 4 will stop blocking on the save wait and let frames run while
a close finishes.  The guard that makes that safe - core_run()
refusing to enter retro_run() while content_closing is set - is
already in place, and is at present completely unexercised: closing
is synchronous, so no frame runs during it, and the guard would go
live in the same change that first creates the situation it protects
against.  If it were wrong, the symptom would be a call into an
unloaded dylib.

So it is driven here first, directly: the real core_run(), in a real
frontend brought up headless, with the flag set.  Links the shipping
objects with only main() replaced; nothing is stubbed.

Three assertions, and the first exists to stop the others passing
vacuously: with the flag CLEAR the core must actually be entered, or
this harness would be proving nothing about a core_run() that never
reaches retro_run() in this environment anyway.  Then with the flag
set it must not be entered, and once cleared it must resume - a
sticky guard would leave the frame loop dead after a close.  A
second lane runs 240 frames with the flag set, the shape of a close
on slow storage, checking core_run() returns cleanly every time
rather than faulting or wedging.

Removing the guard fails both lanes with exactly the message they
exist to produce.

It joins the existing menu-harness workflow, which already makes the
non-Qt build these harnesses need - with Qt enabled ui_qt.o defines
main and the link collides - so it adds about two seconds rather
than another full build.  The step was replayed verbatim from the
workflow before commit, and the menu harness alongside it still
passes.

Verified: strict C89 gate on runloop.c with networking on and off,
which is the check I skipped last time and should not have.

* retroarch: extract the content-close teardown into its own function

Preparation for removing the close freeze, and nothing else: the
sixty lines that run after the save/load wait move into
command_event_finish_content_deinit(), still called from exactly
where they used to run.

They have to become resumable.  The wait above them is the freeze
this work is about, and removing it means this half runs later -
from the frame loop, once the tasks have finished - so it needs to
be callable from somewhere other than the middle of a switch case.
Doing the extraction on its own makes the next change a question of
WHEN it is called rather than what it does, which is the difference
between a revert and an unpicking if that goes wrong.

Every local is re-derived from its accessor rather than passed in,
so the function carries no dependency on the caller's frame - which
is what lets it be called from the frame loop later.

The extracted body was compared statement by statement against the
original block: 53 statements, zero differences.  That check was
worth writing, because the first attempt at this anchored on a
comment that appears twice in the file and silently swallowed an
unrelated case - it failed to compile, but a subtler overshoot would
not have.

Verified: strict C89 gate on retroarch.c with networking on and off;
builds with Qt and headless; both full-program harnesses pass, and
the save_state oracle with them.

---------

Co-authored-by: LibretroAdmin <[email protected]>
2026-08-16 22:11:06 +02:00
LibretroAdmin d16de33c3b task_queue: report handlers that occupy the main thread too long
Phase C guardrail for the non-blocking work.  With Threaded Tasks
off, task handlers run on the thread that also drives the frame
loop, so a handler that does not return promptly is a visible stall
- and until now nothing detected one.  A regression in a budgeted
handler (the directory walks, the playlist parse, the scanner) would
show up as "the menu feels sticky", found by a user rather than by
the build, and attributing it back to a specific task meant
profiling.

The queue is the only place that can make that attribution, so the
measurement lives there: task_queue_set_slow_handler_cb() registers
a callback and a budget, and the untheaded gather reports any
handler invocation that exceeds it.  Two properties keep the cost
honest.  With no callback registered - the default, and what
release builds ship - the queue reads no clock at all.  And only the
untheaded queue is measured: on the threaded queue handlers run on a
worker, where taking a long time is the entire point.

RetroArch registers it in debug builds only, with a one-frame budget
at 60Hz, and only when Threaded Tasks is off.  The report names the
task and is rate-limited per handler, because a task that stalls
once usually stalls on every invocation and a warning per frame
would bury the first and most useful one.

The budget is deliberately loose relative to what the sliced
handlers aim for: they consult the shared per-frame I/O window and
finish far inside it, so anything crossing a whole frame in a single
call is either unsliced work or a slice that has stopped honouring
its budget - which is exactly the regression worth a warning.

A new oracle (samples/tasks/watchdog) compiles the shipping queue
and pins all four properties: a handler inside its budget is silent
however often it runs; one that overruns is reported once,
attributed to that task, with a duration above the budget; the
threaded queue produces no reports; and an unregistered watchdog
never fires, before or after being registered and cleared.

Verified: strict C89 gate on task_queue.c; retroarch.c
syntax-checked with DEBUG defined so the registration path is
compiled, not just skipped; full Linux build links with HAVE_QT=1;
all four lanes pass plain, under ASan+UBSan+LSan and under TSan;
the lanes were falsified by disabling the comparison, which they
catch; the dirwalk, playlist, scan and NAT oracles still pass.
2026-08-15 08:02:36 +02:00
BinBashBananaandlibretroadmin c464c6620a Emscripten libretro-common fixes, use __EMSCRIPTEN__ (#19297)
* Emscripten libretro-common fixes

* memmap: gate the reserve/commit path off for emscripten instead of dropping mman

Emscripten was added to the "No mman available" platform list in
memmap.h, which reaches further than intended. That branch does not
just disable things: it makes memmap.c define mmap(), munmap() and
mprotect() as global symbols with malloc/free semantics on a platform
whose libc already provides working ones, and it declares mmap() with
a size_t offset where <sys/mman.h> uses off_t, so any translation unit
that pulls in both headers gets conflicting declarations. The shim's
mmap() also ignores fildes and offset, so a file-backed request would
return uninitialised memory; that is invisible today only because
Makefile.emscripten never sets HAVE_MMAP and the mapping path in
vfs_implementation.c is therefore compiled out.

What is actually unusable on emscripten is the reserve/commit model,
and that is unusable by construction rather than by omission: a wasm
linear memory grows monotonically, is committed in full, and has no
unmap, no shrink and no page protection. An anonymous PROT_NONE
mapping is a memalign of the whole length followed by a memset over
it, so memreserve() commits and touches every byte the reservation
existed to avoid, mprotect() and madvise() cannot make commit or
decommit mean anything, and munmap() only accepts an exact length
match, so the range cannot be released. Opening large content through
data_transfer would allocate the whole file up front and never give it
back.

Leave memmap.h alone and gate MEMMAP_HAVE_RESERVE instead, so
mempagesize() reports 0, memreserve() returns NULL and callers take
the bounded-allocation fallback they already have for platforms
without virtual memory. memsync() is excluded from the msync() branch
for the same reason: emscripten's msync() only accepts the exact base
of a live mapping and returns -EINVAL for an arbitrary range, while a
wasm linear memory has no separate instruction cache to flush, so the
fallthrough's 0 is both correct and the only honest answer.

mmap(), munmap(), mprotect() and memprotect() keep working through
libc as before.

* memmap: round memrelease() to the page size memreserve() rounded to

memreserve() rounds the requested length up to a whole number of pages
and maps that, but memrelease() passed the caller's unrounded length
straight to munmap(). Linux rounds the length up internally so the
mismatch is invisible there, which is how it survived; an
implementation that takes the length literally and declines a partial
unmap fails the call outright and leaks the entire reservation
whenever the length was not already page-aligned.

Apply the same rounding on the way out. mempagesize() is non-zero
wherever this branch compiles - MEMMAP_HAVE_RESERVE is only defined
when _SC_PAGESIZE is available - but the guard costs nothing and keeps
the expression from dividing the range by zero if that ever changes.

* Revert "memmap: gate the reserve/commit path off for emscripten instead of dropping mman"

This reverts commit 11b85a9421.

* Fix remaining uses of EMSCRIPTEN define

---------

Co-authored-by: libretroadmin <[email protected]>
2026-08-03 04:56:58 +02:00
libretroadmin d8f309e9a3 task_queue: hand out task idents atomically
task_init() assigned task->ident from a plain

   static uint32_t task_count = 0;
   ...
   task->ident = task_count++;

Tasks are pushed from whatever thread wants one - the main thread, the
menu, netplay, a core's own worker - so that read-modify-write runs
concurrently.  Two consequences:

  - It is a data race.  ThreadSanitizer flags it on the concurrent leg
    of samples/tasks/http/http_task_lifetime_test (4 pusher threads x
    400 pushes racing retirement), reporting a 4-byte read and write of
    'task_count.0' at task_queue.c:1292 from two different pusher
    threads.

  - Interleaved pushes can read the same value and hand two live tasks
    the same ident, which defeats the "unique identifier" the field is
    documented to be.

Replace the counter with retro_atomic_int_t and take the ident from an
acq_rel retro_atomic_fetch_add_int(), the same primitive already used
for the one-shot claim in features_cpu.c.  The handout is now
serialised and every task gets a distinct value.

int rather than uint32_t because that is the width retro_atomic offers;
ident is an opaque tag, so the wrap at INT_MAX - 2.1 billion task
creations - is of no consequence, and the cast back to uint32_t is well
defined for every value produced before then.

No ABI or behavioural change: idents remain a monotonically increasing
sequence starting at 0, only the increment is now safe.

http_task_lifetime_test passes under ASan (with leak detection),
UBSan, and TSan; TSan repeated 15x with no report.
2026-08-02 09:55:23 +02:00
libretroadmin 7890b0aa87 task_http: keep task->state alive until the queue retires the task
Fixes a SIGSEGV inside task_http_finder(), reported on Windows:

    #0  strcmp ()
    #1  task_http_finder ()
    #2  retro_task_threaded_find ()
    #3  task_push_http_transfer_generic_titled ()
    #4  task_push_http_download_file ()
    #5  download_pl_thumbnail ()

task_http_transfer_handler() freed its http_handle_t as soon as it set
RETRO_TASK_FLG_FINISHED.  But a task stays *findable* long after its
handler is done: retro_task_threaded_find() scans the running,
finished and retiring lists, and task_http_finder() dereferences
task->state on every candidate it is handed.  task->state therefore
dangled for the entire window between the last handler tick and full
retirement, and any push racing a finishing download read freed
memory.

This is not new.  It survived because connection_url was an inline
char[NAME_MAX_LENGTH]: reading a freed-but-still-mapped array yields
stale bytes and strcmp() plods through them harmlessly.  Making
connection_url a pointer -- so that long URLs stopped defeating the
duplicate-download guard -- turned the same read into "load the freed
chunk's tombstone and dereference it".  The pointer change did not
introduce the defect, it removed the padding that was hiding it, and
the thumbnail downloader moving to task_push_http_download_file() put
far more pushes alongside far more retirements.

The handle is now released in task_http_transfer_cleanup(), which the
queue calls during retirement, with task->state cleared first.  Same
change in the emscripten backend, which had the identical shape.

Also closes the narrow window underneath it in task_queue.c.
retro_task_internal_retire_body() ran the callback and cleanup with
neither lock held while the task was still in tasks_retiring, which
find() scans.  cleanup() is where a task releases task->state, so that
raced any concurrent find().  Retirement is split: the callback still
runs while the task is findable, since it may push follow-up tasks and
so cannot hold finished_lock, but cleanup now runs only after the task
has been pruned from the retiring list and is unreachable.

Separately, 56d5967 left a C90 violation in task_core_updater.c --
output_dir, http_title and _tlen declared after the calloc/goto that
precedes them:

    tasks/task_core_updater.c:822:13: error: ISO C90 forbids mixed
    declarations and code [-Werror=declaration-after-statement]

Declarations moved to the top of the block.  No behavioural change.

TESTS

samples/tasks/http/http_task_lifetime_test.c is the lane that was
missing, and its absence is why the crash shipped.  The other HTTP
samples drive net_http.c directly, which covers the protocol engine
well and the task layer not at all -- and the task layer is where this
lived.  It links the real task_http.c and the real task_queue.c,
threaded, against a loopback server, stubbing only msg_hash_to_str()
and task_window_progress_cb(); neither participates in lifetime.
Threads push GETs over a small set of URLs while the queue finishes
and retires earlier ones, so every push walks all three lists and
collides with retirement continuously.

Verified in both directions: with the teardown moved back into the
handler it reports heap-use-after-free with the same stack as the
crash above and exits 1; with the fix it is clean.  ASan is what makes
it assertable at all -- a use-after-free on a recently freed chunk
otherwise reads plausible bytes and passes.

A new Makefile.dedup lets http_url_dedup_test run under the
sanitizers and at both NAME_MAX_LENGTH values.

CI

A samples-tasks-http job is added to Linux-samples-tasks.yml covering
all five HTTP samples, each under the sanitizers that can catch its
defect, plus a syntax-only C89 pass over the five translation units
this area touches.  That last step exists because the mixed
declaration above reached master: the full C89 build in retroarch.yml
does catch it, but only after a configure and a complete build, and
the C99 habit of declaring at first use is silent under the default
build.  The syntax pass fails in seconds instead.

_GNU_SOURCE is added on top of the Makefile's C89_BUILD flag set
because -ansi otherwise hides the POSIX prototypes (strdup and
friends) these files legitimately use, burying the dialect errors
being checked under unrelated int-conversion noise -- an artefact
worth naming, since a check calibrated wrongly is worse than none.

It runs as its own job so the existing samples-tasks budget is
untouched; the whole job takes well under a minute locally.  Every
step body was executed verbatim before committing, and both the
lifetime step and the C89 step were confirmed to exit 1 on a
reintroduced regression.

VERIFICATION

Full sweep, 27 configurations: all five HTTP samples across baseline,
ASan, TSan, UBSan and ASan+UBSan, with detect_leaks=1 and
detect_stack_use_after_return=1 throughout, plus the dedup sample at
both NAME_MAX_LENGTH values.  All pass; no sanitizer report of any
kind across the whole sweep log.  Explicit LeakSan-only runs of the
three socket-driven suites are clean, which is meaningful because the
stress suite calls net_http_deinit() -- without it the DNS cache and
connection pool hang off file-scope globals and count as still
reachable.

net_http.c, task_queue.c, task_http.c, task_core_updater.c and
task_pl_thumbnail_download.c compile clean and pass the exact
C89_BUILD flag set; task_http_emscripten.c verified with emcc 6.0.5 at
-Wall.
2026-08-02 09:17:21 +02:00
libretroadmin 36e214f562 task_queue: keep tasks findable until fully retired
task_queue_find() in the threaded implementation only scanned the
running list, which made it lie in three windows:

- W1: the worker's gap between removing a finished task from the
  running queue and inserting it into the finished queue (the task
  was momentarily in neither, with all locks dropped)
- W2: a task sitting in the finished queue awaiting its
  main-thread callback
- W3: the span in which the gather has popped a task and is
  executing its callback

Every in-tree find() caller uses it for deduplication ('is this
work already underway?') or liveness ('is this work fully done,
callback included?') - 21 sites, most keyed by path/port/URL.
Reporting 'not found' in these windows lets a duplicate task be
pushed, racing the original over shared destinations (core
downloads, backups, playlist writes, thumbnail files), and lets a
find-based task_queue_wait() condition return before the callback
has run - the teardown-ordering defect already fixed pointwise in
the run-ahead core copy and database info tasks. This fixes the
root cause for all sites at once, including the keyed ones a
per-task flag cannot express.

- the worker now moves finished tasks from the running to the
  finished queue while continuously holding running_lock (closes
  W1); nesting order is running_lock -> finished_lock
- threaded find() scans running, finished, and a new retiring list
  under both locks in that same nesting order (closes W2/W3); the
  scan is atomic with respect to the worker's move
- the gather no longer holds finished_lock across task callbacks:
  callbacks routinely push follow-up tasks (taking running_lock),
  which under the new nesting order would be a classic ABBA
  deadlock. Instead, finished tasks move - still under the lock -
  onto the retiring list, callbacks/cleanup run lock-free, and
  each task is pruned from the retiring list (under the lock)
  before being freed. find() is therefore truthful from any
  thread across the entire finished -> fully-retired span.
- gather is guarded against re-entrancy: task callbacks can
  transitively call task_queue_check(), and a nested gather
  walking and freeing the retiring list would invalidate the
  outer one. Gather only runs on the task-callback thread, so the
  nested call is a safe no-op and the outer loop (which re-reads
  the list head every iteration) picks up the work.
- the per-task retirement body is factored out of
  retro_task_internal_gather() and shared with the (unchanged)
  non-threaded implementation, which has no such windows.

Runtime-tested (Linux) with a dedicated unit harness linking this
file: deterministic finished-but-callback-pending find (the old
code fails this), a 300-iteration cross-thread hammer with a
continuous observer asserting find() never reports false between
handler completion and callback completion (zero violations),
callback-pushes-task chains (deadlocks under the old gather
locking combined with the new nesting), re-entrant
task_queue_check() from a callback, wait(NULL) covering callbacks,
and unchanged non-threaded semantics - 20/20 iterations in both
threaded and non-threaded modes, clean under ThreadSanitizer and AddressSanitizer/LeakSanitizer. The
run-ahead core-copy and database-info harnesses (real find/wait
consumers) also pass unchanged against the modified queue, clean
under ThreadSanitizer.
2026-07-24 00:48:36 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 50f3dd8d17 libretro-common/queues: add task_free_error + document set/free protocol
task_set_title() and task_set_error() take ownership of a heap
pointer and rely on the task system to free it at completion, but
neither setter frees the *previous* value -- so calling either one
twice on the same task without an intervening free leaks the prior
string.  task_free_title() has long existed for the title side of
this protocol; the error side had no symmetric helper at all,
forcing callers that legitimately needed to update the error mid-
task to either guard with task_get_error() or just live with the
leak.

This commit:

* Adds task_free_error(), symmetric to the pre-existing
  task_free_title() (both lock property_lock under HAVE_THREADS,
  free if non-NULL, NULL out the field).

* Documents the free-then-set protocol clearly in
  queues/task_queue.h on both setters, both struct fields, and
  cross-references the helpers via @see -- the previous "@warning
  This does not free the existing X" line was correct but easy to
  miss, and three sites in tasks/task_cloudsync.c missed it.

* Fixes those three task_cloudsync.c violators (lines 107, 1281,
  1331).  task_cloudsync sets the initial title at line 1439 via
  direct assignment, then later replaces it via task_set_title in
  three callbacks without calling task_free_title first.  Each
  replacement leaks the prior strdup.

* Adds a regression test under libretro-common/samples/queues/
  task_queue_title_error_test/ exercising both helpers and the
  free-then-set protocol (single-set, replace-via-free, free-on-
  null no-op, double-free no-op, 50-iteration stress chain).
  Wires it into the existing libretro-common-samples CI workflow,
  so it builds under -fsanitize=address,undefined and LSan flags
  any future regression to the protocol.

The test compiles task_queue.c without HAVE_THREADS so the slock /
scond / sthread paths drop out cleanly -- the title/error
protocol is identical with and without threading; the locks just
serialise it.  The single remaining external dependency
(cpu_features_get_time_usec) is provided as a trivial stub since
no test path drives the queue through gather().

Verified pre-patch: the test fails to link without task_free_error
(undefined reference), confirming it genuinely exercises the new
symbol rather than passing trivially.

Verified post-patch: ASan + UBSan + LSan clean, all ten cases
pass.
2026-04-28 23:46:47 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 8521da9886 libretro-common/queues: NULL-check allocations in generic_queue and task_queue
Several call sites in the queue implementation code allocated a
struct then immediately dereferenced it with no NULL check,
segfaulting on OOM:

  * generic_queue_push (line 79): calloc then 5 field writes.
    Also was missing the 'if (!queue) return' check that the
    sibling generic_queue_shift has at line 134.
  * generic_queue_shift (line 137): same as _push.
  * generic_queue_iterator (line 217): malloc then 3 field writes.
  * retro_task_regular_retrieve (task_queue.c line 312): malloc +
    malloc back-to-back, then field writes on info.  The inner
    info->data malloc additionally fed into data->func which is
    free to dereference it.

All four are void-returning or NULL-returning, so the appropriate
OOM behaviour is a silent skip / NULL return.  length and the
first_item/last_item chain stay consistent on skip because we
return before incrementing anything.
2026-04-23 22:07:07 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre 8104e58ba6 (libretro-common task_queue) fix: task_free_title (line 990) doesn't guard against double-free if called concurrently with retro_task_internal_gather, which also frees task->title 2026-04-09 12:37:35 +02:00
U-DESKTOP-SPFP6AQ\twistedtechre d34d72740d (task_queue) task_queue_remove - Remove redundant check 2026-03-12 17:48:11 +01:00
U-DESKTOP-SPFP6AQ\twistedtechre 88c655a4cd (task_queue) Fix:
Bug in task_queue_retriever_info_next (line 912–921) — use-after-advance
The function advances the link pointer first, then dereferences the new value — skipping the first element and crashing on the last
2026-03-12 17:35:02 +01:00