1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
|
/*
* 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 <string.h>
#include <iostream>
#include "IoThread.hpp"
#include "compat.hpp"
#if !RW_WINDOWS
#include <dlfcn.h>
#include <poll.h>
#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<std::mutex> 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;
}
}
|