File: spare_render_process_host_manager_impl.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1018 lines) | stat: -rw-r--r-- 39,993 bytes parent folder | download | duplicates (2)
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
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/renderer_host/spare_render_process_host_manager_impl.h"

#include "base/check.h"
#include "base/debug/dump_without_crashing.h"
#include "base/memory/memory_pressure_monitor.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/no_destructor.h"
#include "base/strings/strcat.h"
#include "base/system/sys_info.h"
#include "components/performance_manager/scenario_api/performance_scenarios.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/site_instance_impl.h"
#include "content/common/features.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_main_runner.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_features.h"

namespace content {

using performance_scenarios::LoadingScenario;
using performance_scenarios::PerformanceScenarioObserverList;
using performance_scenarios::ScenarioScope;
using SpareProcessMaybeTakeAction =
    content::RenderProcessHostImpl::SpareProcessMaybeTakeAction;

namespace {

// Enables killing spare renders when memory pressure signal is received.
BASE_FEATURE(kKillSpareRenderOnMemoryPressure,
             "KillSpareRenderOnMemoryPressure",
             base::FEATURE_DISABLED_BY_DEFAULT);

// If enabled, MEMORY_PRESSURE_LEVEL_CRITICAL is used as the threshold that
// determines when a spare RPH can be created or killed. By default,
// MEMORY_PRESSURE_LEVEL_MODERATE is used.
BASE_FEATURE(kSpareRPHUseCriticalMemoryPressure,
             "SpareRPHUseCriticalMemoryPressure",
             base::FEATURE_DISABLED_BY_DEFAULT);

// If enabled, only the extra RPHs (controlled by the MultipleSpareRPHs
// experiment) are killed on memory pressure. Does nothing if
// kKillSpareRenderOnMemoryPressure is disabled.
BASE_FEATURE(kSpareRPHKeepOneAliveOnMemoryPressure,
             "kSpareRPHKeepOneAliveOnMemoryPressure",
             base::FEATURE_DISABLED_BY_DEFAULT);

constexpr char kSpareRendererTakenTimeSinceCreation[] =
    "BrowserRenderProcessHost.SpareRendererTaken.TimeSinceCreation";
constexpr char kSpareRendererTakenIsReady[] =
    "BrowserRenderProcessHost.SpareRendererTaken.IsReady";
constexpr char kSpareRendererDispatchResultUmaName[] =
    "BrowserRenderProcessHost.SpareRendererDispatchResult";
constexpr char kPreviouslyTakenSourceUmaName[] =
    "BrowserRenderProcessHost.SpareRendererPreviouslyTaken.Source";
constexpr char kPreviouslyTakenStageUmaName[] =
    "BrowserRenderProcessHost.SpareRendererPreviouslyTaken.Stage";
constexpr char kPreviouslyTakenForCOOPUMAName[] =
    "BrowserRenderProcessHost.SpareRendererPreviouslyTaken.ForCOOP";
constexpr char kSameNavigationStageCombinationUMAName[] =
    "BrowserRenderProcessHost.SpareRendererTakenInSameNavigation."
    "StageCombination";
constexpr char kSameNavigationForCOOPUMAName[] =
    "BrowserRenderProcessHost.SpareRendererTakenInSameNavigation.ForCOOP";

int ToStageCombinationValue(ProcessAllocationNavigationStage previous_stage,
                            ProcessAllocationNavigationStage current_stage) {
  static_assert(static_cast<int>(ProcessAllocationNavigationStage::kMaxValue) <
                10);
  return static_cast<int>(previous_stage) * 100 +
         static_cast<int>(current_stage);
}

content::NoSpareRendererReason MapToNoSpareRendererReason(
    content::SpareRendererDispatchResult dispatch_result) {
  switch (dispatch_result) {
    case content::SpareRendererDispatchResult::kUsed:
      return content::NoSpareRendererReason::kTakenByPreviousNavigation;
    case content::SpareRendererDispatchResult::kTimeout:
      return content::NoSpareRendererReason::kTimeout;
    case content::SpareRendererDispatchResult::kOverridden:
      return content::NoSpareRendererReason::kNotYetCreatedAfterWarmup;
    case content::SpareRendererDispatchResult::kDestroyedNotEnabled:
      return content::NoSpareRendererReason::kNotEnabled;
    case content::SpareRendererDispatchResult::kDestroyedProcessLimit:
      return content::NoSpareRendererReason::kProcessLimit;
    case content::SpareRendererDispatchResult::kProcessExited:
      return content::NoSpareRendererReason::kProcessExited;
    case content::SpareRendererDispatchResult::kProcessHostDestroyed:
      return content::NoSpareRendererReason::kProcessHostDestroyed;
    case content::SpareRendererDispatchResult::kMemoryPressure:
      return content::NoSpareRendererReason::kMemoryPressure;
    case content::SpareRendererDispatchResult::kKillAfterBackgrounded:
      return content::NoSpareRendererReason::kOnceBackgrounded;
  }
}

std::string GetCategorizedSpareProcessMaybeTakeTimeUMAName(
    SpareProcessMaybeTakeAction action) {
  std::string action_name;
  switch (action) {
    case SpareProcessMaybeTakeAction::kNoSparePresent:
      action_name = "NoSparePresent";
      break;
    case SpareProcessMaybeTakeAction::kMismatchedBrowserContext:
      action_name = "MismatchedBrowserContext";
      break;
    case SpareProcessMaybeTakeAction::kMismatchedStoragePartition:
      action_name = "MismatchedStoragePartition";
      break;
    case SpareProcessMaybeTakeAction::kRefusedByEmbedder:
      action_name = "RefusedByEmbedder";
      break;
    case SpareProcessMaybeTakeAction::kSpareTaken:
      action_name = "SpareTaken";
      break;
    case SpareProcessMaybeTakeAction::kRefusedBySiteInstance:
      action_name = "RefusedBySiteInstance";
      break;
    case SpareProcessMaybeTakeAction::kRefusedForPdfContent:
      action_name = "RefusedForPdfContent";
      break;
    case SpareProcessMaybeTakeAction::kRefusedForJitMismatch:
      action_name = "RefusedForJitMismatch";
      break;
    case SpareProcessMaybeTakeAction::kRefusedForV8OptimizationMismatch:
      action_name = "RefusedForV8OptimizationMismatch";
      break;
  }
  return base::StrCat(
      {"BrowserRenderProcessHost.SpareProcessMaybeTakeTime.", action_name});
}

std::string_view GetNoSpareRendererReasonName(NoSpareRendererReason reason) {
  switch (reason) {
    case NoSpareRendererReason::kNotYetCreated:
      return "NotYetCreated";
    case NoSpareRendererReason::kTakenByPreviousNavigation:
      return "TakenByPreviousNavigation";
    case NoSpareRendererReason::kTimeout:
      return "Timeout";
    case NoSpareRendererReason::kNotEnabled:
      return "NotEnabled";
    case NoSpareRendererReason::kProcessLimit:
      return "ProcessLimit";
    case NoSpareRendererReason::kMemoryPressure:
      return "MemoryPressure";
    case NoSpareRendererReason::kProcessExited:
      return "ProcessExited";
    case NoSpareRendererReason::kProcessHostDestroyed:
      return "ProcessHostDestroyed";
    case NoSpareRendererReason::kNotYetCreatedFirstLaunch:
      return "NotYetCreatedFirstLaunch";
    case NoSpareRendererReason::kNotYetCreatedAfterWarmup:
      return "NotYetCreatedAfterWarmup";
    case NoSpareRendererReason::kOnceBackgrounded:
      return "OnceBackgrounded";
  }
}

std::string GetNoSpareRendererAllocationSourceUMAName(
    NoSpareRendererReason reason) {
  return base::StrCat(
      {"BrowserRenderProcessHost.NoSpareRenderer.AllocationSource.",
       GetNoSpareRendererReasonName(reason)});
}

std::string GetNoSpareRendererAllocationNavigationStageUMAName(
    NoSpareRendererReason reason) {
  return base::StrCat(
      {"BrowserRenderProcessHost.NoSpareRenderer.NavigationStage.",
       GetNoSpareRendererReasonName(reason)});
}

std::string GetNoSpareRendererAllocationForCOOPUMAName(
    NoSpareRendererReason reason) {
  return base::StrCat({"BrowserRenderProcessHost.NoSpareRenderer.ForCOOP.",
                       GetNoSpareRendererReasonName(reason)});
}

bool IsCurrentlyUnderMemoryPressure() {
  base::MemoryPressureMonitor* memory_pressure_monitor =
      base::MemoryPressureMonitor::Get();
  if (!memory_pressure_monitor) {
    return false;
  }

  return memory_pressure_monitor->GetCurrentPressureLevel() !=
         base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE;
}

// Returns the number of spare hosts that should be created. Ensures the field
// trial is not activated on excluded machines.
size_t GetSpareRPHCount() {
  static int64_t available_ram = base::SysInfo::AmountOfPhysicalMemoryMB();
  // Exclude machines with less than 4gigs of ram.
  if (available_ram < 4 * 1024) {
    return 1u;
  }
  return features::kMultipleSpareRPHsCount.Get();
}

void LogAllocationContext(const std::string& source_uma_name,
                          const std::string& stage_uma_name,
                          const std::string& for_coop_uma_name,
                          const ProcessAllocationContext& context) {
  base::UmaHistogramEnumeration(source_uma_name, context.source);
  if (context.source == ProcessAllocationSource::kNavigationRequest) {
    CHECK(context.navigation_context.has_value());
    base::UmaHistogramEnumeration(stage_uma_name,
                                  context.navigation_context->stage);
    base::UmaHistogramBoolean(
        for_coop_uma_name,
        context.navigation_context->requires_new_process_for_coop);
  }
}

void LogNoSparePresentUmas(
    NoSpareRendererReason no_spare_renderer_reason,
    const ProcessAllocationContext& allocation_context,
    const std::optional<ProcessAllocationContext>& previous_taken_context) {
  base::UmaHistogramEnumeration(
      "BrowserRenderProcessHost.NoSparePresentReason2",
      no_spare_renderer_reason);
  // Log the allocation context, categorized by NoSpareRendererReason.
  LogAllocationContext(
      GetNoSpareRendererAllocationSourceUMAName(no_spare_renderer_reason),
      GetNoSpareRendererAllocationNavigationStageUMAName(
          no_spare_renderer_reason),
      GetNoSpareRendererAllocationForCOOPUMAName(no_spare_renderer_reason),
      allocation_context);
  if (no_spare_renderer_reason ==
          NoSpareRendererReason::kTakenByPreviousNavigation &&
      previous_taken_context.has_value()) {
    LogAllocationContext(
        kPreviouslyTakenSourceUmaName, kPreviouslyTakenStageUmaName,
        kPreviouslyTakenForCOOPUMAName, previous_taken_context.value());
    const auto& previous_navigation_context =
        previous_taken_context->navigation_context;
    const auto& current_navigation_context =
        allocation_context.navigation_context;
    // Especially, if both the previous and the current allocation happens
    // during the navigation. We will log the combination of the navigation
    // stage and whether the allocation is caused by a COOP swap.
    if (previous_navigation_context.has_value() &&
        current_navigation_context.has_value() &&
        previous_navigation_context->navigation_id ==
            current_navigation_context->navigation_id) {
      base::UmaHistogramSparse(
          kSameNavigationStageCombinationUMAName,
          ToStageCombinationValue(previous_navigation_context->stage,
                                  current_navigation_context->stage));
      // Local traces found that the spare renderer allocation tends to fail
      // if we receive a COOP header in the response. The UMA is added to verify
      // the frequency.
      base::UmaHistogramBoolean(
          kSameNavigationForCOOPUMAName,
          current_navigation_context->requires_new_process_for_coop);
    }
  }
}

void LogSpareProcessTakeActionUMAs(RenderProcessHost* host,
                                   SpareProcessMaybeTakeAction action) {
  base::UmaHistogramEnumeration(
      "BrowserRenderProcessHost.SpareProcessMaybeTakeAction", action);
  if (action == SpareProcessMaybeTakeAction::kSpareTaken) {
    CHECK(host);
    base::UmaHistogramBoolean(kSpareRendererTakenIsReady, host->IsReady());
    base::UmaHistogramLongTimes(
        kSpareRendererTakenTimeSinceCreation,
        base::TimeTicks::Now() - host->GetLastInitTime());
  }
}

// Returns the MemoryPressureLevel threshold that determines when a spare RPH
// can be created or killed.
base::MemoryPressureListener::MemoryPressureLevel
GetMemoryPressureLevelThreshold() {
  if (base::FeatureList::IsEnabled(kSpareRPHUseCriticalMemoryPressure)) {
    return base::MemoryPressureListener::MemoryPressureLevel::
        MEMORY_PRESSURE_LEVEL_CRITICAL;
  }
  return base::MemoryPressureListener::MemoryPressureLevel::
      MEMORY_PRESSURE_LEVEL_MODERATE;
}

}  // namespace

SpareRenderProcessHostManagerImpl::SpareRenderProcessHostManagerImpl()
    : memory_pressure_listener_(
          FROM_HERE,
          base::BindRepeating(
              &SpareRenderProcessHostManagerImpl::OnMemoryPressure,
              base::Unretained(this))),
      check_memory_pressure_timer_(
          FROM_HERE,
          base::Minutes(5),
          base::BindRepeating(
              &SpareRenderProcessHostManagerImpl::CheckIfMemoryPressureEnded,
              base::Unretained(this))),
      metrics_heartbeat_timer_(
          FROM_HERE,
          base::Minutes(2),
          base::BindRepeating(
              &SpareRenderProcessHostManagerImpl::OnMetricsHeartbeatTimerFired,
              base::Unretained(this)))
#if BUILDFLAG(IS_ANDROID)
      ,
      app_status_listener_(
          base::android::ApplicationStatusListener::New(base::BindRepeating(
              &SpareRenderProcessHostManagerImpl::OnApplicationStateChange,
              base::Unretained(this))))
#endif
{
  metrics_heartbeat_timer_.Reset();

  // Immediately start the timer if the system is already under memory pressure.
  if (IsCurrentlyUnderMemoryPressure()) {
    check_memory_pressure_timer_.Reset();
  }

  // Need to register first before checking the state to make sure we don't miss
  // a notification.
  if (auto performance_scenario_observer_list =
          PerformanceScenarioObserverList::GetForScope(
              ScenarioScope::kGlobal)) {
    // Note: SpareRenderProcessHostManagerImpl is a global singleton using
    // base::NoDestructor, so no need to call RemoveObserver() later.
    performance_scenario_observer_list->AddObserver(this);

    is_browser_idle_ =
        performance_scenarios::GetLoadingScenario(ScenarioScope::kGlobal)
            ->load(std::memory_order_relaxed) ==
        LoadingScenario::kNoPageLoading;
  }
#if BUILDFLAG(IS_ANDROID)
  OnApplicationStateChange(
      base::android::ApplicationStatusListener::GetState());
#endif
}

SpareRenderProcessHostManagerImpl::~SpareRenderProcessHostManagerImpl() =
    default;

// static
SpareRenderProcessHostManager& SpareRenderProcessHostManager::Get() {
  return SpareRenderProcessHostManagerImpl::Get();
}

// static
SpareRenderProcessHostManagerImpl& SpareRenderProcessHostManagerImpl::Get() {
  static base::NoDestructor<SpareRenderProcessHostManagerImpl> s_instance;
  return *s_instance;
}

void SpareRenderProcessHostManagerImpl::StartDestroyTimer(
    std::optional<base::TimeDelta> timeout) {
  if (!timeout) {
    return;
  }
  deferred_destroy_timer_.Start(
      FROM_HERE, timeout.value(),
      base::BindOnce(&SpareRenderProcessHostManagerImpl::CleanupSpares,
                     base::Unretained(this),
                     SpareRendererDispatchResult::kTimeout));
}

bool SpareRenderProcessHostManagerImpl::DestroyTimerWillFireBefore(
    base::TimeDelta timeout) {
  return deferred_destroy_timer_.IsRunning() &&
         deferred_destroy_timer_.GetCurrentDelay() < timeout;
}

void SpareRenderProcessHostManagerImpl::AddObserver(Observer* observer) {
  observer_list_.AddObserver(observer);
}

void SpareRenderProcessHostManagerImpl::RemoveObserver(Observer* observer) {
  observer_list_.RemoveObserver(observer);
}

RenderProcessHost* SpareRenderProcessHostManagerImpl::WarmupSpare(
    BrowserContext* browser_context) {
  return WarmupSpare(browser_context, std::nullopt);
}

const std::vector<RenderProcessHost*>&
SpareRenderProcessHostManagerImpl::GetSpares() {
  return spare_rphs_;
}

std::vector<ChildProcessId> SpareRenderProcessHostManagerImpl::GetSpareIds() {
  std::vector<ChildProcessId> spare_ids;
  spare_ids.reserve(spare_rphs_.size());
  for (RenderProcessHost* spare_rph : spare_rphs_) {
    spare_ids.push_back(spare_rph->GetID());
  }
  return spare_ids;
}

void SpareRenderProcessHostManagerImpl::CleanupSparesForTesting() {
  CleanupSpares(std::nullopt);
}

RenderProcessHost* SpareRenderProcessHostManagerImpl::WarmupSpare(
    BrowserContext* browser_context,
    std::optional<base::TimeDelta> timeout) {
  if (delay_timer_) {
    // If the timeout does not have a value, the delayed creation is no longer
    // required since we will create the spare renderer here.
    // Otherwise we will create the spare renderer and have the delayed creation
    // override the timeout later on.
    if (!timeout.has_value()) {
      UMA_HISTOGRAM_TIMES("BrowserRenderProcessHost.SpareProcessDelayTime",
                          delay_timer_->Elapsed());
      delay_timer_.reset();
    }
  }

  // Check if there's already an existing, matching, spare.
  RenderProcessHost* spare_rph =
      !spare_rphs_.empty() ? spare_rphs_.at(0) : nullptr;
  if (spare_rph && spare_rph->GetBrowserContext() == browser_context) {
    DCHECK_EQ(browser_context->GetDefaultStoragePartition(),
              spare_rph->GetStoragePartition());

    // Use the new timeout if the specified timeout will be triggered after the
    // current timeout (or not triggered at all).
    if (!timeout.has_value() || DestroyTimerWillFireBefore(timeout.value())) {
      deferred_destroy_timer_.Stop();
      StartDestroyTimer(timeout);
    }
    return nullptr;
  }

  bool had_spare_renderer = !!spare_rph;
  CleanupSpares(SpareRendererDispatchResult::kOverridden);
  CHECK(no_spare_renderer_reason_ ==
        NoSpareRendererReason::kNotYetCreatedAfterWarmup);
  UMA_HISTOGRAM_BOOLEAN(
      "BrowserRenderProcessHost.SpareProcessEvictedOtherSpare",
      had_spare_renderer);

  // Don't create a spare renderer for a BrowserContext that is in the
  // process of shutting down.
  if (browser_context->ShutdownStarted()) {
    // Create a crash dump to help us assess what scenarios trigger this
    // path to be taken.
    // TODO(acolwell): Remove this call once are confident we've eliminated
    // any problematic callers.
    base::debug::DumpWithoutCrashing();

    return nullptr;
  }

  if (BrowserMainRunner::ExitedMainMessageLoop()) {
    // Don't create a new process when the browser is shutting down. No
    // DumpWithoutCrashing here since there are known cases in the wild. See
    // https://crbug.com/40274462 for details.
    return nullptr;
  }

  // Don't create a spare renderer if we're using --single-process or if we've
  // got too many processes.
  if (RenderProcessHost::IsProcessLimitReached()) {
    no_spare_renderer_reason_ = NoSpareRendererReason::kProcessLimit;
    return nullptr;
  }

  // Don't create a spare renderer when the system is under load.  This is
  // currently approximated by only looking at the memory pressure.  See also
  // https://crbug.com/852905.
  auto* memory_monitor = base::MemoryPressureMonitor::Get();
  if (memory_monitor && memory_monitor->GetCurrentPressureLevel() >=
                            GetMemoryPressureLevelThreshold()) {
    no_spare_renderer_reason_ = NoSpareRendererReason::kMemoryPressure;
    return nullptr;
  }

#if BUILDFLAG(IS_ANDROID)
  if (features::kAndroidSpareRendererKillWhenBackgrounded.Get() &&
      is_app_backgroud_) {
    no_spare_renderer_reason_ = NoSpareRendererReason::kOnceBackgrounded;
    return nullptr;
  }
#endif

  process_startup_timer_ = std::make_unique<base::ElapsedTimer>();

  // Start the timer to track how long it takes for a spare renderer to be used.
  // Note: This timer only makes sense when there is a single spare.
  if (GetSpareRPHCount() == 1u) {
    spare_renderer_maybe_take_timer_ = std::make_unique<base::ElapsedTimer>();
  }
  RenderProcessHost* new_spare_rph =
      RenderProcessHostImpl::CreateRenderProcessHost(
          browser_context, nullptr /* site_instance */);
  new_spare_rph->AddObserver(this);
  new_spare_rph->Init();
  spare_rphs_.push_back(new_spare_rph);

  // Use the new timeout if there is no previous renderer or
  // the specified timeout will be triggered after the current timeout
  // (or not triggered at all).
  if (!had_spare_renderer || !timeout.has_value() ||
      DestroyTimerWillFireBefore(timeout.value())) {
    deferred_destroy_timer_.Stop();
    StartDestroyTimer(timeout);
  }

  // The spare render process isn't ready, so wait and do the "spare render
  // process changed" callback in RenderProcessReady().
  return new_spare_rph;
}

void SpareRenderProcessHostManagerImpl::DeferredWarmupSpare(
    BrowserContext* browser_context,
    base::TimeDelta delay,
    std::optional<base::TimeDelta> timeout) {
  delay_timer_ = std::make_unique<base::ElapsedTimer>();
  deferred_warmup_timer_.Start(
      FROM_HERE, delay,
      base::BindOnce(
          [](SpareRenderProcessHostManagerImpl* self,
             base::WeakPtr<BrowserContext> browser_context,
             std::optional<base::TimeDelta> timeout) {
            // Don't create spare process if the browser context is destroyed
            // or the shutdown has started.
            if (browser_context && !browser_context->ShutdownStarted()) {
              self->WarmupSpare(browser_context.get(), timeout);
            }
          },
          base::Unretained(this), browser_context->GetWeakPtr(), timeout));
}

RenderProcessHost* SpareRenderProcessHostManagerImpl::MaybeTakeSpare(
    BrowserContext* browser_context,
    SiteInstanceImpl* site_instance,
    const ProcessAllocationContext& allocation_context) {
  // Get the StoragePartition for |site_instance|.  Note that this might be
  // different than the default StoragePartition for |browser_context|.
  StoragePartition* site_storage =
      browser_context->GetStoragePartition(site_instance);

  // Bail early if there is no spare renderer available.
  SpareProcessMaybeTakeAction action =
      SpareProcessMaybeTakeAction::kNoSparePresent;
  RenderProcessHost* next_spare_rph =
      !spare_rphs_.empty() ? spare_rphs_.at(0) : nullptr;
  if (!next_spare_rph) {
    LogNoSparePresentUmas(no_spare_renderer_reason_, allocation_context,
                          previous_taken_context_);
  } else if (browser_context != next_spare_rph->GetBrowserContext()) {
    action = SpareProcessMaybeTakeAction::kMismatchedBrowserContext;
  } else if (!next_spare_rph->InSameStoragePartition(site_storage)) {
    action = SpareProcessMaybeTakeAction::kMismatchedStoragePartition;
  } else if (auto refuse_reason =
                 DoesEmbedderAllowSpareUsage(browser_context, site_instance);
             refuse_reason.has_value()) {
    base::UmaHistogramEnumeration(
        "BrowserRenderProcessHost.SpareProcessRefusedByEmbedderReason",
        refuse_reason.value());
    action = SpareProcessMaybeTakeAction::kRefusedByEmbedder;
  } else if (
      // We shouldn't use the spare if:
      // 1. The SiteInstance has already got an associated process.  This is
      //    important to avoid taking and then immediately discarding the spare
      //    for process-per-site scenarios (which the HasProcess call below
      //    accounts for).  Note that HasProcess will return false and allow
      //    using the spare if the given process-per-site process hasn't been
      //    launched.
      // 2. The SiteInstance has opted out of using the spare process.
      // 3. The SiteInstance is a guest SiteInstance.
      site_instance->HasProcess() ||
      !site_instance->CanAssociateWithSpareProcess() ||
      site_instance->IsGuest()) {
    action = SpareProcessMaybeTakeAction::kRefusedBySiteInstance;
  } else if (site_instance->GetSiteInfo().is_pdf()) {
    action = SpareProcessMaybeTakeAction::kRefusedForPdfContent;
  } else if (next_spare_rph->IsJitDisabled() !=
             site_instance->GetSiteInfo().is_jit_disabled()) {
    action = SpareProcessMaybeTakeAction::kRefusedForJitMismatch;
  } else if (next_spare_rph->AreV8OptimizationsDisabled() !=
             site_instance->GetSiteInfo().are_v8_optimizations_disabled()) {
    action = SpareProcessMaybeTakeAction::kRefusedForV8OptimizationMismatch;
  } else {
    action = SpareProcessMaybeTakeAction::kSpareTaken;
  }
  LogSpareProcessTakeActionUMAs(next_spare_rph, action);

  if (spare_renderer_maybe_take_timer_) {
    auto maybe_take_time = spare_renderer_maybe_take_timer_->Elapsed();
    base::UmaHistogramLongTimes(
        "BrowserRenderProcessHost.SpareProcessMaybeTakeTime", maybe_take_time);
    base::UmaHistogramLongTimes(
        GetCategorizedSpareProcessMaybeTakeTimeUMAName(action),
        maybe_take_time);
  }

  // Decide whether to take or drop the spare process.
  RenderProcessHost* returned_process = nullptr;
  if (action == SpareProcessMaybeTakeAction::kSpareTaken) {
    CHECK(next_spare_rph->HostHasNotBeenUsed());

    // If the spare process ends up getting killed, the spare manager should
    // discard the spare RPH, so if one exists, it should always be live here.
    CHECK(next_spare_rph->IsInitializedAndNotDead());

    returned_process = next_spare_rph;
    previous_taken_context_ = allocation_context;
    ReleaseSpare(next_spare_rph, SpareRendererDispatchResult::kUsed);
  } else if (!RenderProcessHostImpl::IsSpareProcessKeptAtAllTimes()) {
    // If the spare shouldn't be kept around, then discard it as soon as we
    // find that the current spare was mismatched.
    CleanupSpares(SpareRendererDispatchResult::kDestroyedNotEnabled);
    CHECK(no_spare_renderer_reason_ == NoSpareRendererReason::kNotEnabled);
  } else if (RenderProcessHost::IsProcessLimitReached()) {
    // Drop all spares if we are at a process limit and the spare wasn't taken.
    // This helps avoid process reuse.
    // TODO(pmonette): Only cleanup n spares, where n is the count of processes
    // that is over the limit.
    CleanupSpares(SpareRendererDispatchResult::kDestroyedProcessLimit);
    CHECK(no_spare_renderer_reason_ == NoSpareRendererReason::kProcessLimit);
  }

  // SetHasSpareRendererPriority(false) will cause the priority to drop until
  // further updates are made. For navigation requests we will keep the priority
  // until the RenderFrameHostImpl constructor sets the priority.
  if (returned_process && !allocation_context.IsForNavigation()) {
    returned_process->SetHasSpareRendererPriority(false);
  }

  return returned_process;
}

std::optional<ContentBrowserClient::SpareProcessRefusedByEmbedderReason>
SpareRenderProcessHostManagerImpl::DoesEmbedderAllowSpareUsage(
    BrowserContext* browser_context,
    SiteInstanceImpl* site_instance) {
  // Give embedder a chance to disable using a spare RenderProcessHost for
  // certain SiteInstances.  Some navigations, such as to NTP or extensions,
  // require passing command-line flags to the renderer process at process
  // launch time, but this cannot be done for spare RenderProcessHosts, which
  // are started before it is known which navigation might use them.  So, a
  // spare RenderProcessHost should not be used in such cases.
  //
  // Note that exempting NTP and extensions from using the spare process might
  // also happen via HasProcess check below (which returns true for
  // process-per-site SiteInstances if the given process-per-site process
  // already exists).  Despite this potential overlap, it is important to do
  // both kinds of checks (to account for other non-ntp/extension
  // process-per-site scenarios + to work correctly even if
  // ShouldUseSpareRenderProcessHost starts covering non-process-per-site
  // scenarios).
  std::optional<ContentBrowserClient::SpareProcessRefusedByEmbedderReason>
      refuse_reason;
  if (!GetContentClient()->browser()->ShouldUseSpareRenderProcessHost(
          browser_context, site_instance->GetSiteInfo().site_url(),
          refuse_reason)) {
    CHECK(refuse_reason.has_value());
    return refuse_reason;
  }

  // The spare RenderProcessHost always launches with JIT enabled, so if JIT
  // is disabled for the site then it's not possible to use this as the JIT
  // policy will differ.
  if (GetContentClient()->browser()->IsJitDisabledForSite(
          browser_context, site_instance->GetSiteInfo().process_lock_url())) {
    return ContentBrowserClient::SpareProcessRefusedByEmbedderReason::
        JitDisabled;
  }

  // V8 optimizations are globally enabled or disabled for a whole process,
  // and spare renderers always have V8 optimizations enabled, so we can never
  // use them if they're supposed to be disabled for this site.
  if (GetContentClient()->browser()->AreV8OptimizationsDisabledForSite(
          browser_context, site_instance->GetSiteInfo().process_lock_url())) {
    return ContentBrowserClient::SpareProcessRefusedByEmbedderReason::
        V8OptimizationsDisabled;
  }

  // V8 feature flags are globally initialized during renderer process
  // startup, and spare renderers allow V8 feature flag overrides by default.
  // As such spare renderers should not be used when v8 flag overrides are
  // disabled.
  if (GetContentClient()->browser()->DisallowV8FeatureFlagOverridesForSite(
          site_instance->GetSiteInfo().process_lock_url())) {
    return ContentBrowserClient::SpareProcessRefusedByEmbedderReason::
        DisallowV8FeatureFlagOverrides;
  }

  return std::nullopt;
}

void SpareRenderProcessHostManagerImpl::PrepareForFutureRequests(
    BrowserContext* browser_context,
    std::optional<base::TimeDelta> delay) {
  if (RenderProcessHostImpl::IsSpareProcessKeptAtAllTimes()) {
    std::optional<base::TimeDelta> timeout = std::nullopt;
    if (base::FeatureList::IsEnabled(
            features::kAndroidWarmUpSpareRendererWithTimeout)) {
      if (features::kAndroidSpareRendererCreationTiming.Get() !=
          features::kAndroidSpareRendererCreationDelayedDuringLoading) {
        // The creation of the spare renderer will be managed in
        // WebContentsImpl::DidStopLoading or
        // WebContentsImpl::OnFirstVisuallyNonEmptyPaint.
        return;
      }
      if (features::kAndroidSpareRendererTimeoutSeconds.Get() > 0) {
        timeout =
            base::Seconds(features::kAndroidSpareRendererTimeoutSeconds.Get());
      }
    }
    // Always keep around a spare process for the most recently requested
    // |browser_context|.
    if (delay.has_value()) {
      DeferredWarmupSpare(browser_context, *delay, timeout);
    } else {
      WarmupSpare(browser_context, timeout);
    }
  } else {
    // Discard the ignored (probably non-matching) spares so as not to waste
    // resources.
    CleanupSpares(SpareRendererDispatchResult::kDestroyedNotEnabled);
    CHECK(no_spare_renderer_reason_ == NoSpareRendererReason::kNotEnabled);
  }
}

void SpareRenderProcessHostManagerImpl::CleanupSpares(
    std::optional<SpareRendererDispatchResult> dispatch_result) {
  std::vector<RenderProcessHost*> spare_rphs = std::move(spare_rphs_);

  // Stop the destroy timer since it is no longer required.
  deferred_destroy_timer_.Stop();

  for (RenderProcessHost* spare_rph : spare_rphs) {
    if (dispatch_result.has_value()) {
      base::UmaHistogramEnumeration(kSpareRendererDispatchResultUmaName,
                                    dispatch_result.value());
    }
    // Stop observing the process, to avoid getting notifications as a
    // consequence of the Cleanup call below - such notification could call
    // back into CleanupSpare leading to stack overflow.
    spare_rph->RemoveObserver(this);

    // Make sure the RenderProcessHost object gets destroyed.
    if (!spare_rph->AreRefCountsDisabled()) {
      spare_rph->Cleanup();
    }

    for (auto& observer : observer_list_) {
      observer.OnSpareRenderProcessHostRemoved(spare_rph);
    }
  }
  if (dispatch_result.has_value()) {
    no_spare_renderer_reason_ =
        MapToNoSpareRendererReason(dispatch_result.value());
    // The timer is not reset during the timeout to collect data about
    // when the spare renderers will be used without timeout. The data
    // will be used to set an appropriate timeout value.
    if (dispatch_result.value() != SpareRendererDispatchResult::kTimeout) {
      spare_renderer_maybe_take_timer_.reset();
    }
  }
}

void SpareRenderProcessHostManagerImpl::CleanupExtraSpares(
    std::optional<SpareRendererDispatchResult> dispatch_result) {
  if (spare_rphs_.size() <= 1u) {
    // There is either zero or one spare. Nothing to do.
    return;
  }

  // Pop the front element, as we want to preserve it.
  RenderProcessHost* first_spare = spare_rphs_.front();

  // Swap the front and back to efficient removal.
  std::swap(spare_rphs_.front(), spare_rphs_.back());
  spare_rphs_.pop_back();

  // Cleanup all remaining spares in the vector.
  CleanupSpares(dispatch_result);

  // Re-add the spare to the vector.
  spare_rphs_.push_back(first_spare);
}

void SpareRenderProcessHostManagerImpl::SetDeferTimerTaskRunnerForTesting(
    scoped_refptr<base::SequencedTaskRunner> task_runner) {
  deferred_warmup_timer_.SetTaskRunner(task_runner);
  deferred_destroy_timer_.SetTaskRunner(task_runner);
}

void SpareRenderProcessHostManagerImpl::SetIsBrowserIdleForTesting(
    bool is_browser_idle) {
  DCHECK(!PerformanceScenarioObserverList::GetForScope(ScenarioScope::kGlobal));
  SetIsBrowserIdle(is_browser_idle);
}

void SpareRenderProcessHostManagerImpl::ReleaseSpare(
    RenderProcessHost* host,
    SpareRendererDispatchResult dispatch_result) {
  // Erase while intentionally preserving the order of the other elements.
  size_t removed = std::erase(spare_rphs_, host);
  base::UmaHistogramEnumeration(kSpareRendererDispatchResultUmaName,
                                dispatch_result);
  CHECK_EQ(removed, 1u);
  host->RemoveObserver(this);
  for (auto& observer : observer_list_) {
    observer.OnSpareRenderProcessHostRemoved(host);
  }

  if (spare_rphs_.empty()) {
    no_spare_renderer_reason_ = MapToNoSpareRendererReason(dispatch_result);
  }

  // Since that a spare was just released, check if we need to start another.
  MaybeCreateExtraSpare();
}

void SpareRenderProcessHostManagerImpl::RenderProcessReady(
    RenderProcessHost* host) {
  CHECK(base::Contains(spare_rphs_, host));

  CHECK(process_startup_timer_);
  UMA_HISTOGRAM_TIMES("BrowserRenderProcessHost.SpareProcessStartupTime",
                      process_startup_timer_->Elapsed());

  if (base::FeatureList::IsEnabled(features::kSpareRendererProcessPriority)) {
    host->SetHasSpareRendererPriority(true);
  }

  process_startup_timer_.reset();

  for (auto& observer : observer_list_) {
    observer.OnSpareRenderProcessHostReady(host);
  }

  // Now that a spare was just fully initialized, check if we need to start
  // another.
  MaybeCreateExtraSpare();
}

void SpareRenderProcessHostManagerImpl::RenderProcessExited(
    RenderProcessHost* host,
    const ChildProcessTerminationInfo& info) {
  ReleaseSpare(host, SpareRendererDispatchResult::kProcessExited);

  // Make sure the RenderProcessHost object gets destroyed.
  if (!host->AreRefCountsDisabled()) {
    host->Cleanup();
  }

  if (spare_rphs_.empty()) {
    deferred_destroy_timer_.Stop();
  }
}

void SpareRenderProcessHostManagerImpl::RenderProcessHostDestroyed(
    RenderProcessHost* host) {
  ReleaseSpare(host, SpareRendererDispatchResult::kProcessHostDestroyed);
}

void SpareRenderProcessHostManagerImpl::OnLoadingScenarioChanged(
    ScenarioScope scope,
    LoadingScenario old_scenario,
    LoadingScenario new_scenario) {
  SetIsBrowserIdle(new_scenario == LoadingScenario::kNoPageLoading);
}

void SpareRenderProcessHostManagerImpl::SetIsBrowserIdle(bool is_browser_idle) {
  if (is_browser_idle_ == is_browser_idle) {
    return;
  }

  is_browser_idle_ = is_browser_idle;

  // Now that the browser is idle, check if we need to start another spare.
  MaybeCreateExtraSpare();
}

void SpareRenderProcessHostManagerImpl::OnMemoryPressure(
    base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
  if (memory_pressure_level < GetMemoryPressureLevelThreshold()) {
    return;
  }

  CHECK_NE(memory_pressure_level,
           base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE);
  if (check_memory_pressure_timer_.IsRunning() ||
      !base::FeatureList::IsEnabled(kKillSpareRenderOnMemoryPressure)) {
    return;
  }

  if (base::FeatureList::IsEnabled(kSpareRPHKeepOneAliveOnMemoryPressure)) {
    CleanupExtraSpares(SpareRendererDispatchResult::kMemoryPressure);
  } else {
    CleanupSpares(SpareRendererDispatchResult::kMemoryPressure);
    CHECK(no_spare_renderer_reason_ == NoSpareRendererReason::kMemoryPressure);
  }

  // `reset()` will start the timer.
  check_memory_pressure_timer_.Reset();
}

void SpareRenderProcessHostManagerImpl::CheckIfMemoryPressureEnded() {
  if (IsCurrentlyUnderMemoryPressure()) {
    return;
  }

  check_memory_pressure_timer_.Stop();

  // Now that the system is no longer under memory pressure, check if we need
  // to start another spare.
  MaybeCreateExtraSpare();
}

bool SpareRenderProcessHostManagerImpl::ShouldCreateExtraSpare() const {
  // Check target spare count. This function has the side-effect of
  // activating the field trial.
  if (spare_rphs_.size() >= GetSpareRPHCount()) {
    return false;
  }

  // Avoid doing work on shutdown.
  if (BrowserMainRunner::ExitedMainMessageLoop()) {
    return false;
  }

  // Only create extra spares when the browser is idle.
  if (!is_browser_idle_) {
    return false;
  }

  // The first spare is created using either WarmupSpare() or
  // PrepareForFutureRequests().
  if (spare_rphs_.empty()) {
    return false;
  }

  // Avoid doing work on shutdown again.
  if (spare_rphs_.back()->GetBrowserContext()->ShutdownStarted()) {
    return false;
  }

  // Don't create spares beyond the renderer count limit.
  if (RenderProcessHost::IsProcessLimitReached()) {
    return false;
  }

  // Don't create spares when under memory pressure.
  if (check_memory_pressure_timer_.IsRunning()) {
    return false;
  }

  // A spare is already being initialized right now.
  if (!spare_rphs_.back()->IsReady()) {
    return false;
  }

  return true;
}

void SpareRenderProcessHostManagerImpl::MaybeCreateExtraSpare() {
  if (!ShouldCreateExtraSpare()) {
    return;
  }

  // Use the same browser context of an existing spare.
  BrowserContext* browser_context = spare_rphs_.at(0)->GetBrowserContext();

  process_startup_timer_ = std::make_unique<base::ElapsedTimer>();
  RenderProcessHost* new_spare_rph =
      RenderProcessHostImpl::CreateRenderProcessHost(
          browser_context, nullptr /* site_instance */);
  new_spare_rph->AddObserver(this);
  new_spare_rph->Init();
  spare_rphs_.push_back(new_spare_rph);
}

void SpareRenderProcessHostManagerImpl::OnMetricsHeartbeatTimerFired() {
  base::UmaHistogramCounts100("BrowserRenderProcessHost.SpareCount",
                              spare_rphs_.size());
}

#if BUILDFLAG(IS_ANDROID)
void SpareRenderProcessHostManagerImpl::OnApplicationStateChange(
    base::android::ApplicationState state) {
  if (!features::kAndroidSpareRendererKillWhenBackgrounded.Get()) {
    return;
  }
  using ApplicationState = base::android::ApplicationState;
  switch (state) {
    case ApplicationState::APPLICATION_STATE_UNKNOWN:
      return;
    case ApplicationState::APPLICATION_STATE_HAS_RUNNING_ACTIVITIES:
    case ApplicationState::APPLICATION_STATE_HAS_PAUSED_ACTIVITIES:
      is_app_backgroud_ = false;
      return;
    case ApplicationState::APPLICATION_STATE_HAS_STOPPED_ACTIVITIES:
    case ApplicationState::APPLICATION_STATE_HAS_DESTROYED_ACTIVITIES:
      if (!is_app_backgroud_) {
        CleanupSpares(SpareRendererDispatchResult::kKillAfterBackgrounded);
      }
      is_app_backgroud_ = true;
      return;
  }
}
#endif

}  // namespace content