diff options
| author | k.kudo <k.kudo@dangofactory> | 2026-11-02 04:40:21 +0900 |
|---|---|---|
| committer | k.kudo <k.kudo@dangofactory> | 2026-11-02 04:40:33 +0900 |
| commit | 74dbff260d8b0d312e644b65a1f6b76404fba440 (patch) | |
| tree | 14740ace7bc84473e1587c8ea16e6a0d6fdfc78d | |
| parent | bf4fab71a32004a9995db4c62cb4fa9cfa7b3ee9 (diff) | |
| download | recfsusb2e-main.tar.gz recfsusb2e-main.zip | |
- FreeBSD の libusb-1.0 は libusb20 のシムで、libusb_handle_events_timeout_completed()
(lib/libusb/libusb10_io.c) は呼び出し側の *completed を一度も書き換えない。
非 NULL を渡すと while(1) が poll(...,0) を空回りし、イベントスレッドが
handle_events から戻らない → join() が 500 ms でタイムアウト → 録音が止まり、
その後チューナがベンダ読みに無応答になる (実測: issued=0, state=2, CPU 98%,
出力が 15.3 MB で凍結)。
- NULL を渡して 1 パスで返す。upstream でも「1 回回して返る」意味なので移植性は同じ。
- em2874-core: レジスタプローブの !(readReg() && ...) は負のエラー値 (-7 など) を
成功扱いしていたので < 0 判定に修正。死んだデバイスは 15 秒ではなく 5 秒で
"EM2874 register probe failed." として落ちる。
- stopStream: TS_ENABLE=0 -> drain -> 残りを cancel の順に変更。
- join() 失敗時のログにスレッドの在処 (0=idle 1=poll 2=handle_events) を出す。
- 実測: ch42->ch43 の IPC 切替で 58,507,480 バイトが途切れず、EIT も変化。
tvserver 経由でも ch41/42/43/41 がすべて 200 (以前は 2 回目以降 503)。
| -rw-r--r-- | recfsusb2n/IoThread.cpp | 84 | ||||
| -rw-r--r-- | recfsusb2n/IoThread.hpp | 7 | ||||
| -rw-r--r-- | recfsusb2n/em2874-core.cpp | 30 |
3 files changed, 98 insertions, 23 deletions
diff --git a/recfsusb2n/IoThread.cpp b/recfsusb2n/IoThread.cpp index bd58305..478c17a 100644 --- a/recfsusb2n/IoThread.cpp +++ b/recfsusb2n/IoThread.cpp @@ -63,7 +63,7 @@ TsIoThread::TsIoThread (UsbHandle *h, const int ep) : handle(h), endpoint(ep), buf_pushIndex(0), buf_popIndex(0), issuedRequestNum(0), unitSize(TSBULKSIZE), slotCount(TSBUFFERSIZE), - ev_thread(NULL), cancel_req(false), thread_done(false) + ev_thread(NULL), cancel_req(false), thread_done(false), loop_state(0) { /* valloc() equivalent: DMA buffers want page alignment, and posix_memalign * is available everywhere we build (including MinGW via _aligned_malloc). */ @@ -276,12 +276,19 @@ void TsIoThread::start() /* One non-blocking libusb pass, then a bounded wait for something to happen. * - * libusb_handle_events_timeout_completed() does NOT honour its timeout on the - * FreeBSD backend once no transfer is pending: it parks in poll() and stays - * there, so a cancel issued in that window was never seen and join() blocked - * for ever (that is the hang every recording ended with, and the SIGKILL used - * to escape it is what degraded the tuner). Waiting on libusb's own pollfds - * here keeps the loop period at 100 ms no matter what libusb does. */ + * FreeBSD is not upstream libusb: libusb-1.0 there is a shim over libusb20 + * (lib/libusb/libusb10_io.c). Two differences matter here and the code is + * written for them rather than for the upstream contract: + * + * - libusb_handle_events_timeout_completed() reads the caller's *completed + * but never writes it, so "wait until *completed != 0" degenerates into + * an endless poll(...,0) spin. It is passed NULL below: one pass, return. + * - The transfer timeout of a control request is not honoured the way the + * code asks for it (100 ms asked, ~4.9 s measured on a silent device), + * so nothing here may rely on a short timeout to bound a dead device. + * + * Waiting on libusb's own pollfds keeps the loop period at 100 ms regardless + * of what the shim does, so a cancel is seen within one iteration. */ int TsIoThread::pumpOnce() { const struct libusb_pollfd **pfds = libusb_get_pollfds(handle->ctx); @@ -302,7 +309,9 @@ int TsIoThread::pumpOnce() libusb_free_pollfds(pfds); if (n > 0) { + loop_state = 1; /* in poll() */ ready = (poll(p, (nfds_t)n, 100) > 0); + loop_state = 0; } else { /* No fds to watch: nothing can complete here, so do not call * libusb at all (see below) -- just keep the 100 ms period. */ @@ -312,14 +321,11 @@ int TsIoThread::pumpOnce() rw_sleep_ms(100); } - /* Only hand control to libusb when one of its fds is readable. - * libusb_handle_events_timeout_completed() on the FreeBSD backend - * ignores its timeval and parks in poll() for ever when nothing is - * pending (measured with gdb: still in _poll() after 5 s, with tv=0), - * so calling it unconditionally is what hung every teardown. */ + /* Only hand control to libusb when one of its fds is readable: one + * pass is all this loop wants, and the shim's own timeval is a zero + * timeval anyway. */ if (ready) { struct timeval zero; - int completed = 0; zero.tv_sec = 0; zero.tv_usec = 0; @@ -328,10 +334,32 @@ int TsIoThread::pumpOnce() issuedRequestNum.load()); fflush(stderr); } - r = libusb_handle_events_timeout_completed(handle->ctx, &zero, &completed); + /* completed MUST be NULL here. + * + * FreeBSD's libusb-1.0 is a shim over libusb20, and its + * libusb_handle_events_timeout_completed() (lib/libusb/libusb10_io.c) + * loops forever unless the caller's *completed changes: + * + * while (1) { + * if (completed != NULL && (*completed != 0 || err != 0)) + * break; + * err = libusb_handle_events_locked(ctx, tv); + * if (completed == NULL) break; + * } + * + * Nothing in that shim ever writes *completed -- the pointer is + * read and never set -- so passing a zero int spins the loop on + * poll(...,0) for ever. That was the "event thread did not stop + * (issued=0, state=2)" hang: the thread never returned to see the + * cancel, join() timed out after 500 ms, the recorder abandoned the + * event thread and stopped writing (measured 2026-11-02: 98% CPU, + * output frozen mid-recording, tuner left answering nothing). */ + loop_state = 2; /* in libusb */ + r = libusb_handle_events_timeout_completed(handle->ctx, &zero, NULL); + loop_state = 0; if (getenv("RECFSUSB2N_DBG_PUMP") != NULL) { - fprintf(stderr, "[pump] handle_events -> %d completed=%d issued=%d\n", - r, completed, issuedRequestNum.load()); + fprintf(stderr, "[pump] handle_events -> %d issued=%d\n", + r, issuedRequestNum.load()); fflush(stderr); } } @@ -397,8 +425,9 @@ bool TsIoThread::join() rw_sleep_ms(10); } if (!thread_done.load()) { - std::cerr << "TsIoThread: event thread is parked inside libusb " - << "(issued=" << issuedRequestNum.load() + std::cerr << "TsIoThread: event thread did not stop (issued=" + << issuedRequestNum.load() << ", state=" + << loop_state.load() << " [0=idle 1=poll 2=handle_events]" << "); abandoning it so the process can exit." << std::endl; ev_thread->detach(); @@ -413,6 +442,25 @@ bool TsIoThread::join() return true; } +/* Wait for the event thread to reap everything by itself. + * + * Measured on this host (evtest, no device): handle_events_timeout_completed() + * returns immediately with either a zero or a 100 ms timeval when nothing is + * pending, so the "it parks for ever" premise the older comments in this file + * rest on does not hold here. What actually fails to return is a cancel of a + * transfer that is sitting in the kernel, which is why the event thread can + * be busy while issuedRequestNum already reads 0. Callers therefore use this + * before cancelling: if the device has merely stopped sending, the in-flight + * transfers complete on their own and nothing has to be cancelled at all. */ +bool TsIoThread::drain(int ms) +{ + for (int waited = 0; waited < ms; waited += 10) { + if (issuedRequestNum.load() <= 0) return true; + rw_sleep_ms(10); + } + return issuedRequestNum.load() <= 0; +} + void TsIoThread::cancelPending() { for (int i = 0; i < IOREQ_RESERVE_NUM; i++) { diff --git a/recfsusb2n/IoThread.hpp b/recfsusb2n/IoThread.hpp index 0fcba92..b50e3fd 100644 --- a/recfsusb2n/IoThread.hpp +++ b/recfsusb2n/IoThread.hpp @@ -49,6 +49,8 @@ public: void cancel(); /* request cancellation (async) */ bool join(); /* wait for every callback to fire; * false = it did not stop in time */ + bool drain(int ms); /* let the event thread reap on its own; + * true = no transfer is left in flight */ int readBuffer(const void **ptr); size_t unit() const { return unitSize; } @@ -88,6 +90,11 @@ protected: std::atomic<bool> cancel_req; std::atomic<bool> thread_done; /* set by the event thread as it returns */ + /* Where the event thread is right now, so a join() timeout can say what + * it was actually doing instead of only "parked inside libusb". + * 0 = between iterations, 1 = in poll(), 2 = in handle_events() */ + std::atomic<int> loop_state; + void cancelPending(); /* cancel every still-submitted transfer */ int pumpOnce(); /* one bounded event-loop iteration */ diff --git a/recfsusb2n/em2874-core.cpp b/recfsusb2n/em2874-core.cpp index d6c4d3e..11306ae 100644 --- a/recfsusb2n/em2874-core.cpp +++ b/recfsusb2n/em2874-core.cpp @@ -90,7 +90,16 @@ EM2874Device* EM2874Device::AllocDevice(int ordinal) /* Same probe the old openDevice() did after claiming the interface. */ uint8_t val; - if (!(pDev->readReg(0x0A, &val) && pDev->readReg(0x0C, &val) && pDev->readReg(0x0B, &val))) { + /* readReg() returns libusb_control_transfer()'s value: the transferred + * byte count (1) on success, a negative LIBUSB_ERROR_* otherwise. As + * "!(a && b && c)" a failure was truthy, so a silent front end passed + * this probe, the recorder went on to initialise a dead chip, and every + * capture ended at 0 bytes (measured 2026-11-02: 0x0A/0x0C/0x0B each + * timed out after ~4.9 s and the probe still reported success). + * Explicit < 0 also short-circuits: one 5 s timeout instead of three. */ + if (pDev->readReg(0x0A, &val) < 0 || + pDev->readReg(0x0C, &val) < 0 || + pDev->readReg(0x0B, &val) < 0) { usb_close_device(pDev->handle); delete pDev->handle; pDev->handle = NULL; @@ -427,11 +436,22 @@ void EM2874Device::stopStream() { if (!isStream) return; - /* Cancel first, then stop the data: writing TS_ENABLE=0 first kills the - * stream, and with no completions the event thread would have nothing - * to wake it. */ - ts_func->cancel(); /* requests cancellation */ + /* Stop the data first, then let the in-flight reads come back on their + * own before touching libusb. + * + * The old order (cancel first) is what left the event thread stuck on + * this backend: a cancelled bulk transfer that already sits in the + * kernel does not always come back, and join() then times out + * (measured 2026-11-02: after an IPC retune stopStream() never + * returned, the recorder wrote nothing more, and the tuner stopped + * answering vendor reads until usbconfig set_config 1). When the + * device merely stops sending, the 20 pending reads complete by + * themselves, so draining usually cancels nothing at all. */ writeReg(EM2874_REG_TS_ENABLE, 0); + if (!ts_func->drain(200)) { + ts_func->cancel(); /* requests cancellation */ + ts_func->drain(200); /* let the callbacks fire */ + } if (ts_func->join()) { /* waits for every callback */ delete ts_func; ts_func = NULL; |
