File: dawn_context_provider.cc

package info (click to toggle)
chromium 139.0.7258.127-2
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 6,122,156 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1215 lines) | stat: -rw-r--r-- 44,789 bytes parent folder | download | duplicates (3)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "gpu/command_buffer/service/dawn_context_provider.h"

#include <memory>
#include <vector>

#include "base/check_op.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/dcheck_is_on.h"
#include "base/debug/crash_logging.h"
#include "base/debug/dump_without_crashing.h"
#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_functions.h"
#include "base/no_destructor.h"
#include "base/notreached.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/synchronization/lock.h"
#include "base/task/single_thread_task_runner.h"
#include "base/thread_annotations.h"
#include "base/threading/platform_thread.h"
#include "base/threading/thread_checker.h"
#include "base/trace_event/memory_dump_manager.h"
#include "base/trace_event/memory_dump_provider.h"
#include "base/trace_event/process_memory_dump.h"
#include "base/trace_event/trace_arguments.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "components/crash/core/common/crash_key.h"
#include "gpu/command_buffer/service/dawn_instance.h"
#include "gpu/command_buffer/service/dawn_platform.h"
#include "gpu/command_buffer/service/skia_utils.h"
#include "gpu/config/gpu_driver_bug_workaround_type.h"
#include "gpu/config/gpu_finch_features.h"
#include "gpu/config/gpu_preferences.h"
#include "gpu/config/gpu_switches.h"
#include "gpu/config/gpu_util.h"
#include "third_party/dawn/include/dawn/webgpu_cpp_print.h"
#include "third_party/skia/include/gpu/graphite/Context.h"
#include "third_party/skia/include/gpu/graphite/dawn/DawnBackendContext.h"
#include "third_party/skia/include/gpu/graphite/dawn/DawnUtils.h"
#include "ui/gl/gl_implementation.h"
#include "ui/gl/gl_switches.h"

#if BUILDFLAG(IS_WIN)
#include <d3d11_4.h>

#include "third_party/dawn/include/dawn/native/D3D11Backend.h"
#include "ui/gl/direct_composition_support.h"
#include "ui/gl/gl_angle_util_win.h"
#endif

#if BUILDFLAG(IS_ANDROID)
#include "base/android/build_info.h"
#endif

namespace gpu {
namespace {

// Used as a flag to test dawn initialization failure.
BASE_FEATURE(kForceDawnInitializeFailure,
             "ForceDawnInitializeFailure",
             base::FEATURE_DISABLED_BY_DEFAULT);

// Sets crash key in thread safe manner. This should be used for any crash keys
// set from dawn error or device lost callbacks that may run on multiple
// threads.
template <uint32_t KeySize>
void SetCrashKeyThreadSafe(crash_reporter::CrashKeyString<KeySize>& crash_key,
                           std::string_view message) {
  static base::NoDestructor<base::Lock> lock;
  base::AutoLock auto_lock(*lock.get());
  crash_key.Set(message);
}

void SetDawnErrorCrashKey(std::string_view message) {
  static crash_reporter::CrashKeyString<1024> error_key("dawn-error");
  SetCrashKeyThreadSafe(error_key, message);
}

// Different versions of DumpWithoutCrashing for different reasons.
// Deliberately prevent inlining so that the crash report's call stack can
// distinguish between them.
#if BUILDFLAG(IS_WIN)
NOINLINE NOOPT void DumpWithoutCrashingOnDXGIError(wgpu::ErrorType error_type,
                                                   std::string_view message) {
  LOG(ERROR) << "DXGI Error: " << message;

  if (features::kSkiaGraphiteDawnDumpWCOnD3DError.Get()) {
    base::debug::DumpWithoutCrashing();
  }
}

NOINLINE NOOPT void DumpWithoutCrashingOnD3D11DebugLayerError(
    wgpu::ErrorType error_type,
    std::string_view message) {
  LOG(ERROR) << message;
  if (features::kSkiaGraphiteDawnDumpWCOnD3DError.Get()) {
    base::debug::DumpWithoutCrashing();
  }
}
#endif

NOINLINE NOOPT void DumpWithoutCrashingOnGenericError(
    wgpu::ErrorType error_type,
    std::string_view message) {
  LOG(ERROR) << message;
  base::debug::DumpWithoutCrashing();
}

void DumpWithoutCrashingOnError(wgpu::ErrorType error_type,
                                std::string_view message) {
  SetDawnErrorCrashKey(message);
#if BUILDFLAG(IS_WIN)
  if (message.find("DXGI_ERROR") != std::string_view::npos) {
    DumpWithoutCrashingOnDXGIError(error_type, message);
  } else if (message.find("The D3D11 debug layer") != std::string_view::npos) {
    DumpWithoutCrashingOnD3D11DebugLayerError(error_type, message);
  } else
#endif
  {
    DumpWithoutCrashingOnGenericError(error_type, message);
  }
}

// NOTE: Update the toggles in GpuInfoCollector whenever a toggle is disabled
// here.
std::vector<const char*> GetDisabledToggles(
    const GpuPreferences& gpu_preferences) {
  std::vector<const char*> disabled_toggles;
  for (const auto& toggle : gpu_preferences.disabled_dawn_features_list) {
    disabled_toggles.push_back(toggle.c_str());
  }
  return disabled_toggles;
}

// NOTE: Update the toggles in GpuInfoCollector whenever a toggle is enabled
// here.
std::vector<const char*> GetEnabledToggles(
    wgpu::BackendType backend_type,
    bool force_fallback_adapter,
    const GpuPreferences& gpu_preferences) {
  // If a new toggle is added here, ForceDawnTogglesForSkia() which collects
  // info for about:gpu should be updated as well.
  std::vector<const char*> enabled_toggles;
  for (const auto& toggle : gpu_preferences.enabled_dawn_features_list) {
    enabled_toggles.push_back(toggle.c_str());
  }

  // The following toggles are all device-scoped toggles so it's not necessary
  // to pass them when creating the Instance above.
  if (features::kSkiaGraphiteDawnBackendDebugLabels.Get()) {
    enabled_toggles.push_back("use_user_defined_labels_in_backend");
  }

  if (features::kSkiaGraphiteDawnSkipValidation.Get()) {
    enabled_toggles.push_back("skip_validation");
  }

  enabled_toggles.push_back("disable_robustness");
  enabled_toggles.push_back("disable_lazy_clear_for_mapped_at_creation_buffer");

#if BUILDFLAG(IS_WIN)
  if (backend_type == wgpu::BackendType::D3D11) {
    // Use packed D24_UNORM_S8_UINT DXGI format for Depth24PlusStencil8
    // format.
    enabled_toggles.push_back("use_packed_depth24_unorm_stencil8_format");

    if (features::kSkiaGraphiteDawnD3D11DelayFlush.Get()) {
      // Tell Dawn to defer sending commands to GPU until swapchain's Present.
      // This will batch the commands better.
      enabled_toggles.push_back("d3d11_delay_flush_to_gpu");
    }
  }
#endif

  if (backend_type == wgpu::BackendType::Vulkan) {
#if BUILDFLAG(IS_ANDROID)
    // Enable this toggle for all Android devices suspecting vulkan image size
    // mismatch causing SharedTextureMemory creation failures, leading to
    // promise image creation failures. See https://crbug.com/377935752 for
    // details.
    enabled_toggles.push_back(
        "ignore_imported_ahardwarebuffer_vulkan_image_size");
#endif

    // Use a single VkPipelineCache inside dawn.
    enabled_toggles.push_back("vulkan_monolithic_pipeline_cache");
  }

  // Skip expensive swiftshader vkCmdDraw* for tests.
  // TODO(penghuang): rename kDisableGLDrawingForTests to
  // kDisableGpuDrawingForTests
  // TODO(crbug.com/407497928): Enable this toggle over GpuInfoCollector.
  auto* command_line = base::CommandLine::ForCurrentProcess();
  if (backend_type == wgpu::BackendType::Vulkan && force_fallback_adapter &&
      command_line->HasSwitch(switches::kDisableGLDrawingForTests)) {
    enabled_toggles.push_back("vulkan_skip_draw");
  }

  return enabled_toggles;
}

std::vector<wgpu::FeatureName> GetRequiredFeatures(
    wgpu::BackendType backend_type,
    wgpu::Adapter adapter) {
  std::vector<wgpu::FeatureName> features = {
      wgpu::FeatureName::DawnInternalUsages,
      wgpu::FeatureName::ImplicitDeviceSynchronization,
#if BUILDFLAG(IS_ANDROID)
      wgpu::FeatureName::TextureCompressionETC2,
#endif
  };

  if (backend_type == wgpu::BackendType::Vulkan) {
#if BUILDFLAG(IS_ANDROID)
    features.push_back(wgpu::FeatureName::StaticSamplers);
    features.push_back(wgpu::FeatureName::YCbCrVulkanSamplers);
#endif
    features.push_back(wgpu::FeatureName::DawnDeviceAllocatorControl);
  }

#if BUILDFLAG(IS_WIN)
  if (backend_type == wgpu::BackendType::D3D11) {
    features.push_back(wgpu::FeatureName::D3D11MultithreadProtected);
  }
#endif

  constexpr wgpu::FeatureName kOptionalFeatures[] = {
      wgpu::FeatureName::BGRA8UnormStorage,
      wgpu::FeatureName::BufferMapExtendedUsages,
      wgpu::FeatureName::DawnMultiPlanarFormats,
      wgpu::FeatureName::DualSourceBlending,
      wgpu::FeatureName::FramebufferFetch,
      wgpu::FeatureName::MultiPlanarFormatExtendedUsages,
      wgpu::FeatureName::MultiPlanarFormatNv16,
      wgpu::FeatureName::MultiPlanarFormatNv24,
      wgpu::FeatureName::MultiPlanarFormatP010,
      wgpu::FeatureName::MultiPlanarFormatP210,
      wgpu::FeatureName::MultiPlanarFormatP410,
      wgpu::FeatureName::MultiPlanarFormatNv12a,
      wgpu::FeatureName::MultiPlanarRenderTargets,
      wgpu::FeatureName::Unorm16TextureFormats,

      // The following features are always supported by the the Metal backend on
      // the Mac versions on which Chrome runs.
      wgpu::FeatureName::SharedTextureMemoryIOSurface,
      wgpu::FeatureName::SharedFenceMTLSharedEvent,

      // The following features are always supported when running on the Vulkan
      // backend on Android.
      wgpu::FeatureName::SharedTextureMemoryAHardwareBuffer,
      wgpu::FeatureName::SharedFenceSyncFD,

      // The following features are always supported by the the D3D backends.
      wgpu::FeatureName::SharedTextureMemoryD3D11Texture2D,
      wgpu::FeatureName::SharedTextureMemoryDXGISharedHandle,
      wgpu::FeatureName::SharedFenceDXGISharedHandle,

      wgpu::FeatureName::TransientAttachments,

      wgpu::FeatureName::DawnLoadResolveTexture,
      wgpu::FeatureName::DawnPartialLoadResolveTexture,
      wgpu::FeatureName::DawnTexelCopyBufferRowAlignment,
      wgpu::FeatureName::FlexibleTextureViews,
  };

  for (auto feature : kOptionalFeatures) {
    if (!adapter.HasFeature(feature)) {
      continue;
    }
    features.push_back(feature);

    // Enabling MSAARenderToSingleSampled causes performance regression without
    // TransientAttachments support.
    if (feature == wgpu::FeatureName::TransientAttachments &&
        adapter.HasFeature(wgpu::FeatureName::MSAARenderToSingleSampled)) {
      features.push_back(wgpu::FeatureName::MSAARenderToSingleSampled);
    }
  }

  return features;
}

class Platform : public webgpu::DawnPlatform {
 public:
  using webgpu::DawnPlatform::DawnPlatform;

  ~Platform() override = default;

  const unsigned char* GetTraceCategoryEnabledFlag(
      dawn::platform::TraceCategory category) override {
    return TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(
        TRACE_DISABLED_BY_DEFAULT("gpu.graphite.dawn"));
  }
};

#if BUILDFLAG(IS_WIN)
bool GetANGLED3D11DeviceLUID(LUID* luid) {
  // On Windows, query the LUID of ANGLE's adapter.
  Microsoft::WRL::ComPtr<ID3D11Device> d3d11_device =
      gl::QueryD3D11DeviceObjectFromANGLE();
  if (!d3d11_device) {
    LOG(ERROR) << "Failed to query ID3D11Device from ANGLE.";
    return false;
  }

  Microsoft::WRL::ComPtr<IDXGIDevice> dxgi_device;
  if (!SUCCEEDED(d3d11_device.As(&dxgi_device))) {
    LOG(ERROR) << "Failed to get IDXGIDevice from ANGLE.";
    return false;
  }

  Microsoft::WRL::ComPtr<IDXGIAdapter> dxgi_adapter;
  if (!SUCCEEDED(dxgi_device->GetAdapter(&dxgi_adapter))) {
    LOG(ERROR) << "Failed to get IDXGIAdapter from ANGLE.";
    return false;
  }

  DXGI_ADAPTER_DESC adapter_desc;
  if (!SUCCEEDED(dxgi_adapter->GetDesc(&adapter_desc))) {
    LOG(ERROR) << "Failed to get DXGI_ADAPTER_DESC from ANGLE.";
    return false;
  }

  *luid = adapter_desc.AdapterLuid;
  return true;
}

bool IsD3D11DebugLayerEnabled(
    const Microsoft::WRL::ComPtr<ID3D11Device>& d3d11_device) {
  Microsoft::WRL::ComPtr<ID3D11Debug> d3d11_debug;
  return SUCCEEDED(d3d11_device.As(&d3d11_debug));
}

const char* HRESULTToString(HRESULT result) {
  switch (result) {
#define ERROR_CASE(E) \
  case E:             \
    return #E;
    ERROR_CASE(DXGI_ERROR_DEVICE_HUNG)
    ERROR_CASE(DXGI_ERROR_DEVICE_REMOVED)
    ERROR_CASE(DXGI_ERROR_DEVICE_RESET)
    ERROR_CASE(DXGI_ERROR_DRIVER_INTERNAL_ERROR)
    ERROR_CASE(DXGI_ERROR_INVALID_CALL)
    ERROR_CASE(S_OK)
#undef ERROR_CASE
    default:
      return nullptr;
  }
}
#endif  // BUILDFLAG(IS_WIN)

const char* BackendTypeToString(wgpu::BackendType backend_type) {
  switch (backend_type) {
    case wgpu::BackendType::D3D11:
      return "D3D11";
    case wgpu::BackendType::D3D12:
      return "D3D12";
    case wgpu::BackendType::Metal:
      return "Metal";
    case wgpu::BackendType::Vulkan:
      return "Vulkan";
    case wgpu::BackendType::OpenGL:
      return "OpenGL";
    case wgpu::BackendType::OpenGLES:
      return "OpenGLES";
    default:
      CHECK(false);
  }
}

}  // namespace

// static
wgpu::BackendType DawnContextProvider::GetDefaultBackendType() {
  const auto switch_value =
      base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
          switches::kSkiaGraphiteBackend);
  if (switch_value == switches::kSkiaGraphiteBackendDawnD3D11) {
    return wgpu::BackendType::D3D11;
  } else if (switch_value == switches::kSkiaGraphiteBackendDawnD3D12) {
    return wgpu::BackendType::D3D12;
  } else if (switch_value == switches::kSkiaGraphiteBackendDawnMetal) {
    return wgpu::BackendType::Metal;
  } else if (switch_value == switches::kSkiaGraphiteBackendDawnSwiftshader ||
             switch_value == switches::kSkiaGraphiteBackendDawnVulkan) {
    return wgpu::BackendType::Vulkan;
  }

  if (gl::GetANGLEImplementation() == gl::ANGLEImplementation::kSwiftShader) {
    return wgpu::BackendType::Vulkan;
  }
#if BUILDFLAG(IS_WIN)
  return base::FeatureList::IsEnabled(features::kSkiaGraphiteDawnUseD3D12)
             ? wgpu::BackendType::D3D12
             : wgpu::BackendType::D3D11;
#elif BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
  return wgpu::BackendType::Vulkan;
#elif BUILDFLAG(IS_APPLE)
  return wgpu::BackendType::Metal;
#else
  NOTREACHED();
#endif
}

// static
bool DawnContextProvider::DefaultForceFallbackAdapter() {
  return base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
             switches::kSkiaGraphiteBackend) ==
             switches::kSkiaGraphiteBackendDawnSwiftshader ||
         gl::GetANGLEImplementation() == gl::ANGLEImplementation::kSwiftShader;
}

// static
bool DawnContextProvider::DefaultValidateAdapterFn(wgpu::BackendType,
                                                   wgpu::Adapter) {
  return true;
}

// Owns the dawn instance/adapter/device so that it's lifetime is not linked to
// a specific DawnContextProvider.
class DawnSharedContext : public base::RefCountedThreadSafe<DawnSharedContext>,
                          public base::trace_event::MemoryDumpProvider {
 public:
  explicit DawnSharedContext(bool thread_safe_graphite_context);

  bool Initialize(wgpu::BackendType backend_type,
                  bool force_fallback_adapter,
                  const GpuPreferences& gpu_preferences,
                  const GpuDriverBugWorkarounds& workarounds,
                  DawnContextProvider::ValidateAdapterFn validate_adapter_fn);
  void SetCachingInterface(
      std::unique_ptr<webgpu::DawnCachingInterface> caching_interface);

  wgpu::Device GetDevice() const { return device_; }
  wgpu::BackendType backend_type() const { return backend_type_; }
  bool is_vulkan_swiftshader_adapter() const {
    return is_vulkan_swiftshader_adapter_;
  }
  wgpu::Adapter GetAdapter() const { return adapter_; }
  wgpu::Instance GetInstance() const { return instance_->Get(); }

#if BUILDFLAG(IS_WIN)
  Microsoft::WRL::ComPtr<ID3D11Device> GetD3D11Device() const {
    if (backend_type() == wgpu::BackendType::D3D11) {
      return dawn::native::d3d11::GetD3D11Device(device_.Get());
    }
    return nullptr;
  }

  void FlushD3D11CommandsIfDelayed() const {
    if (backend_type() != wgpu::BackendType::D3D11) {
      return;
    }

    // This function is meant for delayed flush option.
    if (!features::kSkiaGraphiteDawnD3D11DelayFlush.Get()) {
      return;
    }

    TRACE_EVENT0("gpu", "DawnSharedContext::FlushD3D11Commands");

    Microsoft::WRL::ComPtr<ID3D11Device> d3d11_device =
        dawn::native::d3d11::GetD3D11Device(device_.Get());
    if (!d3d11_device) {
      return;
    }

    Microsoft::WRL::ComPtr<ID3D11DeviceContext> context;
    d3d11_device->GetImmediateContext(&context);
    context->Flush();
  }
#endif

  std::optional<error::ContextLostReason> GetResetStatus() const;

  std::unique_ptr<GraphiteSharedContext> CreateGraphiteSharedContext(
      const skgpu::graphite::ContextOptions& options,
      GpuProcessShmCount* use_shader_cache_shm_count,
      bool is_thread_safe) {
    if (!device_) {
      return nullptr;
    }

    skgpu::graphite::DawnBackendContext backend_context;
    backend_context.fInstance = GetInstance();
    backend_context.fDevice = device_;
    backend_context.fQueue = device_.GetQueue();

    std::unique_ptr<skgpu::graphite::Context> graphite_context =
        skgpu::graphite::ContextFactory::MakeDawn(backend_context, options);
    if (!graphite_context) {
      return nullptr;
    }

    return std::make_unique<GraphiteSharedContext>(
        std::move(graphite_context), use_shader_cache_shm_count, is_thread_safe,
        GetBackendFlushCallback());
  }

  bool use_thread_safe_graphite_context() const {
    return use_thread_safe_graphite_context_;
  }

  GraphiteSharedContext* GetThreadSafeGraphiteSharedContext() const {
    CHECK(use_thread_safe_graphite_context());
    return thread_safe_graphite_shared_context_.get();
  }

  bool InitializeThreadSafeGraphiteContext(
      const skgpu::graphite::ContextOptions& options,
      GpuProcessShmCount* use_shader_cache_shm_count) {
    DCHECK_CALLED_ON_VALID_THREAD(main_thread_checker_);
    CHECK(use_thread_safe_graphite_context());
    CHECK(!thread_safe_graphite_shared_context_);
    thread_safe_graphite_shared_context_ = CreateGraphiteSharedContext(
        options, use_shader_cache_shm_count, /*is_thread_safe=*/true);
    return !!thread_safe_graphite_shared_context_;
  }

 private:
  friend class base::RefCountedThreadSafe<DawnSharedContext>;

  // Provided to wgpu::Device as caching callback.
  static size_t LoadCachedData(const void* key,
                               size_t key_size,
                               void* value,
                               size_t value_size,
                               void* userdata) {
    if (auto& caching_interface =
            static_cast<DawnSharedContext*>(userdata)->caching_interface_) {
      return caching_interface->LoadData(key, key_size, value, value_size);
    }
    return 0;
  }

  // Provided to wgpu::Device as caching callback.
  static void StoreCachedData(const void* key,
                              size_t key_size,
                              const void* value,
                              size_t value_size,
                              void* userdata) {
    if (auto& caching_interface =
            static_cast<DawnSharedContext*>(userdata)->caching_interface_) {
      caching_interface->StoreData(key, key_size, value, value_size);
    }
  }

  // Provided to wgpu::Device as logging callback.
  static void LogInfo(wgpu::LoggingType type,
                      wgpu::StringView message,
                      DawnSharedContext* shared_context) {
    std::string_view view = {message.data, message.length};
    switch (static_cast<wgpu::LoggingType>(type)) {
      case wgpu::LoggingType::Warning:
        LOG(WARNING) << view;
        if (shared_context && !shared_context->device_) {
          // If device hasn't been created yet. This warning message must be
          // from dawn::native::Instance when we try to enumerate adapters or
          // when trying to create the device. In that case, saving the message
          // so that if there is any init failure afterward, we can include the
          // warnings in the LogInitFailure()'s report.
          shared_context->init_warning_msgs_.append(view);
          shared_context->init_warning_msgs_.append("\n");
        }
        break;
      case wgpu::LoggingType::Error:
        LOG(ERROR) << view;
        SetDawnErrorCrashKey(view);
        base::debug::DumpWithoutCrashing();
        break;
      default:
        break;
    }
  }

  ~DawnSharedContext() override;

  GraphiteSharedContext::FlushCallback GetBackendFlushCallback() {
#if BUILDFLAG(IS_WIN)
    return base::BindRepeating(&DawnSharedContext::FlushD3D11CommandsIfDelayed,
                               base::RetainedRef(this));
#else
    return {};
#endif
  }

  void OnError(wgpu::ErrorType error_type, wgpu::StringView message);

  void LogInitFailure(std::string_view reason,
                      bool generate_crash_report,
                      wgpu::BackendType backend_type,
                      bool force_fallback_adapter) {
    LOG(ERROR) << reason;

    if (!generate_crash_report) {
      return;
    }

    SCOPED_CRASH_KEY_STRING256("dawn-shared-context", "init-failure", reason);
    SCOPED_CRASH_KEY_STRING32("dawn-shared-context", "backend-type",
                              BackendTypeToString(backend_type));
    SCOPED_CRASH_KEY_BOOL("dawn-shared-context", "fallback-adapter",
                          force_fallback_adapter);
    // Also include any warning messages collected during the initialization.
    SCOPED_CRASH_KEY_STRING1024("dawn-shared-context", "init-warning-msgs",
                                init_warning_msgs_);
    init_warning_msgs_.clear();
    base::debug::DumpWithoutCrashing();
  }

  // base::trace_event::MemoryDumpProvider implementation:
  bool OnMemoryDump(const base::trace_event::MemoryDumpArgs& args,
                    base::trace_event::ProcessMemoryDump* pmd) override;

  std::unique_ptr<webgpu::DawnCachingInterface> caching_interface_;

  Platform platform_{/*dawn_caching_interface=*/nullptr,
                     /*uma_prefix=*/"GPU.GraphiteDawn.",
                     /*record_cache_count_uma=*/true};
  std::unique_ptr<webgpu::DawnInstance> instance_;
  wgpu::Adapter adapter_;
  wgpu::Device device_;
  wgpu::BackendType backend_type_;
  std::string init_warning_msgs_;
  bool is_vulkan_swiftshader_adapter_ = false;
  bool registered_memory_dump_provider_ = false;

  // If true, both GpuMain and CompositorGpuThread share the same
  // GraphiteSharedContext which is created lazily. If false,
  // DawnContextProvider owns GraphiteSharedContext and each DawnContextProvider
  // (i.e. each thread) has its own GraphiteSharedContext.
  const bool use_thread_safe_graphite_context_;
  std::unique_ptr<GraphiteSharedContext> thread_safe_graphite_shared_context_;

  mutable base::Lock context_lost_lock_;
  std::optional<error::ContextLostReason> context_lost_reason_
      GUARDED_BY(context_lost_lock_);

  THREAD_CHECKER(main_thread_checker_);
};

DawnSharedContext::DawnSharedContext(bool use_thread_safe_graphite_context)
    : use_thread_safe_graphite_context_(use_thread_safe_graphite_context) {
  DCHECK_CALLED_ON_VALID_THREAD(main_thread_checker_);
}

DawnSharedContext::~DawnSharedContext() {
  DCHECK_CALLED_ON_VALID_THREAD(main_thread_checker_);
  if (device_) {
    if (registered_memory_dump_provider_) {
      base::trace_event::MemoryDumpManager::GetInstance()
          ->UnregisterDumpProvider(this);
    }
    device_.SetLoggingCallback([](wgpu::LoggingType, wgpu::StringView) {});

    // Destroy GraphiteSharedContext and skgpu::graphite::Context before
    // device_, on which skgpu::graphite::Context is created.
    thread_safe_graphite_shared_context_ = nullptr;

    // Destroy the device now so that the lost callback, which references this
    // class, is fired now before we clean up the rest of this class.
    device_.Destroy();
  }
  if (instance_) {
    instance_->DisconnectDawnPlatform();
  }
}

namespace {
// Dawn Graphite adapter feature level for metrics.
//
// See also: webgpu.h:WGPUFeatureLevel
//
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
//
// LINT.IfChange(DawnAdapterFeatureLevel)
enum class DawnAdapterFeatureLevel {
  kUnknown = 0,
  kCompatibility = 1,
  kCore = 2,
  kMaxValue = kCore,
};
// LINT.ThenChange(//tools/metrics/histograms/metadata/gpu/enums.xml:DawnAdapterFeatureLevel)

DawnAdapterFeatureLevel DawnAdapterFeatureLevelFromWGPU(
    wgpu::FeatureLevel level) {
  switch (level) {
    case wgpu::FeatureLevel::Compatibility:
      return DawnAdapterFeatureLevel::kCompatibility;
    case wgpu::FeatureLevel::Core:
      return DawnAdapterFeatureLevel::kCore;
    default:
      return DawnAdapterFeatureLevel::kUnknown;
  }
}
}  // namespace

bool DawnSharedContext::Initialize(
    wgpu::BackendType backend_type,
    bool force_fallback_adapter,
    const GpuPreferences& gpu_preferences,
    const GpuDriverBugWorkarounds& workarounds,
    DawnContextProvider::ValidateAdapterFn validate_adapter_fn) {
  // Make Dawn experimental API and WGSL features available since access to this
  // instance doesn't exit the GPU process.
  // LogInfo will be used to receive instance level errors. For example failures
  // of loading libraries, initializing backend, etc
  dawn::native::DawnInstanceDescriptor dawn_instance_desc;
  dawn_instance_desc.SetLoggingCallback(&DawnSharedContext::LogInfo, this);
  instance_ = webgpu::DawnInstance::Create(&platform_, gpu_preferences,
                                           webgpu::SafetyLevel::kUnsafe,
                                           &dawn_instance_desc);

  std::vector<const char*> enabled_toggles =
      GetEnabledToggles(backend_type, force_fallback_adapter, gpu_preferences);
  std::vector<const char*> disabled_toggles =
      GetDisabledToggles(gpu_preferences);

  wgpu::DawnTogglesDescriptor toggles_desc;
  toggles_desc.enabledToggles = enabled_toggles.data();
  toggles_desc.disabledToggles = disabled_toggles.data();
  toggles_desc.enabledToggleCount = enabled_toggles.size();
  toggles_desc.disabledToggleCount = disabled_toggles.size();

  wgpu::RequestAdapterOptions adapter_options;
  adapter_options.backendType = backend_type;
  adapter_options.forceFallbackAdapter = force_fallback_adapter;
  if (workarounds.force_high_performance_gpu) {
    adapter_options.powerPreference = wgpu::PowerPreference::HighPerformance;
  } else {
    adapter_options.powerPreference = wgpu::PowerPreference::LowPower;
  }
  adapter_options.nextInChain = &toggles_desc;

#if BUILDFLAG(IS_WIN)
  dawn::native::d3d::RequestAdapterOptionsLUID adapter_options_luid;
  if ((adapter_options.backendType == wgpu::BackendType::D3D11 ||
       adapter_options.backendType == wgpu::BackendType::D3D12) &&
      GetANGLED3D11DeviceLUID(&adapter_options_luid.adapterLUID)) {
    // Request the GPU that ANGLE is using if possible.
    adapter_options_luid.nextInChain = adapter_options.nextInChain;
    adapter_options.nextInChain = &adapter_options_luid;
  }

  // Share D3D11 device with ANGLE to reduce synchronization overhead.
  dawn::native::d3d11::RequestAdapterOptionsD3D11Device
      adapter_options_d3d11_device;
  if (adapter_options.backendType == wgpu::BackendType::D3D11) {
    Microsoft::WRL::ComPtr<ID3D11Device> d3d11_device =
        gl::QueryD3D11DeviceObjectFromANGLE();
    CHECK(d3d11_device) << "Query d3d11 device from ANGLE failed.";

    static crash_reporter::CrashKeyString<16> feature_level_key(
        "d3d11-feature-level");
    std::string feature_level =
        D3DFeatureLevelToString(d3d11_device->GetFeatureLevel());
    feature_level_key.Set(feature_level.c_str());

    Microsoft::WRL::ComPtr<ID3D11DeviceContext> d3d11_device_context;
    d3d11_device->GetImmediateContext(&d3d11_device_context);

    Microsoft::WRL::ComPtr<ID3D11Multithread> d3d11_multithread;
    HRESULT hr = d3d11_device_context.As(&d3d11_multithread);
    CHECK(SUCCEEDED(hr)) << "Query ID3D11Multithread interface failed: 0x"
                         << std::hex << hr;

    // Dawn requires enable multithread protection for d3d11 device.
    d3d11_multithread->SetMultithreadProtected(TRUE);
    adapter_options_d3d11_device.device = std::move(d3d11_device);
    adapter_options_d3d11_device.nextInChain = adapter_options.nextInChain;
    adapter_options.nextInChain = &adapter_options_d3d11_device;
  }
#endif  // BUILDFLAG(IS_WIN)

  adapter_options.featureLevel = wgpu::FeatureLevel::Core;
  std::vector<dawn::native::Adapter> adapters =
      instance_->EnumerateAdapters(&adapter_options);

  if (adapters.empty()) {
    LOG(ERROR) << "No adapters found for non compatibility mode.";
    adapter_options.featureLevel = wgpu::FeatureLevel::Compatibility;
    adapters = instance_->EnumerateAdapters(&adapter_options);
  }

  if (adapters.empty()) {
    // On Android, it's expected that some devices might not support Dawn atm.
    // So don't generate report for it.
    LogInitFailure("No adapters found.",
                   /*generate_crash_report=*/!BUILDFLAG(IS_ANDROID),
                   backend_type, force_fallback_adapter);
    return false;
  }
  adapter_ = wgpu::Adapter(adapters[0].Get());

  if (!validate_adapter_fn(backend_type, adapter_)) {
    LogInitFailure("Validate adapter failed.",
                   /*generate_crash_report=*/!BUILDFLAG(IS_ANDROID),
                   backend_type, force_fallback_adapter);
    return false;
  }

  // Start initializing dawn device here.
  wgpu::DawnCacheDeviceDescriptor cache_desc;
  cache_desc.loadDataFunction = &DawnSharedContext::LoadCachedData;
  cache_desc.storeDataFunction = &DawnSharedContext::StoreCachedData;
  // The dawn device is owned by this so a pointer back here is safe.
  cache_desc.functionUserdata = this;
  cache_desc.nextInChain = &toggles_desc;

  wgpu::DawnDeviceAllocatorControl allocator_desc;
  wgpu::DeviceDescriptor descriptor;
  if (backend_type == wgpu::BackendType::Vulkan) {
    // Use a 256kb heap block size in the Vulkan backend to minimize
    // fragmentation.
    allocator_desc.allocatorHeapBlockSize = 256 * 1024;
    allocator_desc.nextInChain = &cache_desc;
    descriptor.nextInChain = &allocator_desc;
  } else {
    descriptor.nextInChain = &cache_desc;
  }

  descriptor.SetUncapturedErrorCallback(
      [](const wgpu::Device&, wgpu::ErrorType type, wgpu::StringView message,
         DawnSharedContext* state) {
        if (type != wgpu::ErrorType::NoError) {
          state->OnError(type, message);
        }
      },
      this);
  descriptor.SetDeviceLostCallback(
      wgpu::CallbackMode::AllowSpontaneous,
      [](const wgpu::Device&, wgpu::DeviceLostReason reason,
         wgpu::StringView message, DawnSharedContext* state) {
        if (reason != wgpu::DeviceLostReason::Destroyed) {
          state->OnError(wgpu::ErrorType::Unknown, message);
        }
      },
      this);

  std::vector<wgpu::FeatureName> features =
      GetRequiredFeatures(backend_type, adapter_);
  descriptor.requiredFeatures = features.data();
  descriptor.requiredFeatureCount = std::size(features);

  // Use best limits for the device.
  wgpu::Limits supportedLimits = {};
  if (adapter_.GetLimits(&supportedLimits) != wgpu::Status::Success) {
    LogInitFailure("Failed to call adapter.GetLimits().",
                   /*generate_crash_report=*/true, backend_type,
                   force_fallback_adapter);
    return false;
  }
  descriptor.requiredLimits = &supportedLimits;

  // ANGLE always tries creating D3D11 device with debug layer when dcheck is
  // on, so tries creating dawn device with backend validation as well.
  constexpr bool enable_backend_validation =
      DCHECK_IS_ON() && BUILDFLAG(IS_WIN);

  std::vector<dawn::native::BackendValidationLevel> backend_validation_levels =
      {dawn::native::BackendValidationLevel::Disabled};
  if (features::kSkiaGraphiteDawnBackendValidation.Get() ||
      enable_backend_validation) {
    backend_validation_levels.push_back(
        dawn::native::BackendValidationLevel::Partial);
    backend_validation_levels.push_back(
        dawn::native::BackendValidationLevel::Full);
  }

  if (base::FeatureList::IsEnabled(kForceDawnInitializeFailure)) {
    LOG(ERROR) << "DawnSharedContext creation failed for testing";
    return false;
  }

  // Try create device with backend validation level.
  for (auto it = backend_validation_levels.rbegin();
       it != backend_validation_levels.rend(); ++it) {
    auto level = *it;
    instance_->SetBackendValidationLevel(level);
    device_ = adapter_.CreateDevice(&descriptor);
    if (device_) {
      break;
    }
  }

  if (!device_) {
    LogInitFailure("Failed to create device.", /*generate_crash_report=*/true,
                   backend_type, force_fallback_adapter);
    return false;
  }

  device_.SetLoggingCallback(&DawnSharedContext::LogInfo, this);

  backend_type_ = backend_type;
  is_vulkan_swiftshader_adapter_ =
      backend_type == wgpu::BackendType::Vulkan && force_fallback_adapter;

#if BUILDFLAG(IS_WIN)
  if (auto d3d11_device = GetD3D11Device()) {
    static auto* crash_key = base::debug::AllocateCrashKeyString(
        "d3d11-debug-layer", base::debug::CrashKeySize::Size32);
    const bool enabled = IsD3D11DebugLayerEnabled(d3d11_device);
    base::debug::SetCrashKeyString(crash_key, enabled ? "enabled" : "disabled");
  }
#endif  // BUILDFLAG(IS_WIN)

  if (base::SingleThreadTaskRunner::HasCurrentDefault()) {
    base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
        this, "DawnSharedContext",
        base::SingleThreadTaskRunner::GetCurrentDefault());
    registered_memory_dump_provider_ = true;
  }

  base::UmaHistogramEnumeration(
      "GPU.Dawn.AdapterFeatureLevel",
      DawnAdapterFeatureLevelFromWGPU(adapter_options.featureLevel));
  return true;
}

void DawnSharedContext::SetCachingInterface(
    std::unique_ptr<webgpu::DawnCachingInterface> caching_interface) {
  CHECK(!caching_interface_);
  caching_interface_ = std::move(caching_interface);
}

std::optional<error::ContextLostReason> DawnSharedContext::GetResetStatus()
    const {
  base::AutoLock auto_lock(context_lost_lock_);
  return context_lost_reason_;
}

void DawnSharedContext::OnError(wgpu::ErrorType error_type,
                                wgpu::StringView message) {
#if BUILDFLAG(IS_WIN)
  if (auto d3d11_device = GetD3D11Device()) {
    static crash_reporter::CrashKeyString<64> reason_message_key(
        "d3d11-device-removed-reason");
    HRESULT result = d3d11_device->GetDeviceRemovedReason();

    if (const char* result_string = HRESULTToString(result)) {
      LOG(ERROR) << "Device removed reason: " << result_string;
      SetCrashKeyThreadSafe(reason_message_key, result_string);
    } else {
      auto unknown_error = base::StringPrintf("Unknown error(0x%08lX)", result);
      LOG(ERROR) << "Device removed reason: " << unknown_error;
      SetCrashKeyThreadSafe(reason_message_key, unknown_error.c_str());
    }
  }
#endif

  DumpWithoutCrashingOnError(error_type,
                             static_cast<std::string_view>(message));

#if !DCHECK_IS_ON()
  // Do not provoke context loss on validation failures for non-DCHECK builds.
  // We want to capture the above dump on validation errors, but not necessarily
  // restart the GPU process unless we also have a device loss.
  if (error_type == wgpu::ErrorType::Validation) {
    return;
  }
#endif

  base::AutoLock auto_lock(context_lost_lock_);
  if (context_lost_reason_.has_value()) {
    return;
  }

  switch (error_type) {
    case wgpu::ErrorType::OutOfMemory:
      context_lost_reason_ = error::kOutOfMemory;
      break;
    case wgpu::ErrorType::Validation:
      context_lost_reason_ = error::kGuilty;
      break;
    default:
      context_lost_reason_ = error::kUnknown;
      break;
  }
}

namespace {
static constexpr char kDawnMemoryDumpPrefix[] = "gpu/dawn";

static constexpr char kAllocatorMemoryDumpPrefix[] =
    "gpu/vulkan/graphite_allocator";

class DawnMemoryDump : public dawn::native::MemoryDump {
 public:
  explicit DawnMemoryDump(base::trace_event::ProcessMemoryDump* pmd)
      : pmd_(pmd) {
    CHECK(pmd_);
  }

  ~DawnMemoryDump() override = default;

  void AddScalar(const char* name,
                 const char* key,
                 const char* units,
                 uint64_t value) override {
    pmd_->GetOrCreateAllocatorDump(
            base::JoinString({kDawnMemoryDumpPrefix, name}, "/"))
        ->AddScalar(key, units, value);
  }

  void AddString(const char* name,
                 const char* key,
                 const std::string& value) override {
    pmd_->GetOrCreateAllocatorDump(
            base::JoinString({kDawnMemoryDumpPrefix, name}, "/"))
        ->AddString(key, "", value);
  }

 private:
  const raw_ptr<base::trace_event::ProcessMemoryDump> pmd_;
};
}  // namespace

bool DawnSharedContext::OnMemoryDump(
    const base::trace_event::MemoryDumpArgs& args,
    base::trace_event::ProcessMemoryDump* pmd) {
  using base::trace_event::MemoryAllocatorDump;
  if (args.level_of_detail ==
      base::trace_event::MemoryDumpLevelOfDetail::kBackground) {
    const dawn::native::MemoryUsageInfo mem_usage =
        dawn::native::ComputeEstimatedMemoryUsageInfo(device_.Get());

    pmd->GetOrCreateAllocatorDump(kDawnMemoryDumpPrefix)
        ->AddScalar(MemoryAllocatorDump::kNameSize,
                    MemoryAllocatorDump::kUnitsBytes, mem_usage.totalUsage);
    pmd->GetOrCreateAllocatorDump(
           base::JoinString({kDawnMemoryDumpPrefix, "textures"}, "/"))
        ->AddScalar(MemoryAllocatorDump::kNameSize,
                    MemoryAllocatorDump::kUnitsBytes, mem_usage.texturesUsage);
    pmd
        ->GetOrCreateAllocatorDump(base::JoinString(
            {kDawnMemoryDumpPrefix, "textures/depth_stencil"}, "/"))
        ->AddScalar(MemoryAllocatorDump::kNameSize,
                    MemoryAllocatorDump::kUnitsBytes,
                    mem_usage.depthStencilTexturesUsage);
    auto* msaa_dump = pmd->GetOrCreateAllocatorDump(
        base::JoinString({kDawnMemoryDumpPrefix, "textures/msaa"}, "/"));
    msaa_dump->AddScalar(MemoryAllocatorDump::kNameSize,
                         MemoryAllocatorDump::kUnitsBytes,
                         mem_usage.msaaTexturesUsage);
    msaa_dump->AddScalar(MemoryAllocatorDump::kNameObjectCount,
                         MemoryAllocatorDump::kUnitsObjects,
                         mem_usage.msaaTexturesCount);
    msaa_dump->AddScalar("biggest_size", MemoryAllocatorDump::kUnitsBytes,
                         mem_usage.largestMsaaTextureUsage);
    pmd->GetOrCreateAllocatorDump(
           base::JoinString({kDawnMemoryDumpPrefix, "buffers"}, "/"))
        ->AddScalar(MemoryAllocatorDump::kNameSize,
                    MemoryAllocatorDump::kUnitsBytes, mem_usage.buffersUsage);
  } else {
    DawnMemoryDump dawnMemoryDump(pmd);
    dawn::native::DumpMemoryStatistics(device_.Get(), &dawnMemoryDump);
  }

  if (backend_type() == wgpu::BackendType::Vulkan) {
    // For Graphite-Vulkan backend, report vulkan allocator dumps and
    // statistics.
    auto* dump = pmd->GetOrCreateAllocatorDump(kAllocatorMemoryDumpPrefix);
    const dawn::native::AllocatorMemoryInfo allocator_usage =
        dawn::native::GetAllocatorMemoryInfo(device_.Get());
    // `allocated_size` is memory allocated from the device, used is what is
    // actually used.
    dump->AddScalar("allocated_size", MemoryAllocatorDump::kUnitsBytes,
                    allocator_usage.totalAllocatedMemory -
                        allocator_usage.totalLazyAllocatedMemory);
    dump->AddScalar(
        "used_size", MemoryAllocatorDump::kUnitsBytes,
        allocator_usage.totalUsedMemory - allocator_usage.totalLazyUsedMemory);
    dump->AddScalar(
        "fragmentation_size", MemoryAllocatorDump::kUnitsBytes,
        allocator_usage.totalAllocatedMemory - allocator_usage.totalUsedMemory);
    dump->AddScalar("lazy_allocated_size", MemoryAllocatorDump::kUnitsBytes,
                    allocator_usage.totalLazyAllocatedMemory);
    dump->AddScalar("lazy_used_size", MemoryAllocatorDump::kUnitsBytes,
                    allocator_usage.totalLazyUsedMemory);
  }

  return true;
}

std::unique_ptr<DawnContextProvider> DawnContextProvider::Create(
    const GpuPreferences& gpu_preferences,
    ValidateAdapterFn validate_adapter_fn,
    const GpuDriverBugWorkarounds& gpu_driver_workarounds) {
  return DawnContextProvider::CreateWithBackend(
      GetDefaultBackendType(), DefaultForceFallbackAdapter(), gpu_preferences,
      validate_adapter_fn, gpu_driver_workarounds);
}

std::unique_ptr<DawnContextProvider> DawnContextProvider::CreateWithBackend(
    wgpu::BackendType backend_type,
    bool force_fallback_adapter,
    const GpuPreferences& gpu_preferences,
    ValidateAdapterFn validate_adapter_fn,
    const GpuDriverBugWorkarounds& gpu_driver_workarounds) {
  auto dawn_shared_context = base::MakeRefCounted<DawnSharedContext>(
      features::IsGraphiteContextThreadSafe());
  if (!dawn_shared_context->Initialize(backend_type, force_fallback_adapter,
                                       gpu_preferences, gpu_driver_workarounds,
                                       validate_adapter_fn)) {
    return nullptr;
  }
  return base::WrapUnique(
      new DawnContextProvider(std::move(dawn_shared_context)));
}

std::unique_ptr<DawnContextProvider>
DawnContextProvider::CreateWithSharedDevice(
    const DawnContextProvider* existing) {
  CHECK(existing);
  CHECK(existing->dawn_shared_context_);
  return base::WrapUnique(
      new DawnContextProvider(existing->dawn_shared_context_));
}

DawnContextProvider::DawnContextProvider(
    scoped_refptr<DawnSharedContext> dawn_shared_context)
    : dawn_shared_context_(std::move(dawn_shared_context)) {
  CHECK(dawn_shared_context_);
}

DawnContextProvider::~DawnContextProvider() = default;

wgpu::Device DawnContextProvider::GetDevice() const {
  return dawn_shared_context_->GetDevice();
}

wgpu::BackendType DawnContextProvider::backend_type() const {
  return dawn_shared_context_->backend_type();
}

bool DawnContextProvider::is_vulkan_swiftshader_adapter() const {
  return dawn_shared_context_->is_vulkan_swiftshader_adapter();
}

wgpu::Adapter DawnContextProvider::GetAdapter() const {
  return dawn_shared_context_->GetAdapter();
}

wgpu::Instance DawnContextProvider::GetInstance() const {
  return dawn_shared_context_->GetInstance();
}

bool DawnContextProvider::use_thread_safe_shared_context() const {
  return dawn_shared_context_->use_thread_safe_graphite_context();
}

void DawnContextProvider::InitializeThreadSafeGraphiteContext(
    const skgpu::graphite::ContextOptions& options,
    GpuProcessShmCount* use_shader_cache_shm_count) {
  dawn_shared_context_->InitializeThreadSafeGraphiteContext(
      options, use_shader_cache_shm_count);
}

bool DawnContextProvider::InitializeGraphiteContext(
    const skgpu::graphite::ContextOptions& options,
    GpuProcessShmCount* use_shader_cache_shm_count) {
  if (dawn_shared_context_->use_thread_safe_graphite_context()) {
    return !!dawn_shared_context_->GetThreadSafeGraphiteSharedContext();
  }
  graphite_shared_context_ = dawn_shared_context_->CreateGraphiteSharedContext(
      options, use_shader_cache_shm_count, /*is_thread_safe=*/false);
  return !!graphite_shared_context_;
}

void DawnContextProvider::SetCachingInterface(
    std::unique_ptr<webgpu::DawnCachingInterface> caching_interface) {
  CHECK(dawn_shared_context_->HasOneRef());
  CHECK(!graphite_shared_context_);
  dawn_shared_context_->SetCachingInterface(std::move(caching_interface));
}

#if BUILDFLAG(IS_WIN)
Microsoft::WRL::ComPtr<ID3D11Device> DawnContextProvider::GetD3D11Device()
    const {
  return dawn_shared_context_->GetD3D11Device();
}
#endif

bool DawnContextProvider::SupportsFeature(wgpu::FeatureName feature) {
  return dawn_shared_context_->GetDevice().HasFeature(feature);
}

std::optional<error::ContextLostReason> DawnContextProvider::GetResetStatus()
    const {
  return dawn_shared_context_->GetResetStatus();
}

GraphiteSharedContext* DawnContextProvider::GetGraphiteSharedContext() const {
  if (dawn_shared_context_->use_thread_safe_graphite_context()) {
    // Both threads shares the same GraphiteSharedContext. DawnSharedContext
    // owns GraphiteSharedContext
    return dawn_shared_context_->GetThreadSafeGraphiteSharedContext();
  } else {
    // Each DawnContextProvider owns its own GraphiteSharedContext and
    // skgpu::graphite::Context
    return graphite_shared_context_.get();
  }
}

}  // namespace gpu