Skip to content

Serialize the Razer BlackShark V2 Pro (PlayStation) conversation across processes - #627

Merged
Sapd merged 7 commits into
Sapd:masterfrom
TheWeaklessOne:pr/blackshark-lock
Nov 18, 2026
Merged

Sapd merged 7 commits into
Sapd:masterfrom
TheWeaklessOne:pr/blackshark-lock

Conversation

@TheWeaklessOne

@TheWeaklessOne TheWeaklessOne commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Changes made

Rebased on master now that #626 is in. The first commit adds the lock; the later ones come from reviewing it, and change how often the driver talks to the dongle.

Two HeadsetControl processes talking to the BlackShark dongle at the same time (a tray app polling every second and a CLI call) break each other's reads:

  • the dongle acknowledges every frame through one input report fetched over the control pipe, shared by all handles
  • it sends every reply to every open handle, so a process waiting for its own reply also receives the other's; each process numbered its requests from 1, so a queued reply from the other process passed for its own

To reproduce it, I ran three loops of headsetcontrol -b next to the tray. Before this change 11 of 30 reads came back wrong, mostly as "headset off". After it, all reads were right, and the dongle was back in local mode afterwards.

Why a lock around the conversation, and not something lighter:

  • making the protocol tolerant (random sequence numbers, checking ids) is not enough: the remote/local mode switch is global dongle state another process can undo in the middle of a read, and customer replies carry no sequence number at all
  • locking when the device is opened would keep a CLI call out for as long as a tray app runs
  • hidapi has no exclusive open on Windows or Linux

ProcessLock (in lib/utility.hpp/.cpp, so builds that list the library sources by hand need no new file):

  • Windows: named mutex Global\HeadsetControl-<name>. Its DACL lets any signed-in user wait on it and release it, and only that access is asked for, so users and sessions (console, SSH, elevated or not) share one lock whoever created it. This needs advapi32, which CMake now links; docs/LIBRARY_USAGE.md mentions it for hand-built MinGW setups.
  • elsewhere: flock() on /tmp/headsetcontrol-<name>.lock, independent of the environment so that sudo, cron and a desktop session agree. The file is created with O_EXCL and only its creator makes it 0644; an existing file is never chmodded. It is opened with O_NOFOLLOW | O_NONBLOCK (a FIFO at the path cannot hang the call), used only if it is a plain file with one link, and checked again after flock() in case it was replaced while waiting.
  • the OS releases it if the holder dies
  • status() is Held, Busy (timed out) or Unavailable (the OS facility failed; the caller goes on without a lock, as before this change); recovered() tells that a Windows mutex was abandoned by a dead holder

In the BlackShark driver:

  • getBattery() holds the lock for the whole conversation, mode switch included. After taking it, it discards the reports that queued up on its handle meanwhile, keeping the headset's battery and charging notifications among them.
  • the dongle is switched to remote mode at most every 5 minutes instead of every minute. The headset's percent and charge state arrive as notifications in local mode in between; I saw them arrive over an 8-hour log. Each switch is a window in which a killed process leaves the dongle in remote mode, so this makes that window rare.
  • the mode is checked every 10 seconds, with the headset off too, and a dongle left in remote mode is put back. Remote mode with live traffic (replies nobody here asked for) belongs to another program, such as the vendor's firmware updater, and is left alone.
  • the headset's own figures expire after 15 minutes without a GET or a notification confirming them. A GET that differs by more than 10 points bypasses the percent filter (a change nobody saw, such as charging while nothing was asking). A charge state nobody confirmed since the previous read is forgotten; both GETs are retried once first.
  • if another process holds the lock for more than 5 seconds, the call returns what this handle learnt in the last 15 minutes, or a timeout, and the next calls do not wait for the lock again for 10 seconds (docs/LIBRARY_USAGE.md says so)
  • a frontend that discovers and frees the headset on every poll (headset-battery-indicator does) lost all of this with each handle, so the dongle was switched to remote mode on every poll. HIDDevice gets an optional onConnectionOpened(handle, path) hook, called by Headset when it opens a handle; the driver keeps a closed handle's state by device path and gives it to the next handle on the same path. Such a handle misses the notifications in between, so it re-reads once a minute.
  • the first sequence number is random, which helps against processes that do not take the lock (an older build)

Testing

  • Windows 11, BlackShark dongle:
    • concurrent headsetcontrol -b loops next to a tray running the same build: every read right
    • with a tray that keeps its handle, a passive listener counted 30 link-status queries, 6 mode queries and no mode switch in a minute
    • the percent and charge-state notifications arrive in local mode (8-hour log)
  • Lock alone, with separate processes, on Windows and Linux (WSL):
    • 4 processes × 200 lock/increment/unlock rounds on a shared counter, 800/800, no overlap
    • killing the holder frees it at once
    • a waiter gets Busy after its timeout
  • Unit tests:
    • ProcessLock: hand-over to a waiting thread, name sanitizing, negative timeout, Unavailable when another kind of object holds the name, abandonment on Windows, and the file cases on POSIX (umask, existing mode kept, symlink, hard link, FIFO, removal while waiting)
    • the driver: the busy path, stale and lookalike replies, the mode check, the foreign-session check, expiry, the filter bypass, and state across a reopened handle
    • they pass on Windows (MinGW GCC 16) and on Linux (GCC 15 and Clang 21 with ASan/UBSan); the changed files compile on macOS (Apple clang)
  • Not tested:
    • macOS at runtime
    • a second real Windows account; the cross-user DACL was checked with a restricted token
    • the vendor's firmware updater running next to HeadsetControl. The driver leaves a remote mode with live traffic alone, but an updater that pauses looks like a leftover, so the header says to quit HeadsetControl while updating.

Checklist

  • I adjusted the README (if needed) (n/a)
  • For new features in HeadsetControl: I discussed it beforehand in Issues or Discussions and adhered to the wiki (not discussed beforehand; happy to change the approach)

🤖 Generated with Claude Code

TheWeaklessOne and others added 6 commits November 17, 2026 09:39
The dongle acknowledges every frame through one shared input report and
sends every reply to every open handle. A tray app polling next to a
CLI call therefore reads the other process's acks, and since each
process numbered its requests from 1, it took the other's queued
replies for its own. Three CLI loops beside the tray: 11 of 30 reads
wrong before, 70 of 70 right after (30 and 40 runs).

Making the protocol tolerant is not enough: the mode switch is global
dongle state another process can undo mid-read, and customer replies
carry no sequence number. Locking at open time would keep a CLI out
for as long as a tray app runs, and hidapi has no exclusive open on
Windows or Linux.

Add ProcessLock, held for the lifetime of the object and released by
the OS if the holder dies:
- Windows: a named mutex, Global\ so that sessions share it, Local\ if
  the global one cannot be opened.
- Elsewhere: flock() on /tmp/headsetcontrol-<name>.lock, a path that
  does not depend on the environment, opened with O_NOFOLLOW and only
  used if it is a plain file.
status() tells Held, Busy (timed out) and Unavailable (the OS facility
failed; the caller goes on without the lock). It lives in utility.cpp so
that builds listing the library sources by hand do not need a new file.

getBattery() holds it for the whole conversation, mode switch included.
After taking it, it discards the replies that queued up meanwhile,
keeping any notification among them. If another process holds it for
more than 5 seconds, the last reading on this handle is returned, or a
timeout without one. A lock recovered from a dead holder drops the
voltage cache, so the next read checks the mode. The first sequence
number is random, for processes that do not take the lock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The tests took the real device's ProcessLock with a 100 ms timeout, so
a HeadsetControl running on the same machine (a tray app) made them
fail now and then. The lock name is now a virtual the tests override.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ProcessLock:
- Windows: one Global\ mutex that every signed-in user may wait on, so
  users no longer fall back to separate Local\ locks
- POSIX: chmod only a file this call created, open with O_NONBLOCK so a
  planted FIFO cannot hang the call, and re-take the lock if the file was
  replaced while waiting
- timeouts are clamped to [0, 1 h]

BlackShark driver:
- switch the dongle to remote mode once per 5 minutes instead of every
  minute; percent and charge state arrive as notifications in between
- check the mode every 10 seconds and put back a remote mode left by a
  killed process, but leave a remote session with live traffic alone
- the headset's own figures expire after 15 minutes without confirmation,
  a jump of more than 10 points bypasses the percent filter, and a charge
  state nobody confirmed since the previous read is forgotten
- the headset's own percent is returned when the voltage read fails
- while another process holds the lock, serve only recent figures and do
  not wait again for 10 seconds
- check the event byte of replies; tests use a lock name of their own

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- a dongle stuck in remote mode is reported until the next read, even
  when the headset's own figures are known
- a lost charge-state reply is asked again before the state is forgotten
- the Windows mutex keeps full access for its owner, so builds that open
  it with full access still share it; advapi32 is linked explicitly
- POSIX: a lock file removed between our calls is retried, not given up
- docs: keep a Headset open between polls; MinGW users outside CMake
  link advapi32
- tests: lookalike frames arrive while a command waits, the foreign
  session check is tested against spontaneous frames and customer
  replies, lock file cases on POSIX, and test lock files are removed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A frontend that discovers and frees the headset on every poll (the
headset-battery-indicator tray does) lost the cache with every handle,
so the dongle was switched to remote mode on every poll. HIDDevice gets
an optional onConnectionOpened(handle, path) hook; the driver parks the
state of a closed handle by device path and gives it to the next handle
on the same path. Such a handle misses the notifications in between, so
it re-reads once a minute instead of every five minutes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- a handle that stays open after one reopen goes back to the full cache
- parked state stays for a second handle on the same path
- the percent GET is asked again once, like the charge state
- a recovered lock checks the mode on that poll again

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@TheWeaklessOne
TheWeaklessOne marked this pull request as ready for review November 17, 2026 11:19
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-17T11:30:36.914670Z 633c0ab Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions github-actions Bot added the awaiting-maintainer The author replied or pushed - our move label Nov 17, 2026
Two paths returned a success while the dongle could not be switched
back to local mode:

- the periodic mode check dropped the failure and the cached voltage
  was returned; it is now recorded like a failed switch back after a
  read, and retried by the next read after FAILURE_BACKOFF
- with the lock held by another process, the headset's own figures were
  returned although the previous read had left the dongle in remote
  mode
@Sapd
Sapd merged commit 53ced5f into Sapd:master Nov 18, 2026
7 checks passed
@github-actions github-actions Bot removed the awaiting-maintainer The author replied or pushed - our move label Nov 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants