summaryrefslogtreecommitdiffstats
path: root/dom/ipc/ProcessPriorityManager.cpp
blob: 10fca879a658004b26a29fcca6950408e1f66996 (plain)
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "ProcessPriorityManager.h"
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/dom/CanonicalBrowsingContext.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/BrowserHost.h"
#include "mozilla/dom/BrowserParent.h"
#include "mozilla/Hal.h"
#include "mozilla/IntegerPrintfMacros.h"
#include "mozilla/Preferences.h"
#include "mozilla/ProfilerMarkers.h"
#include "mozilla/ProfilerState.h"
#include "mozilla/Services.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/StaticPrefs_threads.h"
#include "mozilla/Telemetry.h"
#include "mozilla/Unused.h"
#include "mozilla/Logging.h"
#include "nsPrintfCString.h"
#include "nsXULAppAPI.h"
#include "nsFrameLoader.h"
#include "nsINamed.h"
#include "nsIObserverService.h"
#include "StaticPtr.h"
#include "nsIObserver.h"
#include "nsITimer.h"
#include "nsIPropertyBag2.h"
#include "nsComponentManagerUtils.h"
#include "nsCRT.h"
#include "nsTHashSet.h"
#include "nsQueryObject.h"
#include "nsTHashMap.h"

using namespace mozilla;
using namespace mozilla::dom;
using namespace mozilla::hal;

#ifdef XP_WIN
#  include <process.h>
#  define getpid _getpid
#else
#  include <unistd.h>
#endif

#ifdef LOG
#  undef LOG
#endif

// Use LOGP inside a ParticularProcessPriorityManager method; use LOG
// everywhere else.  LOGP prints out information about the particular process
// priority manager.
//
// (Wow, our logging story is a huge mess.)

// #define ENABLE_LOGGING 1

#if defined(ANDROID) && defined(ENABLE_LOGGING)
#  include <android/log.h>
#  define LOG(fmt, ...)                                                        \
    __android_log_print(ANDROID_LOG_INFO, "Gecko:ProcessPriorityManager", fmt, \
                        ##__VA_ARGS__)
#  define LOGP(fmt, ...)                                                \
    __android_log_print(                                                \
        ANDROID_LOG_INFO, "Gecko:ProcessPriorityManager",               \
        "[%schild-id=%" PRIu64 ", pid=%d] " fmt, NameWithComma().get(), \
        static_cast<uint64_t>(ChildID()), Pid(), ##__VA_ARGS__)

#elif defined(ENABLE_LOGGING)
#  define LOG(fmt, ...) \
    printf("ProcessPriorityManager - " fmt "\n", ##__VA_ARGS__)
#  define LOGP(fmt, ...)                                                   \
    printf("ProcessPriorityManager[%schild-id=%" PRIu64 ", pid=%d] - " fmt \
           "\n",                                                           \
           NameWithComma().get(), static_cast<uint64_t>(ChildID()), Pid(), \
           ##__VA_ARGS__)
#else
static LogModule* GetPPMLog() {
  static LazyLogModule sLog("ProcessPriorityManager");
  return sLog;
}
#  define LOG(fmt, ...)                   \
    MOZ_LOG(GetPPMLog(), LogLevel::Debug, \
            ("ProcessPriorityManager - " fmt, ##__VA_ARGS__))
#  define LOGP(fmt, ...)                                                      \
    MOZ_LOG(GetPPMLog(), LogLevel::Debug,                                     \
            ("ProcessPriorityManager[%schild-id=%" PRIu64 ", pid=%d] - " fmt, \
             NameWithComma().get(), static_cast<uint64_t>(ChildID()), Pid(),  \
             ##__VA_ARGS__))
#endif

namespace geckoprofiler::markers {
struct SubProcessPriorityChange {
  static constexpr Span<const char> MarkerTypeName() {
    return MakeStringSpan("subprocessprioritychange");
  }
  static void StreamJSONMarkerData(baseprofiler::SpliceableJSONWriter& aWriter,
                                   int32_t aPid,
                                   const ProfilerString8View& aPreviousPriority,
                                   const ProfilerString8View& aNewPriority) {
    aWriter.IntProperty("pid", aPid);
    aWriter.StringProperty("Before", aPreviousPriority);
    aWriter.StringProperty("After", aNewPriority);
  }
  static MarkerSchema MarkerTypeDisplay() {
    using MS = MarkerSchema;
    MS schema{MS::Location::MarkerChart, MS::Location::MarkerTable};
    schema.AddKeyFormat("pid", MS::Format::Integer);
    schema.AddKeyFormat("Before", MS::Format::String);
    schema.AddKeyFormat("After", MS::Format::String);
    schema.SetAllLabels(
        "priority of child {marker.data.pid}:"
        " {marker.data.Before} -> {marker.data.After}");
    return schema;
  }
};

struct SubProcessPriority {
  static constexpr Span<const char> MarkerTypeName() {
    return MakeStringSpan("subprocesspriority");
  }
  static void StreamJSONMarkerData(baseprofiler::SpliceableJSONWriter& aWriter,
                                   int32_t aPid,
                                   const ProfilerString8View& aPriority,
                                   const ProfilingState& aProfilingState) {
    aWriter.IntProperty("pid", aPid);
    aWriter.StringProperty("Priority", aPriority);
    aWriter.StringProperty("Marker cause",
                           ProfilerString8View::WrapNullTerminatedString(
                               ProfilingStateToString(aProfilingState)));
  }
  static MarkerSchema MarkerTypeDisplay() {
    using MS = MarkerSchema;
    MS schema{MS::Location::MarkerChart, MS::Location::MarkerTable};
    schema.AddKeyFormat("pid", MS::Format::Integer);
    schema.AddKeyFormat("Priority", MS::Format::String);
    schema.AddKeyFormat("Marker cause", MS::Format::String);
    schema.SetAllLabels(
        "priority of child {marker.data.pid}: {marker.data.Priority}");
    return schema;
  }
};
}  // namespace geckoprofiler::markers

namespace {

class ParticularProcessPriorityManager;

/**
 * This singleton class does the work to implement the process priority manager
 * in the main process.  This class may not be used in child processes.  (You
 * can call StaticInit, but it won't do anything, and GetSingleton() will
 * return null.)
 *
 * ProcessPriorityManager::CurrentProcessIsForeground() and
 * ProcessPriorityManager::AnyProcessHasHighPriority() which can be called in
 * any process, are handled separately, by the ProcessPriorityManagerChild
 * class.
 */
class ProcessPriorityManagerImpl final : public nsIObserver,
                                         public nsSupportsWeakReference {
 public:
  /**
   * If we're in the main process, get the ProcessPriorityManagerImpl
   * singleton.  If we're in a child process, return null.
   */
  static ProcessPriorityManagerImpl* GetSingleton();

  static void StaticInit();
  static bool PrefsEnabled();
  static void SetProcessPriorityIfEnabled(int aPid, ProcessPriority aPriority);
  static bool TestMode();

  NS_DECL_ISUPPORTS
  NS_DECL_NSIOBSERVER

  /**
   * This function implements ProcessPriorityManager::SetProcessPriority.
   */
  void SetProcessPriority(ContentParent* aContentParent,
                          ProcessPriority aPriority);

  /**
   * If a magic testing-only pref is set, notify the observer service on the
   * given topic with the given data.  This is used for testing
   */
  void FireTestOnlyObserverNotification(const char* aTopic,
                                        const nsACString& aData);

  /**
   * This must be called by a ParticularProcessPriorityManager when it changes
   * its priority.
   */
  void NotifyProcessPriorityChanged(
      ParticularProcessPriorityManager* aParticularManager,
      hal::ProcessPriority aOldPriority);

  void BrowserPriorityChanged(CanonicalBrowsingContext* aBC, bool aPriority);
  void BrowserPriorityChanged(BrowserParent* aBrowserParent, bool aPriority);

 private:
  static bool sPrefListenersRegistered;
  static bool sInitialized;
  static StaticRefPtr<ProcessPriorityManagerImpl> sSingleton;

  static void PrefChangedCallback(const char* aPref, void* aClosure);

  ProcessPriorityManagerImpl();
  ~ProcessPriorityManagerImpl();
  ProcessPriorityManagerImpl(const ProcessPriorityManagerImpl&) = delete;

  const ProcessPriorityManagerImpl& operator=(
      const ProcessPriorityManagerImpl&) = delete;

  void Init();

  already_AddRefed<ParticularProcessPriorityManager>
  GetParticularProcessPriorityManager(ContentParent* aContentParent);

  void ObserveContentParentDestroyed(nsISupports* aSubject);

  nsTHashMap<uint64_t, RefPtr<ParticularProcessPriorityManager> >
      mParticularManagers;

  /** Contains the PIDs of child processes holding high-priority wakelocks */
  nsTHashSet<uint64_t> mHighPriorityChildIDs;
};

/**
 * This singleton class implements the parts of the process priority manager
 * that are available from all processes.
 */
class ProcessPriorityManagerChild final : public nsIObserver {
 public:
  static void StaticInit();
  static ProcessPriorityManagerChild* Singleton();

  NS_DECL_ISUPPORTS
  NS_DECL_NSIOBSERVER

  bool CurrentProcessIsForeground();

 private:
  static StaticRefPtr<ProcessPriorityManagerChild> sSingleton;

  ProcessPriorityManagerChild();
  ~ProcessPriorityManagerChild() = default;
  ProcessPriorityManagerChild(const ProcessPriorityManagerChild&) = delete;

  const ProcessPriorityManagerChild& operator=(
      const ProcessPriorityManagerChild&) = delete;

  void Init();

  hal::ProcessPriority mCachedPriority;
};

/**
 * This class manages the priority of one particular process.  It is
 * main-process only.
 */
class ParticularProcessPriorityManager final : public WakeLockObserver,
                                               public nsITimerCallback,
                                               public nsINamed,
                                               public nsSupportsWeakReference {
  ~ParticularProcessPriorityManager();

 public:
  explicit ParticularProcessPriorityManager(ContentParent* aContentParent);

  NS_DECL_ISUPPORTS
  NS_DECL_NSITIMERCALLBACK

  virtual void Notify(const WakeLockInformation& aInfo) override;
  void Init();

  int32_t Pid() const;
  uint64_t ChildID() const;

  /**
   * Used in logging, this method returns the ContentParent's name followed by
   * ", ".  If we can't get the ContentParent's name for some reason, it
   * returns an empty string.
   *
   * The reference returned here is guaranteed to be live until the next call
   * to NameWithComma() or until the ParticularProcessPriorityManager is
   * destroyed, whichever comes first.
   */
  const nsAutoCString& NameWithComma();

  ProcessPriority CurrentPriority();
  ProcessPriority ComputePriority();

  enum TimeoutPref {
    BACKGROUND_PERCEIVABLE_GRACE_PERIOD,
    BACKGROUND_GRACE_PERIOD,
  };

  void ScheduleResetPriority(TimeoutPref aTimeoutPref);
  void ResetPriority();
  void ResetPriorityNow();
  void SetPriorityNow(ProcessPriority aPriority);

  void BrowserPriorityChanged(BrowserParent* aBrowserParent, bool aPriority);

  void ShutDown();

  NS_IMETHOD GetName(nsACString& aName) override {
    aName.AssignLiteral("ParticularProcessPriorityManager");
    return NS_OK;
  }

 private:
  void FireTestOnlyObserverNotification(const char* aTopic, const char* aData);

  bool IsHoldingWakeLock(const nsAString& aTopic);

  ContentParent* mContentParent;
  uint64_t mChildID;
  ProcessPriority mPriority;
  bool mHoldsCPUWakeLock;
  bool mHoldsHighPriorityWakeLock;
  bool mHoldsPlayingAudioWakeLock;
  bool mHoldsPlayingVideoWakeLock;

  /**
   * Used to implement NameWithComma().
   */
  nsAutoCString mNameWithComma;

  nsCOMPtr<nsITimer> mResetPriorityTimer;

  // This hashtable contains the list of high priority TabIds for this process.
  nsTHashSet<uint64_t> mHighPriorityBrowserParents;
};

/* static */
bool ProcessPriorityManagerImpl::sInitialized = false;
/* static */
bool ProcessPriorityManagerImpl::sPrefListenersRegistered = false;
/* static */
StaticRefPtr<ProcessPriorityManagerImpl> ProcessPriorityManagerImpl::sSingleton;

NS_IMPL_ISUPPORTS(ProcessPriorityManagerImpl, nsIObserver,
                  nsISupportsWeakReference);

/* static */
void ProcessPriorityManagerImpl::PrefChangedCallback(const char* aPref,
                                                     void* aClosure) {
  StaticInit();
  if (!PrefsEnabled() && sSingleton) {
    sSingleton = nullptr;
    sInitialized = false;
  }
}

/* static */
bool ProcessPriorityManagerImpl::PrefsEnabled() {
  return StaticPrefs::dom_ipc_processPriorityManager_enabled();
}

/* static */
void ProcessPriorityManagerImpl::SetProcessPriorityIfEnabled(
    int aPid, ProcessPriority aPriority) {
  // The preference doesn't disable the process priority manager, but only its
  // effect. This way the IPCs still happen and can be used to collect telemetry
  // about CPU use.
  if (PrefsEnabled()) {
    hal::SetProcessPriority(aPid, aPriority);
  }
}

/* static */
bool ProcessPriorityManagerImpl::TestMode() {
  return StaticPrefs::dom_ipc_processPriorityManager_testMode();
}

/* static */
void ProcessPriorityManagerImpl::StaticInit() {
  if (sInitialized) {
    return;
  }

  // The process priority manager is main-process only.
  if (!XRE_IsParentProcess()) {
    sInitialized = true;
    return;
  }

  // Run StaticInit() again if the pref changes.  We don't expect this to
  // happen in normal operation, but it happens during testing.
  if (!sPrefListenersRegistered) {
    sPrefListenersRegistered = true;
    Preferences::RegisterCallback(PrefChangedCallback,
                                  "dom.ipc.processPriorityManager.enabled");
  }

  sInitialized = true;

  sSingleton = new ProcessPriorityManagerImpl();
  sSingleton->Init();
  ClearOnShutdown(&sSingleton);
}

/* static */
ProcessPriorityManagerImpl* ProcessPriorityManagerImpl::GetSingleton() {
  if (!sSingleton) {
    StaticInit();
  }

  return sSingleton;
}

ProcessPriorityManagerImpl::ProcessPriorityManagerImpl() {
  MOZ_ASSERT(XRE_IsParentProcess());
}

ProcessPriorityManagerImpl::~ProcessPriorityManagerImpl() = default;

void ProcessPriorityManagerImpl::Init() {
  LOG("Starting up.  This is the parent process.");

  // The parent process's priority never changes; set it here and then forget
  // about it. We'll manage only subprocesses' priorities using the process
  // priority manager.
  SetProcessPriorityIfEnabled(getpid(), PROCESS_PRIORITY_PARENT_PROCESS);

  nsCOMPtr<nsIObserverService> os = services::GetObserverService();
  if (os) {
    os->AddObserver(this, "ipc:content-shutdown", /* ownsWeak */ true);
  }
}

NS_IMETHODIMP
ProcessPriorityManagerImpl::Observe(nsISupports* aSubject, const char* aTopic,
                                    const char16_t* aData) {
  nsDependentCString topic(aTopic);
  if (topic.EqualsLiteral("ipc:content-shutdown")) {
    ObserveContentParentDestroyed(aSubject);
  } else {
    MOZ_ASSERT(false);
  }

  return NS_OK;
}

already_AddRefed<ParticularProcessPriorityManager>
ProcessPriorityManagerImpl::GetParticularProcessPriorityManager(
    ContentParent* aContentParent) {
  // If this content parent is already being shut down, there's no
  // need to adjust its priority.
  if (aContentParent->IsDead()) {
    return nullptr;
  }

  const uint64_t cpId = aContentParent->ChildID();
  return mParticularManagers.WithEntryHandle(cpId, [&](auto&& entry) {
    if (!entry) {
      entry.Insert(new ParticularProcessPriorityManager(aContentParent));
      entry.Data()->Init();
    }
    return do_AddRef(entry.Data());
  });
}

void ProcessPriorityManagerImpl::SetProcessPriority(
    ContentParent* aContentParent, ProcessPriority aPriority) {
  MOZ_ASSERT(aContentParent);
  if (RefPtr pppm = GetParticularProcessPriorityManager(aContentParent)) {
    pppm->SetPriorityNow(aPriority);
  }
}

void ProcessPriorityManagerImpl::ObserveContentParentDestroyed(
    nsISupports* aSubject) {
  nsCOMPtr<nsIPropertyBag2> props = do_QueryInterface(aSubject);
  NS_ENSURE_TRUE_VOID(props);

  uint64_t childID = CONTENT_PROCESS_ID_UNKNOWN;
  props->GetPropertyAsUint64(u"childID"_ns, &childID);
  NS_ENSURE_TRUE_VOID(childID != CONTENT_PROCESS_ID_UNKNOWN);

  if (auto entry = mParticularManagers.Lookup(childID)) {
    entry.Data()->ShutDown();
    mHighPriorityChildIDs.Remove(childID);
    entry.Remove();
  }
}

void ProcessPriorityManagerImpl::NotifyProcessPriorityChanged(
    ParticularProcessPriorityManager* aParticularManager,
    ProcessPriority aOldPriority) {
  ProcessPriority newPriority = aParticularManager->CurrentPriority();

  if (newPriority >= PROCESS_PRIORITY_FOREGROUND_HIGH &&
      aOldPriority < PROCESS_PRIORITY_FOREGROUND_HIGH) {
    mHighPriorityChildIDs.Insert(aParticularManager->ChildID());
  } else if (newPriority < PROCESS_PRIORITY_FOREGROUND_HIGH &&
             aOldPriority >= PROCESS_PRIORITY_FOREGROUND_HIGH) {
    mHighPriorityChildIDs.Remove(aParticularManager->ChildID());
  }
}

static nsCString BCToString(dom::CanonicalBrowsingContext* aBC) {
  nsCOMPtr<nsIURI> uri = aBC->GetCurrentURI();
  return nsPrintfCString("id=%" PRIu64 " uri=%s active=%d pactive=%d",
                         aBC->Id(),
                         uri ? uri->GetSpecOrDefault().get() : "(no uri)",
                         aBC->IsActive(), aBC->IsPriorityActive());
}

void ProcessPriorityManagerImpl::BrowserPriorityChanged(
    dom::CanonicalBrowsingContext* aBC, bool aPriority) {
  MOZ_ASSERT(aBC->IsTop());

  LOG("BrowserPriorityChanged(%s, %d)\n", BCToString(aBC).get(), aPriority);

  bool alreadyActive = aBC->IsPriorityActive();
  if (alreadyActive == aPriority) {
    return;
  }

  Telemetry::ScalarAdd(
      Telemetry::ScalarID::DOM_CONTENTPROCESS_OS_PRIORITY_CHANGE_CONSIDERED, 1);

  aBC->SetPriorityActive(aPriority);

  aBC->PreOrderWalk([&](BrowsingContext* aContext) {
    CanonicalBrowsingContext* canonical = aContext->Canonical();
    LOG("PreOrderWalk for %p: %p -> %p, %p\n", aBC, canonical,
        canonical->GetContentParent(), canonical->GetBrowserParent());
    if (ContentParent* cp = canonical->GetContentParent()) {
      if (RefPtr pppm = GetParticularProcessPriorityManager(cp)) {
        if (auto* bp = canonical->GetBrowserParent()) {
          pppm->BrowserPriorityChanged(bp, aPriority);
        }
      }
    }
  });
}

void ProcessPriorityManagerImpl::BrowserPriorityChanged(
    BrowserParent* aBrowserParent, bool aPriority) {
  LOG("BrowserPriorityChanged(bp=%p, %d)\n", aBrowserParent, aPriority);

  if (RefPtr pppm =
          GetParticularProcessPriorityManager(aBrowserParent->Manager())) {
    Telemetry::ScalarAdd(
        Telemetry::ScalarID::DOM_CONTENTPROCESS_OS_PRIORITY_CHANGE_CONSIDERED,
        1);
    pppm->BrowserPriorityChanged(aBrowserParent, aPriority);
  }
}

NS_IMPL_ISUPPORTS(ParticularProcessPriorityManager, nsITimerCallback,
                  nsISupportsWeakReference, nsINamed);

ParticularProcessPriorityManager::ParticularProcessPriorityManager(
    ContentParent* aContentParent)
    : mContentParent(aContentParent),
      mChildID(aContentParent->ChildID()),
      mPriority(PROCESS_PRIORITY_UNKNOWN),
      mHoldsCPUWakeLock(false),
      mHoldsHighPriorityWakeLock(false),
      mHoldsPlayingAudioWakeLock(false),
      mHoldsPlayingVideoWakeLock(false) {
  MOZ_ASSERT(XRE_IsParentProcess());
  MOZ_RELEASE_ASSERT(!aContentParent->IsDead());
  LOGP("Creating ParticularProcessPriorityManager.");
  // Our static analysis doesn't allow capturing ref-counted pointers in
  // lambdas, so we need to hide it in a uintptr_t. This is safe because this
  // lambda will be destroyed in ~ParticularProcessPriorityManager().
  uintptr_t self = reinterpret_cast<uintptr_t>(this);
  profiler_add_state_change_callback(
      AllProfilingStates(),
      [self](ProfilingState aProfilingState) {
        const ParticularProcessPriorityManager* selfPtr =
            reinterpret_cast<const ParticularProcessPriorityManager*>(self);
        PROFILER_MARKER("Subprocess Priority", OTHER,
                        MarkerThreadId::MainThread(), SubProcessPriority,
                        selfPtr->Pid(),
                        ProfilerString8View::WrapNullTerminatedString(
                            ProcessPriorityToString(selfPtr->mPriority)),
                        aProfilingState);
      },
      self);
}

void ParticularProcessPriorityManager::Init() {
  RegisterWakeLockObserver(this);

  // This process may already hold the CPU lock; for example, our parent may
  // have acquired it on our behalf.
  mHoldsCPUWakeLock = IsHoldingWakeLock(u"cpu"_ns);
  mHoldsHighPriorityWakeLock = IsHoldingWakeLock(u"high-priority"_ns);
  mHoldsPlayingAudioWakeLock = IsHoldingWakeLock(u"audio-playing"_ns);
  mHoldsPlayingVideoWakeLock = IsHoldingWakeLock(u"video-playing"_ns);

  LOGP(
      "Done starting up.  mHoldsCPUWakeLock=%d, "
      "mHoldsHighPriorityWakeLock=%d, mHoldsPlayingAudioWakeLock=%d, "
      "mHoldsPlayingVideoWakeLock=%d",
      mHoldsCPUWakeLock, mHoldsHighPriorityWakeLock, mHoldsPlayingAudioWakeLock,
      mHoldsPlayingVideoWakeLock);
}

bool ParticularProcessPriorityManager::IsHoldingWakeLock(
    const nsAString& aTopic) {
  WakeLockInformation info;
  GetWakeLockInfo(aTopic, &info);
  return info.lockingProcesses().Contains(ChildID());
}

ParticularProcessPriorityManager::~ParticularProcessPriorityManager() {
  LOGP("Destroying ParticularProcessPriorityManager.");

  profiler_remove_state_change_callback(reinterpret_cast<uintptr_t>(this));

  ShutDown();
}

/* virtual */
void ParticularProcessPriorityManager::Notify(
    const WakeLockInformation& aInfo) {
  if (!mContentParent) {
    // We've been shut down.
    return;
  }

  bool* dest = nullptr;
  if (aInfo.topic().EqualsLiteral("cpu")) {
    dest = &mHoldsCPUWakeLock;
  } else if (aInfo.topic().EqualsLiteral("high-priority")) {
    dest = &mHoldsHighPriorityWakeLock;
  } else if (aInfo.topic().EqualsLiteral("audio-playing")) {
    dest = &mHoldsPlayingAudioWakeLock;
  } else if (aInfo.topic().EqualsLiteral("video-playing")) {
    dest = &mHoldsPlayingVideoWakeLock;
  }

  if (dest) {
    bool thisProcessLocks = aInfo.lockingProcesses().Contains(ChildID());
    if (thisProcessLocks != *dest) {
      *dest = thisProcessLocks;
      LOGP(
          "Got wake lock changed event. "
          "Now mHoldsCPUWakeLock=%d, mHoldsHighPriorityWakeLock=%d, "
          "mHoldsPlayingAudioWakeLock=%d, mHoldsPlayingVideoWakeLock=%d",
          mHoldsCPUWakeLock, mHoldsHighPriorityWakeLock,
          mHoldsPlayingAudioWakeLock, mHoldsPlayingVideoWakeLock);
      ResetPriority();
    }
  }
}

uint64_t ParticularProcessPriorityManager::ChildID() const {
  // We have to cache mContentParent->ChildID() instead of getting it from the
  // ContentParent each time because after ShutDown() is called, mContentParent
  // is null.  If we didn't cache ChildID(), then we wouldn't be able to run
  // LOGP() after ShutDown().
  return mChildID;
}

int32_t ParticularProcessPriorityManager::Pid() const {
  return mContentParent ? mContentParent->Pid() : -1;
}

const nsAutoCString& ParticularProcessPriorityManager::NameWithComma() {
  mNameWithComma.Truncate();
  if (!mContentParent) {
    return mNameWithComma;  // empty string
  }

  nsAutoString name;
  mContentParent->FriendlyName(name);
  if (name.IsEmpty()) {
    return mNameWithComma;  // empty string
  }

  CopyUTF16toUTF8(name, mNameWithComma);
  mNameWithComma.AppendLiteral(", ");
  return mNameWithComma;
}

void ParticularProcessPriorityManager::ResetPriority() {
  ProcessPriority processPriority = ComputePriority();
  if (mPriority == PROCESS_PRIORITY_UNKNOWN || mPriority > processPriority) {
    // Apps set at a perceivable background priority are often playing media.
    // Most media will have short gaps while changing tracks between songs,
    // switching videos, etc.  Give these apps a longer grace period so they
    // can get their next track started, if there is one, before getting
    // downgraded.
    if (mPriority == PROCESS_PRIORITY_BACKGROUND_PERCEIVABLE) {
      ScheduleResetPriority(BACKGROUND_PERCEIVABLE_GRACE_PERIOD);
    } else {
      ScheduleResetPriority(BACKGROUND_GRACE_PERIOD);
    }
    return;
  }

  SetPriorityNow(processPriority);
}

void ParticularProcessPriorityManager::ResetPriorityNow() {
  SetPriorityNow(ComputePriority());
}

void ParticularProcessPriorityManager::ScheduleResetPriority(
    TimeoutPref aTimeoutPref) {
  if (mResetPriorityTimer) {
    LOGP("ScheduleResetPriority bailing; the timer is already running.");
    return;
  }

  uint32_t timeout = 0;
  switch (aTimeoutPref) {
    case BACKGROUND_PERCEIVABLE_GRACE_PERIOD:
      timeout = StaticPrefs::
          dom_ipc_processPriorityManager_backgroundPerceivableGracePeriodMS();
      break;
    case BACKGROUND_GRACE_PERIOD:
      timeout =
          StaticPrefs::dom_ipc_processPriorityManager_backgroundGracePeriodMS();
      break;
    default:
      MOZ_ASSERT(false, "Unrecognized timeout pref");
      break;
  }

  LOGP("Scheduling reset timer to fire in %dms.", timeout);
  NS_NewTimerWithCallback(getter_AddRefs(mResetPriorityTimer), this, timeout,
                          nsITimer::TYPE_ONE_SHOT);
}

NS_IMETHODIMP
ParticularProcessPriorityManager::Notify(nsITimer* aTimer) {
  LOGP("Reset priority timer callback; about to ResetPriorityNow.");
  ResetPriorityNow();
  mResetPriorityTimer = nullptr;
  return NS_OK;
}

ProcessPriority ParticularProcessPriorityManager::CurrentPriority() {
  return mPriority;
}

ProcessPriority ParticularProcessPriorityManager::ComputePriority() {
  if (!mHighPriorityBrowserParents.IsEmpty() ||
      mContentParent->GetRemoteType() == EXTENSION_REMOTE_TYPE ||
      mHoldsPlayingAudioWakeLock) {
    return PROCESS_PRIORITY_FOREGROUND;
  }

  if (mHoldsCPUWakeLock || mHoldsHighPriorityWakeLock ||
      mHoldsPlayingVideoWakeLock) {
    return PROCESS_PRIORITY_BACKGROUND_PERCEIVABLE;
  }

  return PROCESS_PRIORITY_BACKGROUND;
}

#ifdef XP_MACOSX
// Method used for setting QoS levels on background main threads.
static bool PriorityUsesLowPowerMainThread(
    const hal::ProcessPriority& aPriority) {
  return aPriority == hal::PROCESS_PRIORITY_BACKGROUND ||
         aPriority == hal::PROCESS_PRIORITY_PREALLOC;
}
// Method reduces redundancy in pref check while addressing the edge case
// where a pref is flipped to false during active browser use.
static bool PrefsUseLowPriorityThreads() {
  return StaticPrefs::threads_use_low_power_enabled() &&
         StaticPrefs::threads_lower_mainthread_priority_in_background_enabled();
}
#endif

void ParticularProcessPriorityManager::SetPriorityNow(
    ProcessPriority aPriority) {
  if (aPriority == PROCESS_PRIORITY_UNKNOWN) {
    MOZ_ASSERT(false);
    return;
  }

  LOGP("Changing priority from %s to %s (cp=%p).",
       ProcessPriorityToString(mPriority), ProcessPriorityToString(aPriority),
       mContentParent);

  if (!mContentParent || mPriority == aPriority) {
    return;
  }

  PROFILER_MARKER(
      "Subprocess Priority", OTHER,
      MarkerOptions(MarkerThreadId::MainThread(), MarkerStack::Capture()),
      SubProcessPriorityChange, this->Pid(),
      ProfilerString8View::WrapNullTerminatedString(
          ProcessPriorityToString(mPriority)),
      ProfilerString8View::WrapNullTerminatedString(
          ProcessPriorityToString(aPriority)));

  ProcessPriority oldPriority = mPriority;

  mPriority = aPriority;

  // We skip incrementing the DOM_CONTENTPROCESS_OS_PRIORITY_RAISED if we're
  // transitioning from the PROCESS_PRIORITY_UNKNOWN level, which is where
  // we initialize at.
  if (oldPriority < mPriority && oldPriority != PROCESS_PRIORITY_UNKNOWN) {
    Telemetry::ScalarAdd(
        Telemetry::ScalarID::DOM_CONTENTPROCESS_OS_PRIORITY_RAISED, 1);
  } else if (oldPriority > mPriority) {
    Telemetry::ScalarAdd(
        Telemetry::ScalarID::DOM_CONTENTPROCESS_OS_PRIORITY_LOWERED, 1);
  }

  ProcessPriorityManagerImpl::SetProcessPriorityIfEnabled(Pid(), mPriority);

  if (oldPriority != mPriority) {
    ProcessPriorityManagerImpl::GetSingleton()->NotifyProcessPriorityChanged(
        this, oldPriority);

#ifdef XP_MACOSX
    // In cases where we have low-power threads enabled (such as on MacOS) we
    // can go ahead and put the main thread in the background here. If the new
    // priority is the background priority, we can tell the OS to put the main
    // thread on low-power cores. Alternately, if we are changing from the
    // background to a higher priority, we change the main thread back to its
    // normal state.
    // During shutdown, we will manually set the priority to the highest
    // possible and disallow any additional priority changes.
    //
    // The messages for this will be relayed using the ProcessHangMonitor such
    // that the priority can be raised even if the main thread is unresponsive.
    if (!mContentParent->IsShuttingDown() &&
        PriorityUsesLowPowerMainThread(mPriority) !=
            PriorityUsesLowPowerMainThread(oldPriority)) {
      if (PriorityUsesLowPowerMainThread(mPriority) &&
          PrefsUseLowPriorityThreads()) {
        mContentParent->SetMainThreadQoSPriority(nsIThread::QOS_PRIORITY_LOW);
      } else if (PriorityUsesLowPowerMainThread(oldPriority)) {
        // In the event that the user changes prefs while tabs are in the
        // background, we still want to have the ability to put the main thread
        // back in the foreground to keep tabs from being stuck in the
        // background priority.
        mContentParent->SetMainThreadQoSPriority(
            nsIThread::QOS_PRIORITY_NORMAL);
      }
    }
#endif

    Unused << mContentParent->SendNotifyProcessPriorityChanged(mPriority);
  }

  FireTestOnlyObserverNotification("process-priority-set",
                                   ProcessPriorityToString(mPriority));
}

void ParticularProcessPriorityManager::BrowserPriorityChanged(
    BrowserParent* aBrowserParent, bool aPriority) {
  MOZ_ASSERT(aBrowserParent);

  if (!aPriority) {
    mHighPriorityBrowserParents.Remove(aBrowserParent->GetTabId());
  } else {
    mHighPriorityBrowserParents.Insert(aBrowserParent->GetTabId());
  }

  ResetPriority();
}

void ParticularProcessPriorityManager::ShutDown() {
  LOGP("shutdown for %p (mContentParent %p)", this, mContentParent);

  // Unregister our wake lock observer if ShutDown hasn't been called.  (The
  // wake lock observer takes raw refs, so we don't want to take chances here!)
  // We don't call UnregisterWakeLockObserver unconditionally because the code
  // will print a warning if it's called unnecessarily.
  if (mContentParent) {
    UnregisterWakeLockObserver(this);
  }

  if (mResetPriorityTimer) {
    mResetPriorityTimer->Cancel();
    mResetPriorityTimer = nullptr;
  }

  mContentParent = nullptr;
}

void ProcessPriorityManagerImpl::FireTestOnlyObserverNotification(
    const char* aTopic, const nsACString& aData) {
  if (!TestMode()) {
    return;
  }

  nsCOMPtr<nsIObserverService> os = services::GetObserverService();
  NS_ENSURE_TRUE_VOID(os);

  nsPrintfCString topic("process-priority-manager:TEST-ONLY:%s", aTopic);

  LOG("Notifying observer %s, data %s", topic.get(),
      PromiseFlatCString(aData).get());
  os->NotifyObservers(nullptr, topic.get(), NS_ConvertUTF8toUTF16(aData).get());
}

void ParticularProcessPriorityManager::FireTestOnlyObserverNotification(
    const char* aTopic, const char* aData) {
  MOZ_ASSERT(aData, "Pass in data");

  if (!ProcessPriorityManagerImpl::TestMode()) {
    return;
  }

  nsAutoCString data(nsPrintfCString("%" PRIu64, ChildID()));
  data.Append(':');
  data.AppendASCII(aData);

  // ProcessPriorityManagerImpl::GetSingleton() is guaranteed not to return
  // null, since ProcessPriorityManagerImpl is the only class which creates
  // ParticularProcessPriorityManagers.

  ProcessPriorityManagerImpl::GetSingleton()->FireTestOnlyObserverNotification(
      aTopic, data);
}

StaticRefPtr<ProcessPriorityManagerChild>
    ProcessPriorityManagerChild::sSingleton;

/* static */
void ProcessPriorityManagerChild::StaticInit() {
  if (!sSingleton) {
    sSingleton = new ProcessPriorityManagerChild();
    sSingleton->Init();
    ClearOnShutdown(&sSingleton);
  }
}

/* static */
ProcessPriorityManagerChild* ProcessPriorityManagerChild::Singleton() {
  StaticInit();
  return sSingleton;
}

NS_IMPL_ISUPPORTS(ProcessPriorityManagerChild, nsIObserver)

ProcessPriorityManagerChild::ProcessPriorityManagerChild() {
  if (XRE_IsParentProcess()) {
    mCachedPriority = PROCESS_PRIORITY_PARENT_PROCESS;
  } else {
    mCachedPriority = PROCESS_PRIORITY_UNKNOWN;
  }
}

void ProcessPriorityManagerChild::Init() {
  // The process priority should only be changed in child processes; don't even
  // bother listening for changes if we're in the main process.
  if (!XRE_IsParentProcess()) {
    nsCOMPtr<nsIObserverService> os = services::GetObserverService();
    NS_ENSURE_TRUE_VOID(os);
    os->AddObserver(this, "ipc:process-priority-changed", /* weak = */ false);
  }
}

NS_IMETHODIMP
ProcessPriorityManagerChild::Observe(nsISupports* aSubject, const char* aTopic,
                                     const char16_t* aData) {
  MOZ_ASSERT(!strcmp(aTopic, "ipc:process-priority-changed"));

  nsCOMPtr<nsIPropertyBag2> props = do_QueryInterface(aSubject);
  NS_ENSURE_TRUE(props, NS_OK);

  int32_t priority = static_cast<int32_t>(PROCESS_PRIORITY_UNKNOWN);
  props->GetPropertyAsInt32(u"priority"_ns, &priority);
  NS_ENSURE_TRUE(ProcessPriority(priority) != PROCESS_PRIORITY_UNKNOWN, NS_OK);

  mCachedPriority = static_cast<ProcessPriority>(priority);

  return NS_OK;
}

bool ProcessPriorityManagerChild::CurrentProcessIsForeground() {
  return mCachedPriority == PROCESS_PRIORITY_UNKNOWN ||
         mCachedPriority >= PROCESS_PRIORITY_FOREGROUND;
}

}  // namespace

namespace mozilla {

/* static */
void ProcessPriorityManager::Init() {
  ProcessPriorityManagerImpl::StaticInit();
  ProcessPriorityManagerChild::StaticInit();
}

/* static */
void ProcessPriorityManager::SetProcessPriority(ContentParent* aContentParent,
                                                ProcessPriority aPriority) {
  MOZ_ASSERT(aContentParent);
  MOZ_ASSERT(aContentParent->Pid() != -1);

  ProcessPriorityManagerImpl* singleton =
      ProcessPriorityManagerImpl::GetSingleton();
  if (singleton) {
    singleton->SetProcessPriority(aContentParent, aPriority);
  }
}

/* static */
bool ProcessPriorityManager::CurrentProcessIsForeground() {
  return ProcessPriorityManagerChild::Singleton()->CurrentProcessIsForeground();
}

/* static */
void ProcessPriorityManager::BrowserPriorityChanged(
    CanonicalBrowsingContext* aBC, bool aPriority) {
  if (auto* singleton = ProcessPriorityManagerImpl::GetSingleton()) {
    singleton->BrowserPriorityChanged(aBC, aPriority);
  }
}

/* static */
void ProcessPriorityManager::BrowserPriorityChanged(
    BrowserParent* aBrowserParent, bool aPriority) {
  MOZ_ASSERT(aBrowserParent);

  ProcessPriorityManagerImpl* singleton =
      ProcessPriorityManagerImpl::GetSingleton();
  if (!singleton) {
    return;
  }
  singleton->BrowserPriorityChanged(aBrowserParent, aPriority);
}

}  // namespace mozilla