blob: 2464ca782b6e912b63269ea2daab729f61c6a38d [file] [log] [blame]
Christopher Tate7060b042014-06-09 19:50:00 -07001/*
2 * Copyright (C) 2014 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
17package com.android.server.job;
18
Christopher Tateb5c07882016-05-26 17:11:09 -070019import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
20import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
21
Christopher Tate435c2f42018-01-18 12:59:15 -080022import android.annotation.UserIdInt;
Christopher Tateee7805b2016-07-15 16:56:56 -070023import android.app.Activity;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070024import android.app.ActivityManager;
Makoto Onuki15407842018-01-19 14:23:11 -080025import android.app.ActivityManagerInternal;
Christopher Tated1aebb32018-01-31 13:24:14 -080026import android.app.AlarmManager;
Christopher Tate5568f542014-06-18 13:53:31 -070027import android.app.AppGlobals;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070028import android.app.IUidObserver;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070029import android.app.job.IJobScheduler;
Christopher Tate7060b042014-06-09 19:50:00 -070030import android.app.job.JobInfo;
Shreyas Basarge5db09082016-01-07 13:38:29 +000031import android.app.job.JobParameters;
Tej Singh33a412b2018-03-16 18:43:59 -070032import android.app.job.JobProtoEnums;
Christopher Tate7060b042014-06-09 19:50:00 -070033import android.app.job.JobScheduler;
34import android.app.job.JobService;
Serik Beketayev75915d12018-08-01 16:56:59 -070035import android.app.job.JobSnapshot;
Dianne Hackborn7da13d72017-04-04 17:17:35 -070036import android.app.job.JobWorkItem;
Amith Yamasaniafbccb72017-11-27 10:44:24 -080037import android.app.usage.UsageStatsManager;
Christopher Tatea732f012017-10-26 17:26:53 -070038import android.app.usage.UsageStatsManagerInternal;
39import android.app.usage.UsageStatsManagerInternal.AppIdleStateChangeListener;
Christopher Tate7060b042014-06-09 19:50:00 -070040import android.content.BroadcastReceiver;
41import android.content.ComponentName;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070042import android.content.ContentResolver;
Christopher Tate7060b042014-06-09 19:50:00 -070043import android.content.Context;
44import android.content.Intent;
45import android.content.IntentFilter;
Christopher Tate5568f542014-06-18 13:53:31 -070046import android.content.pm.IPackageManager;
Christopher Tate7060b042014-06-09 19:50:00 -070047import android.content.pm.PackageManager;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -060048import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey01bb5302018-02-21 20:12:40 -070049import android.content.pm.PackageManagerInternal;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070050import android.content.pm.ServiceInfo;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070051import android.database.ContentObserver;
Christopher Tateb5c07882016-05-26 17:11:09 -070052import android.net.Uri;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070053import android.os.BatteryStats;
Amith Yamasani977e11f2018-02-16 11:29:54 -080054import android.os.BatteryStatsInternal;
Christopher Tate7060b042014-06-09 19:50:00 -070055import android.os.Binder;
56import android.os.Handler;
Wei Wang8c0c3c12018-11-14 14:56:52 -080057import android.os.IThermalService;
58import android.os.IThermalStatusListener;
Christopher Tate7060b042014-06-09 19:50:00 -070059import android.os.Looper;
60import android.os.Message;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070061import android.os.Process;
Christopher Tate7060b042014-06-09 19:50:00 -070062import android.os.RemoteException;
Christopher Tate5d346052016-03-08 12:56:08 -080063import android.os.ResultReceiver;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070064import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -070065import android.os.ShellCallback;
Christopher Tate7060b042014-06-09 19:50:00 -070066import android.os.SystemClock;
Wei Wang8c0c3c12018-11-14 14:56:52 -080067import android.os.Temperature;
Christopher Tate7060b042014-06-09 19:50:00 -070068import android.os.UserHandle;
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -070069import android.os.UserManagerInternal;
Kweku Adamsbffea5a2018-12-13 22:13:28 -080070import android.os.WorkSource;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070071import android.provider.Settings;
Amith Yamasani977e11f2018-02-16 11:29:54 -080072import android.text.format.DateUtils;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070073import android.util.KeyValueListParser;
Jeff Sharkey01bb5302018-02-21 20:12:40 -070074import android.util.Log;
Christopher Tate7060b042014-06-09 19:50:00 -070075import android.util.Slog;
76import android.util.SparseArray;
Dianne Hackborn970510b2016-02-24 16:56:42 -080077import android.util.SparseIntArray;
Tej Singhd5747a62018-01-08 20:57:35 -080078import android.util.StatsLog;
Dianne Hackborn970510b2016-02-24 16:56:42 -080079import android.util.TimeUtils;
Kweku Adams85f2fbc2017-12-18 12:04:12 -080080import android.util.proto.ProtoOutputStream;
Christopher Tate5d346052016-03-08 12:56:08 -080081
Wei Wang8c0c3c12018-11-14 14:56:52 -080082import com.android.internal.annotations.GuardedBy;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070083import com.android.internal.annotations.VisibleForTesting;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070084import com.android.internal.app.IBatteryStats;
Jeff Sharkey822cbd12016-02-25 11:09:55 -070085import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060086import com.android.internal.util.DumpUtils;
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -070087import com.android.internal.util.IndentingPrintWriter;
Makoto Onuki15407842018-01-19 14:23:11 -080088import com.android.internal.util.Preconditions;
Jeff Sharkey01bb5302018-02-21 20:12:40 -070089import com.android.server.AppStateTracker;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080090import com.android.server.DeviceIdleController;
Christopher Tate616541d2017-07-26 14:27:38 -070091import com.android.server.FgThread;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080092import com.android.server.LocalServices;
Kweku Adams85f2fbc2017-12-18 12:04:12 -080093import com.android.server.job.JobSchedulerServiceDumpProto.ActiveJob;
94import com.android.server.job.JobSchedulerServiceDumpProto.PendingJob;
Makoto Onukib5d5e972018-02-20 14:44:20 -080095import com.android.server.job.JobSchedulerServiceDumpProto.RegisteredJob;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070096import com.android.server.job.controllers.BackgroundJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070097import com.android.server.job.controllers.BatteryController;
98import com.android.server.job.controllers.ConnectivityController;
Dianne Hackborn1a30bd92016-01-11 11:05:00 -080099import com.android.server.job.controllers.ContentObserverController;
Amith Yamasanicb926fc2016-03-14 17:15:20 -0700100import com.android.server.job.controllers.DeviceIdleJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -0700101import com.android.server.job.controllers.IdleController;
102import com.android.server.job.controllers.JobStatus;
Kweku Adams4836f9d2018-11-12 17:04:17 -0800103import com.android.server.job.controllers.QuotaController;
Christopher Tate7060b042014-06-09 19:50:00 -0700104import com.android.server.job.controllers.StateController;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700105import com.android.server.job.controllers.StorageController;
Christopher Tate7060b042014-06-09 19:50:00 -0700106import com.android.server.job.controllers.TimeController;
107
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700108import libcore.util.EmptyArray;
109
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700110import java.io.FileDescriptor;
111import java.io.PrintWriter;
112import java.time.Clock;
113import java.util.ArrayList;
114import java.util.Arrays;
115import java.util.Collections;
116import java.util.Comparator;
Christopher Tate325768c2018-03-07 16:07:56 -0800117import java.util.HashMap;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700118import java.util.List;
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -0700119import java.util.function.Consumer;
Makoto Onuki15407842018-01-19 14:23:11 -0800120import java.util.function.Predicate;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700121
Christopher Tate7060b042014-06-09 19:50:00 -0700122/**
123 * Responsible for taking jobs representing work to be performed by a client app, and determining
124 * based on the criteria specified when that job should be run against the client application's
125 * endpoint.
126 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
127 * about constraints, or the state of active jobs. It receives callbacks from the various
128 * controllers and completed jobs and operates accordingly.
129 *
130 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
131 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
132 * @hide
133 */
Jeff Sharkey4d89e422018-03-29 18:22:41 -0600134public class JobSchedulerService extends com.android.server.SystemService
Matthew Williams01ac45b2014-07-22 20:44:12 -0700135 implements StateChangedListener, JobCompletedListener {
Jeff Sharkey01bb5302018-02-21 20:12:40 -0700136 public static final String TAG = "JobScheduler";
137 public static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Christopher Tatea732f012017-10-26 17:26:53 -0700138 public static final boolean DEBUG_STANDBY = DEBUG || false;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800139
Dianne Hackborn970510b2016-02-24 16:56:42 -0800140 /** The maximum number of concurrent jobs we run at one time. */
Makoto Onuki714f97d2018-12-05 11:18:13 -0800141 static final int MAX_JOB_CONTEXTS_COUNT = 16;
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800142 /** Enforce a per-app limit on scheduled jobs? */
Christopher Tate0213ace02016-02-24 14:18:35 -0800143 private static final boolean ENFORCE_MAX_JOBS = true;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800144 /** The maximum number of jobs that we allow an unprivileged app to schedule */
145 private static final int MAX_JOBS_PER_APP = 100;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700146
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700147 @VisibleForTesting
148 public static Clock sSystemClock = Clock.systemUTC();
149 @VisibleForTesting
150 public static Clock sUptimeMillisClock = SystemClock.uptimeMillisClock();
151 @VisibleForTesting
152 public static Clock sElapsedRealtimeClock = SystemClock.elapsedRealtimeClock();
Christopher Tate2f36fd62016-02-18 18:36:08 -0800153
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800154 /** Global local for all job scheduler state. */
155 final Object mLock = new Object();
Christopher Tate7060b042014-06-09 19:50:00 -0700156 /** Master list of jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700157 final JobStore mJobs;
Christopher Tatea732f012017-10-26 17:26:53 -0700158 /** Tracking the standby bucket state of each app */
159 final StandbyTracker mStandbyTracker;
Dianne Hackborn807de782016-04-07 17:54:41 -0700160 /** Tracking amount of time each package runs for. */
161 final JobPackageTracker mJobPackageTracker = new JobPackageTracker();
Makoto Onuki714f97d2018-12-05 11:18:13 -0800162 final JobConcurrencyManager mConcurrencyManager;
Christopher Tate7060b042014-06-09 19:50:00 -0700163
164 static final int MSG_JOB_EXPIRED = 0;
165 static final int MSG_CHECK_JOB = 1;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700166 static final int MSG_STOP_JOB = 2;
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000167 static final int MSG_CHECK_JOB_GREEDY = 3;
Makoto Onuki743e0ad2018-02-20 16:01:11 -0800168 static final int MSG_UID_STATE_CHANGED = 4;
169 static final int MSG_UID_GONE = 5;
170 static final int MSG_UID_ACTIVE = 6;
171 static final int MSG_UID_IDLE = 7;
Christopher Tate7060b042014-06-09 19:50:00 -0700172
Christopher Tate7060b042014-06-09 19:50:00 -0700173 /**
174 * Track Services that have currently active or pending jobs. The index is provided by
175 * {@link JobStatus#getServiceToken()}
176 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700177 final List<JobServiceContext> mActiveServices = new ArrayList<>();
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700178
Christopher Tate7060b042014-06-09 19:50:00 -0700179 /** List of controllers that will notify this service of updates to jobs. */
Makoto Onuki714f97d2018-12-05 11:18:13 -0800180 final List<StateController> mControllers;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800181 /** Need direct access to this for testing. */
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700182 private final BatteryController mBatteryController;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700183 /** Need direct access to this for testing. */
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700184 private final StorageController mStorageController;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700185 /** Need directly for sending uid state changes */
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700186 private final DeviceIdleJobsController mDeviceIdleJobsController;
Wei Wang8c0c3c12018-11-14 14:56:52 -0800187 /** Need directly for receiving thermal events */
188 private IThermalService mThermalService;
189 /** Thermal constraint. */
190 @GuardedBy("mLock")
191 private boolean mThermalConstraint = false;
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700192
Christopher Tate7060b042014-06-09 19:50:00 -0700193 /**
194 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
195 * when ready to execute them.
196 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700197 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700198
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700199 int[] mStartedUsers = EmptyArray.INT;
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700200
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700201 final JobHandler mHandler;
202 final JobSchedulerStub mJobSchedulerStub;
203
Christopher Tatea732f012017-10-26 17:26:53 -0700204 PackageManagerInternal mLocalPM;
Makoto Onuki15407842018-01-19 14:23:11 -0800205 ActivityManagerInternal mActivityManagerInternal;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700206 IBatteryStats mBatteryStats;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800207 DeviceIdleController.LocalService mLocalDeviceIdleController;
Makoto Onukie4918212018-02-06 11:30:15 -0800208 AppStateTracker mAppStateTracker;
Christopher Tated1aebb32018-01-31 13:24:14 -0800209 final UsageStatsManagerInternal mUsageStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700210
211 /**
212 * Set to true once we are allowed to run third party apps.
213 */
214 boolean mReadyToRock;
215
Christopher Tate7060b042014-06-09 19:50:00 -0700216 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800217 * What we last reported to DeviceIdleController about whether we are active.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800218 */
219 boolean mReportedActive;
220
221 /**
Christopher Tatea5a85bd2018-01-03 17:20:36 -0800222 * Are we currently in device-wide standby parole?
223 */
224 volatile boolean mInParole;
225
226 /**
Dianne Hackborn970510b2016-02-24 16:56:42 -0800227 * Current limit on the number of concurrent JobServiceContext entries we want to
228 * keep actively running a job.
229 */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700230 int mMaxActiveJobs = 1;
Dianne Hackborn970510b2016-02-24 16:56:42 -0800231
232 /**
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800233 * A mapping of which uids are currently in the foreground to their effective priority.
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800234 */
Dianne Hackborn970510b2016-02-24 16:56:42 -0800235 final SparseIntArray mUidPriorityOverride = new SparseIntArray();
236
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700237 /**
238 * Which uids are currently performing backups, so we shouldn't allow their jobs to run.
239 */
240 final SparseIntArray mBackingUpUids = new SparseIntArray();
241
Christopher Tatea732f012017-10-26 17:26:53 -0700242 /**
243 * Count standby heartbeats, and keep track of which beat each bucket's jobs will
244 * next become runnable. Index into this array is by normalized bucket:
245 * { ACTIVE, WORKING, FREQUENT, RARE, NEVER }. The ACTIVE and NEVER bucket
246 * milestones are not updated: ACTIVE apps get jobs whenever they ask for them,
247 * and NEVER apps don't get them at all.
248 */
249 final long[] mNextBucketHeartbeat = { 0, 0, 0, 0, Long.MAX_VALUE };
250 long mHeartbeat = 0;
Christopher Tated1aebb32018-01-31 13:24:14 -0800251 long mLastHeartbeatTime = sElapsedRealtimeClock.millis();
252
Christopher Tate325768c2018-03-07 16:07:56 -0800253 /**
254 * Named indices into the STANDBY_BEATS array, for clarity in referring to
255 * specific buckets' bookkeeping.
256 */
Kweku Adams4836f9d2018-11-12 17:04:17 -0800257 public static final int ACTIVE_INDEX = 0;
258 public static final int WORKING_INDEX = 1;
259 public static final int FREQUENT_INDEX = 2;
260 public static final int RARE_INDEX = 3;
261 public static final int NEVER_INDEX = 4;
Christopher Tate325768c2018-03-07 16:07:56 -0800262
263 /**
264 * Bookkeeping about when jobs last run. We keep our own record in heartbeat time,
265 * rather than rely on Usage Stats' timestamps, because heartbeat time can be
266 * manipulated for testing purposes and we need job runnability to track that rather
267 * than real time.
268 *
269 * Outer SparseArray slices by user handle; inner map of package name to heartbeat
270 * is a HashMap<> rather than ArrayMap<> because we expect O(hundreds) of keys
271 * and it will be accessed in a known-hot code path.
272 */
273 final SparseArray<HashMap<String, Long>> mLastJobHeartbeats = new SparseArray<>();
274
Christopher Tated1aebb32018-01-31 13:24:14 -0800275 static final String HEARTBEAT_TAG = "*job.heartbeat*";
276 final HeartbeatAlarmListener mHeartbeatAlarm = new HeartbeatAlarmListener();
Christopher Tatea732f012017-10-26 17:26:53 -0700277
Dianne Hackborn970510b2016-02-24 16:56:42 -0800278 // -- Pre-allocated temporaries only for use in assignJobsToContextsLocked --
279
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700280 private class ConstantsObserver extends ContentObserver {
281 private ContentResolver mResolver;
282
283 public ConstantsObserver(Handler handler) {
284 super(handler);
285 }
286
287 public void start(ContentResolver resolver) {
288 mResolver = resolver;
289 mResolver.registerContentObserver(Settings.Global.getUriFor(
290 Settings.Global.JOB_SCHEDULER_CONSTANTS), false, this);
291 updateConstants();
292 }
293
294 @Override
295 public void onChange(boolean selfChange, Uri uri) {
296 updateConstants();
297 }
298
299 private void updateConstants() {
300 synchronized (mLock) {
301 try {
302 mConstants.updateConstantsLocked(Settings.Global.getString(mResolver,
303 Settings.Global.JOB_SCHEDULER_CONSTANTS));
Kweku Adams4836f9d2018-11-12 17:04:17 -0800304 for (int controller = 0; controller < mControllers.size(); controller++) {
305 final StateController sc = mControllers.get(controller);
306 sc.onConstantsUpdatedLocked();
307 }
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700308 } catch (IllegalArgumentException e) {
309 // Failed to parse the settings string, log this and move on
310 // with defaults.
311 Slog.e(TAG, "Bad jobscheduler settings", e);
312 }
313 }
314
Kweku Adams4836f9d2018-11-12 17:04:17 -0800315 if (mConstants.USE_HEARTBEATS) {
316 // Reset the heartbeat alarm based on the new heartbeat duration
317 setNextHeartbeatAlarm();
318 }
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700319 }
320 }
321
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800322 /**
Wei Wang8c0c3c12018-11-14 14:56:52 -0800323 * Thermal event received from Thermal Service
324 */
325 private final class ThermalStatusListener extends IThermalStatusListener.Stub {
326 @Override public void onStatusChange(int status) {
327 // Throttle for Temperature.THROTTLING_SEVERE and above
328 synchronized (mLock) {
329 mThermalConstraint = status >= Temperature.THROTTLING_SEVERE;
330 }
331 onControllerStateChanged();
332 }
333 }
334
Makoto Onuki66a51442018-12-20 14:23:50 -0800335 private static class MaxJobCounts {
336 private final KeyValueListParser.IntValue mTotal;
337 private final KeyValueListParser.IntValue mBg;
338
339 private MaxJobCounts(int totalDefault, String totalKey, int bgDefault, String bgKey) {
340 mTotal = new KeyValueListParser.IntValue(totalKey, totalDefault);
341 mBg = new KeyValueListParser.IntValue(bgKey, bgDefault);
342 }
343
344 public void parse(KeyValueListParser parser) {
345 mTotal.parse(parser);
346 mBg.parse(parser);
347
348 if (mBg.getValue() > mTotal.getValue()) {
349 mBg.setValue(mTotal.getValue());
350 }
351
352 }
353
354 public int getTotalMax() {
355 return mTotal.getValue();
356 }
357
358 public int getBgMax() {
359 return mBg.getValue();
360 }
361
362 public void dump(PrintWriter pw, String prefix) {
363 mTotal.dump(pw, prefix);
364 mBg.dump(pw, prefix);
365 }
366
367 public void dumpProto(ProtoOutputStream proto, long tagTotal, long tagBg) {
368 mTotal.dumpProto(proto, tagTotal);
369 mBg.dumpProto(proto, tagBg);
370 }
371 }
372
Wei Wang8c0c3c12018-11-14 14:56:52 -0800373 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700374 * All times are in milliseconds. These constants are kept synchronized with the system
375 * global Settings. Any access to this class or its fields should be done while
376 * holding the JobSchedulerService.mLock lock.
377 */
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700378 public static class Constants {
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700379 // Key names stored in the settings value.
380 private static final String KEY_MIN_IDLE_COUNT = "min_idle_count";
381 private static final String KEY_MIN_CHARGING_COUNT = "min_charging_count";
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800382 private static final String KEY_MIN_BATTERY_NOT_LOW_COUNT = "min_battery_not_low_count";
Dianne Hackborn532ea262017-03-17 17:50:55 -0700383 private static final String KEY_MIN_STORAGE_NOT_LOW_COUNT = "min_storage_not_low_count";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700384 private static final String KEY_MIN_CONNECTIVITY_COUNT = "min_connectivity_count";
385 private static final String KEY_MIN_CONTENT_COUNT = "min_content_count";
386 private static final String KEY_MIN_READY_JOBS_COUNT = "min_ready_jobs_count";
387 private static final String KEY_HEAVY_USE_FACTOR = "heavy_use_factor";
388 private static final String KEY_MODERATE_USE_FACTOR = "moderate_use_factor";
389 private static final String KEY_FG_JOB_COUNT = "fg_job_count";
390 private static final String KEY_BG_NORMAL_JOB_COUNT = "bg_normal_job_count";
391 private static final String KEY_BG_MODERATE_JOB_COUNT = "bg_moderate_job_count";
392 private static final String KEY_BG_LOW_JOB_COUNT = "bg_low_job_count";
393 private static final String KEY_BG_CRITICAL_JOB_COUNT = "bg_critical_job_count";
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700394 private static final String KEY_MAX_STANDARD_RESCHEDULE_COUNT
395 = "max_standard_reschedule_count";
396 private static final String KEY_MAX_WORK_RESCHEDULE_COUNT = "max_work_reschedule_count";
397 private static final String KEY_MIN_LINEAR_BACKOFF_TIME = "min_linear_backoff_time";
398 private static final String KEY_MIN_EXP_BACKOFF_TIME = "min_exp_backoff_time";
Christopher Tatea732f012017-10-26 17:26:53 -0700399 private static final String KEY_STANDBY_HEARTBEAT_TIME = "standby_heartbeat_time";
400 private static final String KEY_STANDBY_WORKING_BEATS = "standby_working_beats";
401 private static final String KEY_STANDBY_FREQUENT_BEATS = "standby_frequent_beats";
402 private static final String KEY_STANDBY_RARE_BEATS = "standby_rare_beats";
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700403 private static final String KEY_CONN_CONGESTION_DELAY_FRAC = "conn_congestion_delay_frac";
404 private static final String KEY_CONN_PREFETCH_RELAX_FRAC = "conn_prefetch_relax_frac";
Kweku Adams4836f9d2018-11-12 17:04:17 -0800405 private static final String KEY_USE_HEARTBEATS = "use_heartbeats";
Kweku Adamsbffea5a2018-12-13 22:13:28 -0800406 private static final String KEY_TIME_CONTROLLER_SKIP_NOT_READY_JOBS =
407 "tc_skip_not_ready_jobs";
Kweku Adams4836f9d2018-11-12 17:04:17 -0800408 private static final String KEY_QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS =
409 "qc_allowed_time_per_period_ms";
410 private static final String KEY_QUOTA_CONTROLLER_IN_QUOTA_BUFFER_MS =
411 "qc_in_quota_buffer_ms";
412 private static final String KEY_QUOTA_CONTROLLER_WINDOW_SIZE_ACTIVE_MS =
413 "qc_window_size_active_ms";
414 private static final String KEY_QUOTA_CONTROLLER_WINDOW_SIZE_WORKING_MS =
415 "qc_window_size_working_ms";
416 private static final String KEY_QUOTA_CONTROLLER_WINDOW_SIZE_FREQUENT_MS =
417 "qc_window_size_frequent_ms";
418 private static final String KEY_QUOTA_CONTROLLER_WINDOW_SIZE_RARE_MS =
419 "qc_window_size_rare_ms";
Kweku Adams045fb5722018-12-11 14:29:10 -0800420 private static final String KEY_QUOTA_CONTROLLER_MAX_EXECUTION_TIME_MS =
421 "qc_max_execution_time_ms";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700422
423 private static final int DEFAULT_MIN_IDLE_COUNT = 1;
424 private static final int DEFAULT_MIN_CHARGING_COUNT = 1;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800425 private static final int DEFAULT_MIN_BATTERY_NOT_LOW_COUNT = 1;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700426 private static final int DEFAULT_MIN_STORAGE_NOT_LOW_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700427 private static final int DEFAULT_MIN_CONNECTIVITY_COUNT = 1;
428 private static final int DEFAULT_MIN_CONTENT_COUNT = 1;
429 private static final int DEFAULT_MIN_READY_JOBS_COUNT = 1;
430 private static final float DEFAULT_HEAVY_USE_FACTOR = .9f;
431 private static final float DEFAULT_MODERATE_USE_FACTOR = .5f;
432 private static final int DEFAULT_FG_JOB_COUNT = 4;
433 private static final int DEFAULT_BG_NORMAL_JOB_COUNT = 6;
434 private static final int DEFAULT_BG_MODERATE_JOB_COUNT = 4;
Nancy Zhenge39a8a42016-10-05 16:27:14 -0700435 private static final int DEFAULT_BG_LOW_JOB_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700436 private static final int DEFAULT_BG_CRITICAL_JOB_COUNT = 1;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700437 private static final int DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT = Integer.MAX_VALUE;
438 private static final int DEFAULT_MAX_WORK_RESCHEDULE_COUNT = Integer.MAX_VALUE;
439 private static final long DEFAULT_MIN_LINEAR_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
440 private static final long DEFAULT_MIN_EXP_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
Christopher Tatea732f012017-10-26 17:26:53 -0700441 private static final long DEFAULT_STANDBY_HEARTBEAT_TIME = 11 * 60 * 1000L;
Esteban Talavera65254042017-12-15 10:59:28 +0000442 private static final int DEFAULT_STANDBY_WORKING_BEATS = 11; // ~ 2 hours, with 11min beats
443 private static final int DEFAULT_STANDBY_FREQUENT_BEATS = 43; // ~ 8 hours
Christopher Tatea732f012017-10-26 17:26:53 -0700444 private static final int DEFAULT_STANDBY_RARE_BEATS = 130; // ~ 24 hours
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700445 private static final float DEFAULT_CONN_CONGESTION_DELAY_FRAC = 0.5f;
446 private static final float DEFAULT_CONN_PREFETCH_RELAX_FRAC = 0.5f;
Kweku Adams4836f9d2018-11-12 17:04:17 -0800447 private static final boolean DEFAULT_USE_HEARTBEATS = true;
Kweku Adamsbffea5a2018-12-13 22:13:28 -0800448 private static final boolean DEFAULT_TIME_CONTROLLER_SKIP_NOT_READY_JOBS = false;
Kweku Adams4836f9d2018-11-12 17:04:17 -0800449 private static final long DEFAULT_QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS =
450 10 * 60 * 1000L; // 10 minutes
451 private static final long DEFAULT_QUOTA_CONTROLLER_IN_QUOTA_BUFFER_MS =
452 30 * 1000L; // 30 seconds
453 private static final long DEFAULT_QUOTA_CONTROLLER_WINDOW_SIZE_ACTIVE_MS =
454 10 * 60 * 1000L; // 10 minutes for ACTIVE -- ACTIVE apps can run jobs at any time
455 private static final long DEFAULT_QUOTA_CONTROLLER_WINDOW_SIZE_WORKING_MS =
456 2 * 60 * 60 * 1000L; // 2 hours
457 private static final long DEFAULT_QUOTA_CONTROLLER_WINDOW_SIZE_FREQUENT_MS =
458 8 * 60 * 60 * 1000L; // 8 hours
459 private static final long DEFAULT_QUOTA_CONTROLLER_WINDOW_SIZE_RARE_MS =
460 24 * 60 * 60 * 1000L; // 24 hours
Kweku Adams045fb5722018-12-11 14:29:10 -0800461 private static final long DEFAULT_QUOTA_CONTROLLER_MAX_EXECUTION_TIME_MS =
462 4 * 60 * 60 * 1000L; // 4 hours
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700463
464 /**
465 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
466 * early.
467 */
468 int MIN_IDLE_COUNT = DEFAULT_MIN_IDLE_COUNT;
469 /**
470 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule
471 * things early.
472 */
473 int MIN_CHARGING_COUNT = DEFAULT_MIN_CHARGING_COUNT;
474 /**
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800475 * Minimum # of "battery not low" jobs that must be ready in order to force the JMS to
476 * schedule things early.
477 */
478 int MIN_BATTERY_NOT_LOW_COUNT = DEFAULT_MIN_BATTERY_NOT_LOW_COUNT;
479 /**
Dianne Hackborn532ea262017-03-17 17:50:55 -0700480 * Minimum # of "storage not low" jobs that must be ready in order to force the JMS to
481 * schedule things early.
482 */
483 int MIN_STORAGE_NOT_LOW_COUNT = DEFAULT_MIN_STORAGE_NOT_LOW_COUNT;
484 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700485 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
486 * things early. 1 == Run connectivity jobs as soon as ready.
487 */
488 int MIN_CONNECTIVITY_COUNT = DEFAULT_MIN_CONNECTIVITY_COUNT;
489 /**
490 * Minimum # of content trigger jobs that must be ready in order to force the JMS to
491 * schedule things early.
492 */
493 int MIN_CONTENT_COUNT = DEFAULT_MIN_CONTENT_COUNT;
494 /**
495 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy
496 * running some work early. This (and thus the other min counts) is now set to 1, to
497 * prevent any batching at this level. Since we now do batching through doze, that is
498 * a much better mechanism.
499 */
500 int MIN_READY_JOBS_COUNT = DEFAULT_MIN_READY_JOBS_COUNT;
501 /**
502 * This is the job execution factor that is considered to be heavy use of the system.
503 */
504 float HEAVY_USE_FACTOR = DEFAULT_HEAVY_USE_FACTOR;
505 /**
506 * This is the job execution factor that is considered to be moderate use of the system.
507 */
508 float MODERATE_USE_FACTOR = DEFAULT_MODERATE_USE_FACTOR;
509 /**
510 * The number of MAX_JOB_CONTEXTS_COUNT we reserve for the foreground app.
511 */
512 int FG_JOB_COUNT = DEFAULT_FG_JOB_COUNT;
513 /**
514 * The maximum number of background jobs we allow when the system is in a normal
515 * memory state.
516 */
517 int BG_NORMAL_JOB_COUNT = DEFAULT_BG_NORMAL_JOB_COUNT;
518 /**
519 * The maximum number of background jobs we allow when the system is in a moderate
520 * memory state.
521 */
522 int BG_MODERATE_JOB_COUNT = DEFAULT_BG_MODERATE_JOB_COUNT;
523 /**
524 * The maximum number of background jobs we allow when the system is in a low
525 * memory state.
526 */
527 int BG_LOW_JOB_COUNT = DEFAULT_BG_LOW_JOB_COUNT;
528 /**
529 * The maximum number of background jobs we allow when the system is in a critical
530 * memory state.
531 */
532 int BG_CRITICAL_JOB_COUNT = DEFAULT_BG_CRITICAL_JOB_COUNT;
Makoto Onuki66a51442018-12-20 14:23:50 -0800533
534 // Max job counts for screen on / off, for each memory trim level.
535 // TODO Remove the old configs such as FG_JOB_COUNT and BG_*_COUNT, once the code switches
536 // to the below configs.
537
538 final MaxJobCounts MAX_JOB_COUNTS_ON_NORMAL = new MaxJobCounts(
539 4, "max_job_total_on_normal",
540 2, "max_job_bg_on_normal");
541
542 final MaxJobCounts MAX_JOB_COUNTS_ON_MODERATE = new MaxJobCounts(
543 4, "max_job_total_on_moderate",
544 1, "max_job_bg_on_moderate");
545
546 final MaxJobCounts MAX_JOB_COUNTS_ON_LOW = new MaxJobCounts(
547 4, "max_job_total_on_low",
548 1, "max_job_bg_on_low");
549
550 final MaxJobCounts MAX_JOB_COUNTS_ON_CRITICAL = new MaxJobCounts(
551 2, "max_job_total_on_critical",
552 1, "max_job_bg_on_critical");
553
554 final MaxJobCounts MAX_JOB_COUNTS_OFF_NORMAL = new MaxJobCounts(
555 8, "max_job_total_off_normal",
556 4, "max_job_bg_off_normal");
557
558 final MaxJobCounts MAX_JOB_COUNTS_OFF_MODERATE = new MaxJobCounts(
559 6, "max_job_total_off_moderate",
560 4, "max_job_bg_off_moderate");
561
562 final MaxJobCounts MAX_JOB_COUNTS_OFF_LOW = new MaxJobCounts(
563 4, "max_job_total_off_low",
564 1, "max_job_bg_off_low");
565
566 final MaxJobCounts MAX_JOB_COUNTS_OFF_CRITICAL = new MaxJobCounts(
567 2, "max_job_total_off_critical",
568 1, "max_job_bg_off_critical");
569
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700570 /**
571 * The maximum number of times we allow a job to have itself rescheduled before
572 * giving up on it, for standard jobs.
573 */
574 int MAX_STANDARD_RESCHEDULE_COUNT = DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT;
575 /**
576 * The maximum number of times we allow a job to have itself rescheduled before
577 * giving up on it, for jobs that are executing work.
578 */
579 int MAX_WORK_RESCHEDULE_COUNT = DEFAULT_MAX_WORK_RESCHEDULE_COUNT;
580 /**
581 * The minimum backoff time to allow for linear backoff.
582 */
583 long MIN_LINEAR_BACKOFF_TIME = DEFAULT_MIN_LINEAR_BACKOFF_TIME;
584 /**
585 * The minimum backoff time to allow for exponential backoff.
586 */
587 long MIN_EXP_BACKOFF_TIME = DEFAULT_MIN_EXP_BACKOFF_TIME;
Christopher Tatea732f012017-10-26 17:26:53 -0700588 /**
589 * How often we recalculate runnability based on apps' standby bucket assignment.
590 * This should be prime relative to common time interval lengths such as a quarter-
591 * hour or day, so that the heartbeat drifts relative to wall-clock milestones.
592 */
593 long STANDBY_HEARTBEAT_TIME = DEFAULT_STANDBY_HEARTBEAT_TIME;
Christopher Tatea732f012017-10-26 17:26:53 -0700594 /**
595 * Mapping: standby bucket -> number of heartbeats between each sweep of that
596 * bucket's jobs.
597 *
598 * Bucket assignments as recorded in the JobStatus objects are normalized to be
599 * indices into this array, rather than the raw constants used
600 * by AppIdleHistory.
601 */
602 final int[] STANDBY_BEATS = {
603 0,
604 DEFAULT_STANDBY_WORKING_BEATS,
605 DEFAULT_STANDBY_FREQUENT_BEATS,
606 DEFAULT_STANDBY_RARE_BEATS
607 };
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700608 /**
609 * The fraction of a job's running window that must pass before we
610 * consider running it when the network is congested.
611 */
612 public float CONN_CONGESTION_DELAY_FRAC = DEFAULT_CONN_CONGESTION_DELAY_FRAC;
613 /**
614 * The fraction of a prefetch job's running window that must pass before
615 * we consider matching it against a metered network.
616 */
617 public float CONN_PREFETCH_RELAX_FRAC = DEFAULT_CONN_PREFETCH_RELAX_FRAC;
Kweku Adams4836f9d2018-11-12 17:04:17 -0800618 /**
619 * Whether to use heartbeats or rolling window for quota management. True will use
620 * heartbeats, false will use a rolling window.
621 */
622 public boolean USE_HEARTBEATS = DEFAULT_USE_HEARTBEATS;
623
Kweku Adamsbffea5a2018-12-13 22:13:28 -0800624 /**
625 * Whether or not TimeController should skip setting wakeup alarms for jobs that aren't
626 * ready now.
627 */
628 public boolean TIME_CONTROLLER_SKIP_NOT_READY_JOBS =
629 DEFAULT_TIME_CONTROLLER_SKIP_NOT_READY_JOBS;
630
Kweku Adams4836f9d2018-11-12 17:04:17 -0800631 /** How much time each app will have to run jobs within their standby bucket window. */
632 public long QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS =
633 DEFAULT_QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS;
634
635 /**
636 * How much time the package should have before transitioning from out-of-quota to in-quota.
637 * This should not affect processing if the package is already in-quota.
638 */
639 public long QUOTA_CONTROLLER_IN_QUOTA_BUFFER_MS =
640 DEFAULT_QUOTA_CONTROLLER_IN_QUOTA_BUFFER_MS;
641
642 /**
643 * The quota window size of the particular standby bucket. Apps in this standby bucket are
Makoto Onuki66a51442018-12-20 14:23:50 -0800644 * expected to run only {@link #QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS} within the past
Kweku Adams4836f9d2018-11-12 17:04:17 -0800645 * WINDOW_SIZE_MS.
646 */
647 public long QUOTA_CONTROLLER_WINDOW_SIZE_ACTIVE_MS =
648 DEFAULT_QUOTA_CONTROLLER_WINDOW_SIZE_ACTIVE_MS;
649
650 /**
651 * The quota window size of the particular standby bucket. Apps in this standby bucket are
Makoto Onuki66a51442018-12-20 14:23:50 -0800652 * expected to run only {@link #QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS} within the past
Kweku Adams4836f9d2018-11-12 17:04:17 -0800653 * WINDOW_SIZE_MS.
654 */
655 public long QUOTA_CONTROLLER_WINDOW_SIZE_WORKING_MS =
656 DEFAULT_QUOTA_CONTROLLER_WINDOW_SIZE_WORKING_MS;
657
658 /**
659 * The quota window size of the particular standby bucket. Apps in this standby bucket are
Makoto Onuki66a51442018-12-20 14:23:50 -0800660 * expected to run only {@link #QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS} within the past
Kweku Adams4836f9d2018-11-12 17:04:17 -0800661 * WINDOW_SIZE_MS.
662 */
663 public long QUOTA_CONTROLLER_WINDOW_SIZE_FREQUENT_MS =
664 DEFAULT_QUOTA_CONTROLLER_WINDOW_SIZE_FREQUENT_MS;
665
666 /**
667 * The quota window size of the particular standby bucket. Apps in this standby bucket are
Makoto Onuki66a51442018-12-20 14:23:50 -0800668 * expected to run only {@link #QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS} within the past
Kweku Adams4836f9d2018-11-12 17:04:17 -0800669 * WINDOW_SIZE_MS.
670 */
671 public long QUOTA_CONTROLLER_WINDOW_SIZE_RARE_MS =
672 DEFAULT_QUOTA_CONTROLLER_WINDOW_SIZE_RARE_MS;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700673
Kweku Adams045fb5722018-12-11 14:29:10 -0800674 /**
675 * The maximum amount of time an app can have its jobs running within a 24 hour window.
676 */
677 public long QUOTA_CONTROLLER_MAX_EXECUTION_TIME_MS =
678 DEFAULT_QUOTA_CONTROLLER_MAX_EXECUTION_TIME_MS;
679
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700680 private final KeyValueListParser mParser = new KeyValueListParser(',');
681
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700682 void updateConstantsLocked(String value) {
683 try {
684 mParser.setString(value);
685 } catch (Exception e) {
686 // Failed to parse the settings string, log this and move on
687 // with defaults.
688 Slog.e(TAG, "Bad jobscheduler settings", e);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700689 }
Christopher Tated1aebb32018-01-31 13:24:14 -0800690
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700691 MIN_IDLE_COUNT = mParser.getInt(KEY_MIN_IDLE_COUNT,
692 DEFAULT_MIN_IDLE_COUNT);
693 MIN_CHARGING_COUNT = mParser.getInt(KEY_MIN_CHARGING_COUNT,
694 DEFAULT_MIN_CHARGING_COUNT);
695 MIN_BATTERY_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_BATTERY_NOT_LOW_COUNT,
696 DEFAULT_MIN_BATTERY_NOT_LOW_COUNT);
697 MIN_STORAGE_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_STORAGE_NOT_LOW_COUNT,
698 DEFAULT_MIN_STORAGE_NOT_LOW_COUNT);
699 MIN_CONNECTIVITY_COUNT = mParser.getInt(KEY_MIN_CONNECTIVITY_COUNT,
700 DEFAULT_MIN_CONNECTIVITY_COUNT);
701 MIN_CONTENT_COUNT = mParser.getInt(KEY_MIN_CONTENT_COUNT,
702 DEFAULT_MIN_CONTENT_COUNT);
703 MIN_READY_JOBS_COUNT = mParser.getInt(KEY_MIN_READY_JOBS_COUNT,
704 DEFAULT_MIN_READY_JOBS_COUNT);
705 HEAVY_USE_FACTOR = mParser.getFloat(KEY_HEAVY_USE_FACTOR,
706 DEFAULT_HEAVY_USE_FACTOR);
707 MODERATE_USE_FACTOR = mParser.getFloat(KEY_MODERATE_USE_FACTOR,
708 DEFAULT_MODERATE_USE_FACTOR);
709 FG_JOB_COUNT = mParser.getInt(KEY_FG_JOB_COUNT,
710 DEFAULT_FG_JOB_COUNT);
711 BG_NORMAL_JOB_COUNT = mParser.getInt(KEY_BG_NORMAL_JOB_COUNT,
712 DEFAULT_BG_NORMAL_JOB_COUNT);
713 if ((FG_JOB_COUNT+BG_NORMAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
714 BG_NORMAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
715 }
716 BG_MODERATE_JOB_COUNT = mParser.getInt(KEY_BG_MODERATE_JOB_COUNT,
717 DEFAULT_BG_MODERATE_JOB_COUNT);
718 if ((FG_JOB_COUNT+BG_MODERATE_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
719 BG_MODERATE_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
720 }
721 BG_LOW_JOB_COUNT = mParser.getInt(KEY_BG_LOW_JOB_COUNT,
722 DEFAULT_BG_LOW_JOB_COUNT);
723 if ((FG_JOB_COUNT+BG_LOW_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
724 BG_LOW_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
725 }
726 BG_CRITICAL_JOB_COUNT = mParser.getInt(KEY_BG_CRITICAL_JOB_COUNT,
727 DEFAULT_BG_CRITICAL_JOB_COUNT);
728 if ((FG_JOB_COUNT+BG_CRITICAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
729 BG_CRITICAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
730 }
Makoto Onuki66a51442018-12-20 14:23:50 -0800731
732 MAX_JOB_COUNTS_ON_NORMAL.parse(mParser);
733 MAX_JOB_COUNTS_ON_MODERATE.parse(mParser);
734 MAX_JOB_COUNTS_ON_LOW.parse(mParser);
735 MAX_JOB_COUNTS_ON_CRITICAL.parse(mParser);
736
737 MAX_JOB_COUNTS_OFF_NORMAL.parse(mParser);
738 MAX_JOB_COUNTS_OFF_MODERATE.parse(mParser);
739 MAX_JOB_COUNTS_OFF_LOW.parse(mParser);
740 MAX_JOB_COUNTS_OFF_CRITICAL.parse(mParser);
741
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700742 MAX_STANDARD_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_STANDARD_RESCHEDULE_COUNT,
743 DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT);
744 MAX_WORK_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_WORK_RESCHEDULE_COUNT,
745 DEFAULT_MAX_WORK_RESCHEDULE_COUNT);
746 MIN_LINEAR_BACKOFF_TIME = mParser.getDurationMillis(KEY_MIN_LINEAR_BACKOFF_TIME,
747 DEFAULT_MIN_LINEAR_BACKOFF_TIME);
748 MIN_EXP_BACKOFF_TIME = mParser.getDurationMillis(KEY_MIN_EXP_BACKOFF_TIME,
749 DEFAULT_MIN_EXP_BACKOFF_TIME);
750 STANDBY_HEARTBEAT_TIME = mParser.getDurationMillis(KEY_STANDBY_HEARTBEAT_TIME,
751 DEFAULT_STANDBY_HEARTBEAT_TIME);
Christopher Tate325768c2018-03-07 16:07:56 -0800752 STANDBY_BEATS[WORKING_INDEX] = mParser.getInt(KEY_STANDBY_WORKING_BEATS,
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700753 DEFAULT_STANDBY_WORKING_BEATS);
Christopher Tate325768c2018-03-07 16:07:56 -0800754 STANDBY_BEATS[FREQUENT_INDEX] = mParser.getInt(KEY_STANDBY_FREQUENT_BEATS,
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700755 DEFAULT_STANDBY_FREQUENT_BEATS);
Christopher Tate325768c2018-03-07 16:07:56 -0800756 STANDBY_BEATS[RARE_INDEX] = mParser.getInt(KEY_STANDBY_RARE_BEATS,
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700757 DEFAULT_STANDBY_RARE_BEATS);
758 CONN_CONGESTION_DELAY_FRAC = mParser.getFloat(KEY_CONN_CONGESTION_DELAY_FRAC,
759 DEFAULT_CONN_CONGESTION_DELAY_FRAC);
760 CONN_PREFETCH_RELAX_FRAC = mParser.getFloat(KEY_CONN_PREFETCH_RELAX_FRAC,
761 DEFAULT_CONN_PREFETCH_RELAX_FRAC);
Kweku Adams4836f9d2018-11-12 17:04:17 -0800762 USE_HEARTBEATS = mParser.getBoolean(KEY_USE_HEARTBEATS, DEFAULT_USE_HEARTBEATS);
Kweku Adamsbffea5a2018-12-13 22:13:28 -0800763 TIME_CONTROLLER_SKIP_NOT_READY_JOBS = mParser.getBoolean(
764 KEY_TIME_CONTROLLER_SKIP_NOT_READY_JOBS,
765 DEFAULT_TIME_CONTROLLER_SKIP_NOT_READY_JOBS);
Kweku Adams4836f9d2018-11-12 17:04:17 -0800766 QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS = mParser.getDurationMillis(
767 KEY_QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS,
768 DEFAULT_QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS);
769 QUOTA_CONTROLLER_IN_QUOTA_BUFFER_MS = mParser.getDurationMillis(
770 KEY_QUOTA_CONTROLLER_IN_QUOTA_BUFFER_MS,
771 DEFAULT_QUOTA_CONTROLLER_IN_QUOTA_BUFFER_MS);
772 QUOTA_CONTROLLER_WINDOW_SIZE_ACTIVE_MS = mParser.getDurationMillis(
773 KEY_QUOTA_CONTROLLER_WINDOW_SIZE_ACTIVE_MS,
774 DEFAULT_QUOTA_CONTROLLER_WINDOW_SIZE_ACTIVE_MS);
775 QUOTA_CONTROLLER_WINDOW_SIZE_WORKING_MS = mParser.getDurationMillis(
776 KEY_QUOTA_CONTROLLER_WINDOW_SIZE_WORKING_MS,
777 DEFAULT_QUOTA_CONTROLLER_WINDOW_SIZE_WORKING_MS);
778 QUOTA_CONTROLLER_WINDOW_SIZE_FREQUENT_MS = mParser.getDurationMillis(
779 KEY_QUOTA_CONTROLLER_WINDOW_SIZE_FREQUENT_MS,
780 DEFAULT_QUOTA_CONTROLLER_WINDOW_SIZE_FREQUENT_MS);
781 QUOTA_CONTROLLER_WINDOW_SIZE_RARE_MS = mParser.getDurationMillis(
782 KEY_QUOTA_CONTROLLER_WINDOW_SIZE_RARE_MS,
783 DEFAULT_QUOTA_CONTROLLER_WINDOW_SIZE_RARE_MS);
Kweku Adams045fb5722018-12-11 14:29:10 -0800784 QUOTA_CONTROLLER_MAX_EXECUTION_TIME_MS = mParser.getDurationMillis(
785 KEY_QUOTA_CONTROLLER_MAX_EXECUTION_TIME_MS,
786 DEFAULT_QUOTA_CONTROLLER_MAX_EXECUTION_TIME_MS);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700787 }
788
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700789 void dump(IndentingPrintWriter pw) {
790 pw.println("Settings:");
791 pw.increaseIndent();
792 pw.printPair(KEY_MIN_IDLE_COUNT, MIN_IDLE_COUNT).println();
793 pw.printPair(KEY_MIN_CHARGING_COUNT, MIN_CHARGING_COUNT).println();
794 pw.printPair(KEY_MIN_BATTERY_NOT_LOW_COUNT, MIN_BATTERY_NOT_LOW_COUNT).println();
795 pw.printPair(KEY_MIN_STORAGE_NOT_LOW_COUNT, MIN_STORAGE_NOT_LOW_COUNT).println();
796 pw.printPair(KEY_MIN_CONNECTIVITY_COUNT, MIN_CONNECTIVITY_COUNT).println();
797 pw.printPair(KEY_MIN_CONTENT_COUNT, MIN_CONTENT_COUNT).println();
798 pw.printPair(KEY_MIN_READY_JOBS_COUNT, MIN_READY_JOBS_COUNT).println();
799 pw.printPair(KEY_HEAVY_USE_FACTOR, HEAVY_USE_FACTOR).println();
800 pw.printPair(KEY_MODERATE_USE_FACTOR, MODERATE_USE_FACTOR).println();
801 pw.printPair(KEY_FG_JOB_COUNT, FG_JOB_COUNT).println();
802 pw.printPair(KEY_BG_NORMAL_JOB_COUNT, BG_NORMAL_JOB_COUNT).println();
803 pw.printPair(KEY_BG_MODERATE_JOB_COUNT, BG_MODERATE_JOB_COUNT).println();
804 pw.printPair(KEY_BG_LOW_JOB_COUNT, BG_LOW_JOB_COUNT).println();
805 pw.printPair(KEY_BG_CRITICAL_JOB_COUNT, BG_CRITICAL_JOB_COUNT).println();
Makoto Onuki66a51442018-12-20 14:23:50 -0800806
807 MAX_JOB_COUNTS_ON_NORMAL.dump(pw, "");
808 MAX_JOB_COUNTS_ON_MODERATE.dump(pw, "");
809 MAX_JOB_COUNTS_ON_LOW.dump(pw, "");
810 MAX_JOB_COUNTS_ON_CRITICAL.dump(pw, "");
811
812 MAX_JOB_COUNTS_OFF_NORMAL.dump(pw, "");
813 MAX_JOB_COUNTS_OFF_MODERATE.dump(pw, "");
814 MAX_JOB_COUNTS_OFF_LOW.dump(pw, "");
815 MAX_JOB_COUNTS_OFF_CRITICAL.dump(pw, "");
816
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700817 pw.printPair(KEY_MAX_STANDARD_RESCHEDULE_COUNT, MAX_STANDARD_RESCHEDULE_COUNT).println();
818 pw.printPair(KEY_MAX_WORK_RESCHEDULE_COUNT, MAX_WORK_RESCHEDULE_COUNT).println();
819 pw.printPair(KEY_MIN_LINEAR_BACKOFF_TIME, MIN_LINEAR_BACKOFF_TIME).println();
820 pw.printPair(KEY_MIN_EXP_BACKOFF_TIME, MIN_EXP_BACKOFF_TIME).println();
821 pw.printPair(KEY_STANDBY_HEARTBEAT_TIME, STANDBY_HEARTBEAT_TIME).println();
822 pw.print("standby_beats={");
Christopher Tatea732f012017-10-26 17:26:53 -0700823 pw.print(STANDBY_BEATS[0]);
824 for (int i = 1; i < STANDBY_BEATS.length; i++) {
825 pw.print(", ");
826 pw.print(STANDBY_BEATS[i]);
827 }
828 pw.println('}');
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700829 pw.printPair(KEY_CONN_CONGESTION_DELAY_FRAC, CONN_CONGESTION_DELAY_FRAC).println();
830 pw.printPair(KEY_CONN_PREFETCH_RELAX_FRAC, CONN_PREFETCH_RELAX_FRAC).println();
Kweku Adams4836f9d2018-11-12 17:04:17 -0800831 pw.printPair(KEY_USE_HEARTBEATS, USE_HEARTBEATS).println();
Kweku Adamsbffea5a2018-12-13 22:13:28 -0800832 pw.printPair(KEY_TIME_CONTROLLER_SKIP_NOT_READY_JOBS,
833 TIME_CONTROLLER_SKIP_NOT_READY_JOBS).println();
Kweku Adams4836f9d2018-11-12 17:04:17 -0800834 pw.printPair(KEY_QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS,
835 QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS).println();
836 pw.printPair(KEY_QUOTA_CONTROLLER_IN_QUOTA_BUFFER_MS,
837 QUOTA_CONTROLLER_IN_QUOTA_BUFFER_MS).println();
838 pw.printPair(KEY_QUOTA_CONTROLLER_WINDOW_SIZE_ACTIVE_MS,
839 QUOTA_CONTROLLER_WINDOW_SIZE_ACTIVE_MS).println();
840 pw.printPair(KEY_QUOTA_CONTROLLER_WINDOW_SIZE_WORKING_MS,
841 QUOTA_CONTROLLER_WINDOW_SIZE_WORKING_MS).println();
842 pw.printPair(KEY_QUOTA_CONTROLLER_WINDOW_SIZE_FREQUENT_MS,
843 QUOTA_CONTROLLER_WINDOW_SIZE_FREQUENT_MS).println();
844 pw.printPair(KEY_QUOTA_CONTROLLER_WINDOW_SIZE_RARE_MS,
845 QUOTA_CONTROLLER_WINDOW_SIZE_RARE_MS).println();
Kweku Adams045fb5722018-12-11 14:29:10 -0800846 pw.printPair(KEY_QUOTA_CONTROLLER_MAX_EXECUTION_TIME_MS,
847 QUOTA_CONTROLLER_MAX_EXECUTION_TIME_MS).println();
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700848 pw.decreaseIndent();
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700849 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800850
851 void dump(ProtoOutputStream proto, long fieldId) {
852 final long token = proto.start(fieldId);
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800853 proto.write(ConstantsProto.MIN_IDLE_COUNT, MIN_IDLE_COUNT);
854 proto.write(ConstantsProto.MIN_CHARGING_COUNT, MIN_CHARGING_COUNT);
855 proto.write(ConstantsProto.MIN_BATTERY_NOT_LOW_COUNT, MIN_BATTERY_NOT_LOW_COUNT);
856 proto.write(ConstantsProto.MIN_STORAGE_NOT_LOW_COUNT, MIN_STORAGE_NOT_LOW_COUNT);
857 proto.write(ConstantsProto.MIN_CONNECTIVITY_COUNT, MIN_CONNECTIVITY_COUNT);
858 proto.write(ConstantsProto.MIN_CONTENT_COUNT, MIN_CONTENT_COUNT);
859 proto.write(ConstantsProto.MIN_READY_JOBS_COUNT, MIN_READY_JOBS_COUNT);
860 proto.write(ConstantsProto.HEAVY_USE_FACTOR, HEAVY_USE_FACTOR);
861 proto.write(ConstantsProto.MODERATE_USE_FACTOR, MODERATE_USE_FACTOR);
862 proto.write(ConstantsProto.FG_JOB_COUNT, FG_JOB_COUNT);
863 proto.write(ConstantsProto.BG_NORMAL_JOB_COUNT, BG_NORMAL_JOB_COUNT);
864 proto.write(ConstantsProto.BG_MODERATE_JOB_COUNT, BG_MODERATE_JOB_COUNT);
865 proto.write(ConstantsProto.BG_LOW_JOB_COUNT, BG_LOW_JOB_COUNT);
866 proto.write(ConstantsProto.BG_CRITICAL_JOB_COUNT, BG_CRITICAL_JOB_COUNT);
Makoto Onuki66a51442018-12-20 14:23:50 -0800867
868 // TODO Dump max job counts.
869
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800870 proto.write(ConstantsProto.MAX_STANDARD_RESCHEDULE_COUNT, MAX_STANDARD_RESCHEDULE_COUNT);
871 proto.write(ConstantsProto.MAX_WORK_RESCHEDULE_COUNT, MAX_WORK_RESCHEDULE_COUNT);
872 proto.write(ConstantsProto.MIN_LINEAR_BACKOFF_TIME_MS, MIN_LINEAR_BACKOFF_TIME);
873 proto.write(ConstantsProto.MIN_EXP_BACKOFF_TIME_MS, MIN_EXP_BACKOFF_TIME);
874 proto.write(ConstantsProto.STANDBY_HEARTBEAT_TIME_MS, STANDBY_HEARTBEAT_TIME);
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800875 for (int period : STANDBY_BEATS) {
876 proto.write(ConstantsProto.STANDBY_BEATS, period);
877 }
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700878 proto.write(ConstantsProto.CONN_CONGESTION_DELAY_FRAC, CONN_CONGESTION_DELAY_FRAC);
879 proto.write(ConstantsProto.CONN_PREFETCH_RELAX_FRAC, CONN_PREFETCH_RELAX_FRAC);
Kweku Adams4836f9d2018-11-12 17:04:17 -0800880 proto.write(ConstantsProto.USE_HEARTBEATS, USE_HEARTBEATS);
881
Kweku Adamsbffea5a2018-12-13 22:13:28 -0800882 final long tcToken = proto.start(ConstantsProto.TIME_CONTROLLER);
883 proto.write(ConstantsProto.TimeController.SKIP_NOT_READY_JOBS,
884 TIME_CONTROLLER_SKIP_NOT_READY_JOBS);
885 proto.end(tcToken);
886
Kweku Adams4836f9d2018-11-12 17:04:17 -0800887 final long qcToken = proto.start(ConstantsProto.QUOTA_CONTROLLER);
888 proto.write(ConstantsProto.QuotaController.ALLOWED_TIME_PER_PERIOD_MS,
889 QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS);
890 proto.write(ConstantsProto.QuotaController.IN_QUOTA_BUFFER_MS,
891 QUOTA_CONTROLLER_IN_QUOTA_BUFFER_MS);
892 proto.write(ConstantsProto.QuotaController.ACTIVE_WINDOW_SIZE_MS,
893 QUOTA_CONTROLLER_WINDOW_SIZE_ACTIVE_MS);
894 proto.write(ConstantsProto.QuotaController.WORKING_WINDOW_SIZE_MS,
895 QUOTA_CONTROLLER_WINDOW_SIZE_WORKING_MS);
896 proto.write(ConstantsProto.QuotaController.FREQUENT_WINDOW_SIZE_MS,
897 QUOTA_CONTROLLER_WINDOW_SIZE_FREQUENT_MS);
898 proto.write(ConstantsProto.QuotaController.RARE_WINDOW_SIZE_MS,
899 QUOTA_CONTROLLER_WINDOW_SIZE_RARE_MS);
Kweku Adams045fb5722018-12-11 14:29:10 -0800900 proto.write(ConstantsProto.QuotaController.MAX_EXECUTION_TIME_MS,
901 QUOTA_CONTROLLER_MAX_EXECUTION_TIME_MS);
Kweku Adams4836f9d2018-11-12 17:04:17 -0800902 proto.end(qcToken);
903
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800904 proto.end(token);
905 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700906 }
907
908 final Constants mConstants;
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700909 final ConstantsObserver mConstantsObserver;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700910
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700911 static final Comparator<JobStatus> mEnqueueTimeComparator = (o1, o2) -> {
912 if (o1.enqueueTime < o2.enqueueTime) {
913 return -1;
914 }
915 return o1.enqueueTime > o2.enqueueTime ? 1 : 0;
916 };
917
918 static <T> void addOrderedItem(ArrayList<T> array, T newItem, Comparator<T> comparator) {
919 int where = Collections.binarySearch(array, newItem, comparator);
920 if (where < 0) {
921 where = ~where;
922 }
923 array.add(where, newItem);
924 }
925
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700926 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700927 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
928 * still clean up. On reinstall the package will have a new uid.
929 */
930 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
931 @Override
932 public void onReceive(Context context, Intent intent) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700933 final String action = intent.getAction();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700934 if (DEBUG) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700935 Slog.d(TAG, "Receieved: " + action);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700936 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700937 final String pkgName = getPackageName(intent);
938 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
939
Christopher Tateee7805b2016-07-15 16:56:56 -0700940 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
Christopher Tateb5c07882016-05-26 17:11:09 -0700941 // Purge the app's jobs if the whole package was just disabled. When this is
942 // the case the component name will be a bare package name.
Christopher Tateb5c07882016-05-26 17:11:09 -0700943 if (pkgName != null && pkgUid != -1) {
944 final String[] changedComponents = intent.getStringArrayExtra(
945 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
946 if (changedComponents != null) {
947 for (String component : changedComponents) {
948 if (component.equals(pkgName)) {
949 if (DEBUG) {
950 Slog.d(TAG, "Package state change: " + pkgName);
951 }
952 try {
953 final int userId = UserHandle.getUserId(pkgUid);
954 IPackageManager pm = AppGlobals.getPackageManager();
955 final int state = pm.getApplicationEnabledSetting(pkgName, userId);
956 if (state == COMPONENT_ENABLED_STATE_DISABLED
957 || state == COMPONENT_ENABLED_STATE_DISABLED_USER) {
958 if (DEBUG) {
959 Slog.d(TAG, "Removing jobs for package " + pkgName
960 + " in user " + userId);
961 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700962 cancelJobsForPackageAndUid(pkgName, pkgUid,
963 "app disabled");
Christopher Tateb5c07882016-05-26 17:11:09 -0700964 }
Christopher Tate652c5ad2016-10-05 14:45:46 -0700965 } catch (RemoteException|IllegalArgumentException e) {
966 /*
967 * IllegalArgumentException means that the package doesn't exist.
968 * This arises when PACKAGE_CHANGED broadcast delivery has lagged
969 * behind outright uninstall, so by the time we try to act it's gone.
970 * We don't need to act on this PACKAGE_CHANGED when this happens;
971 * we'll get a PACKAGE_REMOVED later and clean up then.
972 *
973 * RemoteException can't actually happen; the package manager is
974 * running in this same process.
975 */
976 }
Christopher Tateb5c07882016-05-26 17:11:09 -0700977 break;
978 }
979 }
Kweku Adamscdbfcb92018-12-06 17:05:15 -0800980 if (DEBUG) {
981 Slog.d(TAG, "Something in " + pkgName
982 + " changed. Reevaluating controller states.");
983 }
984 synchronized (mLock) {
985 for (int c = mControllers.size() - 1; c >= 0; --c) {
986 mControllers.get(c).reevaluateStateLocked(pkgUid);
987 }
988 }
Christopher Tateb5c07882016-05-26 17:11:09 -0700989 }
990 } else {
991 Slog.w(TAG, "PACKAGE_CHANGED for " + pkgName + " / uid " + pkgUid);
992 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700993 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700994 // If this is an outright uninstall rather than the first half of an
995 // app update sequence, cancel the jobs associated with the app.
996 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
997 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
998 if (DEBUG) {
999 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
1000 }
Makoto Onukie7b96182017-08-30 14:53:16 -07001001 cancelJobsForPackageAndUid(pkgName, uidRemoved, "app uninstalled");
Kweku Adamsa9f8e1f2018-12-12 16:06:54 -08001002 synchronized (mLock) {
1003 for (int c = 0; c < mControllers.size(); ++c) {
1004 mControllers.get(c).onAppRemovedLocked(pkgName, pkgUid);
1005 }
1006 }
Christopher Tate7060b042014-06-09 19:50:00 -07001007 }
Christopher Tateee7805b2016-07-15 16:56:56 -07001008 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Christopher Tate7060b042014-06-09 19:50:00 -07001009 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
1010 if (DEBUG) {
1011 Slog.d(TAG, "Removing jobs for user: " + userId);
1012 }
1013 cancelJobsForUser(userId);
Kweku Adamsa9f8e1f2018-12-12 16:06:54 -08001014 synchronized (mLock) {
1015 for (int c = 0; c < mControllers.size(); ++c) {
1016 mControllers.get(c).onUserRemovedLocked(userId);
1017 }
1018 }
Christopher Tateee7805b2016-07-15 16:56:56 -07001019 } else if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
1020 // Has this package scheduled any jobs, such that we will take action
1021 // if it were to be force-stopped?
Christopher Tateee7805b2016-07-15 16:56:56 -07001022 if (pkgUid != -1) {
1023 List<JobStatus> jobsForUid;
1024 synchronized (mLock) {
1025 jobsForUid = mJobs.getJobsByUid(pkgUid);
1026 }
1027 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
1028 if (jobsForUid.get(i).getSourcePackageName().equals(pkgName)) {
1029 if (DEBUG) {
1030 Slog.d(TAG, "Restart query: package " + pkgName + " at uid "
1031 + pkgUid + " has jobs");
1032 }
1033 setResultCode(Activity.RESULT_OK);
1034 break;
1035 }
1036 }
1037 }
1038 } else if (Intent.ACTION_PACKAGE_RESTARTED.equals(action)) {
1039 // possible force-stop
Christopher Tateee7805b2016-07-15 16:56:56 -07001040 if (pkgUid != -1) {
1041 if (DEBUG) {
1042 Slog.d(TAG, "Removing jobs for pkg " + pkgName + " at uid " + pkgUid);
1043 }
Makoto Onukie7b96182017-08-30 14:53:16 -07001044 cancelJobsForPackageAndUid(pkgName, pkgUid, "app force stopped");
Christopher Tateee7805b2016-07-15 16:56:56 -07001045 }
Christopher Tate7060b042014-06-09 19:50:00 -07001046 }
1047 }
1048 };
1049
Christopher Tateb5c07882016-05-26 17:11:09 -07001050 private String getPackageName(Intent intent) {
1051 Uri uri = intent.getData();
1052 String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
1053 return pkg;
1054 }
1055
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001056 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07001057 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki743e0ad2018-02-20 16:01:11 -08001058 mHandler.obtainMessage(MSG_UID_STATE_CHANGED, uid, procState).sendToTarget();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001059 }
1060
Dianne Hackborn3e99f652017-07-05 16:33:56 -07001061 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki743e0ad2018-02-20 16:01:11 -08001062 mHandler.obtainMessage(MSG_UID_GONE, uid, disabled ? 1 : 0).sendToTarget();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001063 }
1064
1065 @Override public void onUidActive(int uid) throws RemoteException {
Makoto Onuki743e0ad2018-02-20 16:01:11 -08001066 mHandler.obtainMessage(MSG_UID_ACTIVE, uid, 0).sendToTarget();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001067 }
1068
Dianne Hackborn3e99f652017-07-05 16:33:56 -07001069 @Override public void onUidIdle(int uid, boolean disabled) {
Makoto Onuki743e0ad2018-02-20 16:01:11 -08001070 mHandler.obtainMessage(MSG_UID_IDLE, uid, disabled ? 1 : 0).sendToTarget();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001071 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07001072
1073 @Override public void onUidCachedChanged(int uid, boolean cached) {
1074 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001075 };
1076
Jeff Sharkey4d89e422018-03-29 18:22:41 -06001077 public Context getTestableContext() {
1078 return getContext();
1079 }
1080
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001081 public Object getLock() {
1082 return mLock;
1083 }
1084
Dianne Hackborn8db0fc12016-04-12 13:48:25 -07001085 public JobStore getJobStore() {
1086 return mJobs;
1087 }
1088
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001089 public Constants getConstants() {
1090 return mConstants;
1091 }
1092
Kweku Adamsbffea5a2018-12-13 22:13:28 -08001093 public boolean isChainedAttributionEnabled() {
1094 return WorkSource.isChainedBatteryAttributionEnabled(getContext());
1095 }
1096
Matthew Williams9ae3dbe2014-08-21 13:47:47 -07001097 @Override
1098 public void onStartUser(int userHandle) {
Kweku Adams8bd5edc2018-12-07 18:33:39 -08001099 synchronized (mLock) {
1100 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userHandle);
1101 }
Jeff Sharkey822cbd12016-02-25 11:09:55 -07001102 // Let's kick any outstanding jobs for this user.
1103 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1104 }
1105
1106 @Override
1107 public void onUnlockUser(int userHandle) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -07001108 // Let's kick any outstanding jobs for this user.
1109 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1110 }
1111
1112 @Override
1113 public void onStopUser(int userHandle) {
Kweku Adams8bd5edc2018-12-07 18:33:39 -08001114 synchronized (mLock) {
1115 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userHandle);
1116 }
Matthew Williams9ae3dbe2014-08-21 13:47:47 -07001117 }
1118
Makoto Onuki15407842018-01-19 14:23:11 -08001119 /**
Makoto Onukie4918212018-02-06 11:30:15 -08001120 * Return whether an UID is active or idle.
Makoto Onuki15407842018-01-19 14:23:11 -08001121 */
Makoto Onukie4918212018-02-06 11:30:15 -08001122 private boolean isUidActive(int uid) {
1123 return mAppStateTracker.isUidActiveSynced(uid);
Makoto Onuki15407842018-01-19 14:23:11 -08001124 }
1125
Makoto Onukie4918212018-02-06 11:30:15 -08001126 private final Predicate<Integer> mIsUidActivePredicate = this::isUidActive;
Makoto Onuki15407842018-01-19 14:23:11 -08001127
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001128 public int scheduleAsPackage(JobInfo job, JobWorkItem work, int uId, String packageName,
1129 int userId, String tag) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001130 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001131 if (ActivityManager.getService().isAppStartModeDisabled(uId,
1132 job.getService().getPackageName())) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001133 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
1134 + " -- package not allowed to start");
1135 return JobScheduler.RESULT_FAILURE;
1136 }
1137 } catch (RemoteException e) {
1138 }
Christopher Tatea732f012017-10-26 17:26:53 -07001139
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001140 synchronized (mLock) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001141 final JobStatus toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
1142
1143 if (work != null && toCancel != null) {
1144 // Fast path: we are adding work to an existing job, and the JobInfo is not
1145 // changing. We can just directly enqueue this work in to the job.
1146 if (toCancel.getJob().equals(job)) {
Makoto Onuki15407842018-01-19 14:23:11 -08001147
Dianne Hackborn342e6032017-04-13 18:04:31 -07001148 toCancel.enqueueWorkLocked(ActivityManager.getService(), work);
Makoto Onuki15407842018-01-19 14:23:11 -08001149
1150 // If any of work item is enqueued when the source is in the foreground,
1151 // exempt the entire job.
Makoto Onukie4918212018-02-06 11:30:15 -08001152 toCancel.maybeAddForegroundExemption(mIsUidActivePredicate);
Makoto Onuki15407842018-01-19 14:23:11 -08001153
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001154 return JobScheduler.RESULT_SUCCESS;
1155 }
1156 }
1157
1158 JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
Makoto Onuki15407842018-01-19 14:23:11 -08001159
1160 // Give exemption if the source is in the foreground just now.
1161 // Note if it's a sync job, this method is called on the handler so it's not exactly
1162 // the state when requestSync() was called, but that should be fine because of the
1163 // 1 minute foreground grace period.
Makoto Onukie4918212018-02-06 11:30:15 -08001164 jobStatus.maybeAddForegroundExemption(mIsUidActivePredicate);
Makoto Onuki15407842018-01-19 14:23:11 -08001165
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001166 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
Christopher Tate2f36fd62016-02-18 18:36:08 -08001167 // Jobs on behalf of others don't apply to the per-app job cap
Christopher Tatedabdf6f2016-02-24 12:30:22 -08001168 if (ENFORCE_MAX_JOBS && packageName == null) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001169 if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
1170 Slog.w(TAG, "Too many jobs for uid " + uId);
1171 throw new IllegalStateException("Apps may not schedule more than "
1172 + MAX_JOBS_PER_APP + " distinct jobs");
1173 }
1174 }
1175
Dianne Hackborna47223f2017-03-30 13:49:13 -07001176 // This may throw a SecurityException.
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001177 jobStatus.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001178
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001179 if (work != null) {
1180 // If work has been supplied, enqueue it into the new job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07001181 jobStatus.enqueueWorkLocked(ActivityManager.getService(), work);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001182 }
Christopher Tate16032042018-10-05 15:53:50 -07001183
1184 if (toCancel != null) {
1185 // Implicitly replaces the existing job record with the new instance
1186 cancelJobImplLocked(toCancel, jobStatus, "job rescheduled by app");
1187 } else {
1188 startTrackingJobLocked(jobStatus, null);
1189 }
Tej Singhd5747a62018-01-08 20:57:35 -08001190 StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08001191 uId, null, jobStatus.getBatteryName(),
Tej Singh33a412b2018-03-16 18:43:59 -07001192 StatsLog.SCHEDULED_JOB_STATE_CHANGED__STATE__SCHEDULED,
1193 JobProtoEnums.STOP_REASON_CANCELLED);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001194
1195 // If the job is immediately ready to run, then we can just immediately
1196 // put it in the pending list and try to schedule it. This is especially
1197 // important for jobs with a 0 deadline constraint, since they will happen a fair
1198 // amount, we want to handle them as quickly as possible, and semantically we want to
1199 // make sure we have started holding the wake lock for the job before returning to
1200 // the caller.
1201 // If the job is not yet ready to run, there is nothing more to do -- we are
1202 // now just waiting for one of its controllers to change state and schedule
1203 // the job appropriately.
1204 if (isReadyToBeExecutedLocked(jobStatus)) {
1205 // This is a new job, we can just immediately put it on the pending
1206 // list and try to run it.
1207 mJobPackageTracker.notePending(jobStatus);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001208 addOrderedItem(mPendingJobs, jobStatus, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001209 maybeRunPendingJobsLocked();
Kweku Adamscdbfcb92018-12-06 17:05:15 -08001210 } else {
1211 evaluateControllerStatesLocked(jobStatus);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001212 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001213 }
Christopher Tate7060b042014-06-09 19:50:00 -07001214 return JobScheduler.RESULT_SUCCESS;
1215 }
1216
1217 public List<JobInfo> getPendingJobs(int uid) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001218 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001219 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
1220 ArrayList<JobInfo> outList = new ArrayList<JobInfo>(jobs.size());
1221 for (int i = jobs.size() - 1; i >= 0; i--) {
1222 JobStatus job = jobs.get(i);
1223 outList.add(job.getJob());
Christopher Tate7060b042014-06-09 19:50:00 -07001224 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001225 return outList;
Christopher Tate7060b042014-06-09 19:50:00 -07001226 }
Christopher Tate7060b042014-06-09 19:50:00 -07001227 }
1228
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001229 public JobInfo getPendingJob(int uid, int jobId) {
1230 synchronized (mLock) {
1231 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
1232 for (int i = jobs.size() - 1; i >= 0; i--) {
1233 JobStatus job = jobs.get(i);
1234 if (job.getJobId() == jobId) {
1235 return job.getJob();
1236 }
1237 }
1238 return null;
1239 }
1240 }
1241
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001242 void cancelJobsForUser(int userHandle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001243 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001244 final List<JobStatus> jobsForUser = mJobs.getJobsByUser(userHandle);
1245 for (int i=0; i<jobsForUser.size(); i++) {
1246 JobStatus toRemove = jobsForUser.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -07001247 cancelJobImplLocked(toRemove, null, "user removed");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001248 }
Christopher Tate7060b042014-06-09 19:50:00 -07001249 }
1250 }
1251
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07001252 private void cancelJobsForNonExistentUsers() {
1253 UserManagerInternal umi = LocalServices.getService(UserManagerInternal.class);
1254 synchronized (mLock) {
1255 mJobs.removeJobsOfNonUsers(umi.getUserIds());
1256 }
1257 }
1258
Makoto Onukie7b96182017-08-30 14:53:16 -07001259 void cancelJobsForPackageAndUid(String pkgName, int uid, String reason) {
1260 if ("android".equals(pkgName)) {
1261 Slog.wtfStack(TAG, "Can't cancel all jobs for system package");
1262 return;
1263 }
Christopher Tateee7805b2016-07-15 16:56:56 -07001264 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001265 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
1266 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
1267 final JobStatus job = jobsForUid.get(i);
1268 if (job.getSourcePackageName().equals(pkgName)) {
Makoto Onukie7b96182017-08-30 14:53:16 -07001269 cancelJobImplLocked(job, null, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001270 }
Christopher Tateee7805b2016-07-15 16:56:56 -07001271 }
1272 }
1273 }
1274
Christopher Tate7060b042014-06-09 19:50:00 -07001275 /**
1276 * Entry point from client to cancel all jobs originating from their uid.
1277 * This will remove the job from the master list, and cancel the job if it was staged for
1278 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -07001279 * @param uid Uid to check against for removal of a job.
Dianne Hackborne07641d2016-11-09 15:07:23 -08001280 *
Christopher Tate7060b042014-06-09 19:50:00 -07001281 */
Christopher Tate8c67d122017-09-29 16:54:26 -07001282 public boolean cancelJobsForUid(int uid, String reason) {
Makoto Onukie7b02982017-08-24 14:23:36 -07001283 if (uid == Process.SYSTEM_UID) {
Makoto Onukie7b96182017-08-30 14:53:16 -07001284 Slog.wtfStack(TAG, "Can't cancel all jobs for system uid");
Christopher Tate8c67d122017-09-29 16:54:26 -07001285 return false;
Makoto Onukie7b02982017-08-24 14:23:36 -07001286 }
Christopher Tate8c67d122017-09-29 16:54:26 -07001287
1288 boolean jobsCanceled = false;
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001289 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001290 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
1291 for (int i=0; i<jobsForUid.size(); i++) {
1292 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -07001293 cancelJobImplLocked(toRemove, null, reason);
Christopher Tate8c67d122017-09-29 16:54:26 -07001294 jobsCanceled = true;
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001295 }
Christopher Tate7060b042014-06-09 19:50:00 -07001296 }
Christopher Tate8c67d122017-09-29 16:54:26 -07001297 return jobsCanceled;
Christopher Tate7060b042014-06-09 19:50:00 -07001298 }
1299
1300 /**
1301 * Entry point from client to cancel the job corresponding to the jobId provided.
1302 * This will remove the job from the master list, and cancel the job if it was staged for
1303 * execution or being executed.
1304 * @param uid Uid of the calling client.
1305 * @param jobId Id of the job, provided at schedule-time.
1306 */
Makoto Onukid2bfec62018-01-12 13:58:01 -08001307 public boolean cancelJob(int uid, int jobId, int callingUid) {
Christopher Tate7060b042014-06-09 19:50:00 -07001308 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001309 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -07001310 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001311 if (toCancel != null) {
Makoto Onukid2bfec62018-01-12 13:58:01 -08001312 cancelJobImplLocked(toCancel, null,
1313 "cancel() called by app, callingUid=" + callingUid
1314 + " uid=" + uid + " jobId=" + jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001315 }
Christopher Tate8c67d122017-09-29 16:54:26 -07001316 return (toCancel != null);
Christopher Tate7060b042014-06-09 19:50:00 -07001317 }
1318 }
1319
Christopher Tate16032042018-10-05 15:53:50 -07001320 /**
1321 * Cancel the given job, stopping it if it's currently executing. If {@code incomingJob}
1322 * is null, the cancelled job is removed outright from the system. If
1323 * {@code incomingJob} is non-null, it replaces {@code cancelled} in the store of
1324 * currently scheduled jobs.
1325 */
Dianne Hackborn729a3282017-06-09 16:06:01 -07001326 private void cancelJobImplLocked(JobStatus cancelled, JobStatus incomingJob, String reason) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001327 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
1328 cancelled.unprepareLocked(ActivityManager.getService());
1329 stopTrackingJobLocked(cancelled, incomingJob, true /* writeBack */);
1330 // Remove from pending queue.
1331 if (mPendingJobs.remove(cancelled)) {
1332 mJobPackageTracker.noteNonpending(cancelled);
Matthew Williams48a30db2014-09-23 13:39:36 -07001333 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001334 // Cancel if running.
Dianne Hackborn729a3282017-06-09 16:06:01 -07001335 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED, reason);
Christopher Tate16032042018-10-05 15:53:50 -07001336 // If this is a replacement, bring in the new version of the job
1337 if (incomingJob != null) {
1338 if (DEBUG) Slog.i(TAG, "Tracking replacement job " + incomingJob.toShortString());
1339 startTrackingJobLocked(incomingJob, cancelled);
1340 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001341 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001342 }
1343
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001344 void updateUidState(int uid, int procState) {
1345 synchronized (mLock) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001346 if (procState == ActivityManager.PROCESS_STATE_TOP) {
1347 // Only use this if we are exactly the top app. All others can live
1348 // with just the foreground priority. This means that persistent processes
1349 // can never be the top app priority... that is fine.
1350 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_TOP_APP);
Makoto Onukiec8b14d2018-12-05 13:22:24 -08001351 } else if (procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
1352 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_FOREGROUND_SERVICE);
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08001353 } else if (procState <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Makoto Onukiec8b14d2018-12-05 13:22:24 -08001354 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_BOUND_FOREGROUND_SERVICE);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001355 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001356 mUidPriorityOverride.delete(uid);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001357 }
1358 }
1359 }
1360
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001361 @Override
1362 public void onDeviceIdleStateChanged(boolean deviceIdle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001363 synchronized (mLock) {
Makoto Onuki0f6499c2018-12-14 16:34:59 -08001364 if (DEBUG) {
1365 Slog.d(TAG, "Doze state changed: " + deviceIdle);
1366 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001367 if (deviceIdle) {
Jeff Sharkey34618b52016-06-01 15:51:19 -06001368 // When becoming idle, make sure no jobs are actively running,
1369 // except those using the idle exemption flag.
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001370 for (int i=0; i<mActiveServices.size(); i++) {
1371 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001372 final JobStatus executing = jsc.getRunningJobLocked();
Jeff Sharkey34618b52016-06-01 15:51:19 -06001373 if (executing != null
1374 && (executing.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07001375 jsc.cancelExecutingJobLocked(JobParameters.REASON_DEVICE_IDLE,
1376 "cancelled due to doze");
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001377 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001378 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001379 } else {
1380 // When coming out of idle, allow thing to start back up.
1381 if (mReadyToRock) {
1382 if (mLocalDeviceIdleController != null) {
1383 if (!mReportedActive) {
1384 mReportedActive = true;
1385 mLocalDeviceIdleController.setJobsActive(true);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001386 }
1387 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001388 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001389 }
1390 }
1391 }
1392 }
1393
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001394 void reportActiveLocked() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001395 // active is true if pending queue contains jobs OR some job is running.
1396 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001397 if (mPendingJobs.size() <= 0) {
1398 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07001399 final JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001400 final JobStatus job = jsc.getRunningJobLocked();
Dianne Hackborn7ab40252016-06-15 17:30:24 -07001401 if (job != null
1402 && (job.getJob().getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0
Christopher Tate20afddd2018-02-28 15:19:19 -08001403 && !job.dozeWhitelisted
1404 && !job.uidActive) {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07001405 // We will report active if we have a job running and it is not an exception
1406 // due to being in the foreground or whitelisted.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001407 active = true;
1408 break;
1409 }
1410 }
1411 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001412
1413 if (mReportedActive != active) {
1414 mReportedActive = active;
1415 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001416 mLocalDeviceIdleController.setJobsActive(active);
1417 }
1418 }
1419 }
1420
Christopher Tated117b292018-01-05 17:32:36 -08001421 void reportAppUsage(String packageName, int userId) {
1422 // This app just transitioned into interactive use or near equivalent, so we should
1423 // take a look at its job state for feedback purposes.
1424 }
1425
Christopher Tate7060b042014-06-09 19:50:00 -07001426 /**
1427 * Initializes the system service.
1428 * <p>
1429 * Subclasses must define a single argument constructor that accepts the context
1430 * and passes it to super.
1431 * </p>
1432 *
1433 * @param context The system server context.
1434 */
1435 public JobSchedulerService(Context context) {
1436 super(context);
Christopher Tatea732f012017-10-26 17:26:53 -07001437
1438 mLocalPM = LocalServices.getService(PackageManagerInternal.class);
Makoto Onuki15407842018-01-19 14:23:11 -08001439 mActivityManagerInternal = Preconditions.checkNotNull(
1440 LocalServices.getService(ActivityManagerInternal.class));
Christopher Tatea732f012017-10-26 17:26:53 -07001441
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001442 mHandler = new JobHandler(context.getMainLooper());
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001443 mConstants = new Constants();
1444 mConstantsObserver = new ConstantsObserver(mHandler);
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001445 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tatea732f012017-10-26 17:26:53 -07001446
Makoto Onuki714f97d2018-12-05 11:18:13 -08001447 mConcurrencyManager = new JobConcurrencyManager(this);
1448
Christopher Tatea732f012017-10-26 17:26:53 -07001449 // Set up the app standby bucketing tracker
Christopher Tated1aebb32018-01-31 13:24:14 -08001450 mStandbyTracker = new StandbyTracker();
1451 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
1452 mUsageStats.addAppIdleStateChangeListener(mStandbyTracker);
Christopher Tatea732f012017-10-26 17:26:53 -07001453
1454 // The job store needs to call back
1455 publishLocalService(JobSchedulerInternal.class, new LocalService());
1456
1457 // Initialize the job store and set up any persisted jobs
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001458 mJobs = JobStore.initAndGet(this);
1459
Christopher Tate7060b042014-06-09 19:50:00 -07001460 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001461 mControllers = new ArrayList<StateController>();
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001462 mControllers.add(new ConnectivityController(this));
1463 mControllers.add(new TimeController(this));
1464 mControllers.add(new IdleController(this));
1465 mBatteryController = new BatteryController(this);
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08001466 mControllers.add(mBatteryController);
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001467 mStorageController = new StorageController(this);
Dianne Hackborn532ea262017-03-17 17:50:55 -07001468 mControllers.add(mStorageController);
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001469 mControllers.add(new BackgroundJobsController(this));
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001470 mControllers.add(new ContentObserverController(this));
1471 mDeviceIdleJobsController = new DeviceIdleJobsController(this);
Suprabh Shukla106203b2017-11-02 21:23:44 -07001472 mControllers.add(mDeviceIdleJobsController);
Kweku Adams4836f9d2018-11-12 17:04:17 -08001473 mControllers.add(new QuotaController(this));
Christopher Tate616541d2017-07-26 14:27:38 -07001474
1475 // If the job store determined that it can't yet reschedule persisted jobs,
1476 // we need to start watching the clock.
1477 if (!mJobs.jobTimesInflatedValid()) {
1478 Slog.w(TAG, "!!! RTC not yet good; tracking time updates for job scheduling");
1479 context.registerReceiver(mTimeSetReceiver, new IntentFilter(Intent.ACTION_TIME_CHANGED));
1480 }
Christopher Tate7060b042014-06-09 19:50:00 -07001481 }
1482
Christopher Tate616541d2017-07-26 14:27:38 -07001483 private final BroadcastReceiver mTimeSetReceiver = new BroadcastReceiver() {
1484 @Override
1485 public void onReceive(Context context, Intent intent) {
1486 if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) {
1487 // When we reach clock sanity, recalculate the temporal windows
1488 // of all affected jobs.
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001489 if (mJobs.clockNowValidToInflate(sSystemClock.millis())) {
Christopher Tate616541d2017-07-26 14:27:38 -07001490 Slog.i(TAG, "RTC now valid; recalculating persisted job windows");
1491
1492 // We've done our job now, so stop watching the time.
1493 context.unregisterReceiver(this);
1494
1495 // And kick off the work to update the affected jobs, using a secondary
1496 // thread instead of chugging away here on the main looper thread.
1497 FgThread.getHandler().post(mJobTimeUpdater);
1498 }
1499 }
1500 }
1501 };
1502
1503 private final Runnable mJobTimeUpdater = () -> {
1504 final ArrayList<JobStatus> toRemove = new ArrayList<>();
1505 final ArrayList<JobStatus> toAdd = new ArrayList<>();
1506 synchronized (mLock) {
1507 // Note: we intentionally both look up the existing affected jobs and replace them
1508 // with recalculated ones inside the same lock lifetime.
1509 getJobStore().getRtcCorrectedJobsLocked(toAdd, toRemove);
1510
1511 // Now, at each position [i], we have both the existing JobStatus
1512 // and the one that replaces it.
1513 final int N = toAdd.size();
1514 for (int i = 0; i < N; i++) {
1515 final JobStatus oldJob = toRemove.get(i);
1516 final JobStatus newJob = toAdd.get(i);
1517 if (DEBUG) {
1518 Slog.v(TAG, " replacing " + oldJob + " with " + newJob);
1519 }
1520 cancelJobImplLocked(oldJob, newJob, "deferred rtc calculation");
1521 }
1522 }
1523 };
1524
Christopher Tate7060b042014-06-09 19:50:00 -07001525 @Override
1526 public void onStart() {
1527 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
1528 }
1529
1530 @Override
1531 public void onBootPhase(int phase) {
1532 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001533 mConstantsObserver.start(getContext().getContentResolver());
Makoto Onuki15407842018-01-19 14:23:11 -08001534
Makoto Onukie4918212018-02-06 11:30:15 -08001535 mAppStateTracker = Preconditions.checkNotNull(
1536 LocalServices.getService(AppStateTracker.class));
Kweku Adams4836f9d2018-11-12 17:04:17 -08001537 if (mConstants.USE_HEARTBEATS) {
1538 setNextHeartbeatAlarm();
1539 }
Makoto Onuki15407842018-01-19 14:23:11 -08001540
Shreyas Basarge5db09082016-01-07 13:38:29 +00001541 // Register br for package removals and user removals.
Christopher Tateb5c07882016-05-26 17:11:09 -07001542 final IntentFilter filter = new IntentFilter();
1543 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1544 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Christopher Tateee7805b2016-07-15 16:56:56 -07001545 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
1546 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
Christopher Tate7060b042014-06-09 19:50:00 -07001547 filter.addDataScheme("package");
1548 getContext().registerReceiverAsUser(
1549 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
1550 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
1551 getContext().registerReceiverAsUser(
1552 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001553 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001554 ActivityManager.getService().registerUidObserver(mUidObserver,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001555 ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001556 | ActivityManager.UID_OBSERVER_IDLE | ActivityManager.UID_OBSERVER_ACTIVE,
1557 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001558 } catch (RemoteException e) {
1559 // ignored; both services live in system_server
1560 }
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07001561 // Remove any jobs that are not associated with any of the current users.
1562 cancelJobsForNonExistentUsers();
Wei Wang8c0c3c12018-11-14 14:56:52 -08001563 // Register thermal callback
1564 mThermalService = IThermalService.Stub.asInterface(
1565 ServiceManager.getService(Context.THERMAL_SERVICE));
1566 if (mThermalService != null) {
1567 try {
1568 mThermalService.registerThermalStatusListener(new ThermalStatusListener());
1569 } catch (RemoteException e) {
1570 Slog.e(TAG, "Failed to register thermal callback.", e);
1571 }
1572 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001573 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001574 synchronized (mLock) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001575 // Let's go!
1576 mReadyToRock = true;
1577 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
1578 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001579 mLocalDeviceIdleController
1580 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001581 // Create the "runners".
1582 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
1583 mActiveServices.add(
Dianne Hackborn807de782016-04-07 17:54:41 -07001584 new JobServiceContext(this, mBatteryStats, mJobPackageTracker,
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001585 getContext().getMainLooper()));
1586 }
1587 // Attach jobs to their controllers.
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07001588 mJobs.forEachJob((job) -> {
1589 for (int controller = 0; controller < mControllers.size(); controller++) {
1590 final StateController sc = mControllers.get(controller);
1591 sc.maybeStartTrackingJobLocked(job, null);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001592 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001593 });
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001594 // GO GO GO!
1595 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1596 }
Christopher Tate7060b042014-06-09 19:50:00 -07001597 }
1598 }
1599
1600 /**
1601 * Called when we have a job status object that we need to insert in our
1602 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
1603 * about.
1604 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001605 private void startTrackingJobLocked(JobStatus jobStatus, JobStatus lastJob) {
1606 if (!jobStatus.isPreparedLocked()) {
1607 Slog.wtf(TAG, "Not yet prepared when started tracking: " + jobStatus);
1608 }
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001609 jobStatus.enqueueTime = sElapsedRealtimeClock.millis();
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001610 final boolean update = mJobs.add(jobStatus);
1611 if (mReadyToRock) {
1612 for (int i = 0; i < mControllers.size(); i++) {
1613 StateController controller = mControllers.get(i);
1614 if (update) {
1615 controller.maybeStopTrackingJobLocked(jobStatus, null, true);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001616 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001617 controller.maybeStartTrackingJobLocked(jobStatus, lastJob);
Christopher Tate7060b042014-06-09 19:50:00 -07001618 }
Christopher Tate7060b042014-06-09 19:50:00 -07001619 }
1620 }
1621
1622 /**
1623 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
1624 * object removed.
1625 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001626 private boolean stopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob,
Dianne Hackborn141f11c2016-04-05 15:46:12 -07001627 boolean writeBack) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001628 // Deal with any remaining work items in the old job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07001629 jobStatus.stopTrackingJobLocked(ActivityManager.getService(), incomingJob);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001630
1631 // Remove from store as well as controllers.
1632 final boolean removed = mJobs.remove(jobStatus, writeBack);
1633 if (removed && mReadyToRock) {
1634 for (int i=0; i<mControllers.size(); i++) {
1635 StateController controller = mControllers.get(i);
1636 controller.maybeStopTrackingJobLocked(jobStatus, incomingJob, false);
Christopher Tate7060b042014-06-09 19:50:00 -07001637 }
1638 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001639 return removed;
Christopher Tate7060b042014-06-09 19:50:00 -07001640 }
1641
Dianne Hackborn729a3282017-06-09 16:06:01 -07001642 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason, String debugReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001643 for (int i=0; i<mActiveServices.size(); i++) {
1644 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001645 final JobStatus executing = jsc.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001646 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07001647 jsc.cancelExecutingJobLocked(reason, debugReason);
Christopher Tate7060b042014-06-09 19:50:00 -07001648 return true;
1649 }
1650 }
1651 return false;
1652 }
1653
1654 /**
1655 * @param job JobStatus we are querying against.
1656 * @return Whether or not the job represented by the status object is currently being run or
1657 * is pending.
1658 */
1659 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001660 for (int i=0; i<mActiveServices.size(); i++) {
1661 JobServiceContext serviceContext = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001662 final JobStatus running = serviceContext.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001663 if (running != null && running.matches(job.getUid(), job.getJobId())) {
1664 return true;
1665 }
1666 }
1667 return false;
1668 }
1669
Dianne Hackborn807de782016-04-07 17:54:41 -07001670 void noteJobsPending(List<JobStatus> jobs) {
1671 for (int i = jobs.size() - 1; i >= 0; i--) {
1672 JobStatus job = jobs.get(i);
1673 mJobPackageTracker.notePending(job);
1674 }
1675 }
1676
1677 void noteJobsNonpending(List<JobStatus> jobs) {
1678 for (int i = jobs.size() - 1; i >= 0; i--) {
1679 JobStatus job = jobs.get(i);
1680 mJobPackageTracker.noteNonpending(job);
1681 }
1682 }
1683
Christopher Tate7060b042014-06-09 19:50:00 -07001684 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001685 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
1686 * specify an override deadline on a failed job (the failed job will run even though it's not
1687 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
1688 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
1689 *
Christopher Tate7060b042014-06-09 19:50:00 -07001690 * @param failureToReschedule Provided job status that we will reschedule.
1691 * @return A newly instantiated JobStatus with the same constraints as the last job except
1692 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001693 *
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001694 * @see #maybeQueueReadyJobsForExecutionLocked
Christopher Tate7060b042014-06-09 19:50:00 -07001695 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001696 private JobStatus getRescheduleJobForFailureLocked(JobStatus failureToReschedule) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001697 final long elapsedNowMillis = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -07001698 final JobInfo job = failureToReschedule.getJob();
1699
1700 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -07001701 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
1702 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -07001703
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001704 if (failureToReschedule.hasWorkLocked()) {
1705 if (backoffAttempts > mConstants.MAX_WORK_RESCHEDULE_COUNT) {
1706 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1707 + backoffAttempts + " > work limit "
1708 + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1709 return null;
1710 }
1711 } else if (backoffAttempts > mConstants.MAX_STANDARD_RESCHEDULE_COUNT) {
1712 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1713 + backoffAttempts + " > std limit " + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1714 return null;
1715 }
1716
Christopher Tate7060b042014-06-09 19:50:00 -07001717 switch (job.getBackoffPolicy()) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001718 case JobInfo.BACKOFF_POLICY_LINEAR: {
1719 long backoff = initialBackoffMillis;
1720 if (backoff < mConstants.MIN_LINEAR_BACKOFF_TIME) {
1721 backoff = mConstants.MIN_LINEAR_BACKOFF_TIME;
1722 }
1723 delayMillis = backoff * backoffAttempts;
1724 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001725 default:
1726 if (DEBUG) {
1727 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
1728 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001729 case JobInfo.BACKOFF_POLICY_EXPONENTIAL: {
1730 long backoff = initialBackoffMillis;
1731 if (backoff < mConstants.MIN_EXP_BACKOFF_TIME) {
1732 backoff = mConstants.MIN_EXP_BACKOFF_TIME;
1733 }
1734 delayMillis = (long) Math.scalb(backoff, backoffAttempts - 1);
1735 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001736 }
Matthew Williamsd1c06752014-08-22 14:15:28 -07001737 delayMillis =
1738 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
Christopher Tatea732f012017-10-26 17:26:53 -07001739 JobStatus newJob = new JobStatus(failureToReschedule, getCurrentHeartbeat(),
1740 elapsedNowMillis + delayMillis,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001741 JobStatus.NO_LATEST_RUNTIME, backoffAttempts,
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001742 failureToReschedule.getLastSuccessfulRunTime(), sSystemClock.millis());
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001743 for (int ic=0; ic<mControllers.size(); ic++) {
1744 StateController controller = mControllers.get(ic);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001745 controller.rescheduleForFailureLocked(newJob, failureToReschedule);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001746 }
1747 return newJob;
Christopher Tate7060b042014-06-09 19:50:00 -07001748 }
1749
1750 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001751 * Called after a periodic has executed so we can reschedule it. We take the last execution
1752 * time of the job to be the time of completion (i.e. the time at which this function is
1753 * called).
Christopher Tatea732f012017-10-26 17:26:53 -07001754 * <p>This could be inaccurate b/c the job can run for as long as
Christopher Tate7060b042014-06-09 19:50:00 -07001755 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
1756 * to underscheduling at least, rather than if we had taken the last execution time to be the
1757 * start of the execution.
Christopher Tatea732f012017-10-26 17:26:53 -07001758 * <p>Unlike a reschedule prior to execution, in this case we advance the next-heartbeat
1759 * tracking as though the job were newly-scheduled.
Christopher Tate7060b042014-06-09 19:50:00 -07001760 * @return A new job representing the execution criteria for this instantiation of the
1761 * recurring job.
1762 */
1763 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001764 final long elapsedNow = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -07001765 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001766 long runEarly = 0L;
1767
1768 // If this periodic was rescheduled it won't have a deadline.
1769 if (periodicToReschedule.hasDeadlineConstraint()) {
1770 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
1771 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001772 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -07001773 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001774 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
1775 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -07001776
1777 if (DEBUG) {
1778 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
1779 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
1780 }
Christopher Tatea732f012017-10-26 17:26:53 -07001781 return new JobStatus(periodicToReschedule, getCurrentHeartbeat(),
1782 newEarliestRunTimeElapsed, newLatestRuntimeElapsed,
1783 0 /* backoffAttempt */,
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001784 sSystemClock.millis() /* lastSuccessfulRunTime */,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001785 periodicToReschedule.getLastFailedRunTime());
Christopher Tate7060b042014-06-09 19:50:00 -07001786 }
1787
Christopher Tate325768c2018-03-07 16:07:56 -08001788 /*
1789 * We default to "long enough ago that every bucket's jobs are immediately runnable" to
1790 * avoid starvation of apps in uncommon-use buckets that might arise from repeated
1791 * reboot behavior.
1792 */
Christopher Tated1aebb32018-01-31 13:24:14 -08001793 long heartbeatWhenJobsLastRun(String packageName, final @UserIdInt int userId) {
Christopher Tate325768c2018-03-07 16:07:56 -08001794 // The furthest back in pre-boot time that we need to bother with
1795 long heartbeat = -mConstants.STANDBY_BEATS[RARE_INDEX];
1796 boolean cacheHit = false;
Christopher Tated1aebb32018-01-31 13:24:14 -08001797 synchronized (mLock) {
Christopher Tate325768c2018-03-07 16:07:56 -08001798 HashMap<String, Long> jobPackages = mLastJobHeartbeats.get(userId);
1799 if (jobPackages != null) {
1800 long cachedValue = jobPackages.getOrDefault(packageName, Long.MAX_VALUE);
1801 if (cachedValue < Long.MAX_VALUE) {
1802 cacheHit = true;
1803 heartbeat = cachedValue;
1804 }
1805 }
1806 if (!cacheHit) {
1807 // We haven't seen it yet; ask usage stats about it
1808 final long timeSinceJob = mUsageStats.getTimeSinceLastJobRun(packageName, userId);
1809 if (timeSinceJob < Long.MAX_VALUE) {
1810 // Usage stats knows about it from before, so calculate back from that
1811 // and go from there.
1812 heartbeat = mHeartbeat - (timeSinceJob / mConstants.STANDBY_HEARTBEAT_TIME);
1813 }
1814 // If usage stats returned its "not found" MAX_VALUE, we still have the
1815 // negative default 'heartbeat' value we established above
1816 setLastJobHeartbeatLocked(packageName, userId, heartbeat);
1817 }
Christopher Tated1aebb32018-01-31 13:24:14 -08001818 }
1819 if (DEBUG_STANDBY) {
Christopher Tate325768c2018-03-07 16:07:56 -08001820 Slog.v(TAG, "Last job heartbeat " + heartbeat + " for "
1821 + packageName + "/" + userId);
Christopher Tated1aebb32018-01-31 13:24:14 -08001822 }
1823 return heartbeat;
1824 }
1825
1826 long heartbeatWhenJobsLastRun(JobStatus job) {
1827 return heartbeatWhenJobsLastRun(job.getSourcePackageName(), job.getSourceUserId());
1828 }
1829
Christopher Tate325768c2018-03-07 16:07:56 -08001830 void setLastJobHeartbeatLocked(String packageName, int userId, long heartbeat) {
1831 HashMap<String, Long> jobPackages = mLastJobHeartbeats.get(userId);
1832 if (jobPackages == null) {
1833 jobPackages = new HashMap<>();
1834 mLastJobHeartbeats.put(userId, jobPackages);
1835 }
1836 jobPackages.put(packageName, heartbeat);
1837 }
1838
Christopher Tate7060b042014-06-09 19:50:00 -07001839 // JobCompletedListener implementations.
1840
1841 /**
1842 * A job just finished executing. We fetch the
1843 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
Christopher Tate325768c2018-03-07 16:07:56 -08001844 * whether we want to reschedule we re-add it to the controllers.
Christopher Tate7060b042014-06-09 19:50:00 -07001845 * @param jobStatus Completed job.
1846 * @param needsReschedule Whether the implementing class should reschedule this job.
1847 */
1848 @Override
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001849 public void onJobCompletedLocked(JobStatus jobStatus, boolean needsReschedule) {
Christopher Tate7060b042014-06-09 19:50:00 -07001850 if (DEBUG) {
1851 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
1852 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001853
1854 // If the job wants to be rescheduled, we first need to make the next upcoming
1855 // job so we can transfer any appropriate state over from the previous job when
1856 // we stop it.
1857 final JobStatus rescheduledJob = needsReschedule
1858 ? getRescheduleJobForFailureLocked(jobStatus) : null;
1859
Shreyas Basarge73f10252016-02-11 17:06:13 +00001860 // Do not write back immediately if this is a periodic job. The job may get lost if system
1861 // shuts down before it is added back.
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001862 if (!stopTrackingJobLocked(jobStatus, rescheduledJob, !jobStatus.getJob().isPeriodic())) {
Christopher Tate7060b042014-06-09 19:50:00 -07001863 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001864 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -07001865 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001866 // We still want to check for jobs to execute, because this job may have
1867 // scheduled a new job under the same job id, and now we can run it.
1868 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001869 return;
1870 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001871
1872 if (rescheduledJob != null) {
Dianne Hackborna47223f2017-03-30 13:49:13 -07001873 try {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001874 rescheduledJob.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001875 } catch (SecurityException e) {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001876 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledJob);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001877 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001878 startTrackingJobLocked(rescheduledJob, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001879 } else if (jobStatus.getJob().isPeriodic()) {
1880 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001881 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001882 rescheduledPeriodic.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001883 } catch (SecurityException e) {
1884 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledPeriodic);
1885 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001886 startTrackingJobLocked(rescheduledPeriodic, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001887 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001888 jobStatus.unprepareLocked(ActivityManager.getService());
1889 reportActiveLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001890 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001891 }
1892
1893 // StateChangedListener implementations.
1894
1895 /**
Matthew Williams48a30db2014-09-23 13:39:36 -07001896 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
1897 * some controller's state has changed, so as to run through the list of jobs and start/stop
1898 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -07001899 */
1900 @Override
1901 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -07001902 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001903 }
1904
1905 @Override
1906 public void onRunJobNow(JobStatus jobStatus) {
1907 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
1908 }
1909
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001910 final private class JobHandler extends Handler {
Christopher Tate7060b042014-06-09 19:50:00 -07001911
1912 public JobHandler(Looper looper) {
1913 super(looper);
1914 }
1915
1916 @Override
1917 public void handleMessage(Message message) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001918 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -07001919 if (!mReadyToRock) {
1920 return;
1921 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001922 switch (message.what) {
1923 case MSG_JOB_EXPIRED: {
Christopher Tate7060b042014-06-09 19:50:00 -07001924 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -07001925 // runNow can be null, which is a controller's way of indicating that its
1926 // state is such that all ready jobs should be run immediately.
Christopher Tateb1d64482017-03-15 12:01:22 -07001927 if (runNow != null && isReadyToBeExecutedLocked(runNow)) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001928 mJobPackageTracker.notePending(runNow);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001929 addOrderedItem(mPendingJobs, runNow, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001930 } else {
1931 queueReadyJobsForExecutionLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001932 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001933 } break;
1934 case MSG_CHECK_JOB:
Makoto Onuki0f6499c2018-12-14 16:34:59 -08001935 if (DEBUG) {
1936 Slog.d(TAG, "MSG_CHECK_JOB");
1937 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001938 if (mReportedActive) {
1939 // if jobs are currently being run, queue all ready jobs for execution.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001940 queueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001941 } else {
1942 // Check the list of jobs and run some of them if we feel inclined.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001943 maybeQueueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001944 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001945 break;
1946 case MSG_CHECK_JOB_GREEDY:
Makoto Onuki0f6499c2018-12-14 16:34:59 -08001947 if (DEBUG) {
1948 Slog.d(TAG, "MSG_CHECK_JOB_GREEDY");
1949 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001950 queueReadyJobsForExecutionLocked();
1951 break;
1952 case MSG_STOP_JOB:
Dianne Hackborn729a3282017-06-09 16:06:01 -07001953 cancelJobImplLocked((JobStatus) message.obj, null,
1954 "app no longer allowed to run");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001955 break;
Makoto Onuki743e0ad2018-02-20 16:01:11 -08001956
1957 case MSG_UID_STATE_CHANGED: {
1958 final int uid = message.arg1;
1959 final int procState = message.arg2;
1960 updateUidState(uid, procState);
1961 break;
1962 }
1963 case MSG_UID_GONE: {
1964 final int uid = message.arg1;
1965 final boolean disabled = message.arg2 != 0;
1966 updateUidState(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
1967 if (disabled) {
1968 cancelJobsForUid(uid, "uid gone");
1969 }
1970 synchronized (mLock) {
1971 mDeviceIdleJobsController.setUidActiveLocked(uid, false);
1972 }
1973 break;
1974 }
1975 case MSG_UID_ACTIVE: {
1976 final int uid = message.arg1;
1977 synchronized (mLock) {
1978 mDeviceIdleJobsController.setUidActiveLocked(uid, true);
1979 }
1980 break;
1981 }
1982 case MSG_UID_IDLE: {
1983 final int uid = message.arg1;
1984 final boolean disabled = message.arg2 != 0;
1985 if (disabled) {
1986 cancelJobsForUid(uid, "app uid idle");
1987 }
1988 synchronized (mLock) {
1989 mDeviceIdleJobsController.setUidActiveLocked(uid, false);
1990 }
1991 break;
1992 }
1993
Matthew Williams75fc5252014-09-02 16:17:53 -07001994 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001995 maybeRunPendingJobsLocked();
1996 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
1997 removeMessages(MSG_CHECK_JOB);
Christopher Tate7060b042014-06-09 19:50:00 -07001998 }
1999 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002000 }
Christopher Tate7060b042014-06-09 19:50:00 -07002001
Wei Wang8c0c3c12018-11-14 14:56:52 -08002002 private boolean isJobThermalConstrainedLocked(JobStatus job) {
2003 return mThermalConstraint && job.hasConnectivityConstraint()
2004 && (evaluateJobPriorityLocked(job) < JobInfo.PRIORITY_FOREGROUND_APP);
2005 }
2006
Dianne Hackborn6d068262017-05-16 13:14:37 -07002007 private void stopNonReadyActiveJobsLocked() {
2008 for (int i=0; i<mActiveServices.size(); i++) {
2009 JobServiceContext serviceContext = mActiveServices.get(i);
2010 final JobStatus running = serviceContext.getRunningJobLocked();
Wei Wang8c0c3c12018-11-14 14:56:52 -08002011 if (running == null) {
2012 continue;
2013 }
2014 if (!running.isReady()) {
Dianne Hackborn6d068262017-05-16 13:14:37 -07002015 serviceContext.cancelExecutingJobLocked(
Dianne Hackborn729a3282017-06-09 16:06:01 -07002016 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED,
2017 "cancelled due to unsatisfied constraints");
Wei Wang8c0c3c12018-11-14 14:56:52 -08002018 } else if (isJobThermalConstrainedLocked(running)) {
2019 serviceContext.cancelExecutingJobLocked(
2020 JobParameters.REASON_DEVICE_THERMAL,
2021 "cancelled due to thermal condition");
Dianne Hackborn6d068262017-05-16 13:14:37 -07002022 }
2023 }
2024 }
2025
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002026 /**
2027 * Run through list of jobs and execute all possible - at least one is expired so we do
2028 * as many as we can.
2029 */
2030 private void queueReadyJobsForExecutionLocked() {
2031 if (DEBUG) {
2032 Slog.d(TAG, "queuing all ready jobs for execution:");
2033 }
2034 noteJobsNonpending(mPendingJobs);
2035 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07002036 stopNonReadyActiveJobsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002037 mJobs.forEachJob(mReadyQueueFunctor);
2038 mReadyQueueFunctor.postProcess();
Christopher Tate2f36fd62016-02-18 18:36:08 -08002039
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002040 if (DEBUG) {
2041 final int queuedJobs = mPendingJobs.size();
2042 if (queuedJobs == 0) {
2043 Slog.d(TAG, "No jobs pending.");
2044 } else {
2045 Slog.d(TAG, queuedJobs + " jobs queued.");
Christopher Tate2f36fd62016-02-18 18:36:08 -08002046 }
2047 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002048 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002049
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002050 final class ReadyJobQueueFunctor implements Consumer<JobStatus> {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002051 ArrayList<JobStatus> newReadyJobs;
Christopher Tate2f36fd62016-02-18 18:36:08 -08002052
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002053 @Override
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002054 public void accept(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002055 if (isReadyToBeExecutedLocked(job)) {
Matthew Williams75fc5252014-09-02 16:17:53 -07002056 if (DEBUG) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002057 Slog.d(TAG, " queued " + job.toShortString());
Matthew Williams75fc5252014-09-02 16:17:53 -07002058 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002059 if (newReadyJobs == null) {
2060 newReadyJobs = new ArrayList<JobStatus>();
2061 }
2062 newReadyJobs.add(job);
Kweku Adamscdbfcb92018-12-06 17:05:15 -08002063 } else {
2064 evaluateControllerStatesLocked(job);
Christopher Tate7060b042014-06-09 19:50:00 -07002065 }
2066 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002067
2068 public void postProcess() {
2069 if (newReadyJobs != null) {
2070 noteJobsPending(newReadyJobs);
2071 mPendingJobs.addAll(newReadyJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002072 if (mPendingJobs.size() > 1) {
2073 mPendingJobs.sort(mEnqueueTimeComparator);
2074 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002075 }
2076 newReadyJobs = null;
2077 }
2078 }
2079 private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
2080
2081 /**
2082 * The state of at least one job has changed. Here is where we could enforce various
2083 * policies on when we want to execute jobs.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002084 */
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002085 final class MaybeReadyJobQueueFunctor implements Consumer<JobStatus> {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002086 int chargingCount;
2087 int batteryNotLowCount;
2088 int storageNotLowCount;
2089 int idleCount;
2090 int backoffCount;
2091 int connectivityCount;
2092 int contentCount;
2093 List<JobStatus> runnableJobs;
2094
2095 public MaybeReadyJobQueueFunctor() {
2096 reset();
2097 }
2098
2099 // Functor method invoked for each job via JobStore.forEachJob()
2100 @Override
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002101 public void accept(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002102 if (isReadyToBeExecutedLocked(job)) {
2103 try {
2104 if (ActivityManager.getService().isAppStartModeDisabled(job.getUid(),
2105 job.getJob().getService().getPackageName())) {
2106 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
2107 + job.getJob().toString() + " -- package not allowed to start");
2108 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
2109 return;
2110 }
2111 } catch (RemoteException e) {
2112 }
2113 if (job.getNumFailures() > 0) {
2114 backoffCount++;
2115 }
2116 if (job.hasIdleConstraint()) {
2117 idleCount++;
2118 }
2119 if (job.hasConnectivityConstraint()) {
2120 connectivityCount++;
2121 }
2122 if (job.hasChargingConstraint()) {
2123 chargingCount++;
2124 }
2125 if (job.hasBatteryNotLowConstraint()) {
2126 batteryNotLowCount++;
2127 }
2128 if (job.hasStorageNotLowConstraint()) {
2129 storageNotLowCount++;
2130 }
2131 if (job.hasContentTriggerConstraint()) {
2132 contentCount++;
2133 }
2134 if (runnableJobs == null) {
2135 runnableJobs = new ArrayList<>();
2136 }
2137 runnableJobs.add(job);
Kweku Adamscdbfcb92018-12-06 17:05:15 -08002138 } else {
2139 evaluateControllerStatesLocked(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002140 }
2141 }
2142
2143 public void postProcess() {
2144 if (backoffCount > 0 ||
2145 idleCount >= mConstants.MIN_IDLE_COUNT ||
2146 connectivityCount >= mConstants.MIN_CONNECTIVITY_COUNT ||
2147 chargingCount >= mConstants.MIN_CHARGING_COUNT ||
2148 batteryNotLowCount >= mConstants.MIN_BATTERY_NOT_LOW_COUNT ||
2149 storageNotLowCount >= mConstants.MIN_STORAGE_NOT_LOW_COUNT ||
2150 contentCount >= mConstants.MIN_CONTENT_COUNT ||
2151 (runnableJobs != null
2152 && runnableJobs.size() >= mConstants.MIN_READY_JOBS_COUNT)) {
2153 if (DEBUG) {
2154 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Running jobs.");
2155 }
2156 noteJobsPending(runnableJobs);
2157 mPendingJobs.addAll(runnableJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002158 if (mPendingJobs.size() > 1) {
2159 mPendingJobs.sort(mEnqueueTimeComparator);
2160 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002161 } else {
2162 if (DEBUG) {
2163 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Not running anything.");
2164 }
2165 }
2166
2167 // Be ready for next time
2168 reset();
2169 }
2170
2171 private void reset() {
2172 chargingCount = 0;
2173 idleCount = 0;
2174 backoffCount = 0;
2175 connectivityCount = 0;
2176 batteryNotLowCount = 0;
2177 storageNotLowCount = 0;
2178 contentCount = 0;
2179 runnableJobs = null;
2180 }
2181 }
2182 private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
2183
2184 private void maybeQueueReadyJobsForExecutionLocked() {
2185 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
2186
2187 noteJobsNonpending(mPendingJobs);
2188 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07002189 stopNonReadyActiveJobsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002190 mJobs.forEachJob(mMaybeQueueFunctor);
2191 mMaybeQueueFunctor.postProcess();
2192 }
2193
Christopher Tated1aebb32018-01-31 13:24:14 -08002194 /**
2195 * Heartbeat tracking. The heartbeat alarm is intentionally non-wakeup.
2196 */
2197 class HeartbeatAlarmListener implements AlarmManager.OnAlarmListener {
2198
2199 @Override
2200 public void onAlarm() {
2201 synchronized (mLock) {
2202 final long sinceLast = sElapsedRealtimeClock.millis() - mLastHeartbeatTime;
2203 final long beatsElapsed = sinceLast / mConstants.STANDBY_HEARTBEAT_TIME;
2204 if (beatsElapsed > 0) {
2205 mLastHeartbeatTime += beatsElapsed * mConstants.STANDBY_HEARTBEAT_TIME;
2206 advanceHeartbeatLocked(beatsElapsed);
2207 }
Christopher Tatea732f012017-10-26 17:26:53 -07002208 }
Christopher Tated1aebb32018-01-31 13:24:14 -08002209 setNextHeartbeatAlarm();
Christopher Tatea732f012017-10-26 17:26:53 -07002210 }
Christopher Tatea732f012017-10-26 17:26:53 -07002211 }
2212
Christopher Tated1aebb32018-01-31 13:24:14 -08002213 // Intentionally does not touch the alarm timing
2214 void advanceHeartbeatLocked(long beatsElapsed) {
Kweku Adams4836f9d2018-11-12 17:04:17 -08002215 if (!mConstants.USE_HEARTBEATS) {
2216 return;
2217 }
Christopher Tated1aebb32018-01-31 13:24:14 -08002218 mHeartbeat += beatsElapsed;
2219 if (DEBUG_STANDBY) {
2220 Slog.v(TAG, "Advancing standby heartbeat by " + beatsElapsed
2221 + " to " + mHeartbeat);
2222 }
2223 // Don't update ACTIVE or NEVER bucket milestones. Note that mHeartbeat
2224 // will be equal to mNextBucketHeartbeat[bucket] for one beat, during which
2225 // new jobs scheduled by apps in that bucket will be permitted to run
2226 // immediately.
2227 boolean didAdvanceBucket = false;
Christopher Tatea732f012017-10-26 17:26:53 -07002228 for (int i = 1; i < mNextBucketHeartbeat.length - 1; i++) {
Christopher Tated1aebb32018-01-31 13:24:14 -08002229 // Did we reach or cross a bucket boundary?
2230 if (mHeartbeat >= mNextBucketHeartbeat[i]) {
2231 didAdvanceBucket = true;
2232 }
2233 while (mHeartbeat > mNextBucketHeartbeat[i]) {
Christopher Tatea732f012017-10-26 17:26:53 -07002234 mNextBucketHeartbeat[i] += mConstants.STANDBY_BEATS[i];
2235 }
2236 if (DEBUG_STANDBY) {
Christopher Tated1aebb32018-01-31 13:24:14 -08002237 Slog.v(TAG, " Bucket " + i + " next heartbeat "
2238 + mNextBucketHeartbeat[i]);
Christopher Tatea732f012017-10-26 17:26:53 -07002239 }
2240 }
Christopher Tated1aebb32018-01-31 13:24:14 -08002241
2242 if (didAdvanceBucket) {
2243 if (DEBUG_STANDBY) {
2244 Slog.v(TAG, "Hit bucket boundary; reevaluating job runnability");
2245 }
2246 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2247 }
2248 }
2249
2250 void setNextHeartbeatAlarm() {
2251 final long heartbeatLength;
2252 synchronized (mLock) {
Kweku Adams4836f9d2018-11-12 17:04:17 -08002253 if (!mConstants.USE_HEARTBEATS) {
2254 return;
2255 }
Christopher Tated1aebb32018-01-31 13:24:14 -08002256 heartbeatLength = mConstants.STANDBY_HEARTBEAT_TIME;
2257 }
2258 final long now = sElapsedRealtimeClock.millis();
2259 final long nextBeatOrdinal = (now + heartbeatLength) / heartbeatLength;
2260 final long nextHeartbeat = nextBeatOrdinal * heartbeatLength;
2261 if (DEBUG_STANDBY) {
2262 Slog.i(TAG, "Setting heartbeat alarm for " + nextHeartbeat
2263 + " = " + TimeUtils.formatDuration(nextHeartbeat - now));
2264 }
2265 AlarmManager am = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
2266 am.setExact(AlarmManager.ELAPSED_REALTIME, nextHeartbeat,
2267 HEARTBEAT_TAG, mHeartbeatAlarm, mHandler);
Christopher Tatea732f012017-10-26 17:26:53 -07002268 }
2269
Kweku Adamscdbfcb92018-12-06 17:05:15 -08002270 /** Returns true if both the calling and source users for the job are started. */
2271 private boolean areUsersStartedLocked(final JobStatus job) {
2272 boolean sourceStarted = ArrayUtils.contains(mStartedUsers, job.getSourceUserId());
2273 if (job.getUserId() == job.getSourceUserId()) {
2274 return sourceStarted;
2275 }
2276 return sourceStarted && ArrayUtils.contains(mStartedUsers, job.getUserId());
2277 }
2278
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002279 /**
2280 * Criteria for moving a job into the pending queue:
2281 * - It's ready.
2282 * - It's not pending.
2283 * - It's not already running on a JSC.
2284 * - The user that requested the job is running.
Christopher Tatea732f012017-10-26 17:26:53 -07002285 * - The job's standby bucket has come due to be runnable.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002286 * - The component is enabled and runnable.
2287 */
2288 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002289 final boolean jobReady = job.isReady();
Dianne Hackborn28d1b662017-04-21 14:17:23 -07002290
2291 if (DEBUG) {
2292 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
2293 + " ready=" + jobReady);
2294 }
2295
2296 // This is a condition that is very likely to be false (most jobs that are
2297 // scheduled are sitting there, not ready yet) and very cheap to check (just
2298 // a few conditions on data in JobStatus).
2299 if (!jobReady) {
Christopher Tate20afddd2018-02-28 15:19:19 -08002300 if (job.getSourcePackageName().equals("android.jobscheduler.cts.jobtestapp")) {
2301 Slog.v(TAG, " NOT READY: " + job);
2302 }
Dianne Hackborn28d1b662017-04-21 14:17:23 -07002303 return false;
2304 }
2305
2306 final boolean jobExists = mJobs.containsJob(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002307
Kweku Adams8bd5edc2018-12-07 18:33:39 -08002308 final boolean userStarted = areUsersStartedLocked(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002309
2310 if (DEBUG) {
2311 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
Dianne Hackborn28d1b662017-04-21 14:17:23 -07002312 + " exists=" + jobExists + " userStarted=" + userStarted);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002313 }
2314
Dianne Hackborn28d1b662017-04-21 14:17:23 -07002315 // These are also fairly cheap to check, though they typically will not
2316 // be conditions we fail.
2317 if (!jobExists || !userStarted) {
2318 return false;
2319 }
2320
Wei Wang8c0c3c12018-11-14 14:56:52 -08002321 if (isJobThermalConstrainedLocked(job)) {
2322 return false;
2323 }
2324
Dianne Hackborn28d1b662017-04-21 14:17:23 -07002325 final boolean jobPending = mPendingJobs.contains(job);
2326 final boolean jobActive = isCurrentlyActiveLocked(job);
2327
2328 if (DEBUG) {
2329 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
2330 + " pending=" + jobPending + " active=" + jobActive);
2331 }
2332
2333 // These can be a little more expensive (especially jobActive, since we need to
2334 // go through the array of all potentially active jobs), so we are doing them
2335 // later... but still before checking with the package manager!
2336 if (jobPending || jobActive) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002337 return false;
2338 }
2339
Kweku Adams4836f9d2018-11-12 17:04:17 -08002340 if (mConstants.USE_HEARTBEATS) {
2341 // If the app is in a non-active standby bucket, make sure we've waited
2342 // an appropriate amount of time since the last invocation. During device-
2343 // wide parole, standby bucketing is ignored.
2344 //
2345 // Jobs in 'active' apps are not subject to standby, nor are jobs that are
2346 // specifically marked as exempt.
Christopher Tate20afddd2018-02-28 15:19:19 -08002347 if (DEBUG_STANDBY) {
Kweku Adams4836f9d2018-11-12 17:04:17 -08002348 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
2349 + " parole=" + mInParole + " active=" + job.uidActive
2350 + " exempt=" + job.getJob().isExemptedFromAppStandby());
Christopher Tate20afddd2018-02-28 15:19:19 -08002351 }
Kweku Adams4836f9d2018-11-12 17:04:17 -08002352 if (!mInParole
2353 && !job.uidActive
2354 && !job.getJob().isExemptedFromAppStandby()) {
2355 final int bucket = job.getStandbyBucket();
2356 if (DEBUG_STANDBY) {
2357 Slog.v(TAG, " bucket=" + bucket + " heartbeat=" + mHeartbeat
2358 + " next=" + mNextBucketHeartbeat[bucket]);
2359 }
2360 if (mHeartbeat < mNextBucketHeartbeat[bucket]) {
2361 // Only skip this job if the app is still waiting for the end of its nominal
2362 // bucket interval. Once it's waited that long, we let it go ahead and clear.
2363 // The final (NEVER) bucket is special; we never age those apps' jobs into
2364 // runnability.
2365 final long appLastRan = heartbeatWhenJobsLastRun(job);
2366 if (bucket >= mConstants.STANDBY_BEATS.length
2367 || (mHeartbeat > appLastRan
2368 && mHeartbeat < appLastRan + mConstants.STANDBY_BEATS[bucket])) {
2369 // TODO: log/trace that we're deferring the job due to bucketing if we
2370 // hit this
2371 if (job.getWhenStandbyDeferred() == 0) {
2372 if (DEBUG_STANDBY) {
2373 Slog.v(TAG, "Bucket deferral: " + mHeartbeat + " < "
2374 + (appLastRan + mConstants.STANDBY_BEATS[bucket])
2375 + " for " + job);
2376 }
2377 job.setWhenStandbyDeferred(sElapsedRealtimeClock.millis());
Christopher Tatea5a85bd2018-01-03 17:20:36 -08002378 }
Kweku Adams4836f9d2018-11-12 17:04:17 -08002379 return false;
2380 } else {
2381 if (DEBUG_STANDBY) {
2382 Slog.v(TAG, "Bucket deferred job aged into runnability at "
2383 + mHeartbeat + " : " + job);
2384 }
Christopher Tatea5a85bd2018-01-03 17:20:36 -08002385 }
Christopher Tate0c4d7682017-12-06 15:10:22 -08002386 }
Christopher Tatea732f012017-10-26 17:26:53 -07002387 }
Christopher Tatea732f012017-10-26 17:26:53 -07002388 }
2389
2390 // The expensive check last: validate that the defined package+service is
2391 // still present & viable.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002392 final boolean componentPresent;
2393 try {
2394 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2395 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
Kweku Adams8bd5edc2018-12-07 18:33:39 -08002396 job.getUserId()) != null);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002397 } catch (RemoteException e) {
2398 throw e.rethrowAsRuntimeException();
2399 }
2400
2401 if (DEBUG) {
2402 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
2403 + " componentPresent=" + componentPresent);
2404 }
2405
2406 // Everything else checked out so far, so this is the final yes/no check
2407 return componentPresent;
2408 }
2409
Kweku Adamscdbfcb92018-12-06 17:05:15 -08002410 private void evaluateControllerStatesLocked(final JobStatus job) {
2411 for (int c = mControllers.size() - 1; c >= 0; --c) {
2412 final StateController sc = mControllers.get(c);
2413 sc.evaluateStateLocked(job);
2414 }
2415 }
2416
2417 /**
2418 * Returns true if non-job constraint components are in place -- if job.isReady() returns true
2419 * and this method returns true, then the job is ready to be executed.
2420 */
2421 public boolean areComponentsInPlaceLocked(JobStatus job) {
2422 // This code is very similar to the code in isReadyToBeExecutedLocked --- it uses the same
2423 // conditions.
2424
2425 final boolean jobExists = mJobs.containsJob(job);
2426 final boolean userStarted = areUsersStartedLocked(job);
2427
2428 if (DEBUG) {
2429 Slog.v(TAG, "areComponentsInPlaceLocked: " + job.toShortString()
2430 + " exists=" + jobExists + " userStarted=" + userStarted);
2431 }
2432
2433 // These are also fairly cheap to check, though they typically will not
2434 // be conditions we fail.
2435 if (!jobExists || !userStarted) {
2436 return false;
2437 }
2438
2439 // Job pending/active doesn't affect the readiness of a job.
2440
2441 // Skipping the hearbeat check as this will only come into play when using the rolling
2442 // window quota management system.
2443
2444 // The expensive check last: validate that the defined package+service is
2445 // still present & viable.
2446 final boolean componentPresent;
2447 try {
2448 // TODO: cache result until we're notified that something in the package changed.
2449 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2450 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2451 job.getUserId()) != null);
2452 } catch (RemoteException e) {
2453 throw e.rethrowAsRuntimeException();
2454 }
2455
2456 if (DEBUG) {
2457 Slog.v(TAG, "areComponentsInPlaceLocked: " + job.toShortString()
2458 + " componentPresent=" + componentPresent);
2459 }
2460
2461 // Everything else checked out so far, so this is the final yes/no check
2462 return componentPresent;
2463 }
2464
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002465 /**
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002466 * Reconcile jobs in the pending queue against available execution contexts.
2467 * A controller can force a job into the pending queue even if it's already running, but
2468 * here is where we decide whether to actually execute it.
2469 */
2470 private void maybeRunPendingJobsLocked() {
2471 if (DEBUG) {
2472 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
2473 }
Makoto Onuki714f97d2018-12-05 11:18:13 -08002474 mConcurrencyManager.assignJobsToContextsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002475 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07002476 }
2477
Dianne Hackborn807de782016-04-07 17:54:41 -07002478 private int adjustJobPriority(int curPriority, JobStatus job) {
2479 if (curPriority < JobInfo.PRIORITY_TOP_APP) {
2480 float factor = mJobPackageTracker.getLoadFactor(job);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002481 if (factor >= mConstants.HEAVY_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07002482 curPriority += JobInfo.PRIORITY_ADJ_ALWAYS_RUNNING;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002483 } else if (factor >= mConstants.MODERATE_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07002484 curPriority += JobInfo.PRIORITY_ADJ_OFTEN_RUNNING;
2485 }
2486 }
2487 return curPriority;
2488 }
2489
Makoto Onuki714f97d2018-12-05 11:18:13 -08002490 int evaluateJobPriorityLocked(JobStatus job) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002491 int priority = job.getPriority();
Makoto Onukiec8b14d2018-12-05 13:22:24 -08002492 if (priority >= JobInfo.PRIORITY_BOUND_FOREGROUND_SERVICE) {
Dianne Hackborn807de782016-04-07 17:54:41 -07002493 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002494 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08002495 int override = mUidPriorityOverride.get(job.getSourceUid(), 0);
2496 if (override != 0) {
Dianne Hackborn807de782016-04-07 17:54:41 -07002497 return adjustJobPriority(override, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002498 }
Dianne Hackborn807de782016-04-07 17:54:41 -07002499 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002500 }
2501
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002502 final class LocalService implements JobSchedulerInternal {
2503
2504 /**
Christopher Tatea732f012017-10-26 17:26:53 -07002505 * The current bucket heartbeat ordinal
2506 */
2507 public long currentHeartbeat() {
2508 return getCurrentHeartbeat();
2509 }
2510
2511 /**
2512 * Heartbeat ordinal at which the given standby bucket's jobs next become runnable
2513 */
2514 public long nextHeartbeatForBucket(int bucket) {
2515 synchronized (mLock) {
2516 return mNextBucketHeartbeat[bucket];
2517 }
2518 }
2519
2520 /**
Christopher Tate435c2f42018-01-18 12:59:15 -08002521 * Heartbeat ordinal for the given app. This is typically the heartbeat at which
2522 * the app last ran jobs, so that a newly-scheduled job in an app that hasn't run
2523 * jobs in a long time is immediately runnable even if the app is bucketed into
2524 * an infrequent time allocation.
2525 */
2526 public long baseHeartbeatForApp(String packageName, @UserIdInt int userId,
2527 final int appStandbyBucket) {
2528 if (appStandbyBucket == 0 ||
2529 appStandbyBucket >= mConstants.STANDBY_BEATS.length) {
2530 // ACTIVE => everything can be run right away
2531 // NEVER => we won't run them anyway, so let them go in the future
2532 // as soon as the app enters normal use
Christopher Tated1aebb32018-01-31 13:24:14 -08002533 if (DEBUG_STANDBY) {
2534 Slog.v(TAG, "Base heartbeat forced ZERO for new job in "
2535 + packageName + "/" + userId);
2536 }
Christopher Tate435c2f42018-01-18 12:59:15 -08002537 return 0;
2538 }
2539
Christopher Tated1aebb32018-01-31 13:24:14 -08002540 final long baseHeartbeat = heartbeatWhenJobsLastRun(packageName, userId);
2541 if (DEBUG_STANDBY) {
2542 Slog.v(TAG, "Base heartbeat " + baseHeartbeat + " for new job in "
2543 + packageName + "/" + userId);
2544 }
2545 return baseHeartbeat;
Christopher Tate435c2f42018-01-18 12:59:15 -08002546 }
2547
Christopher Tate325768c2018-03-07 16:07:56 -08002548 public void noteJobStart(String packageName, int userId) {
2549 synchronized (mLock) {
2550 setLastJobHeartbeatLocked(packageName, userId, mHeartbeat);
2551 }
2552 }
2553
Christopher Tate435c2f42018-01-18 12:59:15 -08002554 /**
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002555 * Returns a list of all pending jobs. A running job is not considered pending. Periodic
2556 * jobs are always considered pending.
2557 */
Amith Yamasanicb926fc2016-03-14 17:15:20 -07002558 @Override
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002559 public List<JobInfo> getSystemScheduledPendingJobs() {
2560 synchronized (mLock) {
2561 final List<JobInfo> pendingJobs = new ArrayList<JobInfo>();
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002562 mJobs.forEachJob(Process.SYSTEM_UID, (job) -> {
2563 if (job.getJob().isPeriodic() || !isCurrentlyActiveLocked(job)) {
2564 pendingJobs.add(job.getJob());
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002565 }
2566 });
2567 return pendingJobs;
2568 }
2569 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002570
2571 @Override
Christopher Tate1d99c392017-12-07 16:54:04 -08002572 public void cancelJobsForUid(int uid, String reason) {
2573 JobSchedulerService.this.cancelJobsForUid(uid, reason);
2574 }
2575
2576 @Override
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002577 public void addBackingUpUid(int uid) {
2578 synchronized (mLock) {
2579 // No need to actually do anything here, since for a full backup the
2580 // activity manager will kill the process which will kill the job (and
2581 // cause it to restart, but now it can't run).
2582 mBackingUpUids.put(uid, uid);
2583 }
2584 }
2585
2586 @Override
2587 public void removeBackingUpUid(int uid) {
2588 synchronized (mLock) {
2589 mBackingUpUids.delete(uid);
2590 // If there are any jobs for this uid, we need to rebuild the pending list
2591 // in case they are now ready to run.
2592 if (mJobs.countJobsForUid(uid) > 0) {
2593 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2594 }
2595 }
2596 }
2597
2598 @Override
2599 public void clearAllBackingUpUids() {
2600 synchronized (mLock) {
2601 if (mBackingUpUids.size() > 0) {
2602 mBackingUpUids.clear();
2603 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2604 }
2605 }
2606 }
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002607
2608 @Override
Christopher Tated117b292018-01-05 17:32:36 -08002609 public void reportAppUsage(String packageName, int userId) {
2610 JobSchedulerService.this.reportAppUsage(packageName, userId);
2611 }
2612
2613 @Override
Makoto Onukie7b02982017-08-24 14:23:36 -07002614 public JobStorePersistStats getPersistStats() {
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002615 synchronized (mLock) {
Makoto Onukie7b02982017-08-24 14:23:36 -07002616 return new JobStorePersistStats(mJobs.getPersistStats());
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002617 }
2618 }
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002619 }
2620
Shreyas Basarge5db09082016-01-07 13:38:29 +00002621 /**
Christopher Tatea732f012017-10-26 17:26:53 -07002622 * Tracking of app assignments to standby buckets
2623 */
2624 final class StandbyTracker extends AppIdleStateChangeListener {
Christopher Tate435c2f42018-01-18 12:59:15 -08002625
Christopher Tatea732f012017-10-26 17:26:53 -07002626 // AppIdleStateChangeListener interface for live updates
2627
2628 @Override
Christopher Tate435c2f42018-01-18 12:59:15 -08002629 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
Amith Yamasani119be9a2018-02-18 22:23:00 -08002630 boolean idle, int bucket, int reason) {
Kweku Adams4836f9d2018-11-12 17:04:17 -08002631 // QuotaController handles this now.
Christopher Tatea732f012017-10-26 17:26:53 -07002632 }
2633
2634 @Override
2635 public void onParoleStateChanged(boolean isParoleOn) {
Christopher Tatea5a85bd2018-01-03 17:20:36 -08002636 if (DEBUG_STANDBY) {
2637 Slog.i(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
2638 }
2639 mInParole = isParoleOn;
Christopher Tatea732f012017-10-26 17:26:53 -07002640 }
Christopher Tated117b292018-01-05 17:32:36 -08002641
2642 @Override
2643 public void onUserInteractionStarted(String packageName, int userId) {
2644 final int uid = mLocalPM.getPackageUid(packageName,
2645 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
2646 if (uid < 0) {
2647 // Quietly ignore; the case is already logged elsewhere
2648 return;
2649 }
2650
Amith Yamasani977e11f2018-02-16 11:29:54 -08002651 long sinceLast = mUsageStats.getTimeSinceLastJobRun(packageName, userId);
2652 if (sinceLast > 2 * DateUtils.DAY_IN_MILLIS) {
2653 // Too long ago, not worth logging
2654 sinceLast = 0L;
2655 }
Christopher Tated117b292018-01-05 17:32:36 -08002656 final DeferredJobCounter counter = new DeferredJobCounter();
2657 synchronized (mLock) {
2658 mJobs.forEachJobForSourceUid(uid, counter);
2659 }
Amith Yamasani977e11f2018-02-16 11:29:54 -08002660 if (counter.numDeferred() > 0 || sinceLast > 0) {
2661 BatteryStatsInternal mBatteryStatsInternal = LocalServices.getService
2662 (BatteryStatsInternal.class);
2663 mBatteryStatsInternal.noteJobsDeferred(uid, counter.numDeferred(), sinceLast);
Yangster-mac96353002018-09-05 11:18:55 -07002664 StatsLog.write_non_chained(StatsLog.DEFERRED_JOB_STATS_REPORTED, uid, null,
2665 counter.numDeferred(), sinceLast);
Amith Yamasani977e11f2018-02-16 11:29:54 -08002666 }
Christopher Tated117b292018-01-05 17:32:36 -08002667 }
2668 }
2669
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002670 static class DeferredJobCounter implements Consumer<JobStatus> {
Christopher Tated117b292018-01-05 17:32:36 -08002671 private int mDeferred = 0;
2672
2673 public int numDeferred() {
2674 return mDeferred;
2675 }
2676
2677 @Override
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002678 public void accept(JobStatus job) {
Christopher Tated117b292018-01-05 17:32:36 -08002679 if (job.getWhenStandbyDeferred() > 0) {
2680 mDeferred++;
2681 }
2682 }
Christopher Tatea732f012017-10-26 17:26:53 -07002683 }
2684
2685 public static int standbyBucketToBucketIndex(int bucket) {
2686 // Normalize AppStandby constants to indices into our bookkeeping
Christopher Tatef2159712018-03-27 16:04:14 -07002687 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) return NEVER_INDEX;
2688 else if (bucket > UsageStatsManager.STANDBY_BUCKET_FREQUENT) return RARE_INDEX;
2689 else if (bucket > UsageStatsManager.STANDBY_BUCKET_WORKING_SET) return FREQUENT_INDEX;
2690 else if (bucket > UsageStatsManager.STANDBY_BUCKET_ACTIVE) return WORKING_INDEX;
2691 else return ACTIVE_INDEX;
Christopher Tatea732f012017-10-26 17:26:53 -07002692 }
2693
Christopher Tated1aebb32018-01-31 13:24:14 -08002694 // Static to support external callers
Christopher Tatea732f012017-10-26 17:26:53 -07002695 public static int standbyBucketForPackage(String packageName, int userId, long elapsedNow) {
2696 UsageStatsManagerInternal usageStats = LocalServices.getService(
2697 UsageStatsManagerInternal.class);
2698 int bucket = usageStats != null
2699 ? usageStats.getAppStandbyBucket(packageName, userId, elapsedNow)
2700 : 0;
2701
2702 bucket = standbyBucketToBucketIndex(bucket);
2703
2704 if (DEBUG_STANDBY) {
2705 Slog.v(TAG, packageName + "/" + userId + " standby bucket index: " + bucket);
2706 }
2707 return bucket;
2708 }
2709
2710 /**
Christopher Tate7060b042014-06-09 19:50:00 -07002711 * Binder stub trampoline implementation
2712 */
2713 final class JobSchedulerStub extends IJobScheduler.Stub {
2714 /** Cache determination of whether a given app can persist jobs
2715 * key is uid of the calling app; value is undetermined/true/false
2716 */
2717 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
2718
2719 // Enforce that only the app itself (or shared uid participant) can schedule a
2720 // job that runs one of the app's services, as well as verifying that the
2721 // named service properly requires the BIND_JOB_SERVICE permission
2722 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -07002723 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -07002724 final ComponentName service = job.getService();
2725 try {
Jeff Sharkeyc7bacab2016-02-09 15:56:11 -07002726 ServiceInfo si = pm.getServiceInfo(service,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002727 PackageManager.MATCH_DIRECT_BOOT_AWARE
2728 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkey12c0da42016-02-25 17:10:50 -07002729 UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -07002730 if (si == null) {
2731 throw new IllegalArgumentException("No such service " + service);
2732 }
Christopher Tate7060b042014-06-09 19:50:00 -07002733 if (si.applicationInfo.uid != uid) {
2734 throw new IllegalArgumentException("uid " + uid +
2735 " cannot schedule job in " + service.getPackageName());
2736 }
2737 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
2738 throw new IllegalArgumentException("Scheduled service " + service
2739 + " does not require android.permission.BIND_JOB_SERVICE permission");
2740 }
Christopher Tate5568f542014-06-18 13:53:31 -07002741 } catch (RemoteException e) {
2742 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07002743 }
2744 }
2745
2746 private boolean canPersistJobs(int pid, int uid) {
2747 // If we get this far we're good to go; all we need to do now is check
2748 // whether the app is allowed to persist its scheduled work.
2749 final boolean canPersist;
2750 synchronized (mPersistCache) {
2751 Boolean cached = mPersistCache.get(uid);
2752 if (cached != null) {
2753 canPersist = cached.booleanValue();
2754 } else {
2755 // Persisting jobs is tantamount to running at boot, so we permit
2756 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
2757 // permission
2758 int result = getContext().checkPermission(
2759 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
2760 canPersist = (result == PackageManager.PERMISSION_GRANTED);
2761 mPersistCache.put(uid, canPersist);
2762 }
2763 }
2764 return canPersist;
2765 }
2766
Makoto Onuki959acb52018-01-26 14:10:03 -08002767 private void validateJobFlags(JobInfo job, int callingUid) {
2768 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
2769 getContext().enforceCallingOrSelfPermission(
2770 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
2771 }
2772 if ((job.getFlags() & JobInfo.FLAG_EXEMPT_FROM_APP_STANDBY) != 0) {
2773 if (callingUid != Process.SYSTEM_UID) {
2774 throw new SecurityException("Job has invalid flags");
2775 }
Makoto Onuki2b5811a2018-02-08 11:09:42 -08002776 if (job.isPeriodic()) {
2777 Slog.wtf(TAG, "Periodic jobs mustn't have"
2778 + " FLAG_EXEMPT_FROM_APP_STANDBY. Job=" + job);
Makoto Onuki959acb52018-01-26 14:10:03 -08002779 }
2780 }
2781 }
2782
Christopher Tate7060b042014-06-09 19:50:00 -07002783 // IJobScheduler implementation
2784 @Override
2785 public int schedule(JobInfo job) throws RemoteException {
2786 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07002787 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07002788 }
2789 final int pid = Binder.getCallingPid();
2790 final int uid = Binder.getCallingUid();
Christopher Tatea732f012017-10-26 17:26:53 -07002791 final int userId = UserHandle.getUserId(uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002792
2793 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07002794 if (job.isPersisted()) {
2795 if (!canPersistJobs(pid, uid)) {
2796 throw new IllegalArgumentException("Error: requested job be persisted without"
2797 + " holding RECEIVE_BOOT_COMPLETED permission.");
2798 }
2799 }
Christopher Tate7060b042014-06-09 19:50:00 -07002800
Makoto Onuki959acb52018-01-26 14:10:03 -08002801 validateJobFlags(job, uid);
Jeff Sharkey785f4942016-07-14 10:31:15 -06002802
Christopher Tate7060b042014-06-09 19:50:00 -07002803 long ident = Binder.clearCallingIdentity();
2804 try {
Christopher Tatea732f012017-10-26 17:26:53 -07002805 return JobSchedulerService.this.scheduleAsPackage(job, null, uid, null, userId,
2806 null);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002807 } finally {
2808 Binder.restoreCallingIdentity(ident);
2809 }
2810 }
2811
2812 // IJobScheduler implementation
2813 @Override
2814 public int enqueue(JobInfo job, JobWorkItem work) throws RemoteException {
2815 if (DEBUG) {
2816 Slog.d(TAG, "Enqueueing job: " + job.toString() + " work: " + work);
2817 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002818 final int uid = Binder.getCallingUid();
Christopher Tatea732f012017-10-26 17:26:53 -07002819 final int userId = UserHandle.getUserId(uid);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002820
2821 enforceValidJobRequest(uid, job);
2822 if (job.isPersisted()) {
2823 throw new IllegalArgumentException("Can't enqueue work for persisted jobs");
2824 }
2825 if (work == null) {
2826 throw new NullPointerException("work is null");
2827 }
2828
Makoto Onuki959acb52018-01-26 14:10:03 -08002829 validateJobFlags(job, uid);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002830
2831 long ident = Binder.clearCallingIdentity();
2832 try {
Christopher Tatea732f012017-10-26 17:26:53 -07002833 return JobSchedulerService.this.scheduleAsPackage(job, work, uid, null, userId,
2834 null);
Christopher Tate7060b042014-06-09 19:50:00 -07002835 } finally {
2836 Binder.restoreCallingIdentity(ident);
2837 }
2838 }
2839
2840 @Override
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002841 public int scheduleAsPackage(JobInfo job, String packageName, int userId, String tag)
Shreyas Basarge968ac752016-01-11 23:09:26 +00002842 throws RemoteException {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002843 final int callerUid = Binder.getCallingUid();
Shreyas Basarge968ac752016-01-11 23:09:26 +00002844 if (DEBUG) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002845 Slog.d(TAG, "Caller uid " + callerUid + " scheduling job: " + job.toString()
Christopher Tatea732f012017-10-26 17:26:53 -07002846 + " on behalf of " + packageName + "/");
Shreyas Basarge968ac752016-01-11 23:09:26 +00002847 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002848
2849 if (packageName == null) {
2850 throw new NullPointerException("Must specify a package for scheduleAsPackage()");
Shreyas Basarge968ac752016-01-11 23:09:26 +00002851 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002852
2853 int mayScheduleForOthers = getContext().checkCallingOrSelfPermission(
2854 android.Manifest.permission.UPDATE_DEVICE_STATS);
2855 if (mayScheduleForOthers != PackageManager.PERMISSION_GRANTED) {
2856 throw new SecurityException("Caller uid " + callerUid
2857 + " not permitted to schedule jobs for other apps");
2858 }
2859
Makoto Onuki959acb52018-01-26 14:10:03 -08002860 validateJobFlags(job, callerUid);
Jeff Sharkey4f100402016-05-03 17:44:23 -06002861
Shreyas Basarge968ac752016-01-11 23:09:26 +00002862 long ident = Binder.clearCallingIdentity();
2863 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002864 return JobSchedulerService.this.scheduleAsPackage(job, null, callerUid,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002865 packageName, userId, tag);
Shreyas Basarge968ac752016-01-11 23:09:26 +00002866 } finally {
2867 Binder.restoreCallingIdentity(ident);
2868 }
2869 }
2870
2871 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002872 public List<JobInfo> getAllPendingJobs() throws RemoteException {
2873 final int uid = Binder.getCallingUid();
2874
2875 long ident = Binder.clearCallingIdentity();
2876 try {
2877 return JobSchedulerService.this.getPendingJobs(uid);
2878 } finally {
2879 Binder.restoreCallingIdentity(ident);
2880 }
2881 }
2882
2883 @Override
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002884 public JobInfo getPendingJob(int jobId) throws RemoteException {
2885 final int uid = Binder.getCallingUid();
2886
2887 long ident = Binder.clearCallingIdentity();
2888 try {
2889 return JobSchedulerService.this.getPendingJob(uid, jobId);
2890 } finally {
2891 Binder.restoreCallingIdentity(ident);
2892 }
2893 }
2894
2895 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002896 public void cancelAll() throws RemoteException {
2897 final int uid = Binder.getCallingUid();
Christopher Tate7060b042014-06-09 19:50:00 -07002898 long ident = Binder.clearCallingIdentity();
2899 try {
Makoto Onukid2bfec62018-01-12 13:58:01 -08002900 JobSchedulerService.this.cancelJobsForUid(uid,
2901 "cancelAll() called by app, callingUid=" + uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002902 } finally {
2903 Binder.restoreCallingIdentity(ident);
2904 }
2905 }
2906
2907 @Override
2908 public void cancel(int jobId) throws RemoteException {
2909 final int uid = Binder.getCallingUid();
2910
2911 long ident = Binder.clearCallingIdentity();
2912 try {
Makoto Onukid2bfec62018-01-12 13:58:01 -08002913 JobSchedulerService.this.cancelJob(uid, jobId, uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002914 } finally {
2915 Binder.restoreCallingIdentity(ident);
2916 }
2917 }
2918
2919 /**
2920 * "dumpsys" infrastructure
2921 */
2922 @Override
2923 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002924 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Christopher Tate7060b042014-06-09 19:50:00 -07002925
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002926 int filterUid = -1;
2927 boolean proto = false;
2928 if (!ArrayUtils.isEmpty(args)) {
2929 int opti = 0;
2930 while (opti < args.length) {
2931 String arg = args[opti];
2932 if ("-h".equals(arg)) {
2933 dumpHelp(pw);
2934 return;
2935 } else if ("-a".equals(arg)) {
2936 // Ignore, we always dump all.
2937 } else if ("--proto".equals(arg)) {
2938 proto = true;
2939 } else if (arg.length() > 0 && arg.charAt(0) == '-') {
2940 pw.println("Unknown option: " + arg);
2941 return;
2942 } else {
2943 break;
2944 }
2945 opti++;
2946 }
2947 if (opti < args.length) {
2948 String pkg = args[opti];
2949 try {
2950 filterUid = getContext().getPackageManager().getPackageUid(pkg,
2951 PackageManager.MATCH_ANY_USER);
2952 } catch (NameNotFoundException ignored) {
2953 pw.println("Invalid package: " + pkg);
2954 return;
2955 }
2956 }
2957 }
2958
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002959 final long identityToken = Binder.clearCallingIdentity();
Christopher Tate7060b042014-06-09 19:50:00 -07002960 try {
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002961 if (proto) {
2962 JobSchedulerService.this.dumpInternalProto(fd, filterUid);
2963 } else {
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002964 JobSchedulerService.this.dumpInternal(new IndentingPrintWriter(pw, " "),
2965 filterUid);
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002966 }
Christopher Tate7060b042014-06-09 19:50:00 -07002967 } finally {
2968 Binder.restoreCallingIdentity(identityToken);
2969 }
2970 }
Christopher Tate5d346052016-03-08 12:56:08 -08002971
2972 @Override
2973 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002974 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Christopher Tate5d346052016-03-08 12:56:08 -08002975 (new JobSchedulerShellCommand(JobSchedulerService.this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002976 this, in, out, err, args, callback, resultReceiver);
Christopher Tate5d346052016-03-08 12:56:08 -08002977 }
Serik Beketayev75915d12018-08-01 16:56:59 -07002978
2979 /**
2980 * <b>For internal system user only!</b>
2981 * Returns a list of all currently-executing jobs.
2982 */
2983 @Override
2984 public List<JobInfo> getStartedJobs() {
2985 final int uid = Binder.getCallingUid();
2986 if (uid != Process.SYSTEM_UID) {
2987 throw new SecurityException(
2988 "getStartedJobs() is system internal use only.");
2989 }
2990
2991 final ArrayList<JobInfo> runningJobs;
2992
2993 synchronized (mLock) {
2994 runningJobs = new ArrayList<>(mActiveServices.size());
2995 for (JobServiceContext jsc : mActiveServices) {
2996 final JobStatus job = jsc.getRunningJobLocked();
2997 if (job != null) {
2998 runningJobs.add(job.getJob());
2999 }
3000 }
3001 }
3002
3003 return runningJobs;
3004 }
3005
3006 /**
3007 * <b>For internal system user only!</b>
3008 * Returns a snapshot of the state of all jobs known to the system.
3009 *
3010 * <p class="note">This is a slow operation, so it should be called sparingly.
3011 */
3012 @Override
3013 public List<JobSnapshot> getAllJobSnapshots() {
3014 final int uid = Binder.getCallingUid();
3015 if (uid != Process.SYSTEM_UID) {
3016 throw new SecurityException(
3017 "getAllJobSnapshots() is system internal use only.");
3018 }
3019 synchronized (mLock) {
3020 final ArrayList<JobSnapshot> snapshots = new ArrayList<>(mJobs.size());
3021 mJobs.forEachJob((job) -> snapshots.add(
3022 new JobSnapshot(job.getJob(), job.getSatisfiedConstraintFlags(),
3023 isReadyToBeExecutedLocked(job))));
3024 return snapshots;
3025 }
3026 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00003027 };
3028
Christopher Tate5d346052016-03-08 12:56:08 -08003029 // Shell command infrastructure: run the given job immediately
3030 int executeRunCommand(String pkgName, int userId, int jobId, boolean force) {
3031 if (DEBUG) {
3032 Slog.v(TAG, "executeRunCommand(): " + pkgName + "/" + userId
3033 + " " + jobId + " f=" + force);
3034 }
3035
3036 try {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003037 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
3038 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
Christopher Tate5d346052016-03-08 12:56:08 -08003039 if (uid < 0) {
3040 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
3041 }
3042
3043 synchronized (mLock) {
3044 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
3045 if (js == null) {
3046 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
3047 }
3048
3049 js.overrideState = (force) ? JobStatus.OVERRIDE_FULL : JobStatus.OVERRIDE_SOFT;
3050 if (!js.isConstraintsSatisfied()) {
3051 js.overrideState = 0;
3052 return JobSchedulerShellCommand.CMD_ERR_CONSTRAINTS;
3053 }
3054
Dianne Hackbornf9bac162017-04-20 17:17:48 -07003055 queueReadyJobsForExecutionLocked();
3056 maybeRunPendingJobsLocked();
Christopher Tate5d346052016-03-08 12:56:08 -08003057 }
3058 } catch (RemoteException e) {
3059 // can't happen
3060 }
3061 return 0;
3062 }
3063
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003064 // Shell command infrastructure: immediately timeout currently executing jobs
3065 int executeTimeoutCommand(PrintWriter pw, String pkgName, int userId,
3066 boolean hasJobId, int jobId) {
3067 if (DEBUG) {
3068 Slog.v(TAG, "executeTimeoutCommand(): " + pkgName + "/" + userId + " " + jobId);
3069 }
3070
3071 synchronized (mLock) {
3072 boolean foundSome = false;
3073 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07003074 final JobServiceContext jc = mActiveServices.get(i);
3075 final JobStatus js = jc.getRunningJobLocked();
Makoto Onukid2bfec62018-01-12 13:58:01 -08003076 if (jc.timeoutIfExecutingLocked(pkgName, userId, hasJobId, jobId, "shell")) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07003077 foundSome = true;
3078 pw.print("Timing out: ");
3079 js.printUniqueId(pw);
3080 pw.print(" ");
3081 pw.println(js.getServiceComponent().flattenToShortString());
3082 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07003083 }
3084 if (!foundSome) {
3085 pw.println("No matching executing jobs found.");
3086 }
3087 }
3088 return 0;
3089 }
3090
Christopher Tate8c67d122017-09-29 16:54:26 -07003091 // Shell command infrastructure: cancel a scheduled job
3092 int executeCancelCommand(PrintWriter pw, String pkgName, int userId,
3093 boolean hasJobId, int jobId) {
3094 if (DEBUG) {
3095 Slog.v(TAG, "executeCancelCommand(): " + pkgName + "/" + userId + " " + jobId);
3096 }
3097
3098 int pkgUid = -1;
3099 try {
3100 IPackageManager pm = AppGlobals.getPackageManager();
3101 pkgUid = pm.getPackageUid(pkgName, 0, userId);
3102 } catch (RemoteException e) { /* can't happen */ }
3103
3104 if (pkgUid < 0) {
3105 pw.println("Package " + pkgName + " not found.");
3106 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
3107 }
3108
3109 if (!hasJobId) {
3110 pw.println("Canceling all jobs for " + pkgName + " in user " + userId);
3111 if (!cancelJobsForUid(pkgUid, "cancel shell command for package")) {
3112 pw.println("No matching jobs found.");
3113 }
3114 } else {
3115 pw.println("Canceling job " + pkgName + "/#" + jobId + " in user " + userId);
Makoto Onukid2bfec62018-01-12 13:58:01 -08003116 if (!cancelJob(pkgUid, jobId, Process.SHELL_UID)) {
Christopher Tate8c67d122017-09-29 16:54:26 -07003117 pw.println("No matching job found.");
3118 }
3119 }
3120
3121 return 0;
3122 }
3123
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08003124 void setMonitorBattery(boolean enabled) {
3125 synchronized (mLock) {
3126 if (mBatteryController != null) {
3127 mBatteryController.getTracker().setMonitorBatteryLocked(enabled);
3128 }
3129 }
3130 }
3131
3132 int getBatterySeq() {
3133 synchronized (mLock) {
3134 return mBatteryController != null ? mBatteryController.getTracker().getSeq() : -1;
3135 }
3136 }
3137
3138 boolean getBatteryCharging() {
3139 synchronized (mLock) {
3140 return mBatteryController != null
3141 ? mBatteryController.getTracker().isOnStablePower() : false;
3142 }
3143 }
3144
3145 boolean getBatteryNotLow() {
3146 synchronized (mLock) {
3147 return mBatteryController != null
3148 ? mBatteryController.getTracker().isBatteryNotLow() : false;
3149 }
3150 }
3151
Dianne Hackborn532ea262017-03-17 17:50:55 -07003152 int getStorageSeq() {
3153 synchronized (mLock) {
3154 return mStorageController != null ? mStorageController.getTracker().getSeq() : -1;
3155 }
3156 }
3157
3158 boolean getStorageNotLow() {
3159 synchronized (mLock) {
3160 return mStorageController != null
3161 ? mStorageController.getTracker().isStorageNotLow() : false;
3162 }
3163 }
3164
Christopher Tatea732f012017-10-26 17:26:53 -07003165 long getCurrentHeartbeat() {
3166 synchronized (mLock) {
3167 return mHeartbeat;
3168 }
3169 }
3170
Christopher Tated1aebb32018-01-31 13:24:14 -08003171 // Shell command infrastructure
Dianne Hackborn6d068262017-05-16 13:14:37 -07003172 int getJobState(PrintWriter pw, String pkgName, int userId, int jobId) {
3173 try {
3174 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
3175 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
3176 if (uid < 0) {
3177 pw.print("unknown("); pw.print(pkgName); pw.println(")");
3178 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
3179 }
3180
3181 synchronized (mLock) {
3182 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
3183 if (DEBUG) Slog.d(TAG, "get-job-state " + uid + "/" + jobId + ": " + js);
3184 if (js == null) {
3185 pw.print("unknown("); UserHandle.formatUid(pw, uid);
3186 pw.print("/jid"); pw.print(jobId); pw.println(")");
3187 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
3188 }
3189
3190 boolean printed = false;
3191 if (mPendingJobs.contains(js)) {
3192 pw.print("pending");
3193 printed = true;
3194 }
3195 if (isCurrentlyActiveLocked(js)) {
3196 if (printed) {
3197 pw.print(" ");
3198 }
3199 printed = true;
3200 pw.println("active");
3201 }
3202 if (!ArrayUtils.contains(mStartedUsers, js.getUserId())) {
3203 if (printed) {
3204 pw.print(" ");
3205 }
3206 printed = true;
3207 pw.println("user-stopped");
3208 }
Kweku Adams8bd5edc2018-12-07 18:33:39 -08003209 if (!ArrayUtils.contains(mStartedUsers, js.getSourceUserId())) {
3210 if (printed) {
3211 pw.print(" ");
3212 }
3213 printed = true;
3214 pw.println("source-user-stopped");
3215 }
Dianne Hackborn6d068262017-05-16 13:14:37 -07003216 if (mBackingUpUids.indexOfKey(js.getSourceUid()) >= 0) {
3217 if (printed) {
3218 pw.print(" ");
3219 }
3220 printed = true;
3221 pw.println("backing-up");
3222 }
3223 boolean componentPresent = false;
3224 try {
3225 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
3226 js.getServiceComponent(),
3227 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
3228 js.getUserId()) != null);
3229 } catch (RemoteException e) {
3230 }
3231 if (!componentPresent) {
3232 if (printed) {
3233 pw.print(" ");
3234 }
3235 printed = true;
3236 pw.println("no-component");
3237 }
3238 if (js.isReady()) {
3239 if (printed) {
3240 pw.print(" ");
3241 }
3242 printed = true;
3243 pw.println("ready");
3244 }
3245 if (!printed) {
3246 pw.print("waiting");
3247 }
3248 pw.println();
3249 }
3250 } catch (RemoteException e) {
3251 // can't happen
3252 }
3253 return 0;
3254 }
3255
Christopher Tated1aebb32018-01-31 13:24:14 -08003256 // Shell command infrastructure
3257 int executeHeartbeatCommand(PrintWriter pw, int numBeats) {
3258 if (numBeats < 1) {
3259 pw.println(getCurrentHeartbeat());
3260 return 0;
3261 }
3262
3263 pw.print("Advancing standby heartbeat by ");
3264 pw.println(numBeats);
3265 synchronized (mLock) {
3266 advanceHeartbeatLocked(numBeats);
3267 }
3268 return 0;
3269 }
3270
lpeter318abc92018-05-04 16:13:14 +08003271 void triggerDockState(boolean idleState) {
3272 final Intent dockIntent;
3273 if (idleState) {
3274 dockIntent = new Intent(Intent.ACTION_DOCK_IDLE);
3275 } else {
3276 dockIntent = new Intent(Intent.ACTION_DOCK_ACTIVE);
3277 }
3278 dockIntent.setPackage("android");
3279 dockIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
3280 getContext().sendBroadcastAsUser(dockIntent, UserHandle.ALL);
3281 }
3282
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003283 static void dumpHelp(PrintWriter pw) {
3284 pw.println("Job Scheduler (jobscheduler) dump options:");
3285 pw.println(" [-h] [package] ...");
3286 pw.println(" -h: print this help");
3287 pw.println(" [package] is an optional package name to limit the output to.");
3288 }
3289
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003290 /** Sort jobs by caller UID, then by Job ID. */
3291 private static void sortJobs(List<JobStatus> jobs) {
3292 Collections.sort(jobs, new Comparator<JobStatus>() {
3293 @Override
3294 public int compare(JobStatus o1, JobStatus o2) {
3295 int uid1 = o1.getUid();
3296 int uid2 = o2.getUid();
3297 int id1 = o1.getJobId();
3298 int id2 = o2.getJobId();
3299 if (uid1 != uid2) {
3300 return uid1 < uid2 ? -1 : 1;
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003301 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003302 return id1 < id2 ? -1 : (id1 > id2 ? 1 : 0);
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003303 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003304 });
3305 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06003306
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003307 void dumpInternal(final IndentingPrintWriter pw, int filterUid) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003308 final int filterUidFinal = UserHandle.getAppId(filterUid);
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07003309 final long nowElapsed = sElapsedRealtimeClock.millis();
3310 final long nowUptime = sUptimeMillisClock.millis();
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003311 final Predicate<JobStatus> predicate = (js) -> {
3312 return filterUidFinal == -1 || UserHandle.getAppId(js.getUid()) == filterUidFinal
3313 || UserHandle.getAppId(js.getSourceUid()) == filterUidFinal;
3314 };
Dianne Hackborn33d31c52016-02-16 10:30:33 -08003315 synchronized (mLock) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003316 mConstants.dump(pw);
3317 pw.println();
Makoto Onukib5d5e972018-02-20 14:44:20 -08003318
3319 pw.println(" Heartbeat:");
3320 pw.print(" Current: "); pw.println(mHeartbeat);
3321 pw.println(" Next");
3322 pw.print(" ACTIVE: "); pw.println(mNextBucketHeartbeat[0]);
3323 pw.print(" WORKING: "); pw.println(mNextBucketHeartbeat[1]);
3324 pw.print(" FREQUENT: "); pw.println(mNextBucketHeartbeat[2]);
3325 pw.print(" RARE: "); pw.println(mNextBucketHeartbeat[3]);
3326 pw.print(" Last heartbeat: ");
3327 TimeUtils.formatDuration(mLastHeartbeatTime, nowElapsed, pw);
3328 pw.println();
3329 pw.print(" Next heartbeat: ");
3330 TimeUtils.formatDuration(mLastHeartbeatTime + mConstants.STANDBY_HEARTBEAT_TIME,
3331 nowElapsed, pw);
3332 pw.println();
Makoto Onuki0525b982018-05-02 14:46:59 -07003333 pw.print(" In parole?: ");
3334 pw.print(mInParole);
3335 pw.println();
Wei Wang8c0c3c12018-11-14 14:56:52 -08003336 pw.print(" In thermal throttling?: ");
3337 pw.print(mThermalConstraint);
3338 pw.println();
Makoto Onukib5d5e972018-02-20 14:44:20 -08003339 pw.println();
3340
Jeff Sharkey822cbd12016-02-25 11:09:55 -07003341 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003342 pw.print("Registered ");
3343 pw.print(mJobs.size());
3344 pw.println(" jobs:");
Christopher Tate7060b042014-06-09 19:50:00 -07003345 if (mJobs.size() > 0) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003346 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003347 sortJobs(jobs);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003348 for (JobStatus job : jobs) {
3349 pw.print(" JOB #"); job.printUniqueId(pw); pw.print(": ");
3350 pw.println(job.toShortStringExceptUniqueId());
3351
3352 // Skip printing details if the caller requested a filter
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003353 if (!predicate.test(job)) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003354 continue;
3355 }
3356
Dianne Hackborn6d068262017-05-16 13:14:37 -07003357 job.dump(pw, " ", true, nowElapsed);
Makoto Onukib5d5e972018-02-20 14:44:20 -08003358 pw.print(" Last run heartbeat: ");
3359 pw.print(heartbeatWhenJobsLastRun(job));
3360 pw.println();
3361
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003362 pw.print(" Ready: ");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07003363 pw.print(isReadyToBeExecutedLocked(job));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003364 pw.print(" (job=");
3365 pw.print(job.isReady());
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003366 pw.print(" user=");
Kweku Adams8bd5edc2018-12-07 18:33:39 -08003367 pw.print(areUsersStartedLocked(job));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07003368 pw.print(" !pending=");
3369 pw.print(!mPendingJobs.contains(job));
3370 pw.print(" !active=");
3371 pw.print(!isCurrentlyActiveLocked(job));
Dianne Hackbornf9bac162017-04-20 17:17:48 -07003372 pw.print(" !backingup=");
3373 pw.print(!(mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07003374 pw.print(" comp=");
3375 boolean componentPresent = false;
3376 try {
3377 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
3378 job.getServiceComponent(),
3379 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
3380 job.getUserId()) != null);
3381 } catch (RemoteException e) {
3382 }
3383 pw.print(componentPresent);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003384 pw.println(")");
3385 }
Christopher Tate7060b042014-06-09 19:50:00 -07003386 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07003387 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07003388 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003389 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07003390 pw.println();
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003391 pw.println(mControllers.get(i).getClass().getSimpleName() + ":");
3392 pw.increaseIndent();
3393 mControllers.get(i).dumpControllerStateLocked(pw, predicate);
3394 pw.decreaseIndent();
Christopher Tate7060b042014-06-09 19:50:00 -07003395 }
3396 pw.println();
Dianne Hackborn970510b2016-02-24 16:56:42 -08003397 pw.println("Uid priority overrides:");
3398 for (int i=0; i< mUidPriorityOverride.size(); i++) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003399 int uid = mUidPriorityOverride.keyAt(i);
3400 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
3401 pw.print(" "); pw.print(UserHandle.formatUid(uid));
3402 pw.print(": "); pw.println(mUidPriorityOverride.valueAt(i));
3403 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003404 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07003405 if (mBackingUpUids.size() > 0) {
3406 pw.println();
3407 pw.println("Backing up uids:");
3408 boolean first = true;
3409 for (int i = 0; i < mBackingUpUids.size(); i++) {
3410 int uid = mBackingUpUids.keyAt(i);
3411 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
3412 if (first) {
3413 pw.print(" ");
3414 first = false;
3415 } else {
3416 pw.print(", ");
3417 }
3418 pw.print(UserHandle.formatUid(uid));
3419 }
3420 }
3421 pw.println();
3422 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003423 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003424 mJobPackageTracker.dump(pw, "", filterUidFinal);
Dianne Hackborn807de782016-04-07 17:54:41 -07003425 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003426 if (mJobPackageTracker.dumpHistory(pw, "", filterUidFinal)) {
3427 pw.println();
3428 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003429 pw.println("Pending queue:");
3430 for (int i=0; i<mPendingJobs.size(); i++) {
3431 JobStatus job = mPendingJobs.get(i);
3432 pw.print(" Pending #"); pw.print(i); pw.print(": ");
3433 pw.println(job.toShortString());
Dianne Hackborn6d068262017-05-16 13:14:37 -07003434 job.dump(pw, " ", false, nowElapsed);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003435 int priority = evaluateJobPriorityLocked(job);
Makoto Onukiec8b14d2018-12-05 13:22:24 -08003436 pw.print(" Evaluated priority: ");
3437 pw.println(JobInfo.getPriorityString(priority));
3438
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003439 pw.print(" Tag: "); pw.println(job.getTag());
Christopher Tate7234fc62017-04-03 17:36:07 -07003440 pw.print(" Enq: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07003441 TimeUtils.formatDuration(job.madePending - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003442 pw.println();
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003443 }
Christopher Tate7060b042014-06-09 19:50:00 -07003444 pw.println();
3445 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003446 for (int i=0; i<mActiveServices.size(); i++) {
3447 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackborn970510b2016-02-24 16:56:42 -08003448 pw.print(" Slot #"); pw.print(i); pw.print(": ");
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003449 final JobStatus job = jsc.getRunningJobLocked();
Christopher Tate7234fc62017-04-03 17:36:07 -07003450 if (job == null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07003451 if (jsc.mStoppedReason != null) {
3452 pw.print("inactive since ");
3453 TimeUtils.formatDuration(jsc.mStoppedTime, nowElapsed, pw);
3454 pw.print(", stopped because: ");
3455 pw.println(jsc.mStoppedReason);
3456 } else {
3457 pw.println("inactive");
3458 }
Christopher Tate7060b042014-06-09 19:50:00 -07003459 continue;
3460 } else {
Christopher Tate7234fc62017-04-03 17:36:07 -07003461 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08003462 pw.print(" Running for: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07003463 TimeUtils.formatDuration(nowElapsed - jsc.getExecutionStartTimeElapsed(), pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08003464 pw.print(", timeout at: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07003465 TimeUtils.formatDuration(jsc.getTimeoutElapsed() - nowElapsed, pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08003466 pw.println();
Dianne Hackborn6d068262017-05-16 13:14:37 -07003467 job.dump(pw, " ", false, nowElapsed);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003468 int priority = evaluateJobPriorityLocked(jsc.getRunningJobLocked());
Makoto Onukiec8b14d2018-12-05 13:22:24 -08003469 pw.print(" Evaluated priority: ");
3470 pw.println(JobInfo.getPriorityString(priority));
3471
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003472 pw.print(" Active at ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07003473 TimeUtils.formatDuration(job.madeActive - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003474 pw.print(", pending for ");
Christopher Tate7234fc62017-04-03 17:36:07 -07003475 TimeUtils.formatDuration(job.madeActive - job.madePending, pw);
3476 pw.println();
Christopher Tate7060b042014-06-09 19:50:00 -07003477 }
3478 }
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003479 if (filterUid == -1) {
3480 pw.println();
3481 pw.print("mReadyToRock="); pw.println(mReadyToRock);
3482 pw.print("mReportedActive="); pw.println(mReportedActive);
3483 pw.print("mMaxActiveJobs="); pw.println(mMaxActiveJobs);
3484 }
Makoto Onukie7b02982017-08-24 14:23:36 -07003485 pw.println();
3486 pw.print("PersistStats: ");
3487 pw.println(mJobs.getPersistStats());
Christopher Tate7060b042014-06-09 19:50:00 -07003488 }
3489 pw.println();
3490 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003491
3492 void dumpInternalProto(final FileDescriptor fd, int filterUid) {
3493 ProtoOutputStream proto = new ProtoOutputStream(fd);
3494 final int filterUidFinal = UserHandle.getAppId(filterUid);
3495 final long nowElapsed = sElapsedRealtimeClock.millis();
3496 final long nowUptime = sUptimeMillisClock.millis();
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003497 final Predicate<JobStatus> predicate = (js) -> {
3498 return filterUidFinal == -1 || UserHandle.getAppId(js.getUid()) == filterUidFinal
3499 || UserHandle.getAppId(js.getSourceUid()) == filterUidFinal;
3500 };
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003501
3502 synchronized (mLock) {
3503 mConstants.dump(proto, JobSchedulerServiceDumpProto.SETTINGS);
Makoto Onukib5d5e972018-02-20 14:44:20 -08003504 proto.write(JobSchedulerServiceDumpProto.CURRENT_HEARTBEAT, mHeartbeat);
3505 proto.write(JobSchedulerServiceDumpProto.NEXT_HEARTBEAT, mNextBucketHeartbeat[0]);
3506 proto.write(JobSchedulerServiceDumpProto.NEXT_HEARTBEAT, mNextBucketHeartbeat[1]);
3507 proto.write(JobSchedulerServiceDumpProto.NEXT_HEARTBEAT, mNextBucketHeartbeat[2]);
3508 proto.write(JobSchedulerServiceDumpProto.NEXT_HEARTBEAT, mNextBucketHeartbeat[3]);
3509 proto.write(JobSchedulerServiceDumpProto.LAST_HEARTBEAT_TIME_MILLIS,
3510 mLastHeartbeatTime - nowUptime);
3511 proto.write(JobSchedulerServiceDumpProto.NEXT_HEARTBEAT_TIME_MILLIS,
3512 mLastHeartbeatTime + mConstants.STANDBY_HEARTBEAT_TIME - nowUptime);
Makoto Onuki0525b982018-05-02 14:46:59 -07003513 proto.write(JobSchedulerServiceDumpProto.IN_PAROLE, mInParole);
Wei Wang8c0c3c12018-11-14 14:56:52 -08003514 proto.write(JobSchedulerServiceDumpProto.IN_THERMAL, mThermalConstraint);
Makoto Onukib5d5e972018-02-20 14:44:20 -08003515
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003516 for (int u : mStartedUsers) {
3517 proto.write(JobSchedulerServiceDumpProto.STARTED_USERS, u);
3518 }
3519 if (mJobs.size() > 0) {
3520 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
3521 sortJobs(jobs);
3522 for (JobStatus job : jobs) {
3523 final long rjToken = proto.start(JobSchedulerServiceDumpProto.REGISTERED_JOBS);
3524 job.writeToShortProto(proto, JobSchedulerServiceDumpProto.RegisteredJob.INFO);
3525
3526 // Skip printing details if the caller requested a filter
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003527 if (!predicate.test(job)) {
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003528 continue;
3529 }
3530
3531 job.dump(proto, JobSchedulerServiceDumpProto.RegisteredJob.DUMP, true, nowElapsed);
3532
3533 // isReadyToBeExecuted
3534 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_READY,
3535 job.isReady());
3536 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_USER_STARTED,
Kweku Adams8bd5edc2018-12-07 18:33:39 -08003537 areUsersStartedLocked(job));
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003538 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_PENDING,
3539 mPendingJobs.contains(job));
3540 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_CURRENTLY_ACTIVE,
3541 isCurrentlyActiveLocked(job));
3542 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_UID_BACKING_UP,
3543 mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0);
3544 boolean componentPresent = false;
3545 try {
3546 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
3547 job.getServiceComponent(),
3548 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
3549 job.getUserId()) != null);
3550 } catch (RemoteException e) {
3551 }
3552 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_COMPONENT_PRESENT,
3553 componentPresent);
Makoto Onukib5d5e972018-02-20 14:44:20 -08003554 proto.write(RegisteredJob.LAST_RUN_HEARTBEAT, heartbeatWhenJobsLastRun(job));
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003555
3556 proto.end(rjToken);
3557 }
3558 }
3559 for (StateController controller : mControllers) {
3560 controller.dumpControllerStateLocked(
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003561 proto, JobSchedulerServiceDumpProto.CONTROLLERS, predicate);
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003562 }
3563 for (int i=0; i< mUidPriorityOverride.size(); i++) {
3564 int uid = mUidPriorityOverride.keyAt(i);
3565 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
3566 long pToken = proto.start(JobSchedulerServiceDumpProto.PRIORITY_OVERRIDES);
3567 proto.write(JobSchedulerServiceDumpProto.PriorityOverride.UID, uid);
3568 proto.write(JobSchedulerServiceDumpProto.PriorityOverride.OVERRIDE_VALUE,
3569 mUidPriorityOverride.valueAt(i));
3570 proto.end(pToken);
3571 }
3572 }
3573 for (int i = 0; i < mBackingUpUids.size(); i++) {
3574 int uid = mBackingUpUids.keyAt(i);
3575 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
3576 proto.write(JobSchedulerServiceDumpProto.BACKING_UP_UIDS, uid);
3577 }
3578 }
3579
3580 mJobPackageTracker.dump(proto, JobSchedulerServiceDumpProto.PACKAGE_TRACKER,
3581 filterUidFinal);
3582 mJobPackageTracker.dumpHistory(proto, JobSchedulerServiceDumpProto.HISTORY,
3583 filterUidFinal);
3584
3585 for (JobStatus job : mPendingJobs) {
3586 final long pjToken = proto.start(JobSchedulerServiceDumpProto.PENDING_JOBS);
3587
3588 job.writeToShortProto(proto, PendingJob.INFO);
3589 job.dump(proto, PendingJob.DUMP, false, nowElapsed);
Makoto Onukiec8b14d2018-12-05 13:22:24 -08003590 proto.write(PendingJob.EVALUATED_PRIORITY, evaluateJobPriorityLocked(job));
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003591 proto.write(PendingJob.ENQUEUED_DURATION_MS, nowUptime - job.madePending);
3592
3593 proto.end(pjToken);
3594 }
3595 for (JobServiceContext jsc : mActiveServices) {
3596 final long ajToken = proto.start(JobSchedulerServiceDumpProto.ACTIVE_JOBS);
3597 final JobStatus job = jsc.getRunningJobLocked();
3598
3599 if (job == null) {
3600 final long ijToken = proto.start(ActiveJob.INACTIVE);
3601
3602 proto.write(ActiveJob.InactiveJob.TIME_SINCE_STOPPED_MS,
3603 nowElapsed - jsc.mStoppedTime);
3604 if (jsc.mStoppedReason != null) {
3605 proto.write(ActiveJob.InactiveJob.STOPPED_REASON,
3606 jsc.mStoppedReason);
3607 }
3608
3609 proto.end(ijToken);
3610 } else {
3611 final long rjToken = proto.start(ActiveJob.RUNNING);
3612
3613 job.writeToShortProto(proto, ActiveJob.RunningJob.INFO);
3614
3615 proto.write(ActiveJob.RunningJob.RUNNING_DURATION_MS,
3616 nowElapsed - jsc.getExecutionStartTimeElapsed());
3617 proto.write(ActiveJob.RunningJob.TIME_UNTIL_TIMEOUT_MS,
3618 jsc.getTimeoutElapsed() - nowElapsed);
3619
3620 job.dump(proto, ActiveJob.RunningJob.DUMP, false, nowElapsed);
3621
Makoto Onukiec8b14d2018-12-05 13:22:24 -08003622 proto.write(ActiveJob.RunningJob.EVALUATED_PRIORITY,
3623 evaluateJobPriorityLocked(jsc.getRunningJobLocked()));
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003624
3625 proto.write(ActiveJob.RunningJob.TIME_SINCE_MADE_ACTIVE_MS,
3626 nowUptime - job.madeActive);
3627 proto.write(ActiveJob.RunningJob.PENDING_DURATION_MS,
3628 job.madeActive - job.madePending);
3629
3630 proto.end(rjToken);
3631 }
3632 proto.end(ajToken);
3633 }
3634 if (filterUid == -1) {
3635 proto.write(JobSchedulerServiceDumpProto.IS_READY_TO_ROCK, mReadyToRock);
3636 proto.write(JobSchedulerServiceDumpProto.REPORTED_ACTIVE, mReportedActive);
3637 proto.write(JobSchedulerServiceDumpProto.MAX_ACTIVE_JOBS, mMaxActiveJobs);
3638 }
3639 }
3640
3641 proto.flush();
3642 }
Christopher Tate7060b042014-06-09 19:50:00 -07003643}