-
Notifications
You must be signed in to change notification settings - Fork 67
/
usb_driver.cc
1770 lines (1514 loc) · 67.8 KB
/
usb_driver.cc
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "driver/usb/usb_driver.h"
#include <bitset>
#include <functional>
#include <queue>
#include <utility>
#include <vector>
#include "api/buffer.h"
#include "api/watchdog.h"
#include "driver/device_buffer_mapper.h"
#include "driver/dma_info_extractor.h"
#include "driver/hardware_structures.h"
#include "driver/interrupt/interrupt_controller_interface.h"
#include "driver/interrupt/top_level_interrupt_manager.h"
#include "driver/memory/address_utilities.h"
#include "driver/memory/dram_allocator.h"
#include "driver/package_registry.h"
#include "driver/single_tpu_request.h"
#include "driver/top_level_handler.h"
#include "driver/tpu_request.h"
#include "driver/usb/usb_dfu_util.h"
#include "driver/usb/usb_latest_firmware.h"
#include "driver/usb/usb_ml_commands.h"
#include "driver_shared/time_stamper/time_stamper.h"
#include "port/cleanup.h"
#include "port/errors.h"
#include "port/integral_types.h"
#include "port/logging.h"
#include "port/ptr_util.h"
#include "port/status.h"
#include "port/status_macros.h"
#include "port/statusor.h"
#include "port/std_mutex_lock.h"
#include "port/stringprintf.h"
#include "port/time.h"
#include "port/tracing.h"
#include "port/unreachable.h"
namespace platforms {
namespace darwinn {
namespace driver {
namespace {
// Sleep time before we try or retry to open a device.
// TODO: revisit this setting after we finalize PHY tuning.
constexpr int kSleepTimeMicroSecondsBeforeRetry = 1000000;
// TODO: revisit this setting after we finalize PHY tuning.
constexpr int kMaxNumOfRetryAfterReset = 25;
constexpr uint16_t kTargetAppVendorId = 0x18D1;
constexpr uint16_t kTargetAppProductId = 0x9302;
constexpr uint16_t kTargetDfuVendorId = 0x1A6E;
constexpr uint16_t kTargetDfuProductId = 0x089A;
// This class implements BasicLockable concept, to be used with
// std::conditional_variable_any.
// The implementation is specialized as no re-locking is needed.
// Since the conditional variable is used in the end of a do-while loop,
// re-locking is just waste of time.
class Lock2 {
public:
Lock2(StdCondMutexLock& m1, StdCondMutexLock& m2) : m1_(m1), m2_(m2) {}
~Lock2() = default;
// Does nothing. This function is part of BasicLockable concept.
void lock() {
// do nothing.
VLOG(10) << "lock (does nothing)";
}
// Unlocks both Lockables. This function is part of BasicLockable concept.
void unlock() {
VLOG(10) << "Unlocks both mutex";
m1_.unlock();
m2_.unlock();
}
private:
StdCondMutexLock& m1_;
StdCondMutexLock& m2_;
};
// Returns the number of entries in a queue concept, protected by the given
// mutex.
template <typename Queue>
static typename Queue::size_type QueueSize(const Queue* queue,
std::mutex* mutex) {
StdCondMutexLock state_lock(mutex);
return queue->size();
}
// Returns if a queue concept is empty, protected by the given mutex.
template <typename Queue>
static bool IsQueueEmpty(const Queue* queue, std::mutex* mutex) {
StdCondMutexLock state_lock(mutex);
return queue->empty();
}
// Returns the first entry in a queue concept, protected by the given mutex.
template <typename Queue>
static typename Queue::value_type QueuePop(Queue* queue, std::mutex* mutex) {
StdCondMutexLock state_lock(mutex);
typename Queue::value_type item = queue->front();
queue->pop();
return item;
}
} // namespace
UsbDriver::UsbDriver(
const api::DriverOptions& driver_options,
std::unique_ptr<config::ChipConfig> chip_config,
std::unique_ptr<UsbRegisters> registers,
std::unique_ptr<TopLevelInterruptManager> top_level_interrupt_manager,
std::unique_ptr<InterruptControllerInterface>
fatal_error_interrupt_controller,
std::unique_ptr<TopLevelHandler> top_level_handler,
std::unique_ptr<DramAllocator> dram_allocator,
std::unique_ptr<PackageRegistry> executable_registry,
const UsbDriverOptions& options,
std::unique_ptr<driver_shared::TimeStamper> time_stamper)
: Driver(
[](config::ChipConfig* chip_config) {
CHECK(chip_config != nullptr);
return chip_config->GetChip();
}(chip_config.get()),
std::move(executable_registry), driver_options,
std::move(time_stamper)),
chip_config_(std::move(chip_config)),
registers_(std::move(registers)),
allocator_(gtl::MakeUnique<AlignedAllocator>(
chip_config_->GetChipStructures().allocation_alignment_bytes)),
top_level_interrupt_manager_(std::move(top_level_interrupt_manager)),
fatal_error_interrupt_controller_(
std::move(fatal_error_interrupt_controller)),
top_level_handler_(std::move(top_level_handler)),
dram_allocator_(std::move(dram_allocator)),
options_(options),
dma_info_extractor_(
options.usb_enable_processing_of_hints
? DmaInfoExtractor::ExtractorType::kDmaHints
: DmaInfoExtractor::ExtractorType::kFirstInstruction,
options.usb_enable_overlapping_requests),
dma_scheduler_(api::Watchdog::MakeWatchdog(
driver_options.watchdog_timeout_ns(),
[this](int64) { HandleWatchdogTimeout(); })),
apex_csr_offsets_(chip_config_->GetApexCsrOffsets()),
cb_bridge_csr_offsets_(chip_config_->GetCbBridgeCsrOffsets()),
hib_kernel_csr_offsets_(chip_config_->GetHibKernelCsrOffsets()),
scu_csr_offsets_(chip_config_->GetScuCsrOffsets()),
usb_csr_offsets_(chip_config_->GetUsbCsrOffsets()),
hib_user_csr_offsets_(chip_config_->GetHibUserCsrOffsets()) {
run_controller_ =
gtl::MakeUnique<RunController>(*chip_config_, registers_.get());
if (options_.mode == OperatingMode::kMultipleEndpointsSoftwareQuery) {
options_.usb_max_num_async_transfers = 1;
VLOG(5) << StringPrintf(
"force setting usb_max_num_async_transfers to 1 for software "
"query mode");
}
}
UsbDriver::UsbDriver(
const api::DriverOptions& driver_options,
std::unique_ptr<config::ChipConfig> chip_config,
std::unique_ptr<UsbMlCommands> usb_device,
std::unique_ptr<UsbRegisters> registers,
std::unique_ptr<TopLevelInterruptManager> top_level_interrupt_manager,
std::unique_ptr<InterruptControllerInterface>
fatal_error_interrupt_controller,
std::unique_ptr<TopLevelHandler> top_level_handler,
std::unique_ptr<DramAllocator> dram_allocator,
std::unique_ptr<PackageRegistry> executable_registry,
const UsbDriverOptions& options,
std::unique_ptr<driver_shared::TimeStamper> time_stamper)
: UsbDriver(driver_options, std::move(chip_config), std::move(registers),
std::move(top_level_interrupt_manager),
std::move(fatal_error_interrupt_controller),
std::move(top_level_handler), std::move(dram_allocator),
std::move(executable_registry), options,
std::move(time_stamper)) {
usb_device_ = std::move(usb_device);
}
UsbDriver::UsbDriver(
const api::DriverOptions& driver_options,
std::unique_ptr<config::ChipConfig> chip_config,
std::function<StatusOr<std::unique_ptr<UsbDeviceInterface>>()>
device_factory,
std::unique_ptr<UsbRegisters> registers,
std::unique_ptr<TopLevelInterruptManager> top_level_interrupt_manager,
std::unique_ptr<InterruptControllerInterface>
fatal_error_interrupt_controller,
std::unique_ptr<TopLevelHandler> top_level_handler,
std::unique_ptr<DramAllocator> dram_allocator,
std::unique_ptr<PackageRegistry> executable_registry,
const UsbDriverOptions& options,
std::unique_ptr<driver_shared::TimeStamper> time_stamper)
: UsbDriver(driver_options, std::move(chip_config), std::move(registers),
std::move(top_level_interrupt_manager),
std::move(fatal_error_interrupt_controller),
std::move(top_level_handler), std::move(dram_allocator),
std::move(executable_registry), options,
std::move(time_stamper)) {
device_factory_ = std::move(device_factory);
}
UsbDriver::~UsbDriver() {
CHECK_OK(UnregisterAll());
if (Close(api::Driver::ClosingMode::kGraceful).ok()) {
LOG(WARNING) << "Driver destroyed when open. Forced Close().";
}
}
Status UsbDriver::ValidateState(State expected_state) const {
return ValidateStates({expected_state});
}
Status UsbDriver::ValidateStates(
const std::vector<State>& expected_states) const {
for (auto& state : expected_states) {
if (state_ == state) {
return Status(); // OK
}
}
return FailedPreconditionError(StringPrintf("Unexpected state %d.", state_));
}
Status UsbDriver::SetState(State next_state) {
driver_state_changed_.notify_all();
if ((next_state == kClosing) || (next_state == kPaused)) {
// Cancel all transfers when we enter closing or paused state.
//
// Cancellation generates new callbacks with canceled status which need to
// be handled for each transfer that is still active. Pointers to task
// records and hence bulk in/out requests could already been invalidated.
usb_device_->TryCancelAllTransfers();
}
switch (state_) {
case kOpen:
if ((next_state == kOpen) || (next_state == kClosing)) {
// There is nothing special to do.
state_ = next_state;
return Status(); // OK
} else if (next_state == kPaused) {
VLOG(7) << StringPrintf("%s try enable clock gating", __func__);
RETURN_IF_ERROR(top_level_handler_->EnableSoftwareClockGate());
state_ = next_state;
return Status(); // OK
}
break;
case kPaused:
if (next_state == kPaused) {
// We're already paused. Do nothing.
return Status(); // OK
} else if ((next_state == kOpen) || (next_state == kClosing)) {
// Disable clock gating so we can access the chip.
VLOG(7) << StringPrintf("%s try disable clock gating", __func__);
RETURN_IF_ERROR(top_level_handler_->DisableSoftwareClockGate());
state_ = next_state;
return Status(); // OK
}
break;
case kClosing:
if (next_state == kClosed) {
state_ = next_state;
return Status(); // OK
}
break;
case kClosed:
if (next_state == kOpen) {
state_ = next_state;
return Status(); // OK
}
break;
}
// Illegal state transition.
return FailedPreconditionError(StringPrintf(
"Invalid state transition. current=%d, next=%d.", state_, next_state));
}
// TODO: review the sequence with hardware team and convert them to
// use named constants.
Status UsbDriver::InitializeChip() {
TRACE_SCOPE("UsbDriver::InitializeChip");
ASSIGN_OR_RETURN(auto omc_reg, registers_->Read32(apex_csr_offsets_.omc0_00));
constexpr int EFUSE_PROGRAMMING_REVISION_SHIFT = 24;
constexpr int EFUSE_PROGRAMMING_REVISION_MASK = 0xFF;
const uint8_t efuse_programming_revision =
(omc_reg >> EFUSE_PROGRAMMING_REVISION_SHIFT) &
EFUSE_PROGRAMMING_REVISION_MASK;
VLOG(1) << StringPrintf("e-fuse programming revision: %d",
efuse_programming_revision);
if (options_.usb_enable_bulk_descriptors_from_device) {
VLOG(7) << StringPrintf("%s Enabling all descriptors", __func__);
RETURN_IF_ERROR(registers_->Write(usb_csr_offsets_.descr_ep, 0xFF));
} else {
VLOG(7) << StringPrintf("%s Enabling only sc host interrupt descriptors",
__func__);
RETURN_IF_ERROR(registers_->Write(usb_csr_offsets_.descr_ep, 0xF0));
}
switch (options_.mode) {
case OperatingMode::kMultipleEndpointsHardwareControl:
case OperatingMode::kMultipleEndpointsSoftwareQuery:
VLOG(7) << StringPrintf("%s Enabling multiple EP mode", __func__);
RETURN_IF_ERROR(registers_->Write(usb_csr_offsets_.multi_bo_ep, 1));
break;
case OperatingMode::kSingleEndpoint:
VLOG(7) << StringPrintf("%s Enabling single EP mode", __func__);
RETURN_IF_ERROR(registers_->Write(usb_csr_offsets_.multi_bo_ep, 0));
break;
default:
return FailedPreconditionError("Unrecognized USB operating mode");
}
if ((!options_.usb_force_largest_bulk_in_chunk_size) &&
(usb_device_->GetDeviceSpeed() ==
UsbStandardCommands::DeviceSpeed::kHigh)) {
// If we know it's USB2 Highspeed (max bulk packet size 512B), and there is
// no option to force max chunk size, use 256B chunk size to limit packet
// length to 256B. This is a workaround for b/73181174
VLOG(7) << StringPrintf("%s Setting 256B chunk for USB 2 High Speed",
__func__);
// This is an optimiaztion for some host controllers, so everyone knows the
// response would be only 256 bytes long. Without this, host would need to
// identify the response as a "short" packet and hence ends transfer. Not
// all host controllers need this change.
cap_bulk_in_size_at_256_bytes_ = true;
RETURN_IF_ERROR(
registers_->Write(usb_csr_offsets_.outfeed_chunk_length, 0x20));
} else {
// Otherwise, use the largest chunk size (1KB) for max bulk packet size
// determined by the hardware.
VLOG(7) << StringPrintf("%s Setting 1KB chunk for bulk-ins", __func__);
cap_bulk_in_size_at_256_bytes_ = false;
RETURN_IF_ERROR(
registers_->Write(usb_csr_offsets_.outfeed_chunk_length, 0x80));
}
return Status(); // OK.
}
Status UsbDriver::RegisterAndEnableAllInterrupts() {
// TODO: Register interrupts to interrupt EP.
RETURN_IF_ERROR(fatal_error_interrupt_controller_->EnableInterrupts());
RETURN_IF_ERROR(top_level_interrupt_manager_->EnableInterrupts());
return Status(); // OK
}
Status UsbDriver::DisableAllInterrupts() {
RETURN_IF_ERROR(top_level_interrupt_manager_->DisableInterrupts());
RETURN_IF_ERROR(fatal_error_interrupt_controller_->DisableInterrupts());
return Status(); // OK
}
void UsbDriver::HandleEvent(const Status& status,
const UsbMlCommands::EventDescriptor& event_info) {
if (status.ok()) {
// TODO: analyze if there is any failure case we can recover from.
CHECK_OK(HandleDmaDescriptor(
event_info.tag, event_info.offset, event_info.length,
options_.usb_enable_bulk_descriptors_from_device));
} else if (IsDeadlineExceeded(status)) {
VLOG(10) << StringPrintf("%s timed out, ignore.", __func__);
} else if (IsCancelled(status)) {
VLOG(10) << StringPrintf("%s cancelled, ignore.", __func__);
} else {
LOG(FATAL) << StringPrintf("%s failed. %s", __func__,
status.error_message().c_str());
}
}
Status UsbDriver::CheckHibError() {
// Indicates no HIB Fatal Error.
constexpr uint64 kHibErrorStatusNone = 0;
ASSIGN_OR_RETURN(uint64 hib_error_status,
registers_->Read(hib_user_csr_offsets_.hib_error_status));
if (hib_error_status == kHibErrorStatusNone) {
return Status(); // OK
}
ASSIGN_OR_RETURN(
uint64 hib_first_error_status,
registers_->Read(hib_user_csr_offsets_.hib_first_error_status));
auto error_string = StringPrintf(
"HIB Error. hib_error_status = %016llx, hib_first_error_status = %016llx",
static_cast<unsigned long long>(hib_error_status), // NOLINT(runtime/int)
static_cast<unsigned long long>( // NOLINT(runtime/int)
hib_first_error_status));
LOG(ERROR) << error_string;
return InternalError(error_string);
}
void UsbDriver::HandleInterrupt(
const Status& status, const UsbMlCommands::InterruptInfo& interrupt_info) {
if (status.ok()) {
VLOG(10) << StringPrintf("%s interrupt received.", __func__);
constexpr uint32_t kFatalErrorInterruptMask = 1;
constexpr int kTopLevelInterruptBitShift = 1;
const uint32_t kTopLevelInterruptMask =
((1 << top_level_interrupt_manager_->NumInterrupts()) - 1)
<< kTopLevelInterruptBitShift;
if (interrupt_info.raw_data & kFatalErrorInterruptMask) {
VLOG(1) << StringPrintf("%s Fatal error interrupt received.", __func__);
CHECK_OK(CheckHibError());
CHECK_OK(fatal_error_interrupt_controller_->ClearInterruptStatus(0));
}
if ((interrupt_info.raw_data & kTopLevelInterruptMask) != 0) {
uint32_t top_level_interrupts = static_cast<uint32_t>(
(interrupt_info.raw_data & kTopLevelInterruptMask) >>
kTopLevelInterruptBitShift);
for (int id = 0; id < top_level_interrupt_manager_->NumInterrupts();
++id) {
const uint32_t mask = 1 << id;
if ((top_level_interrupts & mask) == mask) {
VLOG(1) << StringPrintf("%s Top level interrupt %d received.",
__func__, id);
CHECK_OK(top_level_interrupt_manager_->HandleInterrupt(id));
}
}
}
} else if (IsCancelled(status)) {
VLOG(10) << StringPrintf("%s cancelled, ignore.", __func__);
} else {
VLOG(1) << status.message();
}
}
uint32_t UsbDriver::GetCredits(UsbMlCommands::DescriptorTag tag) {
if (!registers_->Write32(apex_csr_offsets_.omc0_00, 0xffffffff).ok()) {
VLOG(1) << StringPrintf("%s write failed. silently assume 0 credit",
__func__);
return 0;
}
auto query_result = registers_->Read(usb_csr_offsets_.ep_status_credit);
if (!query_result.status().ok()) {
VLOG(1) << StringPrintf("%s read failed. silently assume 0 credit",
__func__);
return 0;
}
const uint64_t gcb_credits = query_result.ValueOrDie();
constexpr uint32_t kCounterInBytes = 8;
constexpr uint32_t kCreditShift = 21;
constexpr uint32_t kCreditMask = (1ULL << kCreditShift) - 1;
const uint32_t instructions =
static_cast<uint32_t>((gcb_credits & kCreditMask) * kCounterInBytes);
const uint32_t input_activations = static_cast<uint32_t>(
((gcb_credits >> kCreditShift) & kCreditMask) * kCounterInBytes);
const uint32_t parameters = static_cast<uint32_t>(
((gcb_credits >> (kCreditShift * 2)) & kCreditMask) * kCounterInBytes);
VLOG(10) << StringPrintf("%s credits: instructions %u, input %u, params %u",
__func__, instructions, input_activations,
parameters);
switch (tag) {
case UsbMlCommands::DescriptorTag::kInstructions:
return instructions;
case UsbMlCommands::DescriptorTag::kInputActivations:
return input_activations;
case UsbMlCommands::DescriptorTag::kParameters:
return parameters;
default:
LOG(FATAL) << StringPrintf("%s unrecognized tag", __func__);
unreachable(); // NOLINT
}
}
// TODO: breaks up this function according to functionality.
StatusOr<bool> UsbDriver::ProcessIo() {
TRACE_SCOPE("UsbDriver::ProcessIO");
static constexpr int kNumBulkOutTags = 3;
static constexpr uint8_t tag_to_bulk_out_endpoint_id[kNumBulkOutTags] = {
UsbMlCommands::kInstructionsEndpoint,
UsbMlCommands::kInputActivationsEndpoint,
UsbMlCommands::kParametersEndpoint};
int num_active_transfers = 0;
std::bitset<kNumBulkOutTags> tag_to_bulk_out_with_unsent_chunk;
// Remove UsbIoRequest that are completed.
while (!io_requests_.empty()) {
const auto& io_request = io_requests_.front();
if (!io_request.IsCompleted()) {
break;
}
// If DMA descriptors are coming in, and hint is not yet matched. Consider
// it not completed.
if (options_.usb_enable_bulk_descriptors_from_device &&
io_request.GetSourceAndMatchStatus() ==
UsbIoRequest::SourceAndMatchStatus::kHintNotYetMatched) {
break;
}
if (io_request.FromDmaHint()) {
CHECK_OK(dma_scheduler_.NotifyDmaCompletion(io_request.dma_info()));
}
if (io_request.GetTag() == UsbMlCommands::DescriptorTag::kInterrupt0) {
TRACE_WITHIN_SCOPE("UsbDriver::ProcessIO::RequestCompletion");
CHECK_OK(dma_scheduler_.NotifyRequestCompletion());
HandleTpuRequestCompletion();
}
VLOG(9) << "IO completed";
io_requests_.pop_front();
}
// TODO: Remove this loop.
// As an intermediate step, IO requests are completely pulled out from a
// Request. Eventually, We should GetNextDma() only when we can perform DMA.
ASSIGN_OR_RETURN(auto* dma_info, dma_scheduler_.GetNextDma());
while (dma_info) {
io_requests_.push_back(UsbIoRequest(dma_info));
ASSIGN_OR_RETURN(dma_info, dma_scheduler_.GetNextDma());
}
// True if some libusb command has been issued and we should skip waiting on
// the completion queue.
bool is_task_state_changed = false;
// All previous bulk out requests must be completed before a bulk in, and
// interrupt 0 request can be processed.
bool is_any_bulk_out_still_uncompleted = false;
bool is_any_bulk_in_still_uncompleted = false;
for (auto& io_request : io_requests_) {
if (io_request.IsCompleted()) {
continue;
}
if (io_request.GetTag() == UsbMlCommands::DescriptorTag::kInterrupt0) {
// Nothing to do for interrupts.
continue;
}
auto io_type = io_request.GetType();
const int tag = static_cast<int>(io_request.GetTag());
if (io_type == UsbIoRequest::Type::kBulkOut) {
// block further processing of any bulk in requests.
is_any_bulk_out_still_uncompleted = true;
if (io_request.IsActive()) {
// simply increase the counter and proceed to see if we can fire another
// request for the next chunk.
num_active_transfers += io_request.GetActiveCounts(
options_.max_bulk_out_transfer_size_in_bytes);
} else {
if (options_.mode == OperatingMode::kMultipleEndpointsHardwareControl) {
// In multiple-ep hardware control mode, let's continue
// searching for a different tag to be sent out. It's never okay to
// interleve/mix chunks from different requests of the same tag.
if (tag_to_bulk_out_with_unsent_chunk[static_cast<int>(
UsbMlCommands::DescriptorTag::kInstructions)]) {
// If there is any uncompleted instructions, break from the search.
break;
} else if (tag_to_bulk_out_with_unsent_chunk.count() ==
(kNumBulkOutTags - 1)) {
// If all endpoints(tags) supported, other than instructions, are
// busy, break from the search. If instructions endpoint is busy, we
// already break from previous clause.
break;
} else if (tag_to_bulk_out_with_unsent_chunk[tag]) {
// If something sharing with my endpoint is busy, keep looking for
// something different.
continue;
}
} else {
if (tag_to_bulk_out_with_unsent_chunk.any()) {
// In other modes, especially for single-ep mode, continue searching
// is not necessary if any previous request has unsent chunk data
// waiting. This is because we only send out header once for each
// request. Note that it's okay to start sending the next chunk if
// the request is already active, as they share the same header.
// Also, it's okay to start processing a new request after the
// previous request has all its data pushed into the pipeline.
break;
}
}
}
if (is_any_bulk_in_still_uncompleted) {
// Prevent any queuing of bulk-out after bulk-in, in single ep mode.
// It's not very safe to allow bulk-out after bulk-in in single ep mode,
// as the bulk-out could hog the internal data path and prevent bulk-in
// from completion. In multiple ep mode, the internal data path cannot
// be occupied for long time, and hence it's safe to queue any request.
if (options_.mode == OperatingMode::kSingleEndpoint) {
// Due to hardware limitation, bulk-out could delay completion of
// bulk-in till deadlock occurs.
VLOG(10) << StringPrintf(
"[%d-%d] all bulk in requests must be completed before "
"processing of bulk out can start, wait",
io_request.id(), tag);
break;
}
} else if (num_active_transfers >= options_.usb_max_num_async_transfers) {
VLOG(10) << StringPrintf(
"[%d-%d] number of concurrent transfers too high, wait "
"(%d >= %d)",
io_request.id(), tag, num_active_transfers,
options_.usb_max_num_async_transfers);
break;
}
if (!io_request.HasNextChunk()) {
// There is nothing we can do for this request. All data has been put
// in transit.
continue;
}
if (options_.mode == OperatingMode::kMultipleEndpointsSoftwareQuery) {
// TODO: add some mechansim to slowly poll for available
// credits.
// Setting this to true would cause unpleasant busy looping.
is_task_state_changed = true;
// query for credits available.
uint32_t credits = GetCredits(io_request.GetTag());
// proceed only if the credits are above some threashold.
if (credits <= options_.software_credits_lower_limit_in_bytes) {
VLOG(10) << StringPrintf(
"[%d-%d] available credits too low, wait (%u <= %u)",
io_request.id(), tag, credits,
options_.software_credits_lower_limit_in_bytes);
// Stop further processing if credit for any endpoint is lower than
// the limit.
// TODO: allow a different endpoint to proceed.
break;
}
// Clamp the transfer size with available credits.
uint32_t transfer_size =
std::min(options_.max_bulk_out_transfer_size_in_bytes, credits);
const auto device_buffer = io_request.GetNextChunk(transfer_size);
auto host_buffer = address_space_.Translate(device_buffer).ValueOrDie();
UsbMlCommands::ConstBuffer transfer_buffer(host_buffer.ptr(),
host_buffer.size_bytes());
++num_active_transfers;
if (io_request.HasNextChunk()) {
// This request still has some data not sent over to the pipeline.
// Setting this to true prevents rquests of the same tag to start, as
// chunks from different requests of the same tag must not interleve.
tag_to_bulk_out_with_unsent_chunk[tag] = true;
}
// To make sure the query result for credits is accurate, we have to
// use sync transfer. Because we only send data according to credits
// available, there is no way we could get a timeout error.
Status status = usb_device_->BulkOutTransfer(
tag_to_bulk_out_endpoint_id[tag], transfer_buffer, __func__);
if (status.ok()) {
io_request.NotifyTransferComplete(transfer_size);
VLOG(10) << StringPrintf("[%d-%d] bulk out for %u bytes done",
io_request.id(), tag, transfer_size);
} else {
// TODO: terminate the task early, as there is no
// chance we can continue. The more reasonable next step would
// be resetting the device.
LOG(FATAL) << StringPrintf(
"[%d-%d] bulk out for %u bytes failed. Abort. %s",
io_request.id(), tag, transfer_size, status.ToString().c_str());
}
} else if (options_.mode ==
OperatingMode::kMultipleEndpointsHardwareControl) {
is_task_state_changed = true;
const auto device_buffer = io_request.GetNextChunk(
options_.max_bulk_out_transfer_size_in_bytes);
auto host_buffer = address_space_.Translate(device_buffer).ValueOrDie();
UsbMlCommands::ConstBuffer transfer_buffer(host_buffer.ptr(),
host_buffer.size_bytes());
uint32_t transfer_size = static_cast<uint32_t>(transfer_buffer.size());
++num_active_transfers;
if (io_request.HasNextChunk()) {
// This request still has some data not sent over to the pipeline.
// Setting this to true prevents rquests of the same tag to start, as
// chunks from different requests of the same tag must not interleve.
tag_to_bulk_out_with_unsent_chunk[tag] = true;
}
Status async_request_status = usb_device_->AsyncBulkOutTransfer(
tag_to_bulk_out_endpoint_id[tag], transfer_buffer,
[this, &io_request, tag, transfer_size](Status status) {
// Inject a functor into a completion queue driven by the worker
// thread. Note that the reference to io_request could have been
// invalidated when the async transfer is cancelled.
StdMutexLock queue_lock(&callback_mutex_);
callback_queue_.push([&io_request, tag, status, transfer_size] {
// Starting from here is an functor which would be executed
// within the worker thread context, after the async transfer
// has been completed.
if (status.ok()) {
io_request.NotifyTransferComplete(transfer_size);
VLOG(10) << StringPrintf("[%d-%d] bulk out for %u bytes done",
io_request.id(), tag, transfer_size);
} else {
// TODO: terminate the task early, as there is no
// chance we can continue. The more reasonable next step
// would be resetting the device.
LOG(FATAL) << StringPrintf(
"[%d-%d] bulk out failed. Abort. %s", io_request.id(),
tag, status.ToString().c_str());
}
});
driver_state_changed_.notify_all();
},
__func__);
if (!async_request_status.ok()) {
// TODO: terminate the task early, as there is no
// chance we can continue. The more reasonable next step would
// be resetting the device.
LOG(FATAL) << StringPrintf(
"[%d-%d] async transfer out for %u bytes failed. Abort. %s",
io_request.id(), tag, transfer_size,
async_request_status.ToString().c_str());
}
} else if (options_.mode == OperatingMode::kSingleEndpoint) {
is_task_state_changed = true;
if (!io_request.IsActive() && !io_request.IsCompleted() &&
!io_request.IsHeaderSent()) {
// Prepare the header with full data size.
// add one extra count for the header transfer.
++num_active_transfers;
VLOG(10) << StringPrintf("%s [%d-%d] bulk out header", __func__,
io_request.id(), tag);
io_request.SetHeader(usb_device_->PrepareHeader(
io_request.GetTag(), io_request.GetBuffer().size_bytes()));
Status async_request_status = usb_device_->AsyncBulkOutTransfer(
UsbMlCommands::kSingleBulkOutEndpoint,
UsbMlCommands::ConstBuffer(io_request.header()),
[this, &io_request, tag](Status status) {
// Inject a functor into a completion queue driven by the worker
// thread. Note that the reference to io_request could have been
// invalidated when the async transfer is cancelled.
StdMutexLock queue_lock(&callback_mutex_);
callback_queue_.push([&io_request, tag, status] {
// Starting from here is an functor which would be executed
// within the worker thread context, after the async transfer
// has been completed.
if (status.ok()) {
VLOG(10) << StringPrintf("[%d-%d] bulk out for header done",
io_request.id(), tag);
} else {
// TODO: terminate the task early, as there is no
// chance we can continue. The more reasonable next step
// would be resetting the device.
LOG(FATAL) << StringPrintf(
"[%d-%d] bulk out for header failed. Abort. %s",
io_request.id(), tag, status.ToString().c_str());
}
});
driver_state_changed_.notify_all();
},
__func__);
if (!async_request_status.ok()) {
// TODO: terminate the task early, as there is no
// chance we can continue. The more reasonable next step would
// be resetting the device.
LOG(FATAL) << StringPrintf(
"[%d-%d] bulk out for header failed. Abort. %s",
io_request.id(), tag, async_request_status.ToString().c_str());
}
}
// Send the actual data in chunks.
const auto device_buffer = io_request.GetNextChunk(
options_.max_bulk_out_transfer_size_in_bytes);
auto host_buffer = address_space_.Translate(device_buffer).ValueOrDie();
UsbMlCommands::ConstBuffer transfer_buffer(host_buffer.ptr(),
host_buffer.size_bytes());
uint32_t transfer_size = static_cast<uint32_t>(transfer_buffer.size());
++num_active_transfers;
if (io_request.HasNextChunk()) {
// This request still has some data not sent over to the pipeline.
// Setting this to true prevents rquests of the same tag to start, as
// chunks from different requests of the same tag must not interleve.
tag_to_bulk_out_with_unsent_chunk[tag] = true;
}
Status async_request_status = usb_device_->AsyncBulkOutTransfer(
UsbMlCommands::kSingleBulkOutEndpoint, transfer_buffer,
[this, &io_request, tag, transfer_size](Status status) {
// Inject a functor into a completion queue driven by the worker
// thread. Note that the reference to io_request could have been
// invalidated when the async transfer is cancelled.
StdMutexLock queue_lock(&callback_mutex_);
callback_queue_.push([&io_request, tag, status, transfer_size] {
// Starting from here is an functor which would be executed
// within the worker thread context, after the async transfer
// has been completed.
if (status.ok()) {
io_request.NotifyTransferComplete(transfer_size);
VLOG(10) << StringPrintf(
"%s [%d-%d] bulk out for %u bytes done", __func__,
io_request.id(), tag, transfer_size);
} else {
// TODO: terminate the task early, as there is no
// chance we can continue. The more reasonable next step
// would be resetting the device.
LOG(FATAL)
<< StringPrintf("transfer on tag %d failed. Abort. %s",
tag, status.ToString().c_str());
}
});
driver_state_changed_.notify_all();
},
__func__);
if (!async_request_status.ok()) {
// TODO: terminate the task early, as there is no
// chance we can continue. The more reasonable next step would
// be resetting the device.
LOG(FATAL) << StringPrintf(
"%s [%d-%d] async transfer out failed. Abort. %s", __func__,
io_request.id(), tag, async_request_status.ToString().c_str());
}
}
} else if (io_type == UsbIoRequest::Type::kBulkIn) {
// If queuing is enabled, bulk-in requests are handled similar to
// interrupt and dma descriptors.
if (options_.usb_enable_queued_bulk_in_requests) {
// Skip if any previous bulk-in request is still incomplete. This is
// because all bulk-in requests have to be serialized.
if (is_any_bulk_in_still_uncompleted) {
continue;
}
// Walk through filled buffer queue.
while (!filled_bulk_in_buffers_.empty()) {
// We're about to change the state of io requests.
// This flag indicates we need to call ProcessIo() again.
is_task_state_changed = true;
// We're getting a reference, as we're directly modifying
// begin_offset.
FilledBulkInInfo& filled_info = filled_bulk_in_buffers_.front();
const Buffer& buffer = bulk_in_buffers_[filled_info.buffer_index];
const size_t available_data_size_bytes =
filled_info.end_offset - filled_info.begin_offset;
auto device_buffer = io_request.GetNextChunk();
auto host_buffer =
address_space_.Translate(device_buffer).ValueOrDie();
const size_t requested_size_bytes = host_buffer.size_bytes();
const size_t transferred_bytes =
std::min(available_data_size_bytes, requested_size_bytes);
memcpy(host_buffer.ptr(), buffer.ptr() + filled_info.begin_offset,
transferred_bytes);
io_request.NotifyTransferComplete(transferred_bytes);
if (available_data_size_bytes <= requested_size_bytes) {
VLOG(10) << StringPrintf(
"[%d-%d] bulk in for %zu bytes has yielded %zu bytes from "
"index [%d]",
io_request.id(), tag, requested_size_bytes,
available_data_size_bytes, filled_info.buffer_index);
// We've depleted the buffer. Return it to available queue.
available_bulk_in_buffers_.push(filled_info.buffer_index);
filled_bulk_in_buffers_.pop();
if (io_request.IsCompleted()) {
// There is no need to check the next buffer, as we've just
// completed this io_request.
break;
}
} else {
VLOG(10) << StringPrintf(
"[%d-%d] bulk in for %zu bytes has yielded %zu bytes "
"(OVERFLOW) from index [%d]",
io_request.id(), tag, requested_size_bytes,
available_data_size_bytes, filled_info.buffer_index);
filled_info.begin_offset += requested_size_bytes;
// We just completed this io_request, stop iterating through
// buffers.
break;
}
}
if (!io_request.IsCompleted()) {
// This flag would prevent further bulk-in request in all modes, and
// further bulk-out in single-ep mode.
is_any_bulk_in_still_uncompleted = true;
}
// Continue to the next io_request.
continue;
}
if (!options_.usb_enable_overlapping_bulk_in_and_out &&
is_any_bulk_out_still_uncompleted) {
VLOG(10) << StringPrintf(
"[%d-%d] configured to start only after all "
"bulk-out requests complete, wait",
io_request.id(), tag);
break;
} else if (num_active_transfers >= options_.usb_max_num_async_transfers) {
VLOG(10) << StringPrintf(
"[%d-%d] number of concurrent transfers too high, wait "
"(%d >= %d)",
io_request.id(), tag, num_active_transfers,
options_.usb_max_num_async_transfers);
break;
} else if (io_request.IsActive()) {
++num_active_transfers;
// Still transferring data in. Break from the loop.
VLOG(10) << StringPrintf(
"[%d-%d] this bulk in request is still active, wait",
io_request.id(), tag);
break;
} else {
is_task_state_changed = true;
is_any_bulk_in_still_uncompleted = true;
auto device_buffer = (cap_bulk_in_size_at_256_bytes_)
? io_request.GetNextChunk(256)
: io_request.GetNextChunk();
auto host_buffer = address_space_.Translate(device_buffer).ValueOrDie();
UsbMlCommands::MutableBuffer transfer_buffer(host_buffer.ptr(),
host_buffer.size_bytes());
uint32_t transfer_size = static_cast<uint32_t>(transfer_buffer.size());
VLOG(10) << StringPrintf("[%d-%d] bulk in for %zu bytes",
io_request.id(), tag, transfer_buffer.size());
++num_active_transfers;
Status async_request_status = usb_device_->AsyncBulkInTransfer(
UsbMlCommands::kBulkInEndpoint, transfer_buffer,
[this, &io_request, tag, transfer_size](
Status status, size_t num_bytes_transferred) {
// Inject a functor into a completion queue driven by the worker
// thread. Note that the reference to io_request could have been
// invalidated when the async transfer is cancelled.