/* * TS I/O thread - libusb-1.0 asynchronous bulk IN * * Behaviour-compatible rewrite of the old usbfs URB loop: * - N = IOREQ_RESERVE_NUM transfers are kept in flight at all times * - every transfer owns one slot of a ring buffer; actualSize[slot] is * TSSIZE_INVALID while the slot is in flight and the byte count once * the transfer completed * - readBuffer() returns the contiguous run of completed slots * * The old loop waited in select() on the usbfs fd and used USBDEVFS_REAPURBNDELAY. * libusb has no fd and no reaping: the callbacks are pumped by the event * thread below, which also serves the exit condition. * * Shutdown order (do not reorder): * cancel() -> libusb_cancel_transfer() only *requests* cancellation * event loop keeps pumping until every callback fired (pending == 0) * join() * ~TsIoThread -> libusb_free_transfer(), safe only at that point */ #include #include #include "IoThread.hpp" #include "compat.hpp" #if !RW_WINDOWS #include #include #endif /* libusb_interrupt_event_handler() is the documented way to wake a thread * parked inside libusb_handle_events*(). It was added in libusb 1.0.21, and * FreeBSD's base libusb exports it even though its LIBUSB_API_VERSION says * 1.0.18 -- so resolve it at run time instead of pinning a version and * breaking the build on whichever libusb a platform ships. * * Why it is needed at all: libusb_handle_events_timeout_completed() does NOT * honour its 100 ms timeout on this backend. Once no transfer is pending it * blocks indefinitely, so a cancel issued while the ring was momentarily * empty was never noticed -- the event thread sat in poll() for ever and * join() never returned. Measured with ./tdev: issued=0, thread still * blocked after 5 s. */ static void wake_event_thread(libusb_context *ctx) { #if !RW_WINDOWS static void (*fn)(libusb_context *) = NULL; static bool looked = false; if (!looked) { looked = true; fn = (void (*)(libusb_context *))dlsym(RTLD_DEFAULT, "libusb_interrupt_event_handler"); } if (fn != NULL && ctx != NULL) fn(ctx); #else (void)ctx; #endif } 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), loop_state(0) { /* valloc() equivalent: DMA buffers want page alignment, and posix_memalign * is available everywhere we build (including MinGW via _aligned_malloc). */ buf = (uint8_t *)rw_aligned_alloc(4096, TSBULKSIZE * TSBUFFERSIZE); actualSize = new size_t[TSBUFFERSIZE]; for (int i = 0; i < IOREQ_RESERVE_NUM; i++) { xfer[i] = NULL; submitted[i] = false; xctx[i].owner = this; xctx[i].slot = -1; } } TsIoThread::~TsIoThread() { /* Only reachable after the event thread has joined, i.e. after every * callback has fired. libusb_free_transfer() on a pending transfer is * a use-after-free. */ for (int i = 0; i < IOREQ_RESERVE_NUM; i++) { if (xfer[i] != NULL) { libusb_free_transfer(xfer[i]); xfer[i] = NULL; } } rw_aligned_free(buf); buf = NULL; delete [] actualSize; actualSize = NULL; } /* ------------------------------------------------------------------ */ /* slot allocation */ /* ------------------------------------------------------------------ */ int TsIoThread::nextSlot() { /* * Reserve the next ring slot. The reservation itself has to be atomic: * onTransferDone() runs on the libusb event thread and calls * submitOne() straight from the callback, so concurrent completions can * race to claim a slot. With a plain load/store pair two of them took * the same index, and two transfers then shared one buffer - which is * what tore the recorder's output into unusable fragments. * * buf_pushIndex stays a ring index so readBuffer() can compute the * unread distance with a single subtraction, but the CAS keeps both the * index and the wrap consistent when the producer reaches the end. */ for (;;) { size_t cur = buf_pushIndex.load(std::memory_order_acquire); size_t nxt = (cur + 1) % (size_t)slotCount; if (buf_pushIndex.compare_exchange_weak(cur, nxt, std::memory_order_acq_rel, std::memory_order_acquire)) { return (int)cur; } /* cur was reloaded by compare_exchange_weak; retry */ } } /* ------------------------------------------------------------------ */ /* submit / callback */ /* ------------------------------------------------------------------ */ void TsIoThread::submitOne(int i) { int slot; int rc; size_t len = unitSize; if (xfer[i] == NULL) { xfer[i] = libusb_alloc_transfer(0); if (xfer[i] == NULL) { rw_fatal("libusb_alloc_transfer failed (out of memory)"); return; } xfer[i]->dev_handle = handle->dev; xfer[i]->endpoint = (unsigned char)endpoint; xfer[i]->type = LIBUSB_TRANSFER_TYPE_BULK; xfer[i]->callback = transferCb; xfer[i]->user_data = &xctx[i]; xfer[i]->flags = 0; } slot = nextSlot(); actualSize[slot] = TSSIZE_INVALID; xctx[i].slot = slot; xfer[i]->buffer = buf + ((size_t)slot * TSBULKSIZE); xfer[i]->length = (int)len; /* Back to "block until data arrives": on this backend the per-transfer * timeout does NOT fire while the endpoint is silent (measured), so a * finite value buys nothing and on other platforms it would cancel * transfers that are legitimately waiting. The escape from a wedged * event thread is join()'s bounded wait, not this. */ xfer[i]->timeout = 0; /* A completion can reach here just after cancel() swept the table: * re-submitting then would leave a transfer nothing ever cancels and * join() would block for ever. Re-check the flag as late as possible. */ if (cancel_req.load()) { actualSize[slot] = 0; xctx[i].slot = -1; return; } rc = libusb_submit_transfer(xfer[i]); if (rc != LIBUSB_SUCCESS) { actualSize[slot] = 0; xctx[i].slot = -1; if (rc == LIBUSB_ERROR_INVALID_PARAM && len > 512) { /* backend refuses a transfer this large (usbfs caps bulk at 16 KiB, * some host controllers less). Halve and retry once. The ring * stride stays TSBULKSIZE; only the payload length shrinks. */ unitSize /= 2; xfer[i]->length = (int)unitSize; rc = libusb_submit_transfer(xfer[i]); if (rc == LIBUSB_SUCCESS) { submitted[i] = true; issuedRequestNum++; return; } } std::cerr << "libusb_submit_transfer failed: " << libusb_error_name(rc) << ": " << libusb_strerror(rc) << std::endl; /* this call never incremented the counter, so do not decrement it * here: the old `issuedRequestNum--` could push it below zero and * hide a still-pending transfer from the loop's exit test. */ cancel_req = true; /* let the loop unwind */ return; } submitted[i] = true; issuedRequestNum++; } void LIBUSB_CALL TsIoThread::transferCb(struct libusb_transfer *t) { XferCtx *ctx = (XferCtx *)t->user_data; if (ctx == NULL || ctx->owner == NULL) return; ctx->owner->onTransferDone(t); } void TsIoThread::onTransferDone(libusb_transfer *t) { XferCtx *ctx = (XferCtx *)t->user_data; int i; /* find our slot in the transfer table */ for (i = 0; i < IOREQ_RESERVE_NUM; i++) { if (xfer[i] == t) break; } if (i == IOREQ_RESERVE_NUM) return; /* not ours */ submitted[i] = false; issuedRequestNum--; /* publish the received bytes. * * release store: the bytes in buf[slot] were written by the host * controller before the callback ran, and the consumer must not see the * new actualSize before those bytes are visible. Plain stores let the * reader observe the size first and copy a half-written slot. */ if (ctx != NULL && ctx->slot >= 0) { std::atomic_thread_fence(std::memory_order_release); /* TIMED_OUT keeps whatever arrived before the 500 ms bound: dropping * it would lose up to 16 KiB of stream every time a transfer was * slow, which shows up as a picture glitch. */ actualSize[ctx->slot] = (t->status == LIBUSB_TRANSFER_COMPLETED || t->status == LIBUSB_TRANSFER_TIMED_OUT) ? (size_t)t->actual_length : (size_t)0; std::atomic_thread_fence(std::memory_order_release); } if (ctx != NULL) ctx->slot = -1; /* Optional transfer-length trace: RECFSUSB2N_DBG_XFER=1 prints the * actual_length of each bulk completion, which is how the 1 MiB chip * buffer (1048576 mod 188 == 100) was located as the source of the * 100-byte packet misalignment. */ { static int dbg_n = 0; static unsigned long dbg_tot = 0; if (dbg_n < 40 && getenv("RECFSUSB2N_DBG_XFER") != NULL) { dbg_tot += (unsigned long)t->actual_length; fprintf(stderr, "[xfer %d] status=%d actual_length=%d req=%d cum=%lu\n", ++dbg_n, t->status, t->actual_length, t->length, dbg_tot); } } if (cancel_req.load()) return; /* drain only, do not resubmit */ /* a stalled endpoint must be cleared before the next submit */ if (t->status == LIBUSB_TRANSFER_STALL) { libusb_clear_halt(handle->dev, (unsigned char)endpoint); } submitOne(i); } /* ------------------------------------------------------------------ */ /* event loop */ /* ------------------------------------------------------------------ */ void TsIoThread::start() { for (int i = 0; i < IOREQ_RESERVE_NUM; i++) { submitOne(i); } ev_thread = new std::thread(&TsIoThread::operator(), this); } /* One non-blocking libusb pass, then a bounded wait for something to happen. * * 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); int ready = 0; int r = 0; if (pfds != NULL) { struct pollfd p[16]; int n = 0; for (int i = 0; pfds[i] != NULL && n < 16; i++) { p[n].fd = pfds[i]->fd; p[n].events = 0; p[n].revents = 0; if (pfds[i]->events & POLLIN) p[n].events |= POLLIN; if (pfds[i]->events & POLLOUT) p[n].events |= POLLOUT; n++; } 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. */ rw_sleep_ms(100); } } else { rw_sleep_ms(100); } /* 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; zero.tv_sec = 0; zero.tv_usec = 0; if (getenv("RECFSUSB2N_DBG_PUMP") != NULL) { fprintf(stderr, "[pump] calling handle_events (issued=%d)\n", issuedRequestNum.load()); fflush(stderr); } /* 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 issued=%d\n", r, issuedRequestNum.load()); fflush(stderr); } } return r; } void TsIoThread::operator()() { while (true) { if (cancel_req.load()) { if (issuedRequestNum.load() <= 0) break; /* Re-sweep: a completion that read the flag just before * cancel() set it may have re-submitted after the first * sweep. Without this the loop never reaches zero and * join() blocks for ever. */ cancelPending(); } int r = pumpOnce(); if (r < 0) { if (r == LIBUSB_ERROR_NO_DEVICE || r == LIBUSB_ERROR_IO) { /* Unplugged. Nothing left to pump. */ break; } if (r == LIBUSB_ERROR_INTERRUPTED) continue; std::cerr << "libusb_handle_events failed: " << libusb_error_name(r) << ": " << libusb_strerror(r) << std::endl; cancel_req = true; } } /* Every callback has now run, so nothing references the transfers any * more and ~TsIoThread may free them. */ { std::lock_guard guard(lock); for (int i = 0; i < IOREQ_RESERVE_NUM; i++) { submitted[i] = false; } } thread_done = true; } /* ------------------------------------------------------------------ */ /* cancellation */ /* ------------------------------------------------------------------ */ bool TsIoThread::join() { if (ev_thread == NULL) return true; /* Bounded wait. The event thread sets thread_done as its last act. * * This has to be short: on the FreeBSD backend libusb_cancel_transfer() * delivers the callbacks on the CALLING thread, so the counter can reach * zero while the event thread is still parked inside * libusb_handle_events_timeout_completed() with nothing left to reap -- * nothing can wake it, and waiting longer only stalls the tool. When * data is flowing the thread returns from handle_events every few ms and * notices the cancel immediately, so the normal case costs ~10 ms. */ for (int i = 0; i < 50; i++) { /* up to 500 ms */ if (thread_done.load()) break; wake_event_thread(handle->ctx); /* harmless if it resolves */ rw_sleep_ms(10); } if (!thread_done.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(); delete ev_thread; ev_thread = NULL; return false; /* caller must not free transfers */ } if (ev_thread->joinable()) ev_thread->join(); delete ev_thread; ev_thread = NULL; 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++) { if (submitted[i] && xfer[i] != NULL) { int rc = libusb_cancel_transfer(xfer[i]); if (rc != LIBUSB_SUCCESS && rc != LIBUSB_ERROR_NOT_FOUND) { std::cerr << "libusb_cancel_transfer failed: " << libusb_error_name(rc) << ": " << libusb_strerror(rc) << std::endl; } } } } void TsIoThread::cancel() { cancel_req = true; /* libusb_cancel_transfer() is asynchronous: the transfer stays owned by * libusb until its callback fires. The event loop keeps running until * issuedRequestNum reaches 0, which is what makes the join() below safe. * The loop re-sweeps as well, because a completion racing this call can * re-submit a transfer after this pass. */ cancelPending(); /* Wake the event thread: it may be parked in libusb_handle_events with * nothing pending (see wake_event_thread above), in which case cancelling * transfers alone never reaches it. */ wake_event_thread(handle->ctx); } /* ------------------------------------------------------------------ */ /* consumer side */ /* ------------------------------------------------------------------ */ int TsIoThread::readBuffer(const void **ptr) { int i; int pop; int push; int avail; int scanned = 0; int remain = -1; pop = (int)buf_popIndex.load(); *ptr = buf + ((size_t)pop * TSBULKSIZE); push = (int)buf_pushIndex.load(); /* Ring occupancy trace: RECFSUSB2N_DBG_RING=1. Shows how far the * producer runs ahead of the consumer, which is what decides whether * the producer laps the ring and overwrites unread slots. */ { static int ring_n = 0; static long ring_max = 0; if (getenv("RECFSUSB2N_DBG_RING") != NULL && ring_n < 200) { int ahead = push - pop; if (ahead < 0) ahead += slotCount; if (ahead > ring_max) ring_max = ahead; fprintf(stderr, "[ring %3d] pop=%4d push=%4d ahead=%4d slots (%.2f MB) max=%ld\n", ++ring_n, pop, push, ahead, ahead * (double)TSBULKSIZE / 1048576.0, ring_max); } } if (push == pop) return 0; /* * Walk forward from pop to the write cursor. * * buf_pushIndex names the slot that has NOT been submitted yet, so it is * the only state that separates fresh slots from ones already handed to * the consumer: a slot past the cursor still carries a stale actualSize * and counting it would replay old data. * * What upstream got wrong is the extra "i < TSBUFFERSIZE" clause: when * pop sits near the end of the ring the walk stopped dead instead of * wrapping, so the burst was silently truncated at the ring boundary. * Hence the explicit wrap and the wrap-aware count below. * * Note this returns WHOLE slots. The ring stride (TSBULKSIZE) is not a * multiple of the 188-byte TS packet, so a run is not packet aligned. * That is inherent to a raw byte stream and is what the device emits; * trimming the length instead would drop the bytes of the packet that * straddles the cut, losing data on every call. Consumers that need * alignment have to resynchronise on the 0x47 sync byte. */ avail = push - pop; if (avail < 0) avail += slotCount; /* * Never hand back a run that crosses the end of the ring. * * Slots live at buf + slot*TSBULKSIZE, so a run of `scanned` slots * starting at `pop` is only contiguous while pop+scanned <= slotCount. * The callers (recfsusb2n, fsq) stage the run with a single memcpy and * write it as one block, so a run that wrapped used to copy the memory * PAST the ring allocation instead of continuing at slot 0: the tail * of the copy was heap garbage and the byte stream's packet phase * shifted, which is what produced captures that were aligned up to an * exact multiple of TSBUFFERSIZE*TSBULKSIZE (16.7 MB) and misaligned * after it. Cap at the ring end; the next call resumes at slot 0. */ if (avail > slotCount - pop) avail = slotCount - pop; for (i = pop; scanned < avail; scanned++) { size_t sz = actualSize[i]; if (sz == TSSIZE_INVALID) break; /* still in flight */ if (sz < (size_t)unitSize) { remain = (int)sz; /* short transfer: end of burst */ break; } if (++i == slotCount) i = 0; /* wrap */ } { int next = i; int continuousSize = scanned * (int)unitSize + ((remain < 0) ? 0 : remain); if (remain >= 0) { if (++next == slotCount) next = 0; } buf_popIndex = (size_t)next; return continuousSize; } }