Debian Codegraph @

apex/jobscheduler/service/java/com/android/server/job/controllers/TareController.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.android.server.job.controllers;
18
19 import static android.app.job.JobInfo.getPriorityString;
20
21 import static com.android.server.job.JobSchedulerService.sElapsedRealtimeClock;
22
23 import android.annotation.NonNull;
24 import android.app.job.JobInfo;
25 import android.util.ArrayMap;
26 import android.util.ArraySet;
27 import android.util.IndentingPrintWriter;
28 import android.util.Log;
29 import android.util.Slog;
30 import android.util.SparseArrayMap;
31
32 import com.android.internal.annotations.GuardedBy;
33 import com.android.server.JobSchedulerBackgroundThread;
34 import com.android.server.LocalServices;
35 import com.android.server.job.JobSchedulerService;
36 import com.android.server.tare.EconomicPolicy;
37 import com.android.server.tare.EconomyManagerInternal;
38 import com.android.server.tare.EconomyManagerInternal.ActionBill;
39 import com.android.server.tare.JobSchedulerEconomicPolicy;
40
41 import java.util.List;
42 import java.util.function.Predicate;
43
44 /**
45 * Controller that interfaces with Tare ({@link EconomyManagerInternal} and manages each job's
46 * ability to run per TARE policies.
47 *
48 * @see JobSchedulerEconomicPolicy
49 */
50 public class TareController extends StateController {
51 private static final String TAG = "JobScheduler.TARE";
52 private static final boolean DEBUG = JobSchedulerService.DEBUG
53 || Log.isLoggable(TAG, Log.DEBUG);
54
55 /**
56 * Bill to use while we're waiting to start a min priority job. If a job isn't running yet,
57 * don't consider it eligible to run unless it can pay for a job start and at least some
58 * period of execution time. We don't want min priority jobs to use up all available credits,
59 * so we make sure to only run them while there are enough credits to run higher priority jobs.
60 */
61 private static final ActionBill BILL_JOB_START_MIN =
62 new ActionBill(List.of(
63 new EconomyManagerInternal.AnticipatedAction(
64 JobSchedulerEconomicPolicy.ACTION_JOB_DEFAULT_START, 1, 0),
65 new EconomyManagerInternal.AnticipatedAction(
66 JobSchedulerEconomicPolicy.ACTION_JOB_DEFAULT_RUNNING, 0, 120_000L)
67 ));
68
69 /**
70 * Bill to use when a min priority job is currently running. We don't want min priority jobs
71 * to use up remaining credits, so we make sure to only run them while there are enough
72 * credits to run higher priority jobs. We stop the job when the app's credits get too low.
73 */
74 private static final ActionBill BILL_JOB_RUNNING_MIN =
75 new ActionBill(List.of(
76 new EconomyManagerInternal.AnticipatedAction(
77 JobSchedulerEconomicPolicy.ACTION_JOB_DEFAULT_RUNNING, 0, 60_000L)
78 ));
79
80 /**
81 * Bill to use while we're waiting to start a low priority job. If a job isn't running yet,
82 * don't consider it eligible to run unless it can pay for a job start and at least some
83 * period of execution time. We don't want low priority jobs to use up all available credits,
84 * so we make sure to only run them while there are enough credits to run higher priority jobs.
85 */
86 private static final ActionBill BILL_JOB_START_LOW =
87 new ActionBill(List.of(
88 new EconomyManagerInternal.AnticipatedAction(
89 JobSchedulerEconomicPolicy.ACTION_JOB_DEFAULT_START, 1, 0),
90 new EconomyManagerInternal.AnticipatedAction(
91 JobSchedulerEconomicPolicy.ACTION_JOB_DEFAULT_RUNNING, 0, 60_000L)
92 ));
93
94 /**
95 * Bill to use when a low priority job is currently running. We don't want low priority jobs
96 * to use up all available credits, so we make sure to only run them while there are enough
97 * credits to run higher priority jobs. We stop the job when the app's credits get too low.
98 */
99 private static final ActionBill BILL_JOB_RUNNING_LOW =
100 new ActionBill(List.of(
101 new EconomyManagerInternal.AnticipatedAction(
102 JobSchedulerEconomicPolicy.ACTION_JOB_DEFAULT_RUNNING, 0, 30_000L)
103 ));
104
105 /**
106 * Bill to use while we're waiting to start a job. If a job isn't running yet, don't consider it
107 * eligible to run unless it can pay for a job start and at least some period of execution time.
108 */
109 private static final ActionBill BILL_JOB_START_DEFAULT =
110 new ActionBill(List.of(
111 new EconomyManagerInternal.AnticipatedAction(
112 JobSchedulerEconomicPolicy.ACTION_JOB_DEFAULT_START, 1, 0),
113 new EconomyManagerInternal.AnticipatedAction(
114 JobSchedulerEconomicPolicy.ACTION_JOB_DEFAULT_RUNNING, 0, 30_000L)
115 ));
116
117 /**
118 * Bill to use when a default priority job is currently running. We want to track and make
119 * sure the app can continue to pay for 1 more second of execution time. We stop the job when
120 * the app can no longer pay for that time.
121 */
122 private static final ActionBill BILL_JOB_RUNNING_DEFAULT =
123 new ActionBill(List.of(
124 new EconomyManagerInternal.AnticipatedAction(
125 JobSchedulerEconomicPolicy.ACTION_JOB_DEFAULT_RUNNING, 0, 1_000L)
126 ));
127
128 /**
129 * Bill to use while we're waiting to start a job. If a job isn't running yet, don't consider it
130 * eligible to run unless it can pay for a job start and at least some period of execution time.
131 */
132 private static final ActionBill BILL_JOB_START_HIGH =
133 new ActionBill(List.of(
134 new EconomyManagerInternal.AnticipatedAction(
135 JobSchedulerEconomicPolicy.ACTION_JOB_HIGH_START, 1, 0),
136 new EconomyManagerInternal.AnticipatedAction(
137 JobSchedulerEconomicPolicy.ACTION_JOB_HIGH_RUNNING, 0, 30_000L)
138 ));
139
140 /**
141 * Bill to use when a high priority job is currently running. We want to track and make sure
142 * the app can continue to pay for 1 more second of execution time. We stop the job when the
143 * app can no longer pay for that time.
144 */
145 private static final ActionBill BILL_JOB_RUNNING_HIGH =
146 new ActionBill(List.of(
147 new EconomyManagerInternal.AnticipatedAction(
148 JobSchedulerEconomicPolicy.ACTION_JOB_HIGH_RUNNING, 0, 1_000L)
149 ));
150
151
152 /**
153 * Bill to use while we're waiting to start a max priority job. This should only be used for
154 * requested-EJs that aren't allowed to run as EJs. If a job isn't running yet, don't consider
155 * it eligible to run unless it can pay for a job start and at least some period of execution
156 * time.
157 */
158 private static final ActionBill BILL_JOB_START_MAX =
159 new ActionBill(List.of(
160 new EconomyManagerInternal.AnticipatedAction(
161 JobSchedulerEconomicPolicy.ACTION_JOB_MAX_START, 1, 0),
162 new EconomyManagerInternal.AnticipatedAction(
163 JobSchedulerEconomicPolicy.ACTION_JOB_MAX_RUNNING, 0, 30_000L)
164 ));
165
166 /**
167 * Bill to use when a max priority job is currently running. This should only be used for
168 * requested-EJs that aren't allowed to run as EJs. We want to track and make sure
169 * the app can continue to pay for 1 more second of execution time. We stop the job when the
170 * app can no longer pay for that time.
171 */
172 private static final ActionBill BILL_JOB_RUNNING_MAX =
173 new ActionBill(List.of(
174 new EconomyManagerInternal.AnticipatedAction(
175 JobSchedulerEconomicPolicy.ACTION_JOB_MAX_RUNNING, 0, 1_000L)
176 ));
177
178 /**
179 * Bill to use while we're waiting to start a job. If a job isn't running yet, don't consider it
180 * eligible to run unless it can pay for a job start and at least some period of execution time.
181 */
182 private static final ActionBill BILL_JOB_START_MAX_EXPEDITED =
183 new ActionBill(List.of(
184 new EconomyManagerInternal.AnticipatedAction(
185 JobSchedulerEconomicPolicy.ACTION_JOB_MAX_START, 1, 0),
186 new EconomyManagerInternal.AnticipatedAction(
187 JobSchedulerEconomicPolicy.ACTION_JOB_MAX_RUNNING, 0, 30_000L)
188 ));
189
190 /**
191 * Bill to use when a max priority EJ is currently running (as an EJ). We want to track and
192 * make sure the app can continue to pay for 1 more second of execution time. We stop the job
193 * when the app can no longer pay for that time.
194 */
195 private static final ActionBill BILL_JOB_RUNNING_MAX_EXPEDITED =
196 new ActionBill(List.of(
197 new EconomyManagerInternal.AnticipatedAction(
198 JobSchedulerEconomicPolicy.ACTION_JOB_MAX_RUNNING, 0, 1_000L)
199 ));
200
201 /**
202 * Bill to use while we're waiting to start a job. If a job isn't running yet, don't consider it
203 * eligible to run unless it can pay for a job start and at least some period of execution time.
204 */
205 private static final ActionBill BILL_JOB_START_HIGH_EXPEDITED =
206 new ActionBill(List.of(
207 new EconomyManagerInternal.AnticipatedAction(
208 JobSchedulerEconomicPolicy.ACTION_JOB_HIGH_START, 1, 0),
209 new EconomyManagerInternal.AnticipatedAction(
210 JobSchedulerEconomicPolicy.ACTION_JOB_HIGH_RUNNING, 0, 30_000L)
211 ));
212
213 /**
214 * Bill to use when a high priority EJ is currently running (as an EJ). We want to track and
215 * make sure the app can continue to pay for 1 more second of execution time. We stop the job
216 * when the app can no longer pay for that time.
217 */
218 private static final ActionBill BILL_JOB_RUNNING_HIGH_EXPEDITED =
219 new ActionBill(List.of(
220 new EconomyManagerInternal.AnticipatedAction(
221 JobSchedulerEconomicPolicy.ACTION_JOB_HIGH_RUNNING, 0, 1_000L)
222 ));
223
224 private final EconomyManagerInternal mEconomyManagerInternal;
225
226 private final BackgroundJobsController mBackgroundJobsController;
227 private final ConnectivityController mConnectivityController;
228
229 /**
230 * Local cache of the ability of each userId-pkg to afford the various bills we're tracking for
231 * them.
232 */
233 @GuardedBy("mLock")
234 private final SparseArrayMap<String, ArrayMap<ActionBill, Boolean>> mAffordabilityCache =
235 new SparseArrayMap<>();
236
237 /**
238 * List of all tracked jobs. Out SparseArrayMap is userId-sourcePkg. The inner mapping is the
239 * anticipated actions and all the jobs that are applicable to them.
240 */
241 @GuardedBy("mLock")
242 private final SparseArrayMap<String, ArrayMap<ActionBill, ArraySet<JobStatus>>>
243 mRegisteredBillsAndJobs = new SparseArrayMap<>();
244
245 private final EconomyManagerInternal.AffordabilityChangeListener mAffordabilityChangeListener =
246 (userId, pkgName, bill, canAfford) -> {
247 final long nowElapsed = sElapsedRealtimeClock.millis();
248 if (DEBUG) {
249 Slog.d(TAG,
250 userId + ":" + pkgName + " affordability for " + getBillName(bill)
251 + " changed to " + canAfford);
252 }
253 synchronized (mLock) {
254 ArrayMap<ActionBill, Boolean> actionAffordability =
255 mAffordabilityCache.get(userId, pkgName);
256 if (actionAffordability == null) {
257 actionAffordability = new ArrayMap<>();
258 mAffordabilityCache.add(userId, pkgName, actionAffordability);
259 }
260 actionAffordability.put(bill, canAfford);
261
262 final ArrayMap<ActionBill, ArraySet<JobStatus>> billToJobMap =
263 mRegisteredBillsAndJobs.get(userId, pkgName);
264 if (billToJobMap != null) {
265 final ArraySet<JobStatus> jobs = billToJobMap.get(bill);
266 if (jobs != null) {
267 final ArraySet<JobStatus> changedJobs = new ArraySet<>();
268 for (int i = 0; i < jobs.size(); ++i) {
269 final JobStatus job = jobs.valueAt(i);
270 // Use hasEnoughWealth if canAfford is false in case the job has
271 // other bills it can depend on (eg. EJs being demoted to
272 // regular jobs).
273 if (job.setTareWealthConstraintSatisfied(nowElapsed,
274 canAfford || hasEnoughWealthLocked(job))) {
275 changedJobs.add(job);
276 }
277 if (job.isRequestedExpeditedJob()
278 && setExpeditedTareApproved(job, nowElapsed,
279 canAffordExpeditedBillLocked(job))) {
280 changedJobs.add(job);
281 }
282 }
283 if (changedJobs.size() > 0) {
284 mStateChangedListener.onControllerStateChanged(changedJobs);
285 }
286 }
287 }
288 }
289 };
290
291 /**
292 * List of jobs that started while the UID was in the TOP state. There will usually be no more
293 * than {@value JobConcurrencyManager#MAX_STANDARD_JOB_CONCURRENCY} running at once, so an
294 * ArraySet is fine.
295 */
296 @GuardedBy("mLock")
297 private final ArraySet<JobStatus> mTopStartedJobs = new ArraySet<>();
298
299 @GuardedBy("mLock")
300 private boolean mIsEnabled;
301
302 public TareController(JobSchedulerService service,
303 @NonNull BackgroundJobsController backgroundJobsController,
304 @NonNull ConnectivityController connectivityController) {
305 super(service);
306 mBackgroundJobsController = backgroundJobsController;
307 mConnectivityController = connectivityController;
308 mEconomyManagerInternal = LocalServices.getService(EconomyManagerInternal.class);
309 mIsEnabled = mConstants.USE_TARE_POLICY;
310 }
311
312 @Override
313 @GuardedBy("mLock")
314 public void maybeStartTrackingJobLocked(JobStatus jobStatus, JobStatus lastJob) {
315 final long nowElapsed = sElapsedRealtimeClock.millis();
316 jobStatus.setTareWealthConstraintSatisfied(nowElapsed, hasEnoughWealthLocked(jobStatus));
317 setExpeditedTareApproved(jobStatus, nowElapsed,
318 jobStatus.isRequestedExpeditedJob() && canAffordExpeditedBillLocked(jobStatus));
319
320 final ArraySet<ActionBill> bills = getPossibleStartBills(jobStatus);
321 for (int i = 0; i < bills.size(); ++i) {
322 addJobToBillList(jobStatus, bills.valueAt(i));
323 }
324 }
325
326 @Override
327 @GuardedBy("mLock")
328 public void prepareForExecutionLocked(JobStatus jobStatus) {
329 final int userId = jobStatus.getSourceUserId();
330 final String pkgName = jobStatus.getSourcePackageName();
331 ArrayMap<ActionBill, ArraySet<JobStatus>> billToJobMap =
332 mRegisteredBillsAndJobs.get(userId, pkgName);
333 if (billToJobMap == null) {
334 Slog.e(TAG, "Job is being prepared but doesn't have a pre-existing billToJobMap");
335 } else {
336 for (int i = 0; i < billToJobMap.size(); ++i) {
337 removeJobFromBillList(jobStatus, billToJobMap.keyAt(i));
338 }
339 }
340 addJobToBillList(jobStatus, getRunningBill(jobStatus));
341
342 final int uid = jobStatus.getSourceUid();
343 if (mService.getUidBias(uid) == JobInfo.BIAS_TOP_APP) {
344 if (DEBUG) {
345 Slog.d(TAG, jobStatus.toShortString() + " is top started job");
346 }
347 mTopStartedJobs.add(jobStatus);
348 // Top jobs won't count towards quota so there's no need to involve the EconomyManager.
349 } else {
350 mEconomyManagerInternal.noteOngoingEventStarted(userId, pkgName,
351 getRunningActionId(jobStatus), String.valueOf(jobStatus.getJobId()));
352 }
353 }
354
355 @Override
356 @GuardedBy("mLock")
357 public void unprepareFromExecutionLocked(JobStatus jobStatus) {
358 final int userId = jobStatus.getSourceUserId();
359 final String pkgName = jobStatus.getSourcePackageName();
360 mEconomyManagerInternal.noteOngoingEventStopped(userId, pkgName,
361 getRunningActionId(jobStatus), String.valueOf(jobStatus.getJobId()));
362 mTopStartedJobs.remove(jobStatus);
363
364 final ArraySet<ActionBill> bills = getPossibleStartBills(jobStatus);
365 ArrayMap<ActionBill, ArraySet<JobStatus>> billToJobMap =
366 mRegisteredBillsAndJobs.get(userId, pkgName);
367 if (billToJobMap == null) {
368 Slog.e(TAG, "Job was just unprepared but didn't have a pre-existing billToJobMap");
369 } else {
370 for (int i = 0; i < billToJobMap.size(); ++i) {
371 removeJobFromBillList(jobStatus, billToJobMap.keyAt(i));
372 }
373 }
374 for (int i = 0; i < bills.size(); ++i) {
375 addJobToBillList(jobStatus, bills.valueAt(i));
376 }
377 }
378
379 @Override
380 @GuardedBy("mLock")
381 public void maybeStopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob,
382 boolean forUpdate) {
383 final int userId = jobStatus.getSourceUserId();
384 final String pkgName = jobStatus.getSourcePackageName();
385 mEconomyManagerInternal.noteOngoingEventStopped(userId, pkgName,
386 getRunningActionId(jobStatus), String.valueOf(jobStatus.getJobId()));
387 mTopStartedJobs.remove(jobStatus);
388 ArrayMap<ActionBill, ArraySet<JobStatus>> billToJobMap =
389 mRegisteredBillsAndJobs.get(userId, pkgName);
390 if (billToJobMap != null) {
391 for (int i = 0; i < billToJobMap.size(); ++i) {
392 removeJobFromBillList(jobStatus, billToJobMap.keyAt(i));
393 }
394 }
395 }
396
397 @Override
398 @GuardedBy("mLock")
399 public void onConstantsUpdatedLocked() {
400 if (mIsEnabled != mConstants.USE_TARE_POLICY) {
401 mIsEnabled = mConstants.USE_TARE_POLICY;
402 // Update job bookkeeping out of band.
403 JobSchedulerBackgroundThread.getHandler().post(() -> {
404 synchronized (mLock) {
405 final long nowElapsed = sElapsedRealtimeClock.millis();
406 mService.getJobStore().forEachJob((jobStatus) -> {
407 if (!mIsEnabled) {
408 jobStatus.setTareWealthConstraintSatisfied(nowElapsed, true);
409 setExpeditedTareApproved(jobStatus, nowElapsed, true);
410 } else {
411 jobStatus.setTareWealthConstraintSatisfied(
412 nowElapsed, hasEnoughWealthLocked(jobStatus));
413 setExpeditedTareApproved(jobStatus, nowElapsed,
414 jobStatus.isRequestedExpeditedJob()
415 && canAffordExpeditedBillLocked(jobStatus));
416 }
417 });
418 }
419 });
420 }
421 }
422
423 @GuardedBy("mLock")
424 public boolean canScheduleEJ(@NonNull JobStatus jobStatus) {
425 if (!mIsEnabled) {
426 return true;
427 }
428 if (jobStatus.getEffectivePriority() == JobInfo.PRIORITY_MAX) {
429 return canAffordBillLocked(jobStatus, BILL_JOB_START_MAX_EXPEDITED);
430 }
431 return canAffordBillLocked(jobStatus, BILL_JOB_START_HIGH_EXPEDITED);
432 }
433
434 /** @return true if the job was started while the app was in the TOP state. */
435 @GuardedBy("mLock")
436 private boolean isTopStartedJobLocked(@NonNull final JobStatus jobStatus) {
437 return mTopStartedJobs.contains(jobStatus);
438 }
439
440 @GuardedBy("mLock")
441 public long getMaxJobExecutionTimeMsLocked(@NonNull JobStatus jobStatus) {
442 if (!mIsEnabled) {
443 return mConstants.RUNTIME_FREE_QUOTA_MAX_LIMIT_MS;
444 }
445 return mEconomyManagerInternal.getMaxDurationMs(
446 jobStatus.getSourceUserId(), jobStatus.getSourcePackageName(),
447 getRunningBill(jobStatus));
448 }
449
450 @GuardedBy("mLock")
451 private void addJobToBillList(@NonNull JobStatus jobStatus, @NonNull ActionBill bill) {
452 final int userId = jobStatus.getSourceUserId();
453 final String pkgName = jobStatus.getSourcePackageName();
454 ArrayMap<ActionBill, ArraySet<JobStatus>> billToJobMap =
455 mRegisteredBillsAndJobs.get(userId, pkgName);
456 if (billToJobMap == null) {
457 billToJobMap = new ArrayMap<>();
458 mRegisteredBillsAndJobs.add(userId, pkgName, billToJobMap);
459 }
460 ArraySet<JobStatus> jobs = billToJobMap.get(bill);
461 if (jobs == null) {
462 jobs = new ArraySet<>();
463 billToJobMap.put(bill, jobs);
464 }
465 if (jobs.add(jobStatus)) {
466 mEconomyManagerInternal.registerAffordabilityChangeListener(userId, pkgName,
467 mAffordabilityChangeListener, bill);
468 }
469 }
470
471 @GuardedBy("mLock")
472 private void removeJobFromBillList(@NonNull JobStatus jobStatus, @NonNull ActionBill bill) {
473 final int userId = jobStatus.getSourceUserId();
474 final String pkgName = jobStatus.getSourcePackageName();
475 final ArrayMap<ActionBill, ArraySet<JobStatus>> billToJobMap =
476 mRegisteredBillsAndJobs.get(userId, pkgName);
477 if (billToJobMap != null) {
478 final ArraySet<JobStatus> jobs = billToJobMap.get(bill);
479 if (jobs == null || (jobs.remove(jobStatus) && jobs.size() == 0)) {
480 mEconomyManagerInternal.unregisterAffordabilityChangeListener(
481 userId, pkgName, mAffordabilityChangeListener, bill);
482 // Remove the cached value so we don't accidentally use it when the app
483 // schedules a new job.
484 final ArrayMap<ActionBill, Boolean> actionAffordability =
485 mAffordabilityCache.get(userId, pkgName);
486 if (actionAffordability != null) {
487 actionAffordability.remove(bill);
488 }
489 }
490 }
491 }
492
493 @NonNull
494 private ArraySet<ActionBill> getPossibleStartBills(JobStatus jobStatus) {
495 // TODO: factor in network cost when available
496 final ArraySet<ActionBill> bills = new ArraySet<>();
497 if (jobStatus.isRequestedExpeditedJob()) {
498 if (jobStatus.getEffectivePriority() == JobInfo.PRIORITY_MAX) {
499 bills.add(BILL_JOB_START_MAX_EXPEDITED);
500 } else {
501 bills.add(BILL_JOB_START_HIGH_EXPEDITED);
502 }
503 }
504 switch (jobStatus.getEffectivePriority()) {
505 case JobInfo.PRIORITY_MAX:
506 bills.add(BILL_JOB_START_MAX);
507 break;
508 case JobInfo.PRIORITY_HIGH:
509 bills.add(BILL_JOB_START_HIGH);
510 break;
511 case JobInfo.PRIORITY_DEFAULT:
512 bills.add(BILL_JOB_START_DEFAULT);
513 break;
514 case JobInfo.PRIORITY_LOW:
515 bills.add(BILL_JOB_START_LOW);
516 break;
517 case JobInfo.PRIORITY_MIN:
518 bills.add(BILL_JOB_START_MIN);
519 break;
520 default:
521 Slog.wtf(TAG, "Unexpected priority: "
522 + JobInfo.getPriorityString(jobStatus.getEffectivePriority()));
523 break;
524 }
525 return bills;
526 }
527
528 @NonNull
529 private ActionBill getRunningBill(JobStatus jobStatus) {
530 // TODO: factor in network cost when available
531 if (jobStatus.shouldTreatAsExpeditedJob() || jobStatus.startedAsExpeditedJob) {
532 if (jobStatus.getEffectivePriority() == JobInfo.PRIORITY_MAX) {
533 return BILL_JOB_RUNNING_MAX_EXPEDITED;
534 } else {
535 return BILL_JOB_RUNNING_HIGH_EXPEDITED;
536 }
537 }
538 switch (jobStatus.getEffectivePriority()) {
539 case JobInfo.PRIORITY_MAX:
540 return BILL_JOB_RUNNING_MAX;
541 case JobInfo.PRIORITY_HIGH:
542 return BILL_JOB_RUNNING_HIGH;
543 case JobInfo.PRIORITY_LOW:
544 return BILL_JOB_RUNNING_LOW;
545 case JobInfo.PRIORITY_MIN:
546 return BILL_JOB_RUNNING_MIN;
547 default:
548 Slog.wtf(TAG, "Got unexpected priority: " + jobStatus.getEffectivePriority());
549 // Intentional fallthrough
550 case JobInfo.PRIORITY_DEFAULT:
551 return BILL_JOB_RUNNING_DEFAULT;
552 }
553 }
554
555 @EconomicPolicy.AppAction
556 private static int getRunningActionId(@NonNull JobStatus job) {
557 switch (job.getEffectivePriority()) {
558 case JobInfo.PRIORITY_MAX:
559 return JobSchedulerEconomicPolicy.ACTION_JOB_MAX_RUNNING;
560 case JobInfo.PRIORITY_HIGH:
561 return JobSchedulerEconomicPolicy.ACTION_JOB_HIGH_RUNNING;
562 case JobInfo.PRIORITY_LOW:
563 return JobSchedulerEconomicPolicy.ACTION_JOB_LOW_RUNNING;
564 case JobInfo.PRIORITY_MIN:
565 return JobSchedulerEconomicPolicy.ACTION_JOB_MIN_RUNNING;
566 default:
567 Slog.wtf(TAG, "Unknown priority: " + getPriorityString(job.getEffectivePriority()));
568 // Intentional fallthrough
569 case JobInfo.PRIORITY_DEFAULT:
570 return JobSchedulerEconomicPolicy.ACTION_JOB_DEFAULT_RUNNING;
571 }
572 }
573
574 @GuardedBy("mLock")
575 private boolean canAffordBillLocked(@NonNull JobStatus jobStatus, @NonNull ActionBill bill) {
576 if (!mIsEnabled) {
577 return true;
578 }
579 if (mService.getUidBias(jobStatus.getSourceUid()) == JobInfo.BIAS_TOP_APP
580 || isTopStartedJobLocked(jobStatus)) {
581 // Jobs for the top app should always be allowed to run, and any jobs started while
582 // the app is on top shouldn't consume any credits.
583 return true;
584 }
585 final int userId = jobStatus.getSourceUserId();
586 final String pkgName = jobStatus.getSourcePackageName();
587 ArrayMap<ActionBill, Boolean> actionAffordability =
588 mAffordabilityCache.get(userId, pkgName);
589 if (actionAffordability == null) {
590 actionAffordability = new ArrayMap<>();
591 mAffordabilityCache.add(userId, pkgName, actionAffordability);
592 }
593
594 if (actionAffordability.containsKey(bill)) {
595 return actionAffordability.get(bill);
596 }
597
598 final boolean canAfford = mEconomyManagerInternal.canPayFor(userId, pkgName, bill);
599 actionAffordability.put(bill, canAfford);
600 return canAfford;
601 }
602
603 @GuardedBy("mLock")
604 private boolean canAffordExpeditedBillLocked(@NonNull JobStatus jobStatus) {
605 if (!mIsEnabled) {
606 return true;
607 }
608 if (!jobStatus.isRequestedExpeditedJob()) {
609 return false;
610 }
611 if (mService.getUidBias(jobStatus.getSourceUid()) == JobInfo.BIAS_TOP_APP
612 || isTopStartedJobLocked(jobStatus)) {
613 // Jobs for the top app should always be allowed to run, and any jobs started while
614 // the app is on top shouldn't consume any credits.
615 return true;
616 }
617 if (mService.isCurrentlyRunningLocked(jobStatus)) {
618 return canAffordBillLocked(jobStatus, getRunningBill(jobStatus));
619 }
620
621 if (jobStatus.getEffectivePriority() == JobInfo.PRIORITY_MAX) {
622 return canAffordBillLocked(jobStatus, BILL_JOB_START_MAX_EXPEDITED);
623 }
624 return canAffordBillLocked(jobStatus, BILL_JOB_START_HIGH_EXPEDITED);
625 }
626
627 @GuardedBy("mLock")
628 private boolean hasEnoughWealthLocked(@NonNull JobStatus jobStatus) {
629 if (!mIsEnabled) {
630 return true;
631 }
632 if (mService.getUidBias(jobStatus.getSourceUid()) == JobInfo.BIAS_TOP_APP
633 || isTopStartedJobLocked(jobStatus)) {
634 // Jobs for the top app should always be allowed to run, and any jobs started while
635 // the app is on top shouldn't consume any credits.
636 return true;
637 }
638 if (mService.isCurrentlyRunningLocked(jobStatus)) {
639 return canAffordBillLocked(jobStatus, getRunningBill(jobStatus));
640 }
641
642 final ArraySet<ActionBill> bills = getPossibleStartBills(jobStatus);
643 for (int i = 0; i < bills.size(); ++i) {
644 ActionBill bill = bills.valueAt(i);
645 if (canAffordBillLocked(jobStatus, bill)) {
646 return true;
647 }
648 }
649 return false;
650 }
651
652 /**
653 * If the satisfaction changes, this will tell connectivity & background jobs controller to
654 * also re-evaluate their state.
655 */
656 private boolean setExpeditedTareApproved(@NonNull JobStatus jobStatus, long nowElapsed,
657 boolean isApproved) {
658 if (jobStatus.setExpeditedJobTareApproved(nowElapsed, isApproved)) {
659 mBackgroundJobsController.evaluateStateLocked(jobStatus);
660 mConnectivityController.evaluateStateLocked(jobStatus);
661 if (isApproved && jobStatus.isReady()) {
662 mStateChangedListener.onRunJobNow(jobStatus);
663 }
664 return true;
665 }
666 return false;
667 }
668
669 @NonNull
670 private String getBillName(@NonNull ActionBill bill) {
671 if (bill.equals(BILL_JOB_START_MAX_EXPEDITED)) {
672 return "EJ_MAX_START_BILL";
673 }
674 if (bill.equals(BILL_JOB_RUNNING_MAX_EXPEDITED)) {
675 return "EJ_MAX_RUNNING_BILL";
676 }
677 if (bill.equals(BILL_JOB_START_HIGH_EXPEDITED)) {
678 return "EJ_HIGH_START_BILL";
679 }
680 if (bill.equals(BILL_JOB_RUNNING_HIGH_EXPEDITED)) {
681 return "EJ_HIGH_RUNNING_BILL";
682 }
683 if (bill.equals(BILL_JOB_START_HIGH)) {
684 return "HIGH_START_BILL";
685 }
686 if (bill.equals(BILL_JOB_RUNNING_HIGH)) {
687 return "HIGH_RUNNING_BILL";
688 }
689 if (bill.equals(BILL_JOB_START_DEFAULT)) {
690 return "DEFAULT_START_BILL";
691 }
692 if (bill.equals(BILL_JOB_RUNNING_DEFAULT)) {
693 return "DEFAULT_RUNNING_BILL";
694 }
695 if (bill.equals(BILL_JOB_START_LOW)) {
696 return "LOW_START_BILL";
697 }
698 if (bill.equals(BILL_JOB_RUNNING_LOW)) {
699 return "LOW_RUNNING_BILL";
700 }
701 if (bill.equals(BILL_JOB_START_MIN)) {
702 return "MIN_START_BILL";
703 }
704 if (bill.equals(BILL_JOB_RUNNING_MIN)) {
705 return "MIN_RUNNING_BILL";
706 }
707 return "UNKNOWN_BILL (" + bill + ")";
708 }
709
710 @Override
711 public void dumpControllerStateLocked(IndentingPrintWriter pw, Predicate<JobStatus> predicate) {
712 pw.print("Is enabled: ");
713 pw.println(mIsEnabled);
714
715 pw.println("Affordability cache:");
716 pw.increaseIndent();
717 mAffordabilityCache.forEach((userId, pkgName, billMap) -> {
718 final int numBills = billMap.size();
719 if (numBills > 0) {
720 pw.print(userId);
721 pw.print(":");
722 pw.print(pkgName);
723 pw.println(":");
724
725 pw.increaseIndent();
726 for (int i = 0; i < numBills; ++i) {
727 pw.print(getBillName(billMap.keyAt(i)));
728 pw.print(": ");
729 pw.println(billMap.valueAt(i));
730 }
731 pw.decreaseIndent();
732 }
733 });
734 pw.decreaseIndent();
735 }
736 }