summaryrefslogtreecommitdiffstats
path: root/ipc/glue/IdleSchedulerParent.cpp
blob: 7f91e9e754b1f21bcc0645abca07f65be2b04d66 (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
/* -*- 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 "mozilla/StaticPrefs_page_load.h"
#include "mozilla/StaticPrefs_javascript.h"
#include "mozilla/Unused.h"
#include "mozilla/ipc/IdleSchedulerParent.h"
#include "mozilla/AppShutdown.h"
#include "mozilla/Telemetry.h"
#include "nsSystemInfo.h"
#include "nsThreadUtils.h"
#include "nsITimer.h"
#include "nsIThread.h"

namespace mozilla::ipc {

base::SharedMemory* IdleSchedulerParent::sActiveChildCounter = nullptr;
std::bitset<NS_IDLE_SCHEDULER_COUNTER_ARRAY_LENGHT>
    IdleSchedulerParent::sInUseChildCounters;
LinkedList<IdleSchedulerParent> IdleSchedulerParent::sIdleAndGCRequests;
int32_t IdleSchedulerParent::sMaxConcurrentIdleTasksInChildProcesses = 1;
uint32_t IdleSchedulerParent::sMaxConcurrentGCs = 1;
uint32_t IdleSchedulerParent::sActiveGCs = 0;
uint32_t IdleSchedulerParent::sChildProcessesRunningPrioritizedOperation = 0;
uint32_t IdleSchedulerParent::sChildProcessesAlive = 0;
nsITimer* IdleSchedulerParent::sStarvationPreventer = nullptr;

uint32_t IdleSchedulerParent::sNumCPUs = 0;
uint32_t IdleSchedulerParent::sPrefConcurrentGCsMax = 0;
uint32_t IdleSchedulerParent::sPrefConcurrentGCsCPUDivisor = 0;

IdleSchedulerParent::IdleSchedulerParent() {
  MOZ_ASSERT(!AppShutdown::IsInOrBeyond(ShutdownPhase::XPCOMShutdownThreads));

  sChildProcessesAlive++;

  uint32_t max_gcs_pref =
      StaticPrefs::javascript_options_concurrent_multiprocess_gcs_max();
  uint32_t cpu_divisor_pref =
      StaticPrefs::javascript_options_concurrent_multiprocess_gcs_cpu_divisor();
  if (!max_gcs_pref) {
    max_gcs_pref = UINT32_MAX;
  }
  if (!cpu_divisor_pref) {
    cpu_divisor_pref = 4;
  }

  if (!sNumCPUs) {
    // While waiting for the real logical core count behave as if there was
    // just one core.
    sNumCPUs = 1;

    // nsISystemInfo can be initialized only on the main thread.
    nsCOMPtr<nsIThread> thread = do_GetCurrentThread();
    nsCOMPtr<nsIRunnable> runnable =
        NS_NewRunnableFunction("cpucount getter", [thread]() {
          ProcessInfo processInfo = {};
          if (NS_SUCCEEDED(CollectProcessInfo(processInfo))) {
            uint32_t num_cpus = processInfo.cpuCount;
            // We have a new cpu count, Update the number of idle tasks.
            if (MOZ_LIKELY(!AppShutdown::IsInOrBeyond(
                    ShutdownPhase::XPCOMShutdownThreads))) {
              nsCOMPtr<nsIRunnable> runnable = NS_NewRunnableFunction(
                  "IdleSchedulerParent::CalculateNumIdleTasks", [num_cpus]() {
                    // We're setting this within this lambda because it's run on
                    // the correct thread and avoids a race.
                    sNumCPUs = num_cpus;

                    // This reads the sPrefConcurrentGCsMax and
                    // sPrefConcurrentGCsCPUDivisor values set below, it will
                    // run after the code that sets those.
                    CalculateNumIdleTasks();
                  });

              thread->Dispatch(runnable, NS_DISPATCH_NORMAL);
            }
          }
        });
    NS_DispatchBackgroundTask(runnable.forget(), NS_DISPATCH_EVENT_MAY_BLOCK);
  }

  if (sPrefConcurrentGCsMax != max_gcs_pref ||
      sPrefConcurrentGCsCPUDivisor != cpu_divisor_pref) {
    // We execute this if these preferences have changed. We also want to make
    // sure it executes for the first IdleSchedulerParent, which it does because
    // sPrefConcurrentGCsMax and sPrefConcurrentGCsCPUDivisor are initially
    // zero.
    sPrefConcurrentGCsMax = max_gcs_pref;
    sPrefConcurrentGCsCPUDivisor = cpu_divisor_pref;

    CalculateNumIdleTasks();
  }
}

void IdleSchedulerParent::CalculateNumIdleTasks() {
  MOZ_ASSERT(sNumCPUs);
  MOZ_ASSERT(sPrefConcurrentGCsMax);
  MOZ_ASSERT(sPrefConcurrentGCsCPUDivisor);

  // On one and two processor (or hardware thread) systems this will
  // allow one concurrent idle task.
  sMaxConcurrentIdleTasksInChildProcesses = int32_t(std::max(sNumCPUs, 1u));
  sMaxConcurrentGCs =
      std::min(std::max(sNumCPUs / sPrefConcurrentGCsCPUDivisor, 1u),
               sPrefConcurrentGCsMax);

  if (sActiveChildCounter && sActiveChildCounter->memory()) {
    static_cast<Atomic<int32_t>*>(
        sActiveChildCounter->memory())[NS_IDLE_SCHEDULER_INDEX_OF_CPU_COUNTER] =
        static_cast<int32_t>(sMaxConcurrentIdleTasksInChildProcesses);
  }
  IdleSchedulerParent::Schedule(nullptr);
}

IdleSchedulerParent::~IdleSchedulerParent() {
  // We can't know if an active process just crashed, so we just always expect
  // that is the case.
  if (mChildId) {
    sInUseChildCounters[mChildId] = false;
    if (sActiveChildCounter && sActiveChildCounter->memory() &&
        static_cast<Atomic<int32_t>*>(
            sActiveChildCounter->memory())[mChildId]) {
      --static_cast<Atomic<int32_t>*>(
          sActiveChildCounter
              ->memory())[NS_IDLE_SCHEDULER_INDEX_OF_ACTIVITY_COUNTER];
      static_cast<Atomic<int32_t>*>(sActiveChildCounter->memory())[mChildId] =
          0;
    }
  }

  if (mRunningPrioritizedOperation) {
    --sChildProcessesRunningPrioritizedOperation;
  }

  if (mDoingGC) {
    // Give back our GC token.
    sActiveGCs--;
  }

  if (mRequestingGC) {
    mRequestingGC.value()(false);
    mRequestingGC = Nothing();
  }

  // Remove from the scheduler's queue.
  if (isInList()) {
    remove();
  }

  MOZ_ASSERT(sChildProcessesAlive > 0);
  sChildProcessesAlive--;
  if (sChildProcessesAlive == 0) {
    MOZ_ASSERT(sIdleAndGCRequests.isEmpty());
    delete sActiveChildCounter;
    sActiveChildCounter = nullptr;

    if (sStarvationPreventer) {
      sStarvationPreventer->Cancel();
      NS_RELEASE(sStarvationPreventer);
    }
  }

  Schedule(nullptr);
}

IPCResult IdleSchedulerParent::RecvInitForIdleUse(
    InitForIdleUseResolver&& aResolve) {
  // This must already be non-zero, if it is zero then the cleanup code for the
  // shared memory (initialised below) will never run.  The invariant is that if
  // the shared memory is initialsed, then this is non-zero.
  MOZ_ASSERT(sChildProcessesAlive > 0);

  MOZ_ASSERT(IsNotDoingIdleTask());

  // Create a shared memory object which is shared across all the relevant
  // processes.
  if (!sActiveChildCounter) {
    sActiveChildCounter = new base::SharedMemory();
    size_t shmemSize = NS_IDLE_SCHEDULER_COUNTER_ARRAY_LENGHT * sizeof(int32_t);
    if (sActiveChildCounter->Create(shmemSize) &&
        sActiveChildCounter->Map(shmemSize)) {
      memset(sActiveChildCounter->memory(), 0, shmemSize);
      sInUseChildCounters[NS_IDLE_SCHEDULER_INDEX_OF_ACTIVITY_COUNTER] = true;
      sInUseChildCounters[NS_IDLE_SCHEDULER_INDEX_OF_CPU_COUNTER] = true;
      static_cast<Atomic<int32_t>*>(
          sActiveChildCounter
              ->memory())[NS_IDLE_SCHEDULER_INDEX_OF_CPU_COUNTER] =
          static_cast<int32_t>(sMaxConcurrentIdleTasksInChildProcesses);
    } else {
      delete sActiveChildCounter;
      sActiveChildCounter = nullptr;
    }
  }
  Maybe<SharedMemoryHandle> activeCounter;
  if (SharedMemoryHandle handle =
          sActiveChildCounter ? sActiveChildCounter->CloneHandle() : nullptr) {
    activeCounter.emplace(std::move(handle));
  }

  uint32_t unusedId = 0;
  for (uint32_t i = 0; i < NS_IDLE_SCHEDULER_COUNTER_ARRAY_LENGHT; ++i) {
    if (!sInUseChildCounters[i]) {
      sInUseChildCounters[i] = true;
      unusedId = i;
      break;
    }
  }

  // If there wasn't an empty item, we'll fallback to 0.
  mChildId = unusedId;

  aResolve(std::tuple<mozilla::Maybe<SharedMemoryHandle>&&, const uint32_t&>(
      std::move(activeCounter), mChildId));
  return IPC_OK();
}

IPCResult IdleSchedulerParent::RecvRequestIdleTime(uint64_t aId,
                                                   TimeDuration aBudget) {
  MOZ_ASSERT(aBudget);
  MOZ_ASSERT(IsNotDoingIdleTask());

  mCurrentRequestId = aId;
  mRequestedIdleBudget = aBudget;

  if (!isInList()) {
    sIdleAndGCRequests.insertBack(this);
  }

  Schedule(this);
  return IPC_OK();
}

IPCResult IdleSchedulerParent::RecvIdleTimeUsed(uint64_t aId) {
  // The client can either signal that they've used the idle time or they're
  // canceling the request.  We cannot use a seperate cancel message because it
  // could arrive after the parent has granted the request.
  MOZ_ASSERT(IsWaitingForIdle() || IsDoingIdleTask());

  // The parent process will always know the ID of the current request (since
  // the IPC channel is reliable).  The IDs are provided so that the client can
  // check them (it's possible for the client to race ahead of the server).
  MOZ_ASSERT(mCurrentRequestId == aId);

  if (IsWaitingForIdle() && !mRequestingGC) {
    remove();
  }
  mRequestedIdleBudget = TimeDuration();
  Schedule(nullptr);
  return IPC_OK();
}

IPCResult IdleSchedulerParent::RecvSchedule() {
  Schedule(nullptr);
  return IPC_OK();
}

IPCResult IdleSchedulerParent::RecvRunningPrioritizedOperation() {
  ++mRunningPrioritizedOperation;
  if (mRunningPrioritizedOperation == 1) {
    ++sChildProcessesRunningPrioritizedOperation;
  }
  return IPC_OK();
}

IPCResult IdleSchedulerParent::RecvPrioritizedOperationDone() {
  MOZ_ASSERT(mRunningPrioritizedOperation);

  --mRunningPrioritizedOperation;
  if (mRunningPrioritizedOperation == 0) {
    --sChildProcessesRunningPrioritizedOperation;
    Schedule(nullptr);
  }
  return IPC_OK();
}

IPCResult IdleSchedulerParent::RecvRequestGC(RequestGCResolver&& aResolver) {
  MOZ_ASSERT(!mDoingGC);
  MOZ_ASSERT(!mRequestingGC);

  mRequestingGC = Some(aResolver);
  if (!isInList()) {
    sIdleAndGCRequests.insertBack(this);
  }

  Schedule(nullptr);
  return IPC_OK();
}

IPCResult IdleSchedulerParent::RecvStartedGC() {
  if (mDoingGC) {
    return IPC_OK();
  }

  mDoingGC = true;
  sActiveGCs++;

  if (mRequestingGC) {
    // We have to respond to the request before dropping it, even though the
    // content process is already doing the GC.
    mRequestingGC.value()(true);
    mRequestingGC = Nothing();
    if (!IsWaitingForIdle()) {
      remove();
    }
  }

  return IPC_OK();
}

IPCResult IdleSchedulerParent::RecvDoneGC() {
  MOZ_ASSERT(mDoingGC);
  sActiveGCs--;
  mDoingGC = false;
  Schedule(nullptr);
  return IPC_OK();
}

int32_t IdleSchedulerParent::ActiveCount() {
  if (sActiveChildCounter) {
    return (static_cast<Atomic<int32_t>*>(
        sActiveChildCounter
            ->memory())[NS_IDLE_SCHEDULER_INDEX_OF_ACTIVITY_COUNTER]);
  }
  return 0;
}

bool IdleSchedulerParent::HasSpareCycles(int32_t aActiveCount) {
  // We can run a new task if we have a spare core.  If we're running a
  // prioritised operation we halve the number of regular spare cores.
  //
  // sMaxConcurrentIdleTasksInChildProcesses will always be >0 so on 1 and 2
  // core systems this will allow 1 idle tasks (0 if running a prioritized
  // operation).
  MOZ_ASSERT(sMaxConcurrentIdleTasksInChildProcesses > 0);
  return sChildProcessesRunningPrioritizedOperation
             ? sMaxConcurrentIdleTasksInChildProcesses / 2 > aActiveCount
             : sMaxConcurrentIdleTasksInChildProcesses > aActiveCount;
}

bool IdleSchedulerParent::HasSpareGCCycles() {
  return sMaxConcurrentGCs > sActiveGCs;
}

void IdleSchedulerParent::SendIdleTime() {
  // We would assert that IsWaitingForIdle() except after potentially removing
  // the task from it's list this will return false.  Instead check
  // mRequestedIdleBudget.
  MOZ_ASSERT(mRequestedIdleBudget);
  Unused << SendIdleTime(mCurrentRequestId, mRequestedIdleBudget);
}

void IdleSchedulerParent::SendMayGC() {
  MOZ_ASSERT(mRequestingGC);
  mRequestingGC.value()(true);
  mRequestingGC = Nothing();
  mDoingGC = true;
  sActiveGCs++;
}

void IdleSchedulerParent::Schedule(IdleSchedulerParent* aRequester) {
  // Tasks won't update the active count until after they receive their message
  // and start to run, so make a copy of it here and increment it for every task
  // we schedule. It will become an estimate of how many tasks will be active
  // shortly.
  int32_t activeCount = ActiveCount();

  if (aRequester && aRequester->mRunningPrioritizedOperation) {
    // Prioritised operations are requested only for idle time requests, so this
    // must be an idle time request.
    MOZ_ASSERT(aRequester->IsWaitingForIdle());

    // If the requester is prioritized, just let it run itself.
    if (aRequester->isInList() && !aRequester->mRequestingGC) {
      aRequester->remove();
    }
    aRequester->SendIdleTime();
    activeCount++;
  }

  RefPtr<IdleSchedulerParent> idleRequester = sIdleAndGCRequests.getFirst();

  bool has_spare_cycles = HasSpareCycles(activeCount);
  bool has_spare_gc_cycles = HasSpareGCCycles();

  while (idleRequester && (has_spare_cycles || has_spare_gc_cycles)) {
    // Get the next element before potentially removing the current one from the
    // list.
    RefPtr<IdleSchedulerParent> next = idleRequester->getNext();

    if (has_spare_cycles && idleRequester->IsWaitingForIdle()) {
      // We can run an idle task.
      activeCount++;
      if (!idleRequester->mRequestingGC) {
        idleRequester->remove();
      }
      idleRequester->SendIdleTime();
      has_spare_cycles = HasSpareCycles(activeCount);
    }

    if (has_spare_gc_cycles && idleRequester->mRequestingGC) {
      if (!idleRequester->IsWaitingForIdle()) {
        idleRequester->remove();
      }
      idleRequester->SendMayGC();
      has_spare_gc_cycles = HasSpareGCCycles();
    }

    idleRequester = next;
  }

  if (!sIdleAndGCRequests.isEmpty() && HasSpareCycles(activeCount)) {
    EnsureStarvationTimer();
  }
}

void IdleSchedulerParent::EnsureStarvationTimer() {
  // Even though idle runnables aren't really guaranteed to get run ever (which
  // is why most of them have the timer fallback), try to not let any child
  // process' idle handling to starve forever in case other processes are busy
  if (!sStarvationPreventer) {
    // Reuse StaticPrefs::page_load_deprioritization_period(), since that
    // is used on child side when deciding the minimum idle period.
    NS_NewTimerWithFuncCallback(
        &sStarvationPreventer, StarvationCallback, nullptr,
        StaticPrefs::page_load_deprioritization_period(),
        nsITimer::TYPE_ONE_SHOT_LOW_PRIORITY, "StarvationCallback");
  }
}

void IdleSchedulerParent::StarvationCallback(nsITimer* aTimer, void* aData) {
  RefPtr<IdleSchedulerParent> idleRequester = sIdleAndGCRequests.getFirst();
  while (idleRequester) {
    if (idleRequester->IsWaitingForIdle()) {
      // Treat the first process waiting for idle time as running prioritized
      // operation so that it gets run.
      ++idleRequester->mRunningPrioritizedOperation;
      ++sChildProcessesRunningPrioritizedOperation;
      Schedule(idleRequester);
      --idleRequester->mRunningPrioritizedOperation;
      --sChildProcessesRunningPrioritizedOperation;
      break;
    }

    idleRequester = idleRequester->getNext();
  }
  NS_RELEASE(sStarvationPreventer);
}

}  // namespace mozilla::ipc