blob: 5295d23ff5443272456945547e68c1b42f20267f [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;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070070import android.provider.Settings;
Amith Yamasani977e11f2018-02-16 11:29:54 -080071import android.text.format.DateUtils;
Dianne Hackborne9a988c2016-05-27 17:59:40 -070072import android.util.KeyValueListParser;
Jeff Sharkey01bb5302018-02-21 20:12:40 -070073import android.util.Log;
Christopher Tate7060b042014-06-09 19:50:00 -070074import android.util.Slog;
75import android.util.SparseArray;
Dianne Hackborn970510b2016-02-24 16:56:42 -080076import android.util.SparseIntArray;
Tej Singhd5747a62018-01-08 20:57:35 -080077import android.util.StatsLog;
Dianne Hackborn970510b2016-02-24 16:56:42 -080078import android.util.TimeUtils;
Kweku Adams85f2fbc2017-12-18 12:04:12 -080079import android.util.proto.ProtoOutputStream;
Christopher Tate5d346052016-03-08 12:56:08 -080080
Wei Wang8c0c3c12018-11-14 14:56:52 -080081import com.android.internal.annotations.GuardedBy;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -070082import com.android.internal.annotations.VisibleForTesting;
Dianne Hackbornfdb19562014-07-11 16:03:36 -070083import com.android.internal.app.IBatteryStats;
Jeff Sharkey822cbd12016-02-25 11:09:55 -070084import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060085import com.android.internal.util.DumpUtils;
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -070086import com.android.internal.util.IndentingPrintWriter;
Makoto Onuki15407842018-01-19 14:23:11 -080087import com.android.internal.util.Preconditions;
Jeff Sharkey01bb5302018-02-21 20:12:40 -070088import com.android.server.AppStateTracker;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080089import com.android.server.DeviceIdleController;
Christopher Tate616541d2017-07-26 14:27:38 -070090import com.android.server.FgThread;
Dianne Hackborn627dfa12015-11-11 18:10:30 -080091import com.android.server.LocalServices;
Kweku Adams85f2fbc2017-12-18 12:04:12 -080092import com.android.server.job.JobSchedulerServiceDumpProto.ActiveJob;
93import com.android.server.job.JobSchedulerServiceDumpProto.PendingJob;
Makoto Onukib5d5e972018-02-20 14:44:20 -080094import com.android.server.job.JobSchedulerServiceDumpProto.RegisteredJob;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -070095import com.android.server.job.controllers.BackgroundJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -070096import com.android.server.job.controllers.BatteryController;
97import com.android.server.job.controllers.ConnectivityController;
Dianne Hackborn1a30bd92016-01-11 11:05:00 -080098import com.android.server.job.controllers.ContentObserverController;
Amith Yamasanicb926fc2016-03-14 17:15:20 -070099import com.android.server.job.controllers.DeviceIdleJobsController;
Christopher Tate7060b042014-06-09 19:50:00 -0700100import com.android.server.job.controllers.IdleController;
101import com.android.server.job.controllers.JobStatus;
Kweku Adams4836f9d2018-11-12 17:04:17 -0800102import com.android.server.job.controllers.QuotaController;
Christopher Tate7060b042014-06-09 19:50:00 -0700103import com.android.server.job.controllers.StateController;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700104import com.android.server.job.controllers.StorageController;
Christopher Tate7060b042014-06-09 19:50:00 -0700105import com.android.server.job.controllers.TimeController;
106
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700107import libcore.util.EmptyArray;
108
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700109import java.io.FileDescriptor;
110import java.io.PrintWriter;
111import java.time.Clock;
112import java.util.ArrayList;
113import java.util.Arrays;
114import java.util.Collections;
115import java.util.Comparator;
Christopher Tate325768c2018-03-07 16:07:56 -0800116import java.util.HashMap;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700117import java.util.List;
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -0700118import java.util.function.Consumer;
Makoto Onuki15407842018-01-19 14:23:11 -0800119import java.util.function.Predicate;
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700120
Christopher Tate7060b042014-06-09 19:50:00 -0700121/**
122 * Responsible for taking jobs representing work to be performed by a client app, and determining
123 * based on the criteria specified when that job should be run against the client application's
124 * endpoint.
125 * Implements logic for scheduling, and rescheduling jobs. The JobSchedulerService knows nothing
126 * about constraints, or the state of active jobs. It receives callbacks from the various
127 * controllers and completed jobs and operates accordingly.
128 *
129 * Note on locking: Any operations that manipulate {@link #mJobs} need to lock on that object.
130 * Any function with the suffix 'Locked' also needs to lock on {@link #mJobs}.
131 * @hide
132 */
Jeff Sharkey4d89e422018-03-29 18:22:41 -0600133public class JobSchedulerService extends com.android.server.SystemService
Matthew Williams01ac45b2014-07-22 20:44:12 -0700134 implements StateChangedListener, JobCompletedListener {
Jeff Sharkey01bb5302018-02-21 20:12:40 -0700135 public static final String TAG = "JobScheduler";
136 public static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Christopher Tatea732f012017-10-26 17:26:53 -0700137 public static final boolean DEBUG_STANDBY = DEBUG || false;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800138
Dianne Hackborn970510b2016-02-24 16:56:42 -0800139 /** The maximum number of concurrent jobs we run at one time. */
Makoto Onuki714f97d2018-12-05 11:18:13 -0800140 static final int MAX_JOB_CONTEXTS_COUNT = 16;
Christopher Tatedabdf6f2016-02-24 12:30:22 -0800141 /** Enforce a per-app limit on scheduled jobs? */
Christopher Tate0213ace02016-02-24 14:18:35 -0800142 private static final boolean ENFORCE_MAX_JOBS = true;
Christopher Tate2f36fd62016-02-18 18:36:08 -0800143 /** The maximum number of jobs that we allow an unprivileged app to schedule */
144 private static final int MAX_JOBS_PER_APP = 100;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700145
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -0700146 @VisibleForTesting
147 public static Clock sSystemClock = Clock.systemUTC();
148 @VisibleForTesting
149 public static Clock sUptimeMillisClock = SystemClock.uptimeMillisClock();
150 @VisibleForTesting
151 public static Clock sElapsedRealtimeClock = SystemClock.elapsedRealtimeClock();
Christopher Tate2f36fd62016-02-18 18:36:08 -0800152
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800153 /** Global local for all job scheduler state. */
154 final Object mLock = new Object();
Christopher Tate7060b042014-06-09 19:50:00 -0700155 /** Master list of jobs. */
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700156 final JobStore mJobs;
Christopher Tatea732f012017-10-26 17:26:53 -0700157 /** Tracking the standby bucket state of each app */
158 final StandbyTracker mStandbyTracker;
Dianne Hackborn807de782016-04-07 17:54:41 -0700159 /** Tracking amount of time each package runs for. */
160 final JobPackageTracker mJobPackageTracker = new JobPackageTracker();
Makoto Onuki714f97d2018-12-05 11:18:13 -0800161 final JobConcurrencyManager mConcurrencyManager;
Christopher Tate7060b042014-06-09 19:50:00 -0700162
163 static final int MSG_JOB_EXPIRED = 0;
164 static final int MSG_CHECK_JOB = 1;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700165 static final int MSG_STOP_JOB = 2;
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +0000166 static final int MSG_CHECK_JOB_GREEDY = 3;
Makoto Onuki743e0ad2018-02-20 16:01:11 -0800167 static final int MSG_UID_STATE_CHANGED = 4;
168 static final int MSG_UID_GONE = 5;
169 static final int MSG_UID_ACTIVE = 6;
170 static final int MSG_UID_IDLE = 7;
Christopher Tate7060b042014-06-09 19:50:00 -0700171
Christopher Tate7060b042014-06-09 19:50:00 -0700172 /**
173 * Track Services that have currently active or pending jobs. The index is provided by
174 * {@link JobStatus#getServiceToken()}
175 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700176 final List<JobServiceContext> mActiveServices = new ArrayList<>();
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700177
Christopher Tate7060b042014-06-09 19:50:00 -0700178 /** List of controllers that will notify this service of updates to jobs. */
Makoto Onuki714f97d2018-12-05 11:18:13 -0800179 final List<StateController> mControllers;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800180 /** Need direct access to this for testing. */
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700181 private final BatteryController mBatteryController;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700182 /** Need direct access to this for testing. */
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700183 private final StorageController mStorageController;
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -0700184 /** Need directly for sending uid state changes */
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700185 private final DeviceIdleJobsController mDeviceIdleJobsController;
Wei Wang8c0c3c12018-11-14 14:56:52 -0800186 /** Need directly for receiving thermal events */
187 private IThermalService mThermalService;
188 /** Thermal constraint. */
189 @GuardedBy("mLock")
190 private boolean mThermalConstraint = false;
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700191
Christopher Tate7060b042014-06-09 19:50:00 -0700192 /**
193 * Queue of pending jobs. The JobServiceContext class will receive jobs from this list
194 * when ready to execute them.
195 */
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700196 final ArrayList<JobStatus> mPendingJobs = new ArrayList<>();
Christopher Tate7060b042014-06-09 19:50:00 -0700197
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700198 int[] mStartedUsers = EmptyArray.INT;
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700199
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700200 final JobHandler mHandler;
201 final JobSchedulerStub mJobSchedulerStub;
202
Christopher Tatea732f012017-10-26 17:26:53 -0700203 PackageManagerInternal mLocalPM;
Makoto Onuki15407842018-01-19 14:23:11 -0800204 ActivityManagerInternal mActivityManagerInternal;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700205 IBatteryStats mBatteryStats;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800206 DeviceIdleController.LocalService mLocalDeviceIdleController;
Makoto Onukie4918212018-02-06 11:30:15 -0800207 AppStateTracker mAppStateTracker;
Christopher Tated1aebb32018-01-31 13:24:14 -0800208 final UsageStatsManagerInternal mUsageStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -0700209
210 /**
211 * Set to true once we are allowed to run third party apps.
212 */
213 boolean mReadyToRock;
214
Christopher Tate7060b042014-06-09 19:50:00 -0700215 /**
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800216 * What we last reported to DeviceIdleController about whether we are active.
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800217 */
218 boolean mReportedActive;
219
220 /**
Christopher Tatea5a85bd2018-01-03 17:20:36 -0800221 * Are we currently in device-wide standby parole?
222 */
223 volatile boolean mInParole;
224
225 /**
Dianne Hackborn970510b2016-02-24 16:56:42 -0800226 * Current limit on the number of concurrent JobServiceContext entries we want to
227 * keep actively running a job.
228 */
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700229 int mMaxActiveJobs = 1;
Dianne Hackborn970510b2016-02-24 16:56:42 -0800230
231 /**
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800232 * A mapping of which uids are currently in the foreground to their effective priority.
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800233 */
Dianne Hackborn970510b2016-02-24 16:56:42 -0800234 final SparseIntArray mUidPriorityOverride = new SparseIntArray();
235
Dianne Hackbornf9bac162017-04-20 17:17:48 -0700236 /**
237 * Which uids are currently performing backups, so we shouldn't allow their jobs to run.
238 */
239 final SparseIntArray mBackingUpUids = new SparseIntArray();
240
Christopher Tatea732f012017-10-26 17:26:53 -0700241 /**
242 * Count standby heartbeats, and keep track of which beat each bucket's jobs will
243 * next become runnable. Index into this array is by normalized bucket:
244 * { ACTIVE, WORKING, FREQUENT, RARE, NEVER }. The ACTIVE and NEVER bucket
245 * milestones are not updated: ACTIVE apps get jobs whenever they ask for them,
246 * and NEVER apps don't get them at all.
247 */
248 final long[] mNextBucketHeartbeat = { 0, 0, 0, 0, Long.MAX_VALUE };
249 long mHeartbeat = 0;
Christopher Tated1aebb32018-01-31 13:24:14 -0800250 long mLastHeartbeatTime = sElapsedRealtimeClock.millis();
251
Christopher Tate325768c2018-03-07 16:07:56 -0800252 /**
253 * Named indices into the STANDBY_BEATS array, for clarity in referring to
254 * specific buckets' bookkeeping.
255 */
Kweku Adams4836f9d2018-11-12 17:04:17 -0800256 public static final int ACTIVE_INDEX = 0;
257 public static final int WORKING_INDEX = 1;
258 public static final int FREQUENT_INDEX = 2;
259 public static final int RARE_INDEX = 3;
260 public static final int NEVER_INDEX = 4;
Christopher Tate325768c2018-03-07 16:07:56 -0800261
262 /**
263 * Bookkeeping about when jobs last run. We keep our own record in heartbeat time,
264 * rather than rely on Usage Stats' timestamps, because heartbeat time can be
265 * manipulated for testing purposes and we need job runnability to track that rather
266 * than real time.
267 *
268 * Outer SparseArray slices by user handle; inner map of package name to heartbeat
269 * is a HashMap<> rather than ArrayMap<> because we expect O(hundreds) of keys
270 * and it will be accessed in a known-hot code path.
271 */
272 final SparseArray<HashMap<String, Long>> mLastJobHeartbeats = new SparseArray<>();
273
Christopher Tated1aebb32018-01-31 13:24:14 -0800274 static final String HEARTBEAT_TAG = "*job.heartbeat*";
275 final HeartbeatAlarmListener mHeartbeatAlarm = new HeartbeatAlarmListener();
Christopher Tatea732f012017-10-26 17:26:53 -0700276
Dianne Hackborn970510b2016-02-24 16:56:42 -0800277 // -- Pre-allocated temporaries only for use in assignJobsToContextsLocked --
278
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700279 private class ConstantsObserver extends ContentObserver {
280 private ContentResolver mResolver;
281
282 public ConstantsObserver(Handler handler) {
283 super(handler);
284 }
285
286 public void start(ContentResolver resolver) {
287 mResolver = resolver;
288 mResolver.registerContentObserver(Settings.Global.getUriFor(
289 Settings.Global.JOB_SCHEDULER_CONSTANTS), false, this);
290 updateConstants();
291 }
292
293 @Override
294 public void onChange(boolean selfChange, Uri uri) {
295 updateConstants();
296 }
297
298 private void updateConstants() {
299 synchronized (mLock) {
300 try {
301 mConstants.updateConstantsLocked(Settings.Global.getString(mResolver,
302 Settings.Global.JOB_SCHEDULER_CONSTANTS));
Kweku Adams4836f9d2018-11-12 17:04:17 -0800303 for (int controller = 0; controller < mControllers.size(); controller++) {
304 final StateController sc = mControllers.get(controller);
305 sc.onConstantsUpdatedLocked();
306 }
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700307 } catch (IllegalArgumentException e) {
308 // Failed to parse the settings string, log this and move on
309 // with defaults.
310 Slog.e(TAG, "Bad jobscheduler settings", e);
311 }
312 }
313
Kweku Adams4836f9d2018-11-12 17:04:17 -0800314 if (mConstants.USE_HEARTBEATS) {
315 // Reset the heartbeat alarm based on the new heartbeat duration
316 setNextHeartbeatAlarm();
317 }
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700318 }
319 }
320
Dianne Hackborn1085ff62016-02-23 17:04:58 -0800321 /**
Wei Wang8c0c3c12018-11-14 14:56:52 -0800322 * Thermal event received from Thermal Service
323 */
324 private final class ThermalStatusListener extends IThermalStatusListener.Stub {
325 @Override public void onStatusChange(int status) {
326 // Throttle for Temperature.THROTTLING_SEVERE and above
327 synchronized (mLock) {
328 mThermalConstraint = status >= Temperature.THROTTLING_SEVERE;
329 }
330 onControllerStateChanged();
331 }
332 }
333
334 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700335 * All times are in milliseconds. These constants are kept synchronized with the system
336 * global Settings. Any access to this class or its fields should be done while
337 * holding the JobSchedulerService.mLock lock.
338 */
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700339 public static class Constants {
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700340 // Key names stored in the settings value.
341 private static final String KEY_MIN_IDLE_COUNT = "min_idle_count";
342 private static final String KEY_MIN_CHARGING_COUNT = "min_charging_count";
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800343 private static final String KEY_MIN_BATTERY_NOT_LOW_COUNT = "min_battery_not_low_count";
Dianne Hackborn532ea262017-03-17 17:50:55 -0700344 private static final String KEY_MIN_STORAGE_NOT_LOW_COUNT = "min_storage_not_low_count";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700345 private static final String KEY_MIN_CONNECTIVITY_COUNT = "min_connectivity_count";
346 private static final String KEY_MIN_CONTENT_COUNT = "min_content_count";
347 private static final String KEY_MIN_READY_JOBS_COUNT = "min_ready_jobs_count";
348 private static final String KEY_HEAVY_USE_FACTOR = "heavy_use_factor";
349 private static final String KEY_MODERATE_USE_FACTOR = "moderate_use_factor";
350 private static final String KEY_FG_JOB_COUNT = "fg_job_count";
351 private static final String KEY_BG_NORMAL_JOB_COUNT = "bg_normal_job_count";
352 private static final String KEY_BG_MODERATE_JOB_COUNT = "bg_moderate_job_count";
353 private static final String KEY_BG_LOW_JOB_COUNT = "bg_low_job_count";
354 private static final String KEY_BG_CRITICAL_JOB_COUNT = "bg_critical_job_count";
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700355 private static final String KEY_MAX_STANDARD_RESCHEDULE_COUNT
356 = "max_standard_reschedule_count";
357 private static final String KEY_MAX_WORK_RESCHEDULE_COUNT = "max_work_reschedule_count";
358 private static final String KEY_MIN_LINEAR_BACKOFF_TIME = "min_linear_backoff_time";
359 private static final String KEY_MIN_EXP_BACKOFF_TIME = "min_exp_backoff_time";
Christopher Tatea732f012017-10-26 17:26:53 -0700360 private static final String KEY_STANDBY_HEARTBEAT_TIME = "standby_heartbeat_time";
361 private static final String KEY_STANDBY_WORKING_BEATS = "standby_working_beats";
362 private static final String KEY_STANDBY_FREQUENT_BEATS = "standby_frequent_beats";
363 private static final String KEY_STANDBY_RARE_BEATS = "standby_rare_beats";
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700364 private static final String KEY_CONN_CONGESTION_DELAY_FRAC = "conn_congestion_delay_frac";
365 private static final String KEY_CONN_PREFETCH_RELAX_FRAC = "conn_prefetch_relax_frac";
Kweku Adams4836f9d2018-11-12 17:04:17 -0800366 private static final String KEY_USE_HEARTBEATS = "use_heartbeats";
367 private static final String KEY_QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS =
368 "qc_allowed_time_per_period_ms";
369 private static final String KEY_QUOTA_CONTROLLER_IN_QUOTA_BUFFER_MS =
370 "qc_in_quota_buffer_ms";
371 private static final String KEY_QUOTA_CONTROLLER_WINDOW_SIZE_ACTIVE_MS =
372 "qc_window_size_active_ms";
373 private static final String KEY_QUOTA_CONTROLLER_WINDOW_SIZE_WORKING_MS =
374 "qc_window_size_working_ms";
375 private static final String KEY_QUOTA_CONTROLLER_WINDOW_SIZE_FREQUENT_MS =
376 "qc_window_size_frequent_ms";
377 private static final String KEY_QUOTA_CONTROLLER_WINDOW_SIZE_RARE_MS =
378 "qc_window_size_rare_ms";
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700379
380 private static final int DEFAULT_MIN_IDLE_COUNT = 1;
381 private static final int DEFAULT_MIN_CHARGING_COUNT = 1;
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800382 private static final int DEFAULT_MIN_BATTERY_NOT_LOW_COUNT = 1;
Dianne Hackborn532ea262017-03-17 17:50:55 -0700383 private static final int DEFAULT_MIN_STORAGE_NOT_LOW_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700384 private static final int DEFAULT_MIN_CONNECTIVITY_COUNT = 1;
385 private static final int DEFAULT_MIN_CONTENT_COUNT = 1;
386 private static final int DEFAULT_MIN_READY_JOBS_COUNT = 1;
387 private static final float DEFAULT_HEAVY_USE_FACTOR = .9f;
388 private static final float DEFAULT_MODERATE_USE_FACTOR = .5f;
389 private static final int DEFAULT_FG_JOB_COUNT = 4;
390 private static final int DEFAULT_BG_NORMAL_JOB_COUNT = 6;
391 private static final int DEFAULT_BG_MODERATE_JOB_COUNT = 4;
Nancy Zhenge39a8a42016-10-05 16:27:14 -0700392 private static final int DEFAULT_BG_LOW_JOB_COUNT = 1;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700393 private static final int DEFAULT_BG_CRITICAL_JOB_COUNT = 1;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700394 private static final int DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT = Integer.MAX_VALUE;
395 private static final int DEFAULT_MAX_WORK_RESCHEDULE_COUNT = Integer.MAX_VALUE;
396 private static final long DEFAULT_MIN_LINEAR_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
397 private static final long DEFAULT_MIN_EXP_BACKOFF_TIME = JobInfo.MIN_BACKOFF_MILLIS;
Christopher Tatea732f012017-10-26 17:26:53 -0700398 private static final long DEFAULT_STANDBY_HEARTBEAT_TIME = 11 * 60 * 1000L;
Esteban Talavera65254042017-12-15 10:59:28 +0000399 private static final int DEFAULT_STANDBY_WORKING_BEATS = 11; // ~ 2 hours, with 11min beats
400 private static final int DEFAULT_STANDBY_FREQUENT_BEATS = 43; // ~ 8 hours
Christopher Tatea732f012017-10-26 17:26:53 -0700401 private static final int DEFAULT_STANDBY_RARE_BEATS = 130; // ~ 24 hours
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700402 private static final float DEFAULT_CONN_CONGESTION_DELAY_FRAC = 0.5f;
403 private static final float DEFAULT_CONN_PREFETCH_RELAX_FRAC = 0.5f;
Kweku Adams4836f9d2018-11-12 17:04:17 -0800404 private static final boolean DEFAULT_USE_HEARTBEATS = true;
405 private static final long DEFAULT_QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS =
406 10 * 60 * 1000L; // 10 minutes
407 private static final long DEFAULT_QUOTA_CONTROLLER_IN_QUOTA_BUFFER_MS =
408 30 * 1000L; // 30 seconds
409 private static final long DEFAULT_QUOTA_CONTROLLER_WINDOW_SIZE_ACTIVE_MS =
410 10 * 60 * 1000L; // 10 minutes for ACTIVE -- ACTIVE apps can run jobs at any time
411 private static final long DEFAULT_QUOTA_CONTROLLER_WINDOW_SIZE_WORKING_MS =
412 2 * 60 * 60 * 1000L; // 2 hours
413 private static final long DEFAULT_QUOTA_CONTROLLER_WINDOW_SIZE_FREQUENT_MS =
414 8 * 60 * 60 * 1000L; // 8 hours
415 private static final long DEFAULT_QUOTA_CONTROLLER_WINDOW_SIZE_RARE_MS =
416 24 * 60 * 60 * 1000L; // 24 hours
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700417
418 /**
419 * Minimum # of idle jobs that must be ready in order to force the JMS to schedule things
420 * early.
421 */
422 int MIN_IDLE_COUNT = DEFAULT_MIN_IDLE_COUNT;
423 /**
424 * Minimum # of charging jobs that must be ready in order to force the JMS to schedule
425 * things early.
426 */
427 int MIN_CHARGING_COUNT = DEFAULT_MIN_CHARGING_COUNT;
428 /**
Dianne Hackborna06ec6a2017-02-13 10:08:42 -0800429 * Minimum # of "battery not low" jobs that must be ready in order to force the JMS to
430 * schedule things early.
431 */
432 int MIN_BATTERY_NOT_LOW_COUNT = DEFAULT_MIN_BATTERY_NOT_LOW_COUNT;
433 /**
Dianne Hackborn532ea262017-03-17 17:50:55 -0700434 * Minimum # of "storage not low" jobs that must be ready in order to force the JMS to
435 * schedule things early.
436 */
437 int MIN_STORAGE_NOT_LOW_COUNT = DEFAULT_MIN_STORAGE_NOT_LOW_COUNT;
438 /**
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700439 * Minimum # of connectivity jobs that must be ready in order to force the JMS to schedule
440 * things early. 1 == Run connectivity jobs as soon as ready.
441 */
442 int MIN_CONNECTIVITY_COUNT = DEFAULT_MIN_CONNECTIVITY_COUNT;
443 /**
444 * Minimum # of content trigger jobs that must be ready in order to force the JMS to
445 * schedule things early.
446 */
447 int MIN_CONTENT_COUNT = DEFAULT_MIN_CONTENT_COUNT;
448 /**
449 * Minimum # of jobs (with no particular constraints) for which the JMS will be happy
450 * running some work early. This (and thus the other min counts) is now set to 1, to
451 * prevent any batching at this level. Since we now do batching through doze, that is
452 * a much better mechanism.
453 */
454 int MIN_READY_JOBS_COUNT = DEFAULT_MIN_READY_JOBS_COUNT;
455 /**
456 * This is the job execution factor that is considered to be heavy use of the system.
457 */
458 float HEAVY_USE_FACTOR = DEFAULT_HEAVY_USE_FACTOR;
459 /**
460 * This is the job execution factor that is considered to be moderate use of the system.
461 */
462 float MODERATE_USE_FACTOR = DEFAULT_MODERATE_USE_FACTOR;
463 /**
464 * The number of MAX_JOB_CONTEXTS_COUNT we reserve for the foreground app.
465 */
466 int FG_JOB_COUNT = DEFAULT_FG_JOB_COUNT;
467 /**
468 * The maximum number of background jobs we allow when the system is in a normal
469 * memory state.
470 */
471 int BG_NORMAL_JOB_COUNT = DEFAULT_BG_NORMAL_JOB_COUNT;
472 /**
473 * The maximum number of background jobs we allow when the system is in a moderate
474 * memory state.
475 */
476 int BG_MODERATE_JOB_COUNT = DEFAULT_BG_MODERATE_JOB_COUNT;
477 /**
478 * The maximum number of background jobs we allow when the system is in a low
479 * memory state.
480 */
481 int BG_LOW_JOB_COUNT = DEFAULT_BG_LOW_JOB_COUNT;
482 /**
483 * The maximum number of background jobs we allow when the system is in a critical
484 * memory state.
485 */
486 int BG_CRITICAL_JOB_COUNT = DEFAULT_BG_CRITICAL_JOB_COUNT;
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700487 /**
488 * The maximum number of times we allow a job to have itself rescheduled before
489 * giving up on it, for standard jobs.
490 */
491 int MAX_STANDARD_RESCHEDULE_COUNT = DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT;
492 /**
493 * The maximum number of times we allow a job to have itself rescheduled before
494 * giving up on it, for jobs that are executing work.
495 */
496 int MAX_WORK_RESCHEDULE_COUNT = DEFAULT_MAX_WORK_RESCHEDULE_COUNT;
497 /**
498 * The minimum backoff time to allow for linear backoff.
499 */
500 long MIN_LINEAR_BACKOFF_TIME = DEFAULT_MIN_LINEAR_BACKOFF_TIME;
501 /**
502 * The minimum backoff time to allow for exponential backoff.
503 */
504 long MIN_EXP_BACKOFF_TIME = DEFAULT_MIN_EXP_BACKOFF_TIME;
Christopher Tatea732f012017-10-26 17:26:53 -0700505 /**
506 * How often we recalculate runnability based on apps' standby bucket assignment.
507 * This should be prime relative to common time interval lengths such as a quarter-
508 * hour or day, so that the heartbeat drifts relative to wall-clock milestones.
509 */
510 long STANDBY_HEARTBEAT_TIME = DEFAULT_STANDBY_HEARTBEAT_TIME;
Christopher Tatea732f012017-10-26 17:26:53 -0700511 /**
512 * Mapping: standby bucket -> number of heartbeats between each sweep of that
513 * bucket's jobs.
514 *
515 * Bucket assignments as recorded in the JobStatus objects are normalized to be
516 * indices into this array, rather than the raw constants used
517 * by AppIdleHistory.
518 */
519 final int[] STANDBY_BEATS = {
520 0,
521 DEFAULT_STANDBY_WORKING_BEATS,
522 DEFAULT_STANDBY_FREQUENT_BEATS,
523 DEFAULT_STANDBY_RARE_BEATS
524 };
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700525 /**
526 * The fraction of a job's running window that must pass before we
527 * consider running it when the network is congested.
528 */
529 public float CONN_CONGESTION_DELAY_FRAC = DEFAULT_CONN_CONGESTION_DELAY_FRAC;
530 /**
531 * The fraction of a prefetch job's running window that must pass before
532 * we consider matching it against a metered network.
533 */
534 public float CONN_PREFETCH_RELAX_FRAC = DEFAULT_CONN_PREFETCH_RELAX_FRAC;
Kweku Adams4836f9d2018-11-12 17:04:17 -0800535 /**
536 * Whether to use heartbeats or rolling window for quota management. True will use
537 * heartbeats, false will use a rolling window.
538 */
539 public boolean USE_HEARTBEATS = DEFAULT_USE_HEARTBEATS;
540
541 /** How much time each app will have to run jobs within their standby bucket window. */
542 public long QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS =
543 DEFAULT_QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS;
544
545 /**
546 * How much time the package should have before transitioning from out-of-quota to in-quota.
547 * This should not affect processing if the package is already in-quota.
548 */
549 public long QUOTA_CONTROLLER_IN_QUOTA_BUFFER_MS =
550 DEFAULT_QUOTA_CONTROLLER_IN_QUOTA_BUFFER_MS;
551
552 /**
553 * The quota window size of the particular standby bucket. Apps in this standby bucket are
554 * expected to run only {@link QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS} within the past
555 * WINDOW_SIZE_MS.
556 */
557 public long QUOTA_CONTROLLER_WINDOW_SIZE_ACTIVE_MS =
558 DEFAULT_QUOTA_CONTROLLER_WINDOW_SIZE_ACTIVE_MS;
559
560 /**
561 * The quota window size of the particular standby bucket. Apps in this standby bucket are
562 * expected to run only {@link QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS} within the past
563 * WINDOW_SIZE_MS.
564 */
565 public long QUOTA_CONTROLLER_WINDOW_SIZE_WORKING_MS =
566 DEFAULT_QUOTA_CONTROLLER_WINDOW_SIZE_WORKING_MS;
567
568 /**
569 * The quota window size of the particular standby bucket. Apps in this standby bucket are
570 * expected to run only {@link QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS} within the past
571 * WINDOW_SIZE_MS.
572 */
573 public long QUOTA_CONTROLLER_WINDOW_SIZE_FREQUENT_MS =
574 DEFAULT_QUOTA_CONTROLLER_WINDOW_SIZE_FREQUENT_MS;
575
576 /**
577 * The quota window size of the particular standby bucket. Apps in this standby bucket are
578 * expected to run only {@link QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS} within the past
579 * WINDOW_SIZE_MS.
580 */
581 public long QUOTA_CONTROLLER_WINDOW_SIZE_RARE_MS =
582 DEFAULT_QUOTA_CONTROLLER_WINDOW_SIZE_RARE_MS;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700583
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700584 private final KeyValueListParser mParser = new KeyValueListParser(',');
585
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700586 void updateConstantsLocked(String value) {
587 try {
588 mParser.setString(value);
589 } catch (Exception e) {
590 // Failed to parse the settings string, log this and move on
591 // with defaults.
592 Slog.e(TAG, "Bad jobscheduler settings", e);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700593 }
Christopher Tated1aebb32018-01-31 13:24:14 -0800594
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700595 MIN_IDLE_COUNT = mParser.getInt(KEY_MIN_IDLE_COUNT,
596 DEFAULT_MIN_IDLE_COUNT);
597 MIN_CHARGING_COUNT = mParser.getInt(KEY_MIN_CHARGING_COUNT,
598 DEFAULT_MIN_CHARGING_COUNT);
599 MIN_BATTERY_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_BATTERY_NOT_LOW_COUNT,
600 DEFAULT_MIN_BATTERY_NOT_LOW_COUNT);
601 MIN_STORAGE_NOT_LOW_COUNT = mParser.getInt(KEY_MIN_STORAGE_NOT_LOW_COUNT,
602 DEFAULT_MIN_STORAGE_NOT_LOW_COUNT);
603 MIN_CONNECTIVITY_COUNT = mParser.getInt(KEY_MIN_CONNECTIVITY_COUNT,
604 DEFAULT_MIN_CONNECTIVITY_COUNT);
605 MIN_CONTENT_COUNT = mParser.getInt(KEY_MIN_CONTENT_COUNT,
606 DEFAULT_MIN_CONTENT_COUNT);
607 MIN_READY_JOBS_COUNT = mParser.getInt(KEY_MIN_READY_JOBS_COUNT,
608 DEFAULT_MIN_READY_JOBS_COUNT);
609 HEAVY_USE_FACTOR = mParser.getFloat(KEY_HEAVY_USE_FACTOR,
610 DEFAULT_HEAVY_USE_FACTOR);
611 MODERATE_USE_FACTOR = mParser.getFloat(KEY_MODERATE_USE_FACTOR,
612 DEFAULT_MODERATE_USE_FACTOR);
613 FG_JOB_COUNT = mParser.getInt(KEY_FG_JOB_COUNT,
614 DEFAULT_FG_JOB_COUNT);
615 BG_NORMAL_JOB_COUNT = mParser.getInt(KEY_BG_NORMAL_JOB_COUNT,
616 DEFAULT_BG_NORMAL_JOB_COUNT);
617 if ((FG_JOB_COUNT+BG_NORMAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
618 BG_NORMAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
619 }
620 BG_MODERATE_JOB_COUNT = mParser.getInt(KEY_BG_MODERATE_JOB_COUNT,
621 DEFAULT_BG_MODERATE_JOB_COUNT);
622 if ((FG_JOB_COUNT+BG_MODERATE_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
623 BG_MODERATE_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
624 }
625 BG_LOW_JOB_COUNT = mParser.getInt(KEY_BG_LOW_JOB_COUNT,
626 DEFAULT_BG_LOW_JOB_COUNT);
627 if ((FG_JOB_COUNT+BG_LOW_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
628 BG_LOW_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
629 }
630 BG_CRITICAL_JOB_COUNT = mParser.getInt(KEY_BG_CRITICAL_JOB_COUNT,
631 DEFAULT_BG_CRITICAL_JOB_COUNT);
632 if ((FG_JOB_COUNT+BG_CRITICAL_JOB_COUNT) > MAX_JOB_CONTEXTS_COUNT) {
633 BG_CRITICAL_JOB_COUNT = MAX_JOB_CONTEXTS_COUNT - FG_JOB_COUNT;
634 }
635 MAX_STANDARD_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_STANDARD_RESCHEDULE_COUNT,
636 DEFAULT_MAX_STANDARD_RESCHEDULE_COUNT);
637 MAX_WORK_RESCHEDULE_COUNT = mParser.getInt(KEY_MAX_WORK_RESCHEDULE_COUNT,
638 DEFAULT_MAX_WORK_RESCHEDULE_COUNT);
639 MIN_LINEAR_BACKOFF_TIME = mParser.getDurationMillis(KEY_MIN_LINEAR_BACKOFF_TIME,
640 DEFAULT_MIN_LINEAR_BACKOFF_TIME);
641 MIN_EXP_BACKOFF_TIME = mParser.getDurationMillis(KEY_MIN_EXP_BACKOFF_TIME,
642 DEFAULT_MIN_EXP_BACKOFF_TIME);
643 STANDBY_HEARTBEAT_TIME = mParser.getDurationMillis(KEY_STANDBY_HEARTBEAT_TIME,
644 DEFAULT_STANDBY_HEARTBEAT_TIME);
Christopher Tate325768c2018-03-07 16:07:56 -0800645 STANDBY_BEATS[WORKING_INDEX] = mParser.getInt(KEY_STANDBY_WORKING_BEATS,
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700646 DEFAULT_STANDBY_WORKING_BEATS);
Christopher Tate325768c2018-03-07 16:07:56 -0800647 STANDBY_BEATS[FREQUENT_INDEX] = mParser.getInt(KEY_STANDBY_FREQUENT_BEATS,
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700648 DEFAULT_STANDBY_FREQUENT_BEATS);
Christopher Tate325768c2018-03-07 16:07:56 -0800649 STANDBY_BEATS[RARE_INDEX] = mParser.getInt(KEY_STANDBY_RARE_BEATS,
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700650 DEFAULT_STANDBY_RARE_BEATS);
651 CONN_CONGESTION_DELAY_FRAC = mParser.getFloat(KEY_CONN_CONGESTION_DELAY_FRAC,
652 DEFAULT_CONN_CONGESTION_DELAY_FRAC);
653 CONN_PREFETCH_RELAX_FRAC = mParser.getFloat(KEY_CONN_PREFETCH_RELAX_FRAC,
654 DEFAULT_CONN_PREFETCH_RELAX_FRAC);
Kweku Adams4836f9d2018-11-12 17:04:17 -0800655 USE_HEARTBEATS = mParser.getBoolean(KEY_USE_HEARTBEATS, DEFAULT_USE_HEARTBEATS);
656 QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS = mParser.getDurationMillis(
657 KEY_QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS,
658 DEFAULT_QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS);
659 QUOTA_CONTROLLER_IN_QUOTA_BUFFER_MS = mParser.getDurationMillis(
660 KEY_QUOTA_CONTROLLER_IN_QUOTA_BUFFER_MS,
661 DEFAULT_QUOTA_CONTROLLER_IN_QUOTA_BUFFER_MS);
662 QUOTA_CONTROLLER_WINDOW_SIZE_ACTIVE_MS = mParser.getDurationMillis(
663 KEY_QUOTA_CONTROLLER_WINDOW_SIZE_ACTIVE_MS,
664 DEFAULT_QUOTA_CONTROLLER_WINDOW_SIZE_ACTIVE_MS);
665 QUOTA_CONTROLLER_WINDOW_SIZE_WORKING_MS = mParser.getDurationMillis(
666 KEY_QUOTA_CONTROLLER_WINDOW_SIZE_WORKING_MS,
667 DEFAULT_QUOTA_CONTROLLER_WINDOW_SIZE_WORKING_MS);
668 QUOTA_CONTROLLER_WINDOW_SIZE_FREQUENT_MS = mParser.getDurationMillis(
669 KEY_QUOTA_CONTROLLER_WINDOW_SIZE_FREQUENT_MS,
670 DEFAULT_QUOTA_CONTROLLER_WINDOW_SIZE_FREQUENT_MS);
671 QUOTA_CONTROLLER_WINDOW_SIZE_RARE_MS = mParser.getDurationMillis(
672 KEY_QUOTA_CONTROLLER_WINDOW_SIZE_RARE_MS,
673 DEFAULT_QUOTA_CONTROLLER_WINDOW_SIZE_RARE_MS);
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700674 }
675
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700676 void dump(IndentingPrintWriter pw) {
677 pw.println("Settings:");
678 pw.increaseIndent();
679 pw.printPair(KEY_MIN_IDLE_COUNT, MIN_IDLE_COUNT).println();
680 pw.printPair(KEY_MIN_CHARGING_COUNT, MIN_CHARGING_COUNT).println();
681 pw.printPair(KEY_MIN_BATTERY_NOT_LOW_COUNT, MIN_BATTERY_NOT_LOW_COUNT).println();
682 pw.printPair(KEY_MIN_STORAGE_NOT_LOW_COUNT, MIN_STORAGE_NOT_LOW_COUNT).println();
683 pw.printPair(KEY_MIN_CONNECTIVITY_COUNT, MIN_CONNECTIVITY_COUNT).println();
684 pw.printPair(KEY_MIN_CONTENT_COUNT, MIN_CONTENT_COUNT).println();
685 pw.printPair(KEY_MIN_READY_JOBS_COUNT, MIN_READY_JOBS_COUNT).println();
686 pw.printPair(KEY_HEAVY_USE_FACTOR, HEAVY_USE_FACTOR).println();
687 pw.printPair(KEY_MODERATE_USE_FACTOR, MODERATE_USE_FACTOR).println();
688 pw.printPair(KEY_FG_JOB_COUNT, FG_JOB_COUNT).println();
689 pw.printPair(KEY_BG_NORMAL_JOB_COUNT, BG_NORMAL_JOB_COUNT).println();
690 pw.printPair(KEY_BG_MODERATE_JOB_COUNT, BG_MODERATE_JOB_COUNT).println();
691 pw.printPair(KEY_BG_LOW_JOB_COUNT, BG_LOW_JOB_COUNT).println();
692 pw.printPair(KEY_BG_CRITICAL_JOB_COUNT, BG_CRITICAL_JOB_COUNT).println();
693 pw.printPair(KEY_MAX_STANDARD_RESCHEDULE_COUNT, MAX_STANDARD_RESCHEDULE_COUNT).println();
694 pw.printPair(KEY_MAX_WORK_RESCHEDULE_COUNT, MAX_WORK_RESCHEDULE_COUNT).println();
695 pw.printPair(KEY_MIN_LINEAR_BACKOFF_TIME, MIN_LINEAR_BACKOFF_TIME).println();
696 pw.printPair(KEY_MIN_EXP_BACKOFF_TIME, MIN_EXP_BACKOFF_TIME).println();
697 pw.printPair(KEY_STANDBY_HEARTBEAT_TIME, STANDBY_HEARTBEAT_TIME).println();
698 pw.print("standby_beats={");
Christopher Tatea732f012017-10-26 17:26:53 -0700699 pw.print(STANDBY_BEATS[0]);
700 for (int i = 1; i < STANDBY_BEATS.length; i++) {
701 pw.print(", ");
702 pw.print(STANDBY_BEATS[i]);
703 }
704 pw.println('}');
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700705 pw.printPair(KEY_CONN_CONGESTION_DELAY_FRAC, CONN_CONGESTION_DELAY_FRAC).println();
706 pw.printPair(KEY_CONN_PREFETCH_RELAX_FRAC, CONN_PREFETCH_RELAX_FRAC).println();
Kweku Adams4836f9d2018-11-12 17:04:17 -0800707 pw.printPair(KEY_USE_HEARTBEATS, USE_HEARTBEATS).println();
708 pw.printPair(KEY_QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS,
709 QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS).println();
710 pw.printPair(KEY_QUOTA_CONTROLLER_IN_QUOTA_BUFFER_MS,
711 QUOTA_CONTROLLER_IN_QUOTA_BUFFER_MS).println();
712 pw.printPair(KEY_QUOTA_CONTROLLER_WINDOW_SIZE_ACTIVE_MS,
713 QUOTA_CONTROLLER_WINDOW_SIZE_ACTIVE_MS).println();
714 pw.printPair(KEY_QUOTA_CONTROLLER_WINDOW_SIZE_WORKING_MS,
715 QUOTA_CONTROLLER_WINDOW_SIZE_WORKING_MS).println();
716 pw.printPair(KEY_QUOTA_CONTROLLER_WINDOW_SIZE_FREQUENT_MS,
717 QUOTA_CONTROLLER_WINDOW_SIZE_FREQUENT_MS).println();
718 pw.printPair(KEY_QUOTA_CONTROLLER_WINDOW_SIZE_RARE_MS,
719 QUOTA_CONTROLLER_WINDOW_SIZE_RARE_MS).println();
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700720 pw.decreaseIndent();
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700721 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800722
723 void dump(ProtoOutputStream proto, long fieldId) {
724 final long token = proto.start(fieldId);
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800725 proto.write(ConstantsProto.MIN_IDLE_COUNT, MIN_IDLE_COUNT);
726 proto.write(ConstantsProto.MIN_CHARGING_COUNT, MIN_CHARGING_COUNT);
727 proto.write(ConstantsProto.MIN_BATTERY_NOT_LOW_COUNT, MIN_BATTERY_NOT_LOW_COUNT);
728 proto.write(ConstantsProto.MIN_STORAGE_NOT_LOW_COUNT, MIN_STORAGE_NOT_LOW_COUNT);
729 proto.write(ConstantsProto.MIN_CONNECTIVITY_COUNT, MIN_CONNECTIVITY_COUNT);
730 proto.write(ConstantsProto.MIN_CONTENT_COUNT, MIN_CONTENT_COUNT);
731 proto.write(ConstantsProto.MIN_READY_JOBS_COUNT, MIN_READY_JOBS_COUNT);
732 proto.write(ConstantsProto.HEAVY_USE_FACTOR, HEAVY_USE_FACTOR);
733 proto.write(ConstantsProto.MODERATE_USE_FACTOR, MODERATE_USE_FACTOR);
734 proto.write(ConstantsProto.FG_JOB_COUNT, FG_JOB_COUNT);
735 proto.write(ConstantsProto.BG_NORMAL_JOB_COUNT, BG_NORMAL_JOB_COUNT);
736 proto.write(ConstantsProto.BG_MODERATE_JOB_COUNT, BG_MODERATE_JOB_COUNT);
737 proto.write(ConstantsProto.BG_LOW_JOB_COUNT, BG_LOW_JOB_COUNT);
738 proto.write(ConstantsProto.BG_CRITICAL_JOB_COUNT, BG_CRITICAL_JOB_COUNT);
739 proto.write(ConstantsProto.MAX_STANDARD_RESCHEDULE_COUNT, MAX_STANDARD_RESCHEDULE_COUNT);
740 proto.write(ConstantsProto.MAX_WORK_RESCHEDULE_COUNT, MAX_WORK_RESCHEDULE_COUNT);
741 proto.write(ConstantsProto.MIN_LINEAR_BACKOFF_TIME_MS, MIN_LINEAR_BACKOFF_TIME);
742 proto.write(ConstantsProto.MIN_EXP_BACKOFF_TIME_MS, MIN_EXP_BACKOFF_TIME);
743 proto.write(ConstantsProto.STANDBY_HEARTBEAT_TIME_MS, STANDBY_HEARTBEAT_TIME);
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800744 for (int period : STANDBY_BEATS) {
745 proto.write(ConstantsProto.STANDBY_BEATS, period);
746 }
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700747 proto.write(ConstantsProto.CONN_CONGESTION_DELAY_FRAC, CONN_CONGESTION_DELAY_FRAC);
748 proto.write(ConstantsProto.CONN_PREFETCH_RELAX_FRAC, CONN_PREFETCH_RELAX_FRAC);
Kweku Adams4836f9d2018-11-12 17:04:17 -0800749 proto.write(ConstantsProto.USE_HEARTBEATS, USE_HEARTBEATS);
750
751 final long qcToken = proto.start(ConstantsProto.QUOTA_CONTROLLER);
752 proto.write(ConstantsProto.QuotaController.ALLOWED_TIME_PER_PERIOD_MS,
753 QUOTA_CONTROLLER_ALLOWED_TIME_PER_PERIOD_MS);
754 proto.write(ConstantsProto.QuotaController.IN_QUOTA_BUFFER_MS,
755 QUOTA_CONTROLLER_IN_QUOTA_BUFFER_MS);
756 proto.write(ConstantsProto.QuotaController.ACTIVE_WINDOW_SIZE_MS,
757 QUOTA_CONTROLLER_WINDOW_SIZE_ACTIVE_MS);
758 proto.write(ConstantsProto.QuotaController.WORKING_WINDOW_SIZE_MS,
759 QUOTA_CONTROLLER_WINDOW_SIZE_WORKING_MS);
760 proto.write(ConstantsProto.QuotaController.FREQUENT_WINDOW_SIZE_MS,
761 QUOTA_CONTROLLER_WINDOW_SIZE_FREQUENT_MS);
762 proto.write(ConstantsProto.QuotaController.RARE_WINDOW_SIZE_MS,
763 QUOTA_CONTROLLER_WINDOW_SIZE_RARE_MS);
764 proto.end(qcToken);
765
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800766 proto.end(token);
767 }
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700768 }
769
770 final Constants mConstants;
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700771 final ConstantsObserver mConstantsObserver;
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700772
Dianne Hackbornbfc23312017-05-11 11:53:24 -0700773 static final Comparator<JobStatus> mEnqueueTimeComparator = (o1, o2) -> {
774 if (o1.enqueueTime < o2.enqueueTime) {
775 return -1;
776 }
777 return o1.enqueueTime > o2.enqueueTime ? 1 : 0;
778 };
779
780 static <T> void addOrderedItem(ArrayList<T> array, T newItem, Comparator<T> comparator) {
781 int where = Collections.binarySearch(array, newItem, comparator);
782 if (where < 0) {
783 where = ~where;
784 }
785 array.add(where, newItem);
786 }
787
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700788 /**
Christopher Tate7060b042014-06-09 19:50:00 -0700789 * Cleans up outstanding jobs when a package is removed. Even if it's being replaced later we
790 * still clean up. On reinstall the package will have a new uid.
791 */
792 private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
793 @Override
794 public void onReceive(Context context, Intent intent) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700795 final String action = intent.getAction();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700796 if (DEBUG) {
Christopher Tateee7805b2016-07-15 16:56:56 -0700797 Slog.d(TAG, "Receieved: " + action);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700798 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700799 final String pkgName = getPackageName(intent);
800 final int pkgUid = intent.getIntExtra(Intent.EXTRA_UID, -1);
801
Christopher Tateee7805b2016-07-15 16:56:56 -0700802 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
Christopher Tateb5c07882016-05-26 17:11:09 -0700803 // Purge the app's jobs if the whole package was just disabled. When this is
804 // the case the component name will be a bare package name.
Christopher Tateb5c07882016-05-26 17:11:09 -0700805 if (pkgName != null && pkgUid != -1) {
806 final String[] changedComponents = intent.getStringArrayExtra(
807 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
808 if (changedComponents != null) {
809 for (String component : changedComponents) {
810 if (component.equals(pkgName)) {
811 if (DEBUG) {
812 Slog.d(TAG, "Package state change: " + pkgName);
813 }
814 try {
815 final int userId = UserHandle.getUserId(pkgUid);
816 IPackageManager pm = AppGlobals.getPackageManager();
817 final int state = pm.getApplicationEnabledSetting(pkgName, userId);
818 if (state == COMPONENT_ENABLED_STATE_DISABLED
819 || state == COMPONENT_ENABLED_STATE_DISABLED_USER) {
820 if (DEBUG) {
821 Slog.d(TAG, "Removing jobs for package " + pkgName
822 + " in user " + userId);
823 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700824 cancelJobsForPackageAndUid(pkgName, pkgUid,
825 "app disabled");
Christopher Tateb5c07882016-05-26 17:11:09 -0700826 }
Christopher Tate652c5ad2016-10-05 14:45:46 -0700827 } catch (RemoteException|IllegalArgumentException e) {
828 /*
829 * IllegalArgumentException means that the package doesn't exist.
830 * This arises when PACKAGE_CHANGED broadcast delivery has lagged
831 * behind outright uninstall, so by the time we try to act it's gone.
832 * We don't need to act on this PACKAGE_CHANGED when this happens;
833 * we'll get a PACKAGE_REMOVED later and clean up then.
834 *
835 * RemoteException can't actually happen; the package manager is
836 * running in this same process.
837 */
838 }
Christopher Tateb5c07882016-05-26 17:11:09 -0700839 break;
840 }
841 }
Kweku Adamscdbfcb92018-12-06 17:05:15 -0800842 if (DEBUG) {
843 Slog.d(TAG, "Something in " + pkgName
844 + " changed. Reevaluating controller states.");
845 }
846 synchronized (mLock) {
847 for (int c = mControllers.size() - 1; c >= 0; --c) {
848 mControllers.get(c).reevaluateStateLocked(pkgUid);
849 }
850 }
Christopher Tateb5c07882016-05-26 17:11:09 -0700851 }
852 } else {
853 Slog.w(TAG, "PACKAGE_CHANGED for " + pkgName + " / uid " + pkgUid);
854 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700855 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
Christopher Tateaad67a32014-10-20 16:29:20 -0700856 // If this is an outright uninstall rather than the first half of an
857 // app update sequence, cancel the jobs associated with the app.
858 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
859 int uidRemoved = intent.getIntExtra(Intent.EXTRA_UID, -1);
860 if (DEBUG) {
861 Slog.d(TAG, "Removing jobs for uid: " + uidRemoved);
862 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700863 cancelJobsForPackageAndUid(pkgName, uidRemoved, "app uninstalled");
Christopher Tate7060b042014-06-09 19:50:00 -0700864 }
Christopher Tateee7805b2016-07-15 16:56:56 -0700865 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Christopher Tate7060b042014-06-09 19:50:00 -0700866 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
867 if (DEBUG) {
868 Slog.d(TAG, "Removing jobs for user: " + userId);
869 }
870 cancelJobsForUser(userId);
Christopher Tateee7805b2016-07-15 16:56:56 -0700871 } else if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
872 // Has this package scheduled any jobs, such that we will take action
873 // if it were to be force-stopped?
Christopher Tateee7805b2016-07-15 16:56:56 -0700874 if (pkgUid != -1) {
875 List<JobStatus> jobsForUid;
876 synchronized (mLock) {
877 jobsForUid = mJobs.getJobsByUid(pkgUid);
878 }
879 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
880 if (jobsForUid.get(i).getSourcePackageName().equals(pkgName)) {
881 if (DEBUG) {
882 Slog.d(TAG, "Restart query: package " + pkgName + " at uid "
883 + pkgUid + " has jobs");
884 }
885 setResultCode(Activity.RESULT_OK);
886 break;
887 }
888 }
889 }
890 } else if (Intent.ACTION_PACKAGE_RESTARTED.equals(action)) {
891 // possible force-stop
Christopher Tateee7805b2016-07-15 16:56:56 -0700892 if (pkgUid != -1) {
893 if (DEBUG) {
894 Slog.d(TAG, "Removing jobs for pkg " + pkgName + " at uid " + pkgUid);
895 }
Makoto Onukie7b96182017-08-30 14:53:16 -0700896 cancelJobsForPackageAndUid(pkgName, pkgUid, "app force stopped");
Christopher Tateee7805b2016-07-15 16:56:56 -0700897 }
Christopher Tate7060b042014-06-09 19:50:00 -0700898 }
899 }
900 };
901
Christopher Tateb5c07882016-05-26 17:11:09 -0700902 private String getPackageName(Intent intent) {
903 Uri uri = intent.getData();
904 String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
905 return pkg;
906 }
907
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700908 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700909 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki743e0ad2018-02-20 16:01:11 -0800910 mHandler.obtainMessage(MSG_UID_STATE_CHANGED, uid, procState).sendToTarget();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700911 }
912
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700913 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki743e0ad2018-02-20 16:01:11 -0800914 mHandler.obtainMessage(MSG_UID_GONE, uid, disabled ? 1 : 0).sendToTarget();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700915 }
916
917 @Override public void onUidActive(int uid) throws RemoteException {
Makoto Onuki743e0ad2018-02-20 16:01:11 -0800918 mHandler.obtainMessage(MSG_UID_ACTIVE, uid, 0).sendToTarget();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700919 }
920
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700921 @Override public void onUidIdle(int uid, boolean disabled) {
Makoto Onuki743e0ad2018-02-20 16:01:11 -0800922 mHandler.obtainMessage(MSG_UID_IDLE, uid, disabled ? 1 : 0).sendToTarget();
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700923 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700924
925 @Override public void onUidCachedChanged(int uid, boolean cached) {
926 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700927 };
928
Jeff Sharkey4d89e422018-03-29 18:22:41 -0600929 public Context getTestableContext() {
930 return getContext();
931 }
932
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800933 public Object getLock() {
934 return mLock;
935 }
936
Dianne Hackborn8db0fc12016-04-12 13:48:25 -0700937 public JobStore getJobStore() {
938 return mJobs;
939 }
940
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -0700941 public Constants getConstants() {
942 return mConstants;
943 }
944
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700945 @Override
946 public void onStartUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700947 mStartedUsers = ArrayUtils.appendInt(mStartedUsers, userHandle);
948 // Let's kick any outstanding jobs for this user.
949 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
950 }
951
952 @Override
953 public void onUnlockUser(int userHandle) {
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700954 // Let's kick any outstanding jobs for this user.
955 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
956 }
957
958 @Override
959 public void onStopUser(int userHandle) {
Jeff Sharkey822cbd12016-02-25 11:09:55 -0700960 mStartedUsers = ArrayUtils.removeInt(mStartedUsers, userHandle);
Matthew Williams9ae3dbe2014-08-21 13:47:47 -0700961 }
962
Makoto Onuki15407842018-01-19 14:23:11 -0800963 /**
Makoto Onukie4918212018-02-06 11:30:15 -0800964 * Return whether an UID is active or idle.
Makoto Onuki15407842018-01-19 14:23:11 -0800965 */
Makoto Onukie4918212018-02-06 11:30:15 -0800966 private boolean isUidActive(int uid) {
967 return mAppStateTracker.isUidActiveSynced(uid);
Makoto Onuki15407842018-01-19 14:23:11 -0800968 }
969
Makoto Onukie4918212018-02-06 11:30:15 -0800970 private final Predicate<Integer> mIsUidActivePredicate = this::isUidActive;
Makoto Onuki15407842018-01-19 14:23:11 -0800971
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700972 public int scheduleAsPackage(JobInfo job, JobWorkItem work, int uId, String packageName,
973 int userId, String tag) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700974 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800975 if (ActivityManager.getService().isAppStartModeDisabled(uId,
976 job.getService().getPackageName())) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700977 Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
978 + " -- package not allowed to start");
979 return JobScheduler.RESULT_FAILURE;
980 }
981 } catch (RemoteException e) {
982 }
Christopher Tatea732f012017-10-26 17:26:53 -0700983
Dianne Hackborn33d31c52016-02-16 10:30:33 -0800984 synchronized (mLock) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700985 final JobStatus toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
986
987 if (work != null && toCancel != null) {
988 // Fast path: we are adding work to an existing job, and the JobInfo is not
989 // changing. We can just directly enqueue this work in to the job.
990 if (toCancel.getJob().equals(job)) {
Makoto Onuki15407842018-01-19 14:23:11 -0800991
Dianne Hackborn342e6032017-04-13 18:04:31 -0700992 toCancel.enqueueWorkLocked(ActivityManager.getService(), work);
Makoto Onuki15407842018-01-19 14:23:11 -0800993
994 // If any of work item is enqueued when the source is in the foreground,
995 // exempt the entire job.
Makoto Onukie4918212018-02-06 11:30:15 -0800996 toCancel.maybeAddForegroundExemption(mIsUidActivePredicate);
Makoto Onuki15407842018-01-19 14:23:11 -0800997
Dianne Hackborn7da13d72017-04-04 17:17:35 -0700998 return JobScheduler.RESULT_SUCCESS;
999 }
1000 }
1001
1002 JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
Makoto Onuki15407842018-01-19 14:23:11 -08001003
1004 // Give exemption if the source is in the foreground just now.
1005 // Note if it's a sync job, this method is called on the handler so it's not exactly
1006 // the state when requestSync() was called, but that should be fine because of the
1007 // 1 minute foreground grace period.
Makoto Onukie4918212018-02-06 11:30:15 -08001008 jobStatus.maybeAddForegroundExemption(mIsUidActivePredicate);
Makoto Onuki15407842018-01-19 14:23:11 -08001009
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001010 if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
Christopher Tate2f36fd62016-02-18 18:36:08 -08001011 // Jobs on behalf of others don't apply to the per-app job cap
Christopher Tatedabdf6f2016-02-24 12:30:22 -08001012 if (ENFORCE_MAX_JOBS && packageName == null) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001013 if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
1014 Slog.w(TAG, "Too many jobs for uid " + uId);
1015 throw new IllegalStateException("Apps may not schedule more than "
1016 + MAX_JOBS_PER_APP + " distinct jobs");
1017 }
1018 }
1019
Dianne Hackborna47223f2017-03-30 13:49:13 -07001020 // This may throw a SecurityException.
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001021 jobStatus.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001022
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001023 if (work != null) {
1024 // If work has been supplied, enqueue it into the new job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07001025 jobStatus.enqueueWorkLocked(ActivityManager.getService(), work);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001026 }
Christopher Tate16032042018-10-05 15:53:50 -07001027
1028 if (toCancel != null) {
1029 // Implicitly replaces the existing job record with the new instance
1030 cancelJobImplLocked(toCancel, jobStatus, "job rescheduled by app");
1031 } else {
1032 startTrackingJobLocked(jobStatus, null);
1033 }
Tej Singhd5747a62018-01-08 20:57:35 -08001034 StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08001035 uId, null, jobStatus.getBatteryName(),
Tej Singh33a412b2018-03-16 18:43:59 -07001036 StatsLog.SCHEDULED_JOB_STATE_CHANGED__STATE__SCHEDULED,
1037 JobProtoEnums.STOP_REASON_CANCELLED);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001038
1039 // If the job is immediately ready to run, then we can just immediately
1040 // put it in the pending list and try to schedule it. This is especially
1041 // important for jobs with a 0 deadline constraint, since they will happen a fair
1042 // amount, we want to handle them as quickly as possible, and semantically we want to
1043 // make sure we have started holding the wake lock for the job before returning to
1044 // the caller.
1045 // If the job is not yet ready to run, there is nothing more to do -- we are
1046 // now just waiting for one of its controllers to change state and schedule
1047 // the job appropriately.
1048 if (isReadyToBeExecutedLocked(jobStatus)) {
1049 // This is a new job, we can just immediately put it on the pending
1050 // list and try to run it.
1051 mJobPackageTracker.notePending(jobStatus);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001052 addOrderedItem(mPendingJobs, jobStatus, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001053 maybeRunPendingJobsLocked();
Kweku Adamscdbfcb92018-12-06 17:05:15 -08001054 } else {
1055 evaluateControllerStatesLocked(jobStatus);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001056 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001057 }
Christopher Tate7060b042014-06-09 19:50:00 -07001058 return JobScheduler.RESULT_SUCCESS;
1059 }
1060
1061 public List<JobInfo> getPendingJobs(int uid) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001062 synchronized (mLock) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08001063 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
1064 ArrayList<JobInfo> outList = new ArrayList<JobInfo>(jobs.size());
1065 for (int i = jobs.size() - 1; i >= 0; i--) {
1066 JobStatus job = jobs.get(i);
1067 outList.add(job.getJob());
Christopher Tate7060b042014-06-09 19:50:00 -07001068 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001069 return outList;
Christopher Tate7060b042014-06-09 19:50:00 -07001070 }
Christopher Tate7060b042014-06-09 19:50:00 -07001071 }
1072
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001073 public JobInfo getPendingJob(int uid, int jobId) {
1074 synchronized (mLock) {
1075 List<JobStatus> jobs = mJobs.getJobsByUid(uid);
1076 for (int i = jobs.size() - 1; i >= 0; i--) {
1077 JobStatus job = jobs.get(i);
1078 if (job.getJobId() == jobId) {
1079 return job.getJob();
1080 }
1081 }
1082 return null;
1083 }
1084 }
1085
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001086 void cancelJobsForUser(int userHandle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001087 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001088 final List<JobStatus> jobsForUser = mJobs.getJobsByUser(userHandle);
1089 for (int i=0; i<jobsForUser.size(); i++) {
1090 JobStatus toRemove = jobsForUser.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -07001091 cancelJobImplLocked(toRemove, null, "user removed");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001092 }
Christopher Tate7060b042014-06-09 19:50:00 -07001093 }
1094 }
1095
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07001096 private void cancelJobsForNonExistentUsers() {
1097 UserManagerInternal umi = LocalServices.getService(UserManagerInternal.class);
1098 synchronized (mLock) {
1099 mJobs.removeJobsOfNonUsers(umi.getUserIds());
1100 }
1101 }
1102
Makoto Onukie7b96182017-08-30 14:53:16 -07001103 void cancelJobsForPackageAndUid(String pkgName, int uid, String reason) {
1104 if ("android".equals(pkgName)) {
1105 Slog.wtfStack(TAG, "Can't cancel all jobs for system package");
1106 return;
1107 }
Christopher Tateee7805b2016-07-15 16:56:56 -07001108 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001109 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
1110 for (int i = jobsForUid.size() - 1; i >= 0; i--) {
1111 final JobStatus job = jobsForUid.get(i);
1112 if (job.getSourcePackageName().equals(pkgName)) {
Makoto Onukie7b96182017-08-30 14:53:16 -07001113 cancelJobImplLocked(job, null, reason);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001114 }
Christopher Tateee7805b2016-07-15 16:56:56 -07001115 }
1116 }
1117 }
1118
Christopher Tate7060b042014-06-09 19:50:00 -07001119 /**
1120 * Entry point from client to cancel all jobs originating from their uid.
1121 * This will remove the job from the master list, and cancel the job if it was staged for
1122 * execution or being executed.
Matthew Williams48a30db2014-09-23 13:39:36 -07001123 * @param uid Uid to check against for removal of a job.
Dianne Hackborne07641d2016-11-09 15:07:23 -08001124 *
Christopher Tate7060b042014-06-09 19:50:00 -07001125 */
Christopher Tate8c67d122017-09-29 16:54:26 -07001126 public boolean cancelJobsForUid(int uid, String reason) {
Makoto Onukie7b02982017-08-24 14:23:36 -07001127 if (uid == Process.SYSTEM_UID) {
Makoto Onukie7b96182017-08-30 14:53:16 -07001128 Slog.wtfStack(TAG, "Can't cancel all jobs for system uid");
Christopher Tate8c67d122017-09-29 16:54:26 -07001129 return false;
Makoto Onukie7b02982017-08-24 14:23:36 -07001130 }
Christopher Tate8c67d122017-09-29 16:54:26 -07001131
1132 boolean jobsCanceled = false;
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001133 synchronized (mLock) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001134 final List<JobStatus> jobsForUid = mJobs.getJobsByUid(uid);
1135 for (int i=0; i<jobsForUid.size(); i++) {
1136 JobStatus toRemove = jobsForUid.get(i);
Dianne Hackborn729a3282017-06-09 16:06:01 -07001137 cancelJobImplLocked(toRemove, null, reason);
Christopher Tate8c67d122017-09-29 16:54:26 -07001138 jobsCanceled = true;
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001139 }
Christopher Tate7060b042014-06-09 19:50:00 -07001140 }
Christopher Tate8c67d122017-09-29 16:54:26 -07001141 return jobsCanceled;
Christopher Tate7060b042014-06-09 19:50:00 -07001142 }
1143
1144 /**
1145 * Entry point from client to cancel the job corresponding to the jobId provided.
1146 * This will remove the job from the master list, and cancel the job if it was staged for
1147 * execution or being executed.
1148 * @param uid Uid of the calling client.
1149 * @param jobId Id of the job, provided at schedule-time.
1150 */
Makoto Onukid2bfec62018-01-12 13:58:01 -08001151 public boolean cancelJob(int uid, int jobId, int callingUid) {
Christopher Tate7060b042014-06-09 19:50:00 -07001152 JobStatus toCancel;
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001153 synchronized (mLock) {
Christopher Tate7060b042014-06-09 19:50:00 -07001154 toCancel = mJobs.getJobByUidAndJobId(uid, jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001155 if (toCancel != null) {
Makoto Onukid2bfec62018-01-12 13:58:01 -08001156 cancelJobImplLocked(toCancel, null,
1157 "cancel() called by app, callingUid=" + callingUid
1158 + " uid=" + uid + " jobId=" + jobId);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001159 }
Christopher Tate8c67d122017-09-29 16:54:26 -07001160 return (toCancel != null);
Christopher Tate7060b042014-06-09 19:50:00 -07001161 }
1162 }
1163
Christopher Tate16032042018-10-05 15:53:50 -07001164 /**
1165 * Cancel the given job, stopping it if it's currently executing. If {@code incomingJob}
1166 * is null, the cancelled job is removed outright from the system. If
1167 * {@code incomingJob} is non-null, it replaces {@code cancelled} in the store of
1168 * currently scheduled jobs.
1169 */
Dianne Hackborn729a3282017-06-09 16:06:01 -07001170 private void cancelJobImplLocked(JobStatus cancelled, JobStatus incomingJob, String reason) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001171 if (DEBUG) Slog.d(TAG, "CANCEL: " + cancelled.toShortString());
1172 cancelled.unprepareLocked(ActivityManager.getService());
1173 stopTrackingJobLocked(cancelled, incomingJob, true /* writeBack */);
1174 // Remove from pending queue.
1175 if (mPendingJobs.remove(cancelled)) {
1176 mJobPackageTracker.noteNonpending(cancelled);
Matthew Williams48a30db2014-09-23 13:39:36 -07001177 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001178 // Cancel if running.
Dianne Hackborn729a3282017-06-09 16:06:01 -07001179 stopJobOnServiceContextLocked(cancelled, JobParameters.REASON_CANCELED, reason);
Christopher Tate16032042018-10-05 15:53:50 -07001180 // If this is a replacement, bring in the new version of the job
1181 if (incomingJob != null) {
1182 if (DEBUG) Slog.i(TAG, "Tracking replacement job " + incomingJob.toShortString());
1183 startTrackingJobLocked(incomingJob, cancelled);
1184 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001185 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001186 }
1187
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001188 void updateUidState(int uid, int procState) {
1189 synchronized (mLock) {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001190 if (procState == ActivityManager.PROCESS_STATE_TOP) {
1191 // Only use this if we are exactly the top app. All others can live
1192 // with just the foreground priority. This means that persistent processes
1193 // can never be the top app priority... that is fine.
1194 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_TOP_APP);
Makoto Onukiec8b14d2018-12-05 13:22:24 -08001195 } else if (procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
1196 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_FOREGROUND_SERVICE);
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08001197 } else if (procState <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Makoto Onukiec8b14d2018-12-05 13:22:24 -08001198 mUidPriorityOverride.put(uid, JobInfo.PRIORITY_BOUND_FOREGROUND_SERVICE);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001199 } else {
Dianne Hackborn970510b2016-02-24 16:56:42 -08001200 mUidPriorityOverride.delete(uid);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001201 }
1202 }
1203 }
1204
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001205 @Override
1206 public void onDeviceIdleStateChanged(boolean deviceIdle) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001207 synchronized (mLock) {
Makoto Onuki0f6499c2018-12-14 16:34:59 -08001208 if (DEBUG) {
1209 Slog.d(TAG, "Doze state changed: " + deviceIdle);
1210 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001211 if (deviceIdle) {
Jeff Sharkey34618b52016-06-01 15:51:19 -06001212 // When becoming idle, make sure no jobs are actively running,
1213 // except those using the idle exemption flag.
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001214 for (int i=0; i<mActiveServices.size(); i++) {
1215 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001216 final JobStatus executing = jsc.getRunningJobLocked();
Jeff Sharkey34618b52016-06-01 15:51:19 -06001217 if (executing != null
1218 && (executing.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07001219 jsc.cancelExecutingJobLocked(JobParameters.REASON_DEVICE_IDLE,
1220 "cancelled due to doze");
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001221 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001222 }
Amith Yamasanicb926fc2016-03-14 17:15:20 -07001223 } else {
1224 // When coming out of idle, allow thing to start back up.
1225 if (mReadyToRock) {
1226 if (mLocalDeviceIdleController != null) {
1227 if (!mReportedActive) {
1228 mReportedActive = true;
1229 mLocalDeviceIdleController.setJobsActive(true);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001230 }
1231 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001232 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Dianne Hackborn88e98df2015-03-23 13:29:14 -07001233 }
1234 }
1235 }
1236 }
1237
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001238 void reportActiveLocked() {
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001239 // active is true if pending queue contains jobs OR some job is running.
1240 boolean active = mPendingJobs.size() > 0;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001241 if (mPendingJobs.size() <= 0) {
1242 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07001243 final JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001244 final JobStatus job = jsc.getRunningJobLocked();
Dianne Hackborn7ab40252016-06-15 17:30:24 -07001245 if (job != null
1246 && (job.getJob().getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0
Christopher Tate20afddd2018-02-28 15:19:19 -08001247 && !job.dozeWhitelisted
1248 && !job.uidActive) {
Dianne Hackborn7ab40252016-06-15 17:30:24 -07001249 // We will report active if we have a job running and it is not an exception
1250 // due to being in the foreground or whitelisted.
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001251 active = true;
1252 break;
1253 }
1254 }
1255 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001256
1257 if (mReportedActive != active) {
1258 mReportedActive = active;
1259 if (mLocalDeviceIdleController != null) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001260 mLocalDeviceIdleController.setJobsActive(active);
1261 }
1262 }
1263 }
1264
Christopher Tated117b292018-01-05 17:32:36 -08001265 void reportAppUsage(String packageName, int userId) {
1266 // This app just transitioned into interactive use or near equivalent, so we should
1267 // take a look at its job state for feedback purposes.
1268 }
1269
Christopher Tate7060b042014-06-09 19:50:00 -07001270 /**
1271 * Initializes the system service.
1272 * <p>
1273 * Subclasses must define a single argument constructor that accepts the context
1274 * and passes it to super.
1275 * </p>
1276 *
1277 * @param context The system server context.
1278 */
1279 public JobSchedulerService(Context context) {
1280 super(context);
Christopher Tatea732f012017-10-26 17:26:53 -07001281
1282 mLocalPM = LocalServices.getService(PackageManagerInternal.class);
Makoto Onuki15407842018-01-19 14:23:11 -08001283 mActivityManagerInternal = Preconditions.checkNotNull(
1284 LocalServices.getService(ActivityManagerInternal.class));
Christopher Tatea732f012017-10-26 17:26:53 -07001285
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001286 mHandler = new JobHandler(context.getMainLooper());
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001287 mConstants = new Constants();
1288 mConstantsObserver = new ConstantsObserver(mHandler);
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001289 mJobSchedulerStub = new JobSchedulerStub();
Christopher Tatea732f012017-10-26 17:26:53 -07001290
Makoto Onuki714f97d2018-12-05 11:18:13 -08001291 mConcurrencyManager = new JobConcurrencyManager(this);
1292
Christopher Tatea732f012017-10-26 17:26:53 -07001293 // Set up the app standby bucketing tracker
Christopher Tated1aebb32018-01-31 13:24:14 -08001294 mStandbyTracker = new StandbyTracker();
1295 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
1296 mUsageStats.addAppIdleStateChangeListener(mStandbyTracker);
Christopher Tatea732f012017-10-26 17:26:53 -07001297
1298 // The job store needs to call back
1299 publishLocalService(JobSchedulerInternal.class, new LocalService());
1300
1301 // Initialize the job store and set up any persisted jobs
Dianne Hackborn970e3f42016-06-01 10:55:13 -07001302 mJobs = JobStore.initAndGet(this);
1303
Christopher Tate7060b042014-06-09 19:50:00 -07001304 // Create the controllers.
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001305 mControllers = new ArrayList<StateController>();
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001306 mControllers.add(new ConnectivityController(this));
1307 mControllers.add(new TimeController(this));
1308 mControllers.add(new IdleController(this));
1309 mBatteryController = new BatteryController(this);
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08001310 mControllers.add(mBatteryController);
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001311 mStorageController = new StorageController(this);
Dianne Hackborn532ea262017-03-17 17:50:55 -07001312 mControllers.add(mStorageController);
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001313 mControllers.add(new BackgroundJobsController(this));
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001314 mControllers.add(new ContentObserverController(this));
1315 mDeviceIdleJobsController = new DeviceIdleJobsController(this);
Suprabh Shukla106203b2017-11-02 21:23:44 -07001316 mControllers.add(mDeviceIdleJobsController);
Kweku Adams4836f9d2018-11-12 17:04:17 -08001317 mControllers.add(new QuotaController(this));
Christopher Tate616541d2017-07-26 14:27:38 -07001318
1319 // If the job store determined that it can't yet reschedule persisted jobs,
1320 // we need to start watching the clock.
1321 if (!mJobs.jobTimesInflatedValid()) {
1322 Slog.w(TAG, "!!! RTC not yet good; tracking time updates for job scheduling");
1323 context.registerReceiver(mTimeSetReceiver, new IntentFilter(Intent.ACTION_TIME_CHANGED));
1324 }
Christopher Tate7060b042014-06-09 19:50:00 -07001325 }
1326
Christopher Tate616541d2017-07-26 14:27:38 -07001327 private final BroadcastReceiver mTimeSetReceiver = new BroadcastReceiver() {
1328 @Override
1329 public void onReceive(Context context, Intent intent) {
1330 if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) {
1331 // When we reach clock sanity, recalculate the temporal windows
1332 // of all affected jobs.
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001333 if (mJobs.clockNowValidToInflate(sSystemClock.millis())) {
Christopher Tate616541d2017-07-26 14:27:38 -07001334 Slog.i(TAG, "RTC now valid; recalculating persisted job windows");
1335
1336 // We've done our job now, so stop watching the time.
1337 context.unregisterReceiver(this);
1338
1339 // And kick off the work to update the affected jobs, using a secondary
1340 // thread instead of chugging away here on the main looper thread.
1341 FgThread.getHandler().post(mJobTimeUpdater);
1342 }
1343 }
1344 }
1345 };
1346
1347 private final Runnable mJobTimeUpdater = () -> {
1348 final ArrayList<JobStatus> toRemove = new ArrayList<>();
1349 final ArrayList<JobStatus> toAdd = new ArrayList<>();
1350 synchronized (mLock) {
1351 // Note: we intentionally both look up the existing affected jobs and replace them
1352 // with recalculated ones inside the same lock lifetime.
1353 getJobStore().getRtcCorrectedJobsLocked(toAdd, toRemove);
1354
1355 // Now, at each position [i], we have both the existing JobStatus
1356 // and the one that replaces it.
1357 final int N = toAdd.size();
1358 for (int i = 0; i < N; i++) {
1359 final JobStatus oldJob = toRemove.get(i);
1360 final JobStatus newJob = toAdd.get(i);
1361 if (DEBUG) {
1362 Slog.v(TAG, " replacing " + oldJob + " with " + newJob);
1363 }
1364 cancelJobImplLocked(oldJob, newJob, "deferred rtc calculation");
1365 }
1366 }
1367 };
1368
Christopher Tate7060b042014-06-09 19:50:00 -07001369 @Override
1370 public void onStart() {
1371 publishBinderService(Context.JOB_SCHEDULER_SERVICE, mJobSchedulerStub);
1372 }
1373
1374 @Override
1375 public void onBootPhase(int phase) {
1376 if (PHASE_SYSTEM_SERVICES_READY == phase) {
Jeff Sharkeyac2e8ef2018-02-22 16:06:44 -07001377 mConstantsObserver.start(getContext().getContentResolver());
Makoto Onuki15407842018-01-19 14:23:11 -08001378
Makoto Onukie4918212018-02-06 11:30:15 -08001379 mAppStateTracker = Preconditions.checkNotNull(
1380 LocalServices.getService(AppStateTracker.class));
Kweku Adams4836f9d2018-11-12 17:04:17 -08001381 if (mConstants.USE_HEARTBEATS) {
1382 setNextHeartbeatAlarm();
1383 }
Makoto Onuki15407842018-01-19 14:23:11 -08001384
Shreyas Basarge5db09082016-01-07 13:38:29 +00001385 // Register br for package removals and user removals.
Christopher Tateb5c07882016-05-26 17:11:09 -07001386 final IntentFilter filter = new IntentFilter();
1387 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1388 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Christopher Tateee7805b2016-07-15 16:56:56 -07001389 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
1390 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
Christopher Tate7060b042014-06-09 19:50:00 -07001391 filter.addDataScheme("package");
1392 getContext().registerReceiverAsUser(
1393 mBroadcastReceiver, UserHandle.ALL, filter, null, null);
1394 final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
1395 getContext().registerReceiverAsUser(
1396 mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001397 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001398 ActivityManager.getService().registerUidObserver(mUidObserver,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08001399 ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE
Suprabh Shukla3ac1daa2017-07-14 12:15:27 -07001400 | ActivityManager.UID_OBSERVER_IDLE | ActivityManager.UID_OBSERVER_ACTIVE,
1401 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001402 } catch (RemoteException e) {
1403 // ignored; both services live in system_server
1404 }
Michael Wachenschwanz3f2b6552017-05-15 13:53:09 -07001405 // Remove any jobs that are not associated with any of the current users.
1406 cancelJobsForNonExistentUsers();
Wei Wang8c0c3c12018-11-14 14:56:52 -08001407 // Register thermal callback
1408 mThermalService = IThermalService.Stub.asInterface(
1409 ServiceManager.getService(Context.THERMAL_SERVICE));
1410 if (mThermalService != null) {
1411 try {
1412 mThermalService.registerThermalStatusListener(new ThermalStatusListener());
1413 } catch (RemoteException e) {
1414 Slog.e(TAG, "Failed to register thermal callback.", e);
1415 }
1416 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001417 } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001418 synchronized (mLock) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001419 // Let's go!
1420 mReadyToRock = true;
1421 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
1422 BatteryStats.SERVICE_NAME));
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001423 mLocalDeviceIdleController
1424 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001425 // Create the "runners".
1426 for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
1427 mActiveServices.add(
Dianne Hackborn807de782016-04-07 17:54:41 -07001428 new JobServiceContext(this, mBatteryStats, mJobPackageTracker,
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001429 getContext().getMainLooper()));
1430 }
1431 // Attach jobs to their controllers.
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07001432 mJobs.forEachJob((job) -> {
1433 for (int controller = 0; controller < mControllers.size(); controller++) {
1434 final StateController sc = mControllers.get(controller);
1435 sc.maybeStartTrackingJobLocked(job, null);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001436 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001437 });
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001438 // GO GO GO!
1439 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
1440 }
Christopher Tate7060b042014-06-09 19:50:00 -07001441 }
1442 }
1443
1444 /**
1445 * Called when we have a job status object that we need to insert in our
1446 * {@link com.android.server.job.JobStore}, and make sure all the relevant controllers know
1447 * about.
1448 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001449 private void startTrackingJobLocked(JobStatus jobStatus, JobStatus lastJob) {
1450 if (!jobStatus.isPreparedLocked()) {
1451 Slog.wtf(TAG, "Not yet prepared when started tracking: " + jobStatus);
1452 }
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001453 jobStatus.enqueueTime = sElapsedRealtimeClock.millis();
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001454 final boolean update = mJobs.add(jobStatus);
1455 if (mReadyToRock) {
1456 for (int i = 0; i < mControllers.size(); i++) {
1457 StateController controller = mControllers.get(i);
1458 if (update) {
1459 controller.maybeStopTrackingJobLocked(jobStatus, null, true);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001460 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001461 controller.maybeStartTrackingJobLocked(jobStatus, lastJob);
Christopher Tate7060b042014-06-09 19:50:00 -07001462 }
Christopher Tate7060b042014-06-09 19:50:00 -07001463 }
1464 }
1465
1466 /**
1467 * Called when we want to remove a JobStatus object that we've finished executing. Returns the
1468 * object removed.
1469 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001470 private boolean stopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob,
Dianne Hackborn141f11c2016-04-05 15:46:12 -07001471 boolean writeBack) {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001472 // Deal with any remaining work items in the old job.
Dianne Hackborn342e6032017-04-13 18:04:31 -07001473 jobStatus.stopTrackingJobLocked(ActivityManager.getService(), incomingJob);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001474
1475 // Remove from store as well as controllers.
1476 final boolean removed = mJobs.remove(jobStatus, writeBack);
1477 if (removed && mReadyToRock) {
1478 for (int i=0; i<mControllers.size(); i++) {
1479 StateController controller = mControllers.get(i);
1480 controller.maybeStopTrackingJobLocked(jobStatus, incomingJob, false);
Christopher Tate7060b042014-06-09 19:50:00 -07001481 }
1482 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001483 return removed;
Christopher Tate7060b042014-06-09 19:50:00 -07001484 }
1485
Dianne Hackborn729a3282017-06-09 16:06:01 -07001486 private boolean stopJobOnServiceContextLocked(JobStatus job, int reason, String debugReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001487 for (int i=0; i<mActiveServices.size(); i++) {
1488 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001489 final JobStatus executing = jsc.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001490 if (executing != null && executing.matches(job.getUid(), job.getJobId())) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07001491 jsc.cancelExecutingJobLocked(reason, debugReason);
Christopher Tate7060b042014-06-09 19:50:00 -07001492 return true;
1493 }
1494 }
1495 return false;
1496 }
1497
1498 /**
1499 * @param job JobStatus we are querying against.
1500 * @return Whether or not the job represented by the status object is currently being run or
1501 * is pending.
1502 */
1503 private boolean isCurrentlyActiveLocked(JobStatus job) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07001504 for (int i=0; i<mActiveServices.size(); i++) {
1505 JobServiceContext serviceContext = mActiveServices.get(i);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001506 final JobStatus running = serviceContext.getRunningJobLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001507 if (running != null && running.matches(job.getUid(), job.getJobId())) {
1508 return true;
1509 }
1510 }
1511 return false;
1512 }
1513
Dianne Hackborn807de782016-04-07 17:54:41 -07001514 void noteJobsPending(List<JobStatus> jobs) {
1515 for (int i = jobs.size() - 1; i >= 0; i--) {
1516 JobStatus job = jobs.get(i);
1517 mJobPackageTracker.notePending(job);
1518 }
1519 }
1520
1521 void noteJobsNonpending(List<JobStatus> jobs) {
1522 for (int i = jobs.size() - 1; i >= 0; i--) {
1523 JobStatus job = jobs.get(i);
1524 mJobPackageTracker.noteNonpending(job);
1525 }
1526 }
1527
Christopher Tate7060b042014-06-09 19:50:00 -07001528 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001529 * Reschedules the given job based on the job's backoff policy. It doesn't make sense to
1530 * specify an override deadline on a failed job (the failed job will run even though it's not
1531 * ready), so we reschedule it with {@link JobStatus#NO_LATEST_RUNTIME}, but specify that any
1532 * ready job with {@link JobStatus#numFailures} > 0 will be executed.
1533 *
Christopher Tate7060b042014-06-09 19:50:00 -07001534 * @param failureToReschedule Provided job status that we will reschedule.
1535 * @return A newly instantiated JobStatus with the same constraints as the last job except
1536 * with adjusted timing constraints.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001537 *
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001538 * @see #maybeQueueReadyJobsForExecutionLocked
Christopher Tate7060b042014-06-09 19:50:00 -07001539 */
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001540 private JobStatus getRescheduleJobForFailureLocked(JobStatus failureToReschedule) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001541 final long elapsedNowMillis = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -07001542 final JobInfo job = failureToReschedule.getJob();
1543
1544 final long initialBackoffMillis = job.getInitialBackoffMillis();
Matthew Williamsd1c06752014-08-22 14:15:28 -07001545 final int backoffAttempts = failureToReschedule.getNumFailures() + 1;
1546 long delayMillis;
Christopher Tate7060b042014-06-09 19:50:00 -07001547
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001548 if (failureToReschedule.hasWorkLocked()) {
1549 if (backoffAttempts > mConstants.MAX_WORK_RESCHEDULE_COUNT) {
1550 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1551 + backoffAttempts + " > work limit "
1552 + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1553 return null;
1554 }
1555 } else if (backoffAttempts > mConstants.MAX_STANDARD_RESCHEDULE_COUNT) {
1556 Slog.w(TAG, "Not rescheduling " + failureToReschedule + ": attempt #"
1557 + backoffAttempts + " > std limit " + mConstants.MAX_STANDARD_RESCHEDULE_COUNT);
1558 return null;
1559 }
1560
Christopher Tate7060b042014-06-09 19:50:00 -07001561 switch (job.getBackoffPolicy()) {
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001562 case JobInfo.BACKOFF_POLICY_LINEAR: {
1563 long backoff = initialBackoffMillis;
1564 if (backoff < mConstants.MIN_LINEAR_BACKOFF_TIME) {
1565 backoff = mConstants.MIN_LINEAR_BACKOFF_TIME;
1566 }
1567 delayMillis = backoff * backoffAttempts;
1568 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001569 default:
1570 if (DEBUG) {
1571 Slog.v(TAG, "Unrecognised back-off policy, defaulting to exponential.");
1572 }
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001573 case JobInfo.BACKOFF_POLICY_EXPONENTIAL: {
1574 long backoff = initialBackoffMillis;
1575 if (backoff < mConstants.MIN_EXP_BACKOFF_TIME) {
1576 backoff = mConstants.MIN_EXP_BACKOFF_TIME;
1577 }
1578 delayMillis = (long) Math.scalb(backoff, backoffAttempts - 1);
1579 } break;
Christopher Tate7060b042014-06-09 19:50:00 -07001580 }
Matthew Williamsd1c06752014-08-22 14:15:28 -07001581 delayMillis =
1582 Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS);
Christopher Tatea732f012017-10-26 17:26:53 -07001583 JobStatus newJob = new JobStatus(failureToReschedule, getCurrentHeartbeat(),
1584 elapsedNowMillis + delayMillis,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001585 JobStatus.NO_LATEST_RUNTIME, backoffAttempts,
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001586 failureToReschedule.getLastSuccessfulRunTime(), sSystemClock.millis());
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001587 for (int ic=0; ic<mControllers.size(); ic++) {
1588 StateController controller = mControllers.get(ic);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001589 controller.rescheduleForFailureLocked(newJob, failureToReschedule);
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001590 }
1591 return newJob;
Christopher Tate7060b042014-06-09 19:50:00 -07001592 }
1593
1594 /**
Matthew Williams1bde39a2015-10-07 14:29:30 -07001595 * Called after a periodic has executed so we can reschedule it. We take the last execution
1596 * time of the job to be the time of completion (i.e. the time at which this function is
1597 * called).
Christopher Tatea732f012017-10-26 17:26:53 -07001598 * <p>This could be inaccurate b/c the job can run for as long as
Christopher Tate7060b042014-06-09 19:50:00 -07001599 * {@link com.android.server.job.JobServiceContext#EXECUTING_TIMESLICE_MILLIS}, but will lead
1600 * to underscheduling at least, rather than if we had taken the last execution time to be the
1601 * start of the execution.
Christopher Tatea732f012017-10-26 17:26:53 -07001602 * <p>Unlike a reschedule prior to execution, in this case we advance the next-heartbeat
1603 * tracking as though the job were newly-scheduled.
Christopher Tate7060b042014-06-09 19:50:00 -07001604 * @return A new job representing the execution criteria for this instantiation of the
1605 * recurring job.
1606 */
1607 private JobStatus getRescheduleJobForPeriodic(JobStatus periodicToReschedule) {
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001608 final long elapsedNow = sElapsedRealtimeClock.millis();
Christopher Tate7060b042014-06-09 19:50:00 -07001609 // Compute how much of the period is remaining.
Matthew Williams1bde39a2015-10-07 14:29:30 -07001610 long runEarly = 0L;
1611
1612 // If this periodic was rescheduled it won't have a deadline.
1613 if (periodicToReschedule.hasDeadlineConstraint()) {
1614 runEarly = Math.max(periodicToReschedule.getLatestRunTimeElapsed() - elapsedNow, 0L);
1615 }
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001616 long flex = periodicToReschedule.getJob().getFlexMillis();
Christopher Tate7060b042014-06-09 19:50:00 -07001617 long period = periodicToReschedule.getJob().getIntervalMillis();
Shreyas Basarge89ee6182015-12-17 15:16:36 +00001618 long newLatestRuntimeElapsed = elapsedNow + runEarly + period;
1619 long newEarliestRunTimeElapsed = newLatestRuntimeElapsed - flex;
Christopher Tate7060b042014-06-09 19:50:00 -07001620
1621 if (DEBUG) {
1622 Slog.v(TAG, "Rescheduling executed periodic. New execution window [" +
1623 newEarliestRunTimeElapsed/1000 + ", " + newLatestRuntimeElapsed/1000 + "]s");
1624 }
Christopher Tatea732f012017-10-26 17:26:53 -07001625 return new JobStatus(periodicToReschedule, getCurrentHeartbeat(),
1626 newEarliestRunTimeElapsed, newLatestRuntimeElapsed,
1627 0 /* backoffAttempt */,
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07001628 sSystemClock.millis() /* lastSuccessfulRunTime */,
Makoto Onukiab8a67f2017-06-20 12:20:34 -07001629 periodicToReschedule.getLastFailedRunTime());
Christopher Tate7060b042014-06-09 19:50:00 -07001630 }
1631
Christopher Tate325768c2018-03-07 16:07:56 -08001632 /*
1633 * We default to "long enough ago that every bucket's jobs are immediately runnable" to
1634 * avoid starvation of apps in uncommon-use buckets that might arise from repeated
1635 * reboot behavior.
1636 */
Christopher Tated1aebb32018-01-31 13:24:14 -08001637 long heartbeatWhenJobsLastRun(String packageName, final @UserIdInt int userId) {
Christopher Tate325768c2018-03-07 16:07:56 -08001638 // The furthest back in pre-boot time that we need to bother with
1639 long heartbeat = -mConstants.STANDBY_BEATS[RARE_INDEX];
1640 boolean cacheHit = false;
Christopher Tated1aebb32018-01-31 13:24:14 -08001641 synchronized (mLock) {
Christopher Tate325768c2018-03-07 16:07:56 -08001642 HashMap<String, Long> jobPackages = mLastJobHeartbeats.get(userId);
1643 if (jobPackages != null) {
1644 long cachedValue = jobPackages.getOrDefault(packageName, Long.MAX_VALUE);
1645 if (cachedValue < Long.MAX_VALUE) {
1646 cacheHit = true;
1647 heartbeat = cachedValue;
1648 }
1649 }
1650 if (!cacheHit) {
1651 // We haven't seen it yet; ask usage stats about it
1652 final long timeSinceJob = mUsageStats.getTimeSinceLastJobRun(packageName, userId);
1653 if (timeSinceJob < Long.MAX_VALUE) {
1654 // Usage stats knows about it from before, so calculate back from that
1655 // and go from there.
1656 heartbeat = mHeartbeat - (timeSinceJob / mConstants.STANDBY_HEARTBEAT_TIME);
1657 }
1658 // If usage stats returned its "not found" MAX_VALUE, we still have the
1659 // negative default 'heartbeat' value we established above
1660 setLastJobHeartbeatLocked(packageName, userId, heartbeat);
1661 }
Christopher Tated1aebb32018-01-31 13:24:14 -08001662 }
1663 if (DEBUG_STANDBY) {
Christopher Tate325768c2018-03-07 16:07:56 -08001664 Slog.v(TAG, "Last job heartbeat " + heartbeat + " for "
1665 + packageName + "/" + userId);
Christopher Tated1aebb32018-01-31 13:24:14 -08001666 }
1667 return heartbeat;
1668 }
1669
1670 long heartbeatWhenJobsLastRun(JobStatus job) {
1671 return heartbeatWhenJobsLastRun(job.getSourcePackageName(), job.getSourceUserId());
1672 }
1673
Christopher Tate325768c2018-03-07 16:07:56 -08001674 void setLastJobHeartbeatLocked(String packageName, int userId, long heartbeat) {
1675 HashMap<String, Long> jobPackages = mLastJobHeartbeats.get(userId);
1676 if (jobPackages == null) {
1677 jobPackages = new HashMap<>();
1678 mLastJobHeartbeats.put(userId, jobPackages);
1679 }
1680 jobPackages.put(packageName, heartbeat);
1681 }
1682
Christopher Tate7060b042014-06-09 19:50:00 -07001683 // JobCompletedListener implementations.
1684
1685 /**
1686 * A job just finished executing. We fetch the
1687 * {@link com.android.server.job.controllers.JobStatus} from the store and depending on
Christopher Tate325768c2018-03-07 16:07:56 -08001688 * whether we want to reschedule we re-add it to the controllers.
Christopher Tate7060b042014-06-09 19:50:00 -07001689 * @param jobStatus Completed job.
1690 * @param needsReschedule Whether the implementing class should reschedule this job.
1691 */
1692 @Override
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001693 public void onJobCompletedLocked(JobStatus jobStatus, boolean needsReschedule) {
Christopher Tate7060b042014-06-09 19:50:00 -07001694 if (DEBUG) {
1695 Slog.d(TAG, "Completed " + jobStatus + ", reschedule=" + needsReschedule);
1696 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001697
1698 // If the job wants to be rescheduled, we first need to make the next upcoming
1699 // job so we can transfer any appropriate state over from the previous job when
1700 // we stop it.
1701 final JobStatus rescheduledJob = needsReschedule
1702 ? getRescheduleJobForFailureLocked(jobStatus) : null;
1703
Shreyas Basarge73f10252016-02-11 17:06:13 +00001704 // Do not write back immediately if this is a periodic job. The job may get lost if system
1705 // shuts down before it is added back.
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001706 if (!stopTrackingJobLocked(jobStatus, rescheduledJob, !jobStatus.getJob().isPeriodic())) {
Christopher Tate7060b042014-06-09 19:50:00 -07001707 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07001708 Slog.d(TAG, "Could not find job to remove. Was job removed while executing?");
Christopher Tate7060b042014-06-09 19:50:00 -07001709 }
Dianne Hackborn1a30bd92016-01-11 11:05:00 -08001710 // We still want to check for jobs to execute, because this job may have
1711 // scheduled a new job under the same job id, and now we can run it.
1712 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001713 return;
1714 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001715
1716 if (rescheduledJob != null) {
Dianne Hackborna47223f2017-03-30 13:49:13 -07001717 try {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001718 rescheduledJob.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001719 } catch (SecurityException e) {
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001720 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledJob);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001721 }
Dianne Hackbornfd8807a2017-04-17 13:34:51 -07001722 startTrackingJobLocked(rescheduledJob, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001723 } else if (jobStatus.getJob().isPeriodic()) {
1724 JobStatus rescheduledPeriodic = getRescheduleJobForPeriodic(jobStatus);
Dianne Hackborna47223f2017-03-30 13:49:13 -07001725 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001726 rescheduledPeriodic.prepareLocked(ActivityManager.getService());
Dianne Hackborna47223f2017-03-30 13:49:13 -07001727 } catch (SecurityException e) {
1728 Slog.w(TAG, "Unable to regrant job permissions for " + rescheduledPeriodic);
1729 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001730 startTrackingJobLocked(rescheduledPeriodic, jobStatus);
Christopher Tate7060b042014-06-09 19:50:00 -07001731 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07001732 jobStatus.unprepareLocked(ActivityManager.getService());
1733 reportActiveLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001734 mHandler.obtainMessage(MSG_CHECK_JOB_GREEDY).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001735 }
1736
1737 // StateChangedListener implementations.
1738
1739 /**
Matthew Williams48a30db2014-09-23 13:39:36 -07001740 * Posts a message to the {@link com.android.server.job.JobSchedulerService.JobHandler} that
1741 * some controller's state has changed, so as to run through the list of jobs and start/stop
1742 * any that are eligible.
Christopher Tate7060b042014-06-09 19:50:00 -07001743 */
1744 @Override
1745 public void onControllerStateChanged() {
Matthew Williams48a30db2014-09-23 13:39:36 -07001746 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
Christopher Tate7060b042014-06-09 19:50:00 -07001747 }
1748
1749 @Override
1750 public void onRunJobNow(JobStatus jobStatus) {
1751 mHandler.obtainMessage(MSG_JOB_EXPIRED, jobStatus).sendToTarget();
1752 }
1753
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001754 final private class JobHandler extends Handler {
Christopher Tate7060b042014-06-09 19:50:00 -07001755
1756 public JobHandler(Looper looper) {
1757 super(looper);
1758 }
1759
1760 @Override
1761 public void handleMessage(Message message) {
Dianne Hackborn33d31c52016-02-16 10:30:33 -08001762 synchronized (mLock) {
Matthew Williams48a30db2014-09-23 13:39:36 -07001763 if (!mReadyToRock) {
1764 return;
1765 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001766 switch (message.what) {
1767 case MSG_JOB_EXPIRED: {
Christopher Tate7060b042014-06-09 19:50:00 -07001768 JobStatus runNow = (JobStatus) message.obj;
Matthew Williamsbafeeb92014-08-08 11:51:06 -07001769 // runNow can be null, which is a controller's way of indicating that its
1770 // state is such that all ready jobs should be run immediately.
Christopher Tateb1d64482017-03-15 12:01:22 -07001771 if (runNow != null && isReadyToBeExecutedLocked(runNow)) {
Dianne Hackborn807de782016-04-07 17:54:41 -07001772 mJobPackageTracker.notePending(runNow);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001773 addOrderedItem(mPendingJobs, runNow, mEnqueueTimeComparator);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001774 } else {
1775 queueReadyJobsForExecutionLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07001776 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001777 } break;
1778 case MSG_CHECK_JOB:
Makoto Onuki0f6499c2018-12-14 16:34:59 -08001779 if (DEBUG) {
1780 Slog.d(TAG, "MSG_CHECK_JOB");
1781 }
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001782 if (mReportedActive) {
1783 // if jobs are currently being run, queue all ready jobs for execution.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001784 queueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001785 } else {
1786 // Check the list of jobs and run some of them if we feel inclined.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001787 maybeQueueReadyJobsForExecutionLocked();
Shreyas Basarge4cff8ac2015-12-10 21:32:52 +00001788 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001789 break;
1790 case MSG_CHECK_JOB_GREEDY:
Makoto Onuki0f6499c2018-12-14 16:34:59 -08001791 if (DEBUG) {
1792 Slog.d(TAG, "MSG_CHECK_JOB_GREEDY");
1793 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001794 queueReadyJobsForExecutionLocked();
1795 break;
1796 case MSG_STOP_JOB:
Dianne Hackborn729a3282017-06-09 16:06:01 -07001797 cancelJobImplLocked((JobStatus) message.obj, null,
1798 "app no longer allowed to run");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001799 break;
Makoto Onuki743e0ad2018-02-20 16:01:11 -08001800
1801 case MSG_UID_STATE_CHANGED: {
1802 final int uid = message.arg1;
1803 final int procState = message.arg2;
1804 updateUidState(uid, procState);
1805 break;
1806 }
1807 case MSG_UID_GONE: {
1808 final int uid = message.arg1;
1809 final boolean disabled = message.arg2 != 0;
1810 updateUidState(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
1811 if (disabled) {
1812 cancelJobsForUid(uid, "uid gone");
1813 }
1814 synchronized (mLock) {
1815 mDeviceIdleJobsController.setUidActiveLocked(uid, false);
1816 }
1817 break;
1818 }
1819 case MSG_UID_ACTIVE: {
1820 final int uid = message.arg1;
1821 synchronized (mLock) {
1822 mDeviceIdleJobsController.setUidActiveLocked(uid, true);
1823 }
1824 break;
1825 }
1826 case MSG_UID_IDLE: {
1827 final int uid = message.arg1;
1828 final boolean disabled = message.arg2 != 0;
1829 if (disabled) {
1830 cancelJobsForUid(uid, "app uid idle");
1831 }
1832 synchronized (mLock) {
1833 mDeviceIdleJobsController.setUidActiveLocked(uid, false);
1834 }
1835 break;
1836 }
1837
Matthew Williams75fc5252014-09-02 16:17:53 -07001838 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001839 maybeRunPendingJobsLocked();
1840 // Don't remove JOB_EXPIRED in case one came along while processing the queue.
1841 removeMessages(MSG_CHECK_JOB);
Christopher Tate7060b042014-06-09 19:50:00 -07001842 }
1843 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001844 }
Christopher Tate7060b042014-06-09 19:50:00 -07001845
Wei Wang8c0c3c12018-11-14 14:56:52 -08001846 private boolean isJobThermalConstrainedLocked(JobStatus job) {
1847 return mThermalConstraint && job.hasConnectivityConstraint()
1848 && (evaluateJobPriorityLocked(job) < JobInfo.PRIORITY_FOREGROUND_APP);
1849 }
1850
Dianne Hackborn6d068262017-05-16 13:14:37 -07001851 private void stopNonReadyActiveJobsLocked() {
1852 for (int i=0; i<mActiveServices.size(); i++) {
1853 JobServiceContext serviceContext = mActiveServices.get(i);
1854 final JobStatus running = serviceContext.getRunningJobLocked();
Wei Wang8c0c3c12018-11-14 14:56:52 -08001855 if (running == null) {
1856 continue;
1857 }
1858 if (!running.isReady()) {
Dianne Hackborn6d068262017-05-16 13:14:37 -07001859 serviceContext.cancelExecutingJobLocked(
Dianne Hackborn729a3282017-06-09 16:06:01 -07001860 JobParameters.REASON_CONSTRAINTS_NOT_SATISFIED,
1861 "cancelled due to unsatisfied constraints");
Wei Wang8c0c3c12018-11-14 14:56:52 -08001862 } else if (isJobThermalConstrainedLocked(running)) {
1863 serviceContext.cancelExecutingJobLocked(
1864 JobParameters.REASON_DEVICE_THERMAL,
1865 "cancelled due to thermal condition");
Dianne Hackborn6d068262017-05-16 13:14:37 -07001866 }
1867 }
1868 }
1869
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001870 /**
1871 * Run through list of jobs and execute all possible - at least one is expired so we do
1872 * as many as we can.
1873 */
1874 private void queueReadyJobsForExecutionLocked() {
1875 if (DEBUG) {
1876 Slog.d(TAG, "queuing all ready jobs for execution:");
1877 }
1878 noteJobsNonpending(mPendingJobs);
1879 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07001880 stopNonReadyActiveJobsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001881 mJobs.forEachJob(mReadyQueueFunctor);
1882 mReadyQueueFunctor.postProcess();
Christopher Tate2f36fd62016-02-18 18:36:08 -08001883
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001884 if (DEBUG) {
1885 final int queuedJobs = mPendingJobs.size();
1886 if (queuedJobs == 0) {
1887 Slog.d(TAG, "No jobs pending.");
1888 } else {
1889 Slog.d(TAG, queuedJobs + " jobs queued.");
Christopher Tate2f36fd62016-02-18 18:36:08 -08001890 }
1891 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001892 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08001893
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07001894 final class ReadyJobQueueFunctor implements Consumer<JobStatus> {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001895 ArrayList<JobStatus> newReadyJobs;
Christopher Tate2f36fd62016-02-18 18:36:08 -08001896
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001897 @Override
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07001898 public void accept(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001899 if (isReadyToBeExecutedLocked(job)) {
Matthew Williams75fc5252014-09-02 16:17:53 -07001900 if (DEBUG) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001901 Slog.d(TAG, " queued " + job.toShortString());
Matthew Williams75fc5252014-09-02 16:17:53 -07001902 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001903 if (newReadyJobs == null) {
1904 newReadyJobs = new ArrayList<JobStatus>();
1905 }
1906 newReadyJobs.add(job);
Kweku Adamscdbfcb92018-12-06 17:05:15 -08001907 } else {
1908 evaluateControllerStatesLocked(job);
Christopher Tate7060b042014-06-09 19:50:00 -07001909 }
1910 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001911
1912 public void postProcess() {
1913 if (newReadyJobs != null) {
1914 noteJobsPending(newReadyJobs);
1915 mPendingJobs.addAll(newReadyJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07001916 if (mPendingJobs.size() > 1) {
1917 mPendingJobs.sort(mEnqueueTimeComparator);
1918 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001919 }
1920 newReadyJobs = null;
1921 }
1922 }
1923 private final ReadyJobQueueFunctor mReadyQueueFunctor = new ReadyJobQueueFunctor();
1924
1925 /**
1926 * The state of at least one job has changed. Here is where we could enforce various
1927 * policies on when we want to execute jobs.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001928 */
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07001929 final class MaybeReadyJobQueueFunctor implements Consumer<JobStatus> {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001930 int chargingCount;
1931 int batteryNotLowCount;
1932 int storageNotLowCount;
1933 int idleCount;
1934 int backoffCount;
1935 int connectivityCount;
1936 int contentCount;
1937 List<JobStatus> runnableJobs;
1938
1939 public MaybeReadyJobQueueFunctor() {
1940 reset();
1941 }
1942
1943 // Functor method invoked for each job via JobStore.forEachJob()
1944 @Override
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07001945 public void accept(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001946 if (isReadyToBeExecutedLocked(job)) {
1947 try {
1948 if (ActivityManager.getService().isAppStartModeDisabled(job.getUid(),
1949 job.getJob().getService().getPackageName())) {
1950 Slog.w(TAG, "Aborting job " + job.getUid() + ":"
1951 + job.getJob().toString() + " -- package not allowed to start");
1952 mHandler.obtainMessage(MSG_STOP_JOB, job).sendToTarget();
1953 return;
1954 }
1955 } catch (RemoteException e) {
1956 }
1957 if (job.getNumFailures() > 0) {
1958 backoffCount++;
1959 }
1960 if (job.hasIdleConstraint()) {
1961 idleCount++;
1962 }
1963 if (job.hasConnectivityConstraint()) {
1964 connectivityCount++;
1965 }
1966 if (job.hasChargingConstraint()) {
1967 chargingCount++;
1968 }
1969 if (job.hasBatteryNotLowConstraint()) {
1970 batteryNotLowCount++;
1971 }
1972 if (job.hasStorageNotLowConstraint()) {
1973 storageNotLowCount++;
1974 }
1975 if (job.hasContentTriggerConstraint()) {
1976 contentCount++;
1977 }
1978 if (runnableJobs == null) {
1979 runnableJobs = new ArrayList<>();
1980 }
1981 runnableJobs.add(job);
Kweku Adamscdbfcb92018-12-06 17:05:15 -08001982 } else {
1983 evaluateControllerStatesLocked(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07001984 }
1985 }
1986
1987 public void postProcess() {
1988 if (backoffCount > 0 ||
1989 idleCount >= mConstants.MIN_IDLE_COUNT ||
1990 connectivityCount >= mConstants.MIN_CONNECTIVITY_COUNT ||
1991 chargingCount >= mConstants.MIN_CHARGING_COUNT ||
1992 batteryNotLowCount >= mConstants.MIN_BATTERY_NOT_LOW_COUNT ||
1993 storageNotLowCount >= mConstants.MIN_STORAGE_NOT_LOW_COUNT ||
1994 contentCount >= mConstants.MIN_CONTENT_COUNT ||
1995 (runnableJobs != null
1996 && runnableJobs.size() >= mConstants.MIN_READY_JOBS_COUNT)) {
1997 if (DEBUG) {
1998 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Running jobs.");
1999 }
2000 noteJobsPending(runnableJobs);
2001 mPendingJobs.addAll(runnableJobs);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07002002 if (mPendingJobs.size() > 1) {
2003 mPendingJobs.sort(mEnqueueTimeComparator);
2004 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002005 } else {
2006 if (DEBUG) {
2007 Slog.d(TAG, "maybeQueueReadyJobsForExecutionLocked: Not running anything.");
2008 }
2009 }
2010
2011 // Be ready for next time
2012 reset();
2013 }
2014
2015 private void reset() {
2016 chargingCount = 0;
2017 idleCount = 0;
2018 backoffCount = 0;
2019 connectivityCount = 0;
2020 batteryNotLowCount = 0;
2021 storageNotLowCount = 0;
2022 contentCount = 0;
2023 runnableJobs = null;
2024 }
2025 }
2026 private final MaybeReadyJobQueueFunctor mMaybeQueueFunctor = new MaybeReadyJobQueueFunctor();
2027
2028 private void maybeQueueReadyJobsForExecutionLocked() {
2029 if (DEBUG) Slog.d(TAG, "Maybe queuing ready jobs...");
2030
2031 noteJobsNonpending(mPendingJobs);
2032 mPendingJobs.clear();
Dianne Hackborn6d068262017-05-16 13:14:37 -07002033 stopNonReadyActiveJobsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002034 mJobs.forEachJob(mMaybeQueueFunctor);
2035 mMaybeQueueFunctor.postProcess();
2036 }
2037
Christopher Tated1aebb32018-01-31 13:24:14 -08002038 /**
2039 * Heartbeat tracking. The heartbeat alarm is intentionally non-wakeup.
2040 */
2041 class HeartbeatAlarmListener implements AlarmManager.OnAlarmListener {
2042
2043 @Override
2044 public void onAlarm() {
2045 synchronized (mLock) {
2046 final long sinceLast = sElapsedRealtimeClock.millis() - mLastHeartbeatTime;
2047 final long beatsElapsed = sinceLast / mConstants.STANDBY_HEARTBEAT_TIME;
2048 if (beatsElapsed > 0) {
2049 mLastHeartbeatTime += beatsElapsed * mConstants.STANDBY_HEARTBEAT_TIME;
2050 advanceHeartbeatLocked(beatsElapsed);
2051 }
Christopher Tatea732f012017-10-26 17:26:53 -07002052 }
Christopher Tated1aebb32018-01-31 13:24:14 -08002053 setNextHeartbeatAlarm();
Christopher Tatea732f012017-10-26 17:26:53 -07002054 }
Christopher Tatea732f012017-10-26 17:26:53 -07002055 }
2056
Christopher Tated1aebb32018-01-31 13:24:14 -08002057 // Intentionally does not touch the alarm timing
2058 void advanceHeartbeatLocked(long beatsElapsed) {
Kweku Adams4836f9d2018-11-12 17:04:17 -08002059 if (!mConstants.USE_HEARTBEATS) {
2060 return;
2061 }
Christopher Tated1aebb32018-01-31 13:24:14 -08002062 mHeartbeat += beatsElapsed;
2063 if (DEBUG_STANDBY) {
2064 Slog.v(TAG, "Advancing standby heartbeat by " + beatsElapsed
2065 + " to " + mHeartbeat);
2066 }
2067 // Don't update ACTIVE or NEVER bucket milestones. Note that mHeartbeat
2068 // will be equal to mNextBucketHeartbeat[bucket] for one beat, during which
2069 // new jobs scheduled by apps in that bucket will be permitted to run
2070 // immediately.
2071 boolean didAdvanceBucket = false;
Christopher Tatea732f012017-10-26 17:26:53 -07002072 for (int i = 1; i < mNextBucketHeartbeat.length - 1; i++) {
Christopher Tated1aebb32018-01-31 13:24:14 -08002073 // Did we reach or cross a bucket boundary?
2074 if (mHeartbeat >= mNextBucketHeartbeat[i]) {
2075 didAdvanceBucket = true;
2076 }
2077 while (mHeartbeat > mNextBucketHeartbeat[i]) {
Christopher Tatea732f012017-10-26 17:26:53 -07002078 mNextBucketHeartbeat[i] += mConstants.STANDBY_BEATS[i];
2079 }
2080 if (DEBUG_STANDBY) {
Christopher Tated1aebb32018-01-31 13:24:14 -08002081 Slog.v(TAG, " Bucket " + i + " next heartbeat "
2082 + mNextBucketHeartbeat[i]);
Christopher Tatea732f012017-10-26 17:26:53 -07002083 }
2084 }
Christopher Tated1aebb32018-01-31 13:24:14 -08002085
2086 if (didAdvanceBucket) {
2087 if (DEBUG_STANDBY) {
2088 Slog.v(TAG, "Hit bucket boundary; reevaluating job runnability");
2089 }
2090 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2091 }
2092 }
2093
2094 void setNextHeartbeatAlarm() {
2095 final long heartbeatLength;
2096 synchronized (mLock) {
Kweku Adams4836f9d2018-11-12 17:04:17 -08002097 if (!mConstants.USE_HEARTBEATS) {
2098 return;
2099 }
Christopher Tated1aebb32018-01-31 13:24:14 -08002100 heartbeatLength = mConstants.STANDBY_HEARTBEAT_TIME;
2101 }
2102 final long now = sElapsedRealtimeClock.millis();
2103 final long nextBeatOrdinal = (now + heartbeatLength) / heartbeatLength;
2104 final long nextHeartbeat = nextBeatOrdinal * heartbeatLength;
2105 if (DEBUG_STANDBY) {
2106 Slog.i(TAG, "Setting heartbeat alarm for " + nextHeartbeat
2107 + " = " + TimeUtils.formatDuration(nextHeartbeat - now));
2108 }
2109 AlarmManager am = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
2110 am.setExact(AlarmManager.ELAPSED_REALTIME, nextHeartbeat,
2111 HEARTBEAT_TAG, mHeartbeatAlarm, mHandler);
Christopher Tatea732f012017-10-26 17:26:53 -07002112 }
2113
Kweku Adamscdbfcb92018-12-06 17:05:15 -08002114 /** Returns true if both the calling and source users for the job are started. */
2115 private boolean areUsersStartedLocked(final JobStatus job) {
2116 boolean sourceStarted = ArrayUtils.contains(mStartedUsers, job.getSourceUserId());
2117 if (job.getUserId() == job.getSourceUserId()) {
2118 return sourceStarted;
2119 }
2120 return sourceStarted && ArrayUtils.contains(mStartedUsers, job.getUserId());
2121 }
2122
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002123 /**
2124 * Criteria for moving a job into the pending queue:
2125 * - It's ready.
2126 * - It's not pending.
2127 * - It's not already running on a JSC.
2128 * - The user that requested the job is running.
Christopher Tatea732f012017-10-26 17:26:53 -07002129 * - The job's standby bucket has come due to be runnable.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002130 * - The component is enabled and runnable.
2131 */
2132 private boolean isReadyToBeExecutedLocked(JobStatus job) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002133 final boolean jobReady = job.isReady();
Dianne Hackborn28d1b662017-04-21 14:17:23 -07002134
2135 if (DEBUG) {
2136 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
2137 + " ready=" + jobReady);
2138 }
2139
2140 // This is a condition that is very likely to be false (most jobs that are
2141 // scheduled are sitting there, not ready yet) and very cheap to check (just
2142 // a few conditions on data in JobStatus).
2143 if (!jobReady) {
Christopher Tate20afddd2018-02-28 15:19:19 -08002144 if (job.getSourcePackageName().equals("android.jobscheduler.cts.jobtestapp")) {
2145 Slog.v(TAG, " NOT READY: " + job);
2146 }
Dianne Hackborn28d1b662017-04-21 14:17:23 -07002147 return false;
2148 }
2149
2150 final boolean jobExists = mJobs.containsJob(job);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002151
2152 final int userId = job.getUserId();
2153 final boolean userStarted = ArrayUtils.contains(mStartedUsers, userId);
2154
2155 if (DEBUG) {
2156 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
Dianne Hackborn28d1b662017-04-21 14:17:23 -07002157 + " exists=" + jobExists + " userStarted=" + userStarted);
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002158 }
2159
Dianne Hackborn28d1b662017-04-21 14:17:23 -07002160 // These are also fairly cheap to check, though they typically will not
2161 // be conditions we fail.
2162 if (!jobExists || !userStarted) {
2163 return false;
2164 }
2165
Wei Wang8c0c3c12018-11-14 14:56:52 -08002166 if (isJobThermalConstrainedLocked(job)) {
2167 return false;
2168 }
2169
Dianne Hackborn28d1b662017-04-21 14:17:23 -07002170 final boolean jobPending = mPendingJobs.contains(job);
2171 final boolean jobActive = isCurrentlyActiveLocked(job);
2172
2173 if (DEBUG) {
2174 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
2175 + " pending=" + jobPending + " active=" + jobActive);
2176 }
2177
2178 // These can be a little more expensive (especially jobActive, since we need to
2179 // go through the array of all potentially active jobs), so we are doing them
2180 // later... but still before checking with the package manager!
2181 if (jobPending || jobActive) {
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002182 return false;
2183 }
2184
Kweku Adams4836f9d2018-11-12 17:04:17 -08002185 if (mConstants.USE_HEARTBEATS) {
2186 // If the app is in a non-active standby bucket, make sure we've waited
2187 // an appropriate amount of time since the last invocation. During device-
2188 // wide parole, standby bucketing is ignored.
2189 //
2190 // Jobs in 'active' apps are not subject to standby, nor are jobs that are
2191 // specifically marked as exempt.
Christopher Tate20afddd2018-02-28 15:19:19 -08002192 if (DEBUG_STANDBY) {
Kweku Adams4836f9d2018-11-12 17:04:17 -08002193 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
2194 + " parole=" + mInParole + " active=" + job.uidActive
2195 + " exempt=" + job.getJob().isExemptedFromAppStandby());
Christopher Tate20afddd2018-02-28 15:19:19 -08002196 }
Kweku Adams4836f9d2018-11-12 17:04:17 -08002197 if (!mInParole
2198 && !job.uidActive
2199 && !job.getJob().isExemptedFromAppStandby()) {
2200 final int bucket = job.getStandbyBucket();
2201 if (DEBUG_STANDBY) {
2202 Slog.v(TAG, " bucket=" + bucket + " heartbeat=" + mHeartbeat
2203 + " next=" + mNextBucketHeartbeat[bucket]);
2204 }
2205 if (mHeartbeat < mNextBucketHeartbeat[bucket]) {
2206 // Only skip this job if the app is still waiting for the end of its nominal
2207 // bucket interval. Once it's waited that long, we let it go ahead and clear.
2208 // The final (NEVER) bucket is special; we never age those apps' jobs into
2209 // runnability.
2210 final long appLastRan = heartbeatWhenJobsLastRun(job);
2211 if (bucket >= mConstants.STANDBY_BEATS.length
2212 || (mHeartbeat > appLastRan
2213 && mHeartbeat < appLastRan + mConstants.STANDBY_BEATS[bucket])) {
2214 // TODO: log/trace that we're deferring the job due to bucketing if we
2215 // hit this
2216 if (job.getWhenStandbyDeferred() == 0) {
2217 if (DEBUG_STANDBY) {
2218 Slog.v(TAG, "Bucket deferral: " + mHeartbeat + " < "
2219 + (appLastRan + mConstants.STANDBY_BEATS[bucket])
2220 + " for " + job);
2221 }
2222 job.setWhenStandbyDeferred(sElapsedRealtimeClock.millis());
Christopher Tatea5a85bd2018-01-03 17:20:36 -08002223 }
Kweku Adams4836f9d2018-11-12 17:04:17 -08002224 return false;
2225 } else {
2226 if (DEBUG_STANDBY) {
2227 Slog.v(TAG, "Bucket deferred job aged into runnability at "
2228 + mHeartbeat + " : " + job);
2229 }
Christopher Tatea5a85bd2018-01-03 17:20:36 -08002230 }
Christopher Tate0c4d7682017-12-06 15:10:22 -08002231 }
Christopher Tatea732f012017-10-26 17:26:53 -07002232 }
Christopher Tatea732f012017-10-26 17:26:53 -07002233 }
2234
2235 // The expensive check last: validate that the defined package+service is
2236 // still present & viable.
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002237 final boolean componentPresent;
2238 try {
2239 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2240 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2241 userId) != null);
2242 } catch (RemoteException e) {
2243 throw e.rethrowAsRuntimeException();
2244 }
2245
2246 if (DEBUG) {
2247 Slog.v(TAG, "isReadyToBeExecutedLocked: " + job.toShortString()
2248 + " componentPresent=" + componentPresent);
2249 }
2250
2251 // Everything else checked out so far, so this is the final yes/no check
2252 return componentPresent;
2253 }
2254
Kweku Adamscdbfcb92018-12-06 17:05:15 -08002255 private void evaluateControllerStatesLocked(final JobStatus job) {
2256 for (int c = mControllers.size() - 1; c >= 0; --c) {
2257 final StateController sc = mControllers.get(c);
2258 sc.evaluateStateLocked(job);
2259 }
2260 }
2261
2262 /**
2263 * Returns true if non-job constraint components are in place -- if job.isReady() returns true
2264 * and this method returns true, then the job is ready to be executed.
2265 */
2266 public boolean areComponentsInPlaceLocked(JobStatus job) {
2267 // This code is very similar to the code in isReadyToBeExecutedLocked --- it uses the same
2268 // conditions.
2269
2270 final boolean jobExists = mJobs.containsJob(job);
2271 final boolean userStarted = areUsersStartedLocked(job);
2272
2273 if (DEBUG) {
2274 Slog.v(TAG, "areComponentsInPlaceLocked: " + job.toShortString()
2275 + " exists=" + jobExists + " userStarted=" + userStarted);
2276 }
2277
2278 // These are also fairly cheap to check, though they typically will not
2279 // be conditions we fail.
2280 if (!jobExists || !userStarted) {
2281 return false;
2282 }
2283
2284 // Job pending/active doesn't affect the readiness of a job.
2285
2286 // Skipping the hearbeat check as this will only come into play when using the rolling
2287 // window quota management system.
2288
2289 // The expensive check last: validate that the defined package+service is
2290 // still present & viable.
2291 final boolean componentPresent;
2292 try {
2293 // TODO: cache result until we're notified that something in the package changed.
2294 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
2295 job.getServiceComponent(), PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2296 job.getUserId()) != null);
2297 } catch (RemoteException e) {
2298 throw e.rethrowAsRuntimeException();
2299 }
2300
2301 if (DEBUG) {
2302 Slog.v(TAG, "areComponentsInPlaceLocked: " + job.toShortString()
2303 + " componentPresent=" + componentPresent);
2304 }
2305
2306 // Everything else checked out so far, so this is the final yes/no check
2307 return componentPresent;
2308 }
2309
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002310 /**
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002311 * Reconcile jobs in the pending queue against available execution contexts.
2312 * A controller can force a job into the pending queue even if it's already running, but
2313 * here is where we decide whether to actually execute it.
2314 */
2315 private void maybeRunPendingJobsLocked() {
2316 if (DEBUG) {
2317 Slog.d(TAG, "pending queue: " + mPendingJobs.size() + " jobs.");
2318 }
Makoto Onuki714f97d2018-12-05 11:18:13 -08002319 mConcurrencyManager.assignJobsToContextsLocked();
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002320 reportActiveLocked();
Christopher Tate7060b042014-06-09 19:50:00 -07002321 }
2322
Dianne Hackborn807de782016-04-07 17:54:41 -07002323 private int adjustJobPriority(int curPriority, JobStatus job) {
2324 if (curPriority < JobInfo.PRIORITY_TOP_APP) {
2325 float factor = mJobPackageTracker.getLoadFactor(job);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002326 if (factor >= mConstants.HEAVY_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07002327 curPriority += JobInfo.PRIORITY_ADJ_ALWAYS_RUNNING;
Dianne Hackborne9a988c2016-05-27 17:59:40 -07002328 } else if (factor >= mConstants.MODERATE_USE_FACTOR) {
Dianne Hackborn807de782016-04-07 17:54:41 -07002329 curPriority += JobInfo.PRIORITY_ADJ_OFTEN_RUNNING;
2330 }
2331 }
2332 return curPriority;
2333 }
2334
Makoto Onuki714f97d2018-12-05 11:18:13 -08002335 int evaluateJobPriorityLocked(JobStatus job) {
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002336 int priority = job.getPriority();
Makoto Onukiec8b14d2018-12-05 13:22:24 -08002337 if (priority >= JobInfo.PRIORITY_BOUND_FOREGROUND_SERVICE) {
Dianne Hackborn807de782016-04-07 17:54:41 -07002338 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002339 }
Dianne Hackborn970510b2016-02-24 16:56:42 -08002340 int override = mUidPriorityOverride.get(job.getSourceUid(), 0);
2341 if (override != 0) {
Dianne Hackborn807de782016-04-07 17:54:41 -07002342 return adjustJobPriority(override, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002343 }
Dianne Hackborn807de782016-04-07 17:54:41 -07002344 return adjustJobPriority(priority, job);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002345 }
2346
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002347 final class LocalService implements JobSchedulerInternal {
2348
2349 /**
Christopher Tatea732f012017-10-26 17:26:53 -07002350 * The current bucket heartbeat ordinal
2351 */
2352 public long currentHeartbeat() {
2353 return getCurrentHeartbeat();
2354 }
2355
2356 /**
2357 * Heartbeat ordinal at which the given standby bucket's jobs next become runnable
2358 */
2359 public long nextHeartbeatForBucket(int bucket) {
2360 synchronized (mLock) {
2361 return mNextBucketHeartbeat[bucket];
2362 }
2363 }
2364
2365 /**
Christopher Tate435c2f42018-01-18 12:59:15 -08002366 * Heartbeat ordinal for the given app. This is typically the heartbeat at which
2367 * the app last ran jobs, so that a newly-scheduled job in an app that hasn't run
2368 * jobs in a long time is immediately runnable even if the app is bucketed into
2369 * an infrequent time allocation.
2370 */
2371 public long baseHeartbeatForApp(String packageName, @UserIdInt int userId,
2372 final int appStandbyBucket) {
2373 if (appStandbyBucket == 0 ||
2374 appStandbyBucket >= mConstants.STANDBY_BEATS.length) {
2375 // ACTIVE => everything can be run right away
2376 // NEVER => we won't run them anyway, so let them go in the future
2377 // as soon as the app enters normal use
Christopher Tated1aebb32018-01-31 13:24:14 -08002378 if (DEBUG_STANDBY) {
2379 Slog.v(TAG, "Base heartbeat forced ZERO for new job in "
2380 + packageName + "/" + userId);
2381 }
Christopher Tate435c2f42018-01-18 12:59:15 -08002382 return 0;
2383 }
2384
Christopher Tated1aebb32018-01-31 13:24:14 -08002385 final long baseHeartbeat = heartbeatWhenJobsLastRun(packageName, userId);
2386 if (DEBUG_STANDBY) {
2387 Slog.v(TAG, "Base heartbeat " + baseHeartbeat + " for new job in "
2388 + packageName + "/" + userId);
2389 }
2390 return baseHeartbeat;
Christopher Tate435c2f42018-01-18 12:59:15 -08002391 }
2392
Christopher Tate325768c2018-03-07 16:07:56 -08002393 public void noteJobStart(String packageName, int userId) {
2394 synchronized (mLock) {
2395 setLastJobHeartbeatLocked(packageName, userId, mHeartbeat);
2396 }
2397 }
2398
Christopher Tate435c2f42018-01-18 12:59:15 -08002399 /**
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002400 * Returns a list of all pending jobs. A running job is not considered pending. Periodic
2401 * jobs are always considered pending.
2402 */
Amith Yamasanicb926fc2016-03-14 17:15:20 -07002403 @Override
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002404 public List<JobInfo> getSystemScheduledPendingJobs() {
2405 synchronized (mLock) {
2406 final List<JobInfo> pendingJobs = new ArrayList<JobInfo>();
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002407 mJobs.forEachJob(Process.SYSTEM_UID, (job) -> {
2408 if (job.getJob().isPeriodic() || !isCurrentlyActiveLocked(job)) {
2409 pendingJobs.add(job.getJob());
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002410 }
2411 });
2412 return pendingJobs;
2413 }
2414 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002415
2416 @Override
Christopher Tate1d99c392017-12-07 16:54:04 -08002417 public void cancelJobsForUid(int uid, String reason) {
2418 JobSchedulerService.this.cancelJobsForUid(uid, reason);
2419 }
2420
2421 @Override
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002422 public void addBackingUpUid(int uid) {
2423 synchronized (mLock) {
2424 // No need to actually do anything here, since for a full backup the
2425 // activity manager will kill the process which will kill the job (and
2426 // cause it to restart, but now it can't run).
2427 mBackingUpUids.put(uid, uid);
2428 }
2429 }
2430
2431 @Override
2432 public void removeBackingUpUid(int uid) {
2433 synchronized (mLock) {
2434 mBackingUpUids.delete(uid);
2435 // If there are any jobs for this uid, we need to rebuild the pending list
2436 // in case they are now ready to run.
2437 if (mJobs.countJobsForUid(uid) > 0) {
2438 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2439 }
2440 }
2441 }
2442
2443 @Override
2444 public void clearAllBackingUpUids() {
2445 synchronized (mLock) {
2446 if (mBackingUpUids.size() > 0) {
2447 mBackingUpUids.clear();
2448 mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
2449 }
2450 }
2451 }
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002452
2453 @Override
Christopher Tated117b292018-01-05 17:32:36 -08002454 public void reportAppUsage(String packageName, int userId) {
2455 JobSchedulerService.this.reportAppUsage(packageName, userId);
2456 }
2457
2458 @Override
Makoto Onukie7b02982017-08-24 14:23:36 -07002459 public JobStorePersistStats getPersistStats() {
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002460 synchronized (mLock) {
Makoto Onukie7b02982017-08-24 14:23:36 -07002461 return new JobStorePersistStats(mJobs.getPersistStats());
Makoto Onukidd4b14f2017-08-17 14:03:48 -07002462 }
2463 }
Shreyas Basargecbf5ae92016-03-08 16:13:06 +00002464 }
2465
Shreyas Basarge5db09082016-01-07 13:38:29 +00002466 /**
Christopher Tatea732f012017-10-26 17:26:53 -07002467 * Tracking of app assignments to standby buckets
2468 */
2469 final class StandbyTracker extends AppIdleStateChangeListener {
Christopher Tate435c2f42018-01-18 12:59:15 -08002470
Christopher Tatea732f012017-10-26 17:26:53 -07002471 // AppIdleStateChangeListener interface for live updates
2472
2473 @Override
Christopher Tate435c2f42018-01-18 12:59:15 -08002474 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
Amith Yamasani119be9a2018-02-18 22:23:00 -08002475 boolean idle, int bucket, int reason) {
Kweku Adams4836f9d2018-11-12 17:04:17 -08002476 // QuotaController handles this now.
Christopher Tatea732f012017-10-26 17:26:53 -07002477 }
2478
2479 @Override
2480 public void onParoleStateChanged(boolean isParoleOn) {
Christopher Tatea5a85bd2018-01-03 17:20:36 -08002481 if (DEBUG_STANDBY) {
2482 Slog.i(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
2483 }
2484 mInParole = isParoleOn;
Christopher Tatea732f012017-10-26 17:26:53 -07002485 }
Christopher Tated117b292018-01-05 17:32:36 -08002486
2487 @Override
2488 public void onUserInteractionStarted(String packageName, int userId) {
2489 final int uid = mLocalPM.getPackageUid(packageName,
2490 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
2491 if (uid < 0) {
2492 // Quietly ignore; the case is already logged elsewhere
2493 return;
2494 }
2495
Amith Yamasani977e11f2018-02-16 11:29:54 -08002496 long sinceLast = mUsageStats.getTimeSinceLastJobRun(packageName, userId);
2497 if (sinceLast > 2 * DateUtils.DAY_IN_MILLIS) {
2498 // Too long ago, not worth logging
2499 sinceLast = 0L;
2500 }
Christopher Tated117b292018-01-05 17:32:36 -08002501 final DeferredJobCounter counter = new DeferredJobCounter();
2502 synchronized (mLock) {
2503 mJobs.forEachJobForSourceUid(uid, counter);
2504 }
Amith Yamasani977e11f2018-02-16 11:29:54 -08002505 if (counter.numDeferred() > 0 || sinceLast > 0) {
2506 BatteryStatsInternal mBatteryStatsInternal = LocalServices.getService
2507 (BatteryStatsInternal.class);
2508 mBatteryStatsInternal.noteJobsDeferred(uid, counter.numDeferred(), sinceLast);
Yangster-mac96353002018-09-05 11:18:55 -07002509 StatsLog.write_non_chained(StatsLog.DEFERRED_JOB_STATS_REPORTED, uid, null,
2510 counter.numDeferred(), sinceLast);
Amith Yamasani977e11f2018-02-16 11:29:54 -08002511 }
Christopher Tated117b292018-01-05 17:32:36 -08002512 }
2513 }
2514
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002515 static class DeferredJobCounter implements Consumer<JobStatus> {
Christopher Tated117b292018-01-05 17:32:36 -08002516 private int mDeferred = 0;
2517
2518 public int numDeferred() {
2519 return mDeferred;
2520 }
2521
2522 @Override
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002523 public void accept(JobStatus job) {
Christopher Tated117b292018-01-05 17:32:36 -08002524 if (job.getWhenStandbyDeferred() > 0) {
2525 mDeferred++;
2526 }
2527 }
Christopher Tatea732f012017-10-26 17:26:53 -07002528 }
2529
2530 public static int standbyBucketToBucketIndex(int bucket) {
2531 // Normalize AppStandby constants to indices into our bookkeeping
Christopher Tatef2159712018-03-27 16:04:14 -07002532 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) return NEVER_INDEX;
2533 else if (bucket > UsageStatsManager.STANDBY_BUCKET_FREQUENT) return RARE_INDEX;
2534 else if (bucket > UsageStatsManager.STANDBY_BUCKET_WORKING_SET) return FREQUENT_INDEX;
2535 else if (bucket > UsageStatsManager.STANDBY_BUCKET_ACTIVE) return WORKING_INDEX;
2536 else return ACTIVE_INDEX;
Christopher Tatea732f012017-10-26 17:26:53 -07002537 }
2538
Christopher Tated1aebb32018-01-31 13:24:14 -08002539 // Static to support external callers
Christopher Tatea732f012017-10-26 17:26:53 -07002540 public static int standbyBucketForPackage(String packageName, int userId, long elapsedNow) {
2541 UsageStatsManagerInternal usageStats = LocalServices.getService(
2542 UsageStatsManagerInternal.class);
2543 int bucket = usageStats != null
2544 ? usageStats.getAppStandbyBucket(packageName, userId, elapsedNow)
2545 : 0;
2546
2547 bucket = standbyBucketToBucketIndex(bucket);
2548
2549 if (DEBUG_STANDBY) {
2550 Slog.v(TAG, packageName + "/" + userId + " standby bucket index: " + bucket);
2551 }
2552 return bucket;
2553 }
2554
2555 /**
Christopher Tate7060b042014-06-09 19:50:00 -07002556 * Binder stub trampoline implementation
2557 */
2558 final class JobSchedulerStub extends IJobScheduler.Stub {
2559 /** Cache determination of whether a given app can persist jobs
2560 * key is uid of the calling app; value is undetermined/true/false
2561 */
2562 private final SparseArray<Boolean> mPersistCache = new SparseArray<Boolean>();
2563
2564 // Enforce that only the app itself (or shared uid participant) can schedule a
2565 // job that runs one of the app's services, as well as verifying that the
2566 // named service properly requires the BIND_JOB_SERVICE permission
2567 private void enforceValidJobRequest(int uid, JobInfo job) {
Christopher Tate5568f542014-06-18 13:53:31 -07002568 final IPackageManager pm = AppGlobals.getPackageManager();
Christopher Tate7060b042014-06-09 19:50:00 -07002569 final ComponentName service = job.getService();
2570 try {
Jeff Sharkeyc7bacab2016-02-09 15:56:11 -07002571 ServiceInfo si = pm.getServiceInfo(service,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002572 PackageManager.MATCH_DIRECT_BOOT_AWARE
2573 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
Jeff Sharkey12c0da42016-02-25 17:10:50 -07002574 UserHandle.getUserId(uid));
Christopher Tate5568f542014-06-18 13:53:31 -07002575 if (si == null) {
2576 throw new IllegalArgumentException("No such service " + service);
2577 }
Christopher Tate7060b042014-06-09 19:50:00 -07002578 if (si.applicationInfo.uid != uid) {
2579 throw new IllegalArgumentException("uid " + uid +
2580 " cannot schedule job in " + service.getPackageName());
2581 }
2582 if (!JobService.PERMISSION_BIND.equals(si.permission)) {
2583 throw new IllegalArgumentException("Scheduled service " + service
2584 + " does not require android.permission.BIND_JOB_SERVICE permission");
2585 }
Christopher Tate5568f542014-06-18 13:53:31 -07002586 } catch (RemoteException e) {
2587 // Can't happen; the Package Manager is in this same process
Christopher Tate7060b042014-06-09 19:50:00 -07002588 }
2589 }
2590
2591 private boolean canPersistJobs(int pid, int uid) {
2592 // If we get this far we're good to go; all we need to do now is check
2593 // whether the app is allowed to persist its scheduled work.
2594 final boolean canPersist;
2595 synchronized (mPersistCache) {
2596 Boolean cached = mPersistCache.get(uid);
2597 if (cached != null) {
2598 canPersist = cached.booleanValue();
2599 } else {
2600 // Persisting jobs is tantamount to running at boot, so we permit
2601 // it when the app has declared that it uses the RECEIVE_BOOT_COMPLETED
2602 // permission
2603 int result = getContext().checkPermission(
2604 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, pid, uid);
2605 canPersist = (result == PackageManager.PERMISSION_GRANTED);
2606 mPersistCache.put(uid, canPersist);
2607 }
2608 }
2609 return canPersist;
2610 }
2611
Makoto Onuki959acb52018-01-26 14:10:03 -08002612 private void validateJobFlags(JobInfo job, int callingUid) {
2613 if ((job.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0) {
2614 getContext().enforceCallingOrSelfPermission(
2615 android.Manifest.permission.CONNECTIVITY_INTERNAL, TAG);
2616 }
2617 if ((job.getFlags() & JobInfo.FLAG_EXEMPT_FROM_APP_STANDBY) != 0) {
2618 if (callingUid != Process.SYSTEM_UID) {
2619 throw new SecurityException("Job has invalid flags");
2620 }
Makoto Onuki2b5811a2018-02-08 11:09:42 -08002621 if (job.isPeriodic()) {
2622 Slog.wtf(TAG, "Periodic jobs mustn't have"
2623 + " FLAG_EXEMPT_FROM_APP_STANDBY. Job=" + job);
Makoto Onuki959acb52018-01-26 14:10:03 -08002624 }
2625 }
2626 }
2627
Christopher Tate7060b042014-06-09 19:50:00 -07002628 // IJobScheduler implementation
2629 @Override
2630 public int schedule(JobInfo job) throws RemoteException {
2631 if (DEBUG) {
Matthew Williamsee410da2014-07-25 11:30:40 -07002632 Slog.d(TAG, "Scheduling job: " + job.toString());
Christopher Tate7060b042014-06-09 19:50:00 -07002633 }
2634 final int pid = Binder.getCallingPid();
2635 final int uid = Binder.getCallingUid();
Christopher Tatea732f012017-10-26 17:26:53 -07002636 final int userId = UserHandle.getUserId(uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002637
2638 enforceValidJobRequest(uid, job);
Matthew Williams900c67f2014-07-09 12:46:53 -07002639 if (job.isPersisted()) {
2640 if (!canPersistJobs(pid, uid)) {
2641 throw new IllegalArgumentException("Error: requested job be persisted without"
2642 + " holding RECEIVE_BOOT_COMPLETED permission.");
2643 }
2644 }
Christopher Tate7060b042014-06-09 19:50:00 -07002645
Makoto Onuki959acb52018-01-26 14:10:03 -08002646 validateJobFlags(job, uid);
Jeff Sharkey785f4942016-07-14 10:31:15 -06002647
Christopher Tate7060b042014-06-09 19:50:00 -07002648 long ident = Binder.clearCallingIdentity();
2649 try {
Christopher Tatea732f012017-10-26 17:26:53 -07002650 return JobSchedulerService.this.scheduleAsPackage(job, null, uid, null, userId,
2651 null);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002652 } finally {
2653 Binder.restoreCallingIdentity(ident);
2654 }
2655 }
2656
2657 // IJobScheduler implementation
2658 @Override
2659 public int enqueue(JobInfo job, JobWorkItem work) throws RemoteException {
2660 if (DEBUG) {
2661 Slog.d(TAG, "Enqueueing job: " + job.toString() + " work: " + work);
2662 }
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002663 final int uid = Binder.getCallingUid();
Christopher Tatea732f012017-10-26 17:26:53 -07002664 final int userId = UserHandle.getUserId(uid);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002665
2666 enforceValidJobRequest(uid, job);
2667 if (job.isPersisted()) {
2668 throw new IllegalArgumentException("Can't enqueue work for persisted jobs");
2669 }
2670 if (work == null) {
2671 throw new NullPointerException("work is null");
2672 }
2673
Makoto Onuki959acb52018-01-26 14:10:03 -08002674 validateJobFlags(job, uid);
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002675
2676 long ident = Binder.clearCallingIdentity();
2677 try {
Christopher Tatea732f012017-10-26 17:26:53 -07002678 return JobSchedulerService.this.scheduleAsPackage(job, work, uid, null, userId,
2679 null);
Christopher Tate7060b042014-06-09 19:50:00 -07002680 } finally {
2681 Binder.restoreCallingIdentity(ident);
2682 }
2683 }
2684
2685 @Override
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002686 public int scheduleAsPackage(JobInfo job, String packageName, int userId, String tag)
Shreyas Basarge968ac752016-01-11 23:09:26 +00002687 throws RemoteException {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002688 final int callerUid = Binder.getCallingUid();
Shreyas Basarge968ac752016-01-11 23:09:26 +00002689 if (DEBUG) {
Christopher Tate2f36fd62016-02-18 18:36:08 -08002690 Slog.d(TAG, "Caller uid " + callerUid + " scheduling job: " + job.toString()
Christopher Tatea732f012017-10-26 17:26:53 -07002691 + " on behalf of " + packageName + "/");
Shreyas Basarge968ac752016-01-11 23:09:26 +00002692 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002693
2694 if (packageName == null) {
2695 throw new NullPointerException("Must specify a package for scheduleAsPackage()");
Shreyas Basarge968ac752016-01-11 23:09:26 +00002696 }
Christopher Tate2f36fd62016-02-18 18:36:08 -08002697
2698 int mayScheduleForOthers = getContext().checkCallingOrSelfPermission(
2699 android.Manifest.permission.UPDATE_DEVICE_STATS);
2700 if (mayScheduleForOthers != PackageManager.PERMISSION_GRANTED) {
2701 throw new SecurityException("Caller uid " + callerUid
2702 + " not permitted to schedule jobs for other apps");
2703 }
2704
Makoto Onuki959acb52018-01-26 14:10:03 -08002705 validateJobFlags(job, callerUid);
Jeff Sharkey4f100402016-05-03 17:44:23 -06002706
Shreyas Basarge968ac752016-01-11 23:09:26 +00002707 long ident = Binder.clearCallingIdentity();
2708 try {
Dianne Hackborn7da13d72017-04-04 17:17:35 -07002709 return JobSchedulerService.this.scheduleAsPackage(job, null, callerUid,
Dianne Hackborn1085ff62016-02-23 17:04:58 -08002710 packageName, userId, tag);
Shreyas Basarge968ac752016-01-11 23:09:26 +00002711 } finally {
2712 Binder.restoreCallingIdentity(ident);
2713 }
2714 }
2715
2716 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002717 public List<JobInfo> getAllPendingJobs() throws RemoteException {
2718 final int uid = Binder.getCallingUid();
2719
2720 long ident = Binder.clearCallingIdentity();
2721 try {
2722 return JobSchedulerService.this.getPendingJobs(uid);
2723 } finally {
2724 Binder.restoreCallingIdentity(ident);
2725 }
2726 }
2727
2728 @Override
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002729 public JobInfo getPendingJob(int jobId) throws RemoteException {
2730 final int uid = Binder.getCallingUid();
2731
2732 long ident = Binder.clearCallingIdentity();
2733 try {
2734 return JobSchedulerService.this.getPendingJob(uid, jobId);
2735 } finally {
2736 Binder.restoreCallingIdentity(ident);
2737 }
2738 }
2739
2740 @Override
Christopher Tate7060b042014-06-09 19:50:00 -07002741 public void cancelAll() throws RemoteException {
2742 final int uid = Binder.getCallingUid();
Christopher Tate7060b042014-06-09 19:50:00 -07002743 long ident = Binder.clearCallingIdentity();
2744 try {
Makoto Onukid2bfec62018-01-12 13:58:01 -08002745 JobSchedulerService.this.cancelJobsForUid(uid,
2746 "cancelAll() called by app, callingUid=" + uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002747 } finally {
2748 Binder.restoreCallingIdentity(ident);
2749 }
2750 }
2751
2752 @Override
2753 public void cancel(int jobId) throws RemoteException {
2754 final int uid = Binder.getCallingUid();
2755
2756 long ident = Binder.clearCallingIdentity();
2757 try {
Makoto Onukid2bfec62018-01-12 13:58:01 -08002758 JobSchedulerService.this.cancelJob(uid, jobId, uid);
Christopher Tate7060b042014-06-09 19:50:00 -07002759 } finally {
2760 Binder.restoreCallingIdentity(ident);
2761 }
2762 }
2763
2764 /**
2765 * "dumpsys" infrastructure
2766 */
2767 @Override
2768 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002769 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Christopher Tate7060b042014-06-09 19:50:00 -07002770
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002771 int filterUid = -1;
2772 boolean proto = false;
2773 if (!ArrayUtils.isEmpty(args)) {
2774 int opti = 0;
2775 while (opti < args.length) {
2776 String arg = args[opti];
2777 if ("-h".equals(arg)) {
2778 dumpHelp(pw);
2779 return;
2780 } else if ("-a".equals(arg)) {
2781 // Ignore, we always dump all.
2782 } else if ("--proto".equals(arg)) {
2783 proto = true;
2784 } else if (arg.length() > 0 && arg.charAt(0) == '-') {
2785 pw.println("Unknown option: " + arg);
2786 return;
2787 } else {
2788 break;
2789 }
2790 opti++;
2791 }
2792 if (opti < args.length) {
2793 String pkg = args[opti];
2794 try {
2795 filterUid = getContext().getPackageManager().getPackageUid(pkg,
2796 PackageManager.MATCH_ANY_USER);
2797 } catch (NameNotFoundException ignored) {
2798 pw.println("Invalid package: " + pkg);
2799 return;
2800 }
2801 }
2802 }
2803
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002804 final long identityToken = Binder.clearCallingIdentity();
Christopher Tate7060b042014-06-09 19:50:00 -07002805 try {
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002806 if (proto) {
2807 JobSchedulerService.this.dumpInternalProto(fd, filterUid);
2808 } else {
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07002809 JobSchedulerService.this.dumpInternal(new IndentingPrintWriter(pw, " "),
2810 filterUid);
Kweku Adams85f2fbc2017-12-18 12:04:12 -08002811 }
Christopher Tate7060b042014-06-09 19:50:00 -07002812 } finally {
2813 Binder.restoreCallingIdentity(identityToken);
2814 }
2815 }
Christopher Tate5d346052016-03-08 12:56:08 -08002816
2817 @Override
2818 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002819 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Christopher Tate5d346052016-03-08 12:56:08 -08002820 (new JobSchedulerShellCommand(JobSchedulerService.this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002821 this, in, out, err, args, callback, resultReceiver);
Christopher Tate5d346052016-03-08 12:56:08 -08002822 }
Serik Beketayev75915d12018-08-01 16:56:59 -07002823
2824 /**
2825 * <b>For internal system user only!</b>
2826 * Returns a list of all currently-executing jobs.
2827 */
2828 @Override
2829 public List<JobInfo> getStartedJobs() {
2830 final int uid = Binder.getCallingUid();
2831 if (uid != Process.SYSTEM_UID) {
2832 throw new SecurityException(
2833 "getStartedJobs() is system internal use only.");
2834 }
2835
2836 final ArrayList<JobInfo> runningJobs;
2837
2838 synchronized (mLock) {
2839 runningJobs = new ArrayList<>(mActiveServices.size());
2840 for (JobServiceContext jsc : mActiveServices) {
2841 final JobStatus job = jsc.getRunningJobLocked();
2842 if (job != null) {
2843 runningJobs.add(job.getJob());
2844 }
2845 }
2846 }
2847
2848 return runningJobs;
2849 }
2850
2851 /**
2852 * <b>For internal system user only!</b>
2853 * Returns a snapshot of the state of all jobs known to the system.
2854 *
2855 * <p class="note">This is a slow operation, so it should be called sparingly.
2856 */
2857 @Override
2858 public List<JobSnapshot> getAllJobSnapshots() {
2859 final int uid = Binder.getCallingUid();
2860 if (uid != Process.SYSTEM_UID) {
2861 throw new SecurityException(
2862 "getAllJobSnapshots() is system internal use only.");
2863 }
2864 synchronized (mLock) {
2865 final ArrayList<JobSnapshot> snapshots = new ArrayList<>(mJobs.size());
2866 mJobs.forEachJob((job) -> snapshots.add(
2867 new JobSnapshot(job.getJob(), job.getSatisfiedConstraintFlags(),
2868 isReadyToBeExecutedLocked(job))));
2869 return snapshots;
2870 }
2871 }
Shreyas Basarge5db09082016-01-07 13:38:29 +00002872 };
2873
Christopher Tate5d346052016-03-08 12:56:08 -08002874 // Shell command infrastructure: run the given job immediately
2875 int executeRunCommand(String pkgName, int userId, int jobId, boolean force) {
2876 if (DEBUG) {
2877 Slog.v(TAG, "executeRunCommand(): " + pkgName + "/" + userId
2878 + " " + jobId + " f=" + force);
2879 }
2880
2881 try {
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002882 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
2883 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
Christopher Tate5d346052016-03-08 12:56:08 -08002884 if (uid < 0) {
2885 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2886 }
2887
2888 synchronized (mLock) {
2889 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
2890 if (js == null) {
2891 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
2892 }
2893
2894 js.overrideState = (force) ? JobStatus.OVERRIDE_FULL : JobStatus.OVERRIDE_SOFT;
2895 if (!js.isConstraintsSatisfied()) {
2896 js.overrideState = 0;
2897 return JobSchedulerShellCommand.CMD_ERR_CONSTRAINTS;
2898 }
2899
Dianne Hackbornf9bac162017-04-20 17:17:48 -07002900 queueReadyJobsForExecutionLocked();
2901 maybeRunPendingJobsLocked();
Christopher Tate5d346052016-03-08 12:56:08 -08002902 }
2903 } catch (RemoteException e) {
2904 // can't happen
2905 }
2906 return 0;
2907 }
2908
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002909 // Shell command infrastructure: immediately timeout currently executing jobs
2910 int executeTimeoutCommand(PrintWriter pw, String pkgName, int userId,
2911 boolean hasJobId, int jobId) {
2912 if (DEBUG) {
2913 Slog.v(TAG, "executeTimeoutCommand(): " + pkgName + "/" + userId + " " + jobId);
2914 }
2915
2916 synchronized (mLock) {
2917 boolean foundSome = false;
2918 for (int i=0; i<mActiveServices.size(); i++) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07002919 final JobServiceContext jc = mActiveServices.get(i);
2920 final JobStatus js = jc.getRunningJobLocked();
Makoto Onukid2bfec62018-01-12 13:58:01 -08002921 if (jc.timeoutIfExecutingLocked(pkgName, userId, hasJobId, jobId, "shell")) {
Dianne Hackborneb90fa92017-06-30 14:03:36 -07002922 foundSome = true;
2923 pw.print("Timing out: ");
2924 js.printUniqueId(pw);
2925 pw.print(" ");
2926 pw.println(js.getServiceComponent().flattenToShortString());
2927 }
Dianne Hackborn83b40f62017-04-26 13:59:47 -07002928 }
2929 if (!foundSome) {
2930 pw.println("No matching executing jobs found.");
2931 }
2932 }
2933 return 0;
2934 }
2935
Christopher Tate8c67d122017-09-29 16:54:26 -07002936 // Shell command infrastructure: cancel a scheduled job
2937 int executeCancelCommand(PrintWriter pw, String pkgName, int userId,
2938 boolean hasJobId, int jobId) {
2939 if (DEBUG) {
2940 Slog.v(TAG, "executeCancelCommand(): " + pkgName + "/" + userId + " " + jobId);
2941 }
2942
2943 int pkgUid = -1;
2944 try {
2945 IPackageManager pm = AppGlobals.getPackageManager();
2946 pkgUid = pm.getPackageUid(pkgName, 0, userId);
2947 } catch (RemoteException e) { /* can't happen */ }
2948
2949 if (pkgUid < 0) {
2950 pw.println("Package " + pkgName + " not found.");
2951 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
2952 }
2953
2954 if (!hasJobId) {
2955 pw.println("Canceling all jobs for " + pkgName + " in user " + userId);
2956 if (!cancelJobsForUid(pkgUid, "cancel shell command for package")) {
2957 pw.println("No matching jobs found.");
2958 }
2959 } else {
2960 pw.println("Canceling job " + pkgName + "/#" + jobId + " in user " + userId);
Makoto Onukid2bfec62018-01-12 13:58:01 -08002961 if (!cancelJob(pkgUid, jobId, Process.SHELL_UID)) {
Christopher Tate8c67d122017-09-29 16:54:26 -07002962 pw.println("No matching job found.");
2963 }
2964 }
2965
2966 return 0;
2967 }
2968
Dianne Hackborna06ec6a2017-02-13 10:08:42 -08002969 void setMonitorBattery(boolean enabled) {
2970 synchronized (mLock) {
2971 if (mBatteryController != null) {
2972 mBatteryController.getTracker().setMonitorBatteryLocked(enabled);
2973 }
2974 }
2975 }
2976
2977 int getBatterySeq() {
2978 synchronized (mLock) {
2979 return mBatteryController != null ? mBatteryController.getTracker().getSeq() : -1;
2980 }
2981 }
2982
2983 boolean getBatteryCharging() {
2984 synchronized (mLock) {
2985 return mBatteryController != null
2986 ? mBatteryController.getTracker().isOnStablePower() : false;
2987 }
2988 }
2989
2990 boolean getBatteryNotLow() {
2991 synchronized (mLock) {
2992 return mBatteryController != null
2993 ? mBatteryController.getTracker().isBatteryNotLow() : false;
2994 }
2995 }
2996
Dianne Hackborn532ea262017-03-17 17:50:55 -07002997 int getStorageSeq() {
2998 synchronized (mLock) {
2999 return mStorageController != null ? mStorageController.getTracker().getSeq() : -1;
3000 }
3001 }
3002
3003 boolean getStorageNotLow() {
3004 synchronized (mLock) {
3005 return mStorageController != null
3006 ? mStorageController.getTracker().isStorageNotLow() : false;
3007 }
3008 }
3009
Christopher Tatea732f012017-10-26 17:26:53 -07003010 long getCurrentHeartbeat() {
3011 synchronized (mLock) {
3012 return mHeartbeat;
3013 }
3014 }
3015
Christopher Tated1aebb32018-01-31 13:24:14 -08003016 // Shell command infrastructure
Dianne Hackborn6d068262017-05-16 13:14:37 -07003017 int getJobState(PrintWriter pw, String pkgName, int userId, int jobId) {
3018 try {
3019 final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
3020 userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
3021 if (uid < 0) {
3022 pw.print("unknown("); pw.print(pkgName); pw.println(")");
3023 return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
3024 }
3025
3026 synchronized (mLock) {
3027 final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
3028 if (DEBUG) Slog.d(TAG, "get-job-state " + uid + "/" + jobId + ": " + js);
3029 if (js == null) {
3030 pw.print("unknown("); UserHandle.formatUid(pw, uid);
3031 pw.print("/jid"); pw.print(jobId); pw.println(")");
3032 return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
3033 }
3034
3035 boolean printed = false;
3036 if (mPendingJobs.contains(js)) {
3037 pw.print("pending");
3038 printed = true;
3039 }
3040 if (isCurrentlyActiveLocked(js)) {
3041 if (printed) {
3042 pw.print(" ");
3043 }
3044 printed = true;
3045 pw.println("active");
3046 }
3047 if (!ArrayUtils.contains(mStartedUsers, js.getUserId())) {
3048 if (printed) {
3049 pw.print(" ");
3050 }
3051 printed = true;
3052 pw.println("user-stopped");
3053 }
3054 if (mBackingUpUids.indexOfKey(js.getSourceUid()) >= 0) {
3055 if (printed) {
3056 pw.print(" ");
3057 }
3058 printed = true;
3059 pw.println("backing-up");
3060 }
3061 boolean componentPresent = false;
3062 try {
3063 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
3064 js.getServiceComponent(),
3065 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
3066 js.getUserId()) != null);
3067 } catch (RemoteException e) {
3068 }
3069 if (!componentPresent) {
3070 if (printed) {
3071 pw.print(" ");
3072 }
3073 printed = true;
3074 pw.println("no-component");
3075 }
3076 if (js.isReady()) {
3077 if (printed) {
3078 pw.print(" ");
3079 }
3080 printed = true;
3081 pw.println("ready");
3082 }
3083 if (!printed) {
3084 pw.print("waiting");
3085 }
3086 pw.println();
3087 }
3088 } catch (RemoteException e) {
3089 // can't happen
3090 }
3091 return 0;
3092 }
3093
Christopher Tated1aebb32018-01-31 13:24:14 -08003094 // Shell command infrastructure
3095 int executeHeartbeatCommand(PrintWriter pw, int numBeats) {
3096 if (numBeats < 1) {
3097 pw.println(getCurrentHeartbeat());
3098 return 0;
3099 }
3100
3101 pw.print("Advancing standby heartbeat by ");
3102 pw.println(numBeats);
3103 synchronized (mLock) {
3104 advanceHeartbeatLocked(numBeats);
3105 }
3106 return 0;
3107 }
3108
lpeter318abc92018-05-04 16:13:14 +08003109 void triggerDockState(boolean idleState) {
3110 final Intent dockIntent;
3111 if (idleState) {
3112 dockIntent = new Intent(Intent.ACTION_DOCK_IDLE);
3113 } else {
3114 dockIntent = new Intent(Intent.ACTION_DOCK_ACTIVE);
3115 }
3116 dockIntent.setPackage("android");
3117 dockIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
3118 getContext().sendBroadcastAsUser(dockIntent, UserHandle.ALL);
3119 }
3120
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003121 static void dumpHelp(PrintWriter pw) {
3122 pw.println("Job Scheduler (jobscheduler) dump options:");
3123 pw.println(" [-h] [package] ...");
3124 pw.println(" -h: print this help");
3125 pw.println(" [package] is an optional package name to limit the output to.");
3126 }
3127
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003128 /** Sort jobs by caller UID, then by Job ID. */
3129 private static void sortJobs(List<JobStatus> jobs) {
3130 Collections.sort(jobs, new Comparator<JobStatus>() {
3131 @Override
3132 public int compare(JobStatus o1, JobStatus o2) {
3133 int uid1 = o1.getUid();
3134 int uid2 = o2.getUid();
3135 int id1 = o1.getJobId();
3136 int id2 = o2.getJobId();
3137 if (uid1 != uid2) {
3138 return uid1 < uid2 ? -1 : 1;
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003139 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003140 return id1 < id2 ? -1 : (id1 > id2 ? 1 : 0);
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003141 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003142 });
3143 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06003144
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003145 void dumpInternal(final IndentingPrintWriter pw, int filterUid) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003146 final int filterUidFinal = UserHandle.getAppId(filterUid);
Jeff Sharkeyd0fff2e2017-11-07 16:55:06 -07003147 final long nowElapsed = sElapsedRealtimeClock.millis();
3148 final long nowUptime = sUptimeMillisClock.millis();
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003149 final Predicate<JobStatus> predicate = (js) -> {
3150 return filterUidFinal == -1 || UserHandle.getAppId(js.getUid()) == filterUidFinal
3151 || UserHandle.getAppId(js.getSourceUid()) == filterUidFinal;
3152 };
Dianne Hackborn33d31c52016-02-16 10:30:33 -08003153 synchronized (mLock) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003154 mConstants.dump(pw);
3155 pw.println();
Makoto Onukib5d5e972018-02-20 14:44:20 -08003156
3157 pw.println(" Heartbeat:");
3158 pw.print(" Current: "); pw.println(mHeartbeat);
3159 pw.println(" Next");
3160 pw.print(" ACTIVE: "); pw.println(mNextBucketHeartbeat[0]);
3161 pw.print(" WORKING: "); pw.println(mNextBucketHeartbeat[1]);
3162 pw.print(" FREQUENT: "); pw.println(mNextBucketHeartbeat[2]);
3163 pw.print(" RARE: "); pw.println(mNextBucketHeartbeat[3]);
3164 pw.print(" Last heartbeat: ");
3165 TimeUtils.formatDuration(mLastHeartbeatTime, nowElapsed, pw);
3166 pw.println();
3167 pw.print(" Next heartbeat: ");
3168 TimeUtils.formatDuration(mLastHeartbeatTime + mConstants.STANDBY_HEARTBEAT_TIME,
3169 nowElapsed, pw);
3170 pw.println();
Makoto Onuki0525b982018-05-02 14:46:59 -07003171 pw.print(" In parole?: ");
3172 pw.print(mInParole);
3173 pw.println();
Wei Wang8c0c3c12018-11-14 14:56:52 -08003174 pw.print(" In thermal throttling?: ");
3175 pw.print(mThermalConstraint);
3176 pw.println();
Makoto Onukib5d5e972018-02-20 14:44:20 -08003177 pw.println();
3178
Jeff Sharkey822cbd12016-02-25 11:09:55 -07003179 pw.println("Started users: " + Arrays.toString(mStartedUsers));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003180 pw.print("Registered ");
3181 pw.print(mJobs.size());
3182 pw.println(" jobs:");
Christopher Tate7060b042014-06-09 19:50:00 -07003183 if (mJobs.size() > 0) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003184 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003185 sortJobs(jobs);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003186 for (JobStatus job : jobs) {
3187 pw.print(" JOB #"); job.printUniqueId(pw); pw.print(": ");
3188 pw.println(job.toShortStringExceptUniqueId());
3189
3190 // Skip printing details if the caller requested a filter
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003191 if (!predicate.test(job)) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003192 continue;
3193 }
3194
Dianne Hackborn6d068262017-05-16 13:14:37 -07003195 job.dump(pw, " ", true, nowElapsed);
Makoto Onukib5d5e972018-02-20 14:44:20 -08003196 pw.print(" Last run heartbeat: ");
3197 pw.print(heartbeatWhenJobsLastRun(job));
3198 pw.println();
3199
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003200 pw.print(" Ready: ");
Dianne Hackbornf9bac162017-04-20 17:17:48 -07003201 pw.print(isReadyToBeExecutedLocked(job));
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003202 pw.print(" (job=");
3203 pw.print(job.isReady());
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003204 pw.print(" user=");
3205 pw.print(ArrayUtils.contains(mStartedUsers, job.getUserId()));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07003206 pw.print(" !pending=");
3207 pw.print(!mPendingJobs.contains(job));
3208 pw.print(" !active=");
3209 pw.print(!isCurrentlyActiveLocked(job));
Dianne Hackbornf9bac162017-04-20 17:17:48 -07003210 pw.print(" !backingup=");
3211 pw.print(!(mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0));
Dianne Hackborn0aa43132017-03-22 11:42:03 -07003212 pw.print(" comp=");
3213 boolean componentPresent = false;
3214 try {
3215 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
3216 job.getServiceComponent(),
3217 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
3218 job.getUserId()) != null);
3219 } catch (RemoteException e) {
3220 }
3221 pw.print(componentPresent);
Dianne Hackborne9a988c2016-05-27 17:59:40 -07003222 pw.println(")");
3223 }
Christopher Tate7060b042014-06-09 19:50:00 -07003224 } else {
Christopher Tatef973a7b2014-08-29 12:54:08 -07003225 pw.println(" None.");
Christopher Tate7060b042014-06-09 19:50:00 -07003226 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003227 for (int i=0; i<mControllers.size(); i++) {
Christopher Tate7060b042014-06-09 19:50:00 -07003228 pw.println();
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003229 pw.println(mControllers.get(i).getClass().getSimpleName() + ":");
3230 pw.increaseIndent();
3231 mControllers.get(i).dumpControllerStateLocked(pw, predicate);
3232 pw.decreaseIndent();
Christopher Tate7060b042014-06-09 19:50:00 -07003233 }
3234 pw.println();
Dianne Hackborn970510b2016-02-24 16:56:42 -08003235 pw.println("Uid priority overrides:");
3236 for (int i=0; i< mUidPriorityOverride.size(); i++) {
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003237 int uid = mUidPriorityOverride.keyAt(i);
3238 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
3239 pw.print(" "); pw.print(UserHandle.formatUid(uid));
3240 pw.print(": "); pw.println(mUidPriorityOverride.valueAt(i));
3241 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003242 }
Dianne Hackbornf9bac162017-04-20 17:17:48 -07003243 if (mBackingUpUids.size() > 0) {
3244 pw.println();
3245 pw.println("Backing up uids:");
3246 boolean first = true;
3247 for (int i = 0; i < mBackingUpUids.size(); i++) {
3248 int uid = mBackingUpUids.keyAt(i);
3249 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
3250 if (first) {
3251 pw.print(" ");
3252 first = false;
3253 } else {
3254 pw.print(", ");
3255 }
3256 pw.print(UserHandle.formatUid(uid));
3257 }
3258 }
3259 pw.println();
3260 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003261 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003262 mJobPackageTracker.dump(pw, "", filterUidFinal);
Dianne Hackborn807de782016-04-07 17:54:41 -07003263 pw.println();
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003264 if (mJobPackageTracker.dumpHistory(pw, "", filterUidFinal)) {
3265 pw.println();
3266 }
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003267 pw.println("Pending queue:");
3268 for (int i=0; i<mPendingJobs.size(); i++) {
3269 JobStatus job = mPendingJobs.get(i);
3270 pw.print(" Pending #"); pw.print(i); pw.print(": ");
3271 pw.println(job.toShortString());
Dianne Hackborn6d068262017-05-16 13:14:37 -07003272 job.dump(pw, " ", false, nowElapsed);
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003273 int priority = evaluateJobPriorityLocked(job);
Makoto Onukiec8b14d2018-12-05 13:22:24 -08003274 pw.print(" Evaluated priority: ");
3275 pw.println(JobInfo.getPriorityString(priority));
3276
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003277 pw.print(" Tag: "); pw.println(job.getTag());
Christopher Tate7234fc62017-04-03 17:36:07 -07003278 pw.print(" Enq: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07003279 TimeUtils.formatDuration(job.madePending - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003280 pw.println();
Dianne Hackborn1085ff62016-02-23 17:04:58 -08003281 }
Christopher Tate7060b042014-06-09 19:50:00 -07003282 pw.println();
3283 pw.println("Active jobs:");
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003284 for (int i=0; i<mActiveServices.size(); i++) {
3285 JobServiceContext jsc = mActiveServices.get(i);
Dianne Hackborn970510b2016-02-24 16:56:42 -08003286 pw.print(" Slot #"); pw.print(i); pw.print(": ");
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003287 final JobStatus job = jsc.getRunningJobLocked();
Christopher Tate7234fc62017-04-03 17:36:07 -07003288 if (job == null) {
Dianne Hackborn729a3282017-06-09 16:06:01 -07003289 if (jsc.mStoppedReason != null) {
3290 pw.print("inactive since ");
3291 TimeUtils.formatDuration(jsc.mStoppedTime, nowElapsed, pw);
3292 pw.print(", stopped because: ");
3293 pw.println(jsc.mStoppedReason);
3294 } else {
3295 pw.println("inactive");
3296 }
Christopher Tate7060b042014-06-09 19:50:00 -07003297 continue;
3298 } else {
Christopher Tate7234fc62017-04-03 17:36:07 -07003299 pw.println(job.toShortString());
Dianne Hackborn970510b2016-02-24 16:56:42 -08003300 pw.print(" Running for: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07003301 TimeUtils.formatDuration(nowElapsed - jsc.getExecutionStartTimeElapsed(), pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08003302 pw.print(", timeout at: ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07003303 TimeUtils.formatDuration(jsc.getTimeoutElapsed() - nowElapsed, pw);
Dianne Hackborn970510b2016-02-24 16:56:42 -08003304 pw.println();
Dianne Hackborn6d068262017-05-16 13:14:37 -07003305 job.dump(pw, " ", false, nowElapsed);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003306 int priority = evaluateJobPriorityLocked(jsc.getRunningJobLocked());
Makoto Onukiec8b14d2018-12-05 13:22:24 -08003307 pw.print(" Evaluated priority: ");
3308 pw.println(JobInfo.getPriorityString(priority));
3309
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003310 pw.print(" Active at ");
Dianne Hackborn6d068262017-05-16 13:14:37 -07003311 TimeUtils.formatDuration(job.madeActive - nowUptime, pw);
Dianne Hackbornbfc23312017-05-11 11:53:24 -07003312 pw.print(", pending for ");
Christopher Tate7234fc62017-04-03 17:36:07 -07003313 TimeUtils.formatDuration(job.madeActive - job.madePending, pw);
3314 pw.println();
Christopher Tate7060b042014-06-09 19:50:00 -07003315 }
3316 }
Dianne Hackbornef3aa6e2016-04-29 18:18:08 -07003317 if (filterUid == -1) {
3318 pw.println();
3319 pw.print("mReadyToRock="); pw.println(mReadyToRock);
3320 pw.print("mReportedActive="); pw.println(mReportedActive);
3321 pw.print("mMaxActiveJobs="); pw.println(mMaxActiveJobs);
3322 }
Makoto Onukie7b02982017-08-24 14:23:36 -07003323 pw.println();
3324 pw.print("PersistStats: ");
3325 pw.println(mJobs.getPersistStats());
Christopher Tate7060b042014-06-09 19:50:00 -07003326 }
3327 pw.println();
3328 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003329
3330 void dumpInternalProto(final FileDescriptor fd, int filterUid) {
3331 ProtoOutputStream proto = new ProtoOutputStream(fd);
3332 final int filterUidFinal = UserHandle.getAppId(filterUid);
3333 final long nowElapsed = sElapsedRealtimeClock.millis();
3334 final long nowUptime = sUptimeMillisClock.millis();
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003335 final Predicate<JobStatus> predicate = (js) -> {
3336 return filterUidFinal == -1 || UserHandle.getAppId(js.getUid()) == filterUidFinal
3337 || UserHandle.getAppId(js.getSourceUid()) == filterUidFinal;
3338 };
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003339
3340 synchronized (mLock) {
3341 mConstants.dump(proto, JobSchedulerServiceDumpProto.SETTINGS);
Makoto Onukib5d5e972018-02-20 14:44:20 -08003342 proto.write(JobSchedulerServiceDumpProto.CURRENT_HEARTBEAT, mHeartbeat);
3343 proto.write(JobSchedulerServiceDumpProto.NEXT_HEARTBEAT, mNextBucketHeartbeat[0]);
3344 proto.write(JobSchedulerServiceDumpProto.NEXT_HEARTBEAT, mNextBucketHeartbeat[1]);
3345 proto.write(JobSchedulerServiceDumpProto.NEXT_HEARTBEAT, mNextBucketHeartbeat[2]);
3346 proto.write(JobSchedulerServiceDumpProto.NEXT_HEARTBEAT, mNextBucketHeartbeat[3]);
3347 proto.write(JobSchedulerServiceDumpProto.LAST_HEARTBEAT_TIME_MILLIS,
3348 mLastHeartbeatTime - nowUptime);
3349 proto.write(JobSchedulerServiceDumpProto.NEXT_HEARTBEAT_TIME_MILLIS,
3350 mLastHeartbeatTime + mConstants.STANDBY_HEARTBEAT_TIME - nowUptime);
Makoto Onuki0525b982018-05-02 14:46:59 -07003351 proto.write(JobSchedulerServiceDumpProto.IN_PAROLE, mInParole);
Wei Wang8c0c3c12018-11-14 14:56:52 -08003352 proto.write(JobSchedulerServiceDumpProto.IN_THERMAL, mThermalConstraint);
Makoto Onukib5d5e972018-02-20 14:44:20 -08003353
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003354 for (int u : mStartedUsers) {
3355 proto.write(JobSchedulerServiceDumpProto.STARTED_USERS, u);
3356 }
3357 if (mJobs.size() > 0) {
3358 final List<JobStatus> jobs = mJobs.mJobSet.getAllJobs();
3359 sortJobs(jobs);
3360 for (JobStatus job : jobs) {
3361 final long rjToken = proto.start(JobSchedulerServiceDumpProto.REGISTERED_JOBS);
3362 job.writeToShortProto(proto, JobSchedulerServiceDumpProto.RegisteredJob.INFO);
3363
3364 // Skip printing details if the caller requested a filter
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003365 if (!predicate.test(job)) {
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003366 continue;
3367 }
3368
3369 job.dump(proto, JobSchedulerServiceDumpProto.RegisteredJob.DUMP, true, nowElapsed);
3370
3371 // isReadyToBeExecuted
3372 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_READY,
3373 job.isReady());
3374 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_USER_STARTED,
3375 ArrayUtils.contains(mStartedUsers, job.getUserId()));
3376 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_PENDING,
3377 mPendingJobs.contains(job));
3378 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_JOB_CURRENTLY_ACTIVE,
3379 isCurrentlyActiveLocked(job));
3380 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_UID_BACKING_UP,
3381 mBackingUpUids.indexOfKey(job.getSourceUid()) >= 0);
3382 boolean componentPresent = false;
3383 try {
3384 componentPresent = (AppGlobals.getPackageManager().getServiceInfo(
3385 job.getServiceComponent(),
3386 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
3387 job.getUserId()) != null);
3388 } catch (RemoteException e) {
3389 }
3390 proto.write(JobSchedulerServiceDumpProto.RegisteredJob.IS_COMPONENT_PRESENT,
3391 componentPresent);
Makoto Onukib5d5e972018-02-20 14:44:20 -08003392 proto.write(RegisteredJob.LAST_RUN_HEARTBEAT, heartbeatWhenJobsLastRun(job));
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003393
3394 proto.end(rjToken);
3395 }
3396 }
3397 for (StateController controller : mControllers) {
3398 controller.dumpControllerStateLocked(
Jeff Sharkeyfee8c7b2018-02-21 22:18:45 -07003399 proto, JobSchedulerServiceDumpProto.CONTROLLERS, predicate);
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003400 }
3401 for (int i=0; i< mUidPriorityOverride.size(); i++) {
3402 int uid = mUidPriorityOverride.keyAt(i);
3403 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
3404 long pToken = proto.start(JobSchedulerServiceDumpProto.PRIORITY_OVERRIDES);
3405 proto.write(JobSchedulerServiceDumpProto.PriorityOverride.UID, uid);
3406 proto.write(JobSchedulerServiceDumpProto.PriorityOverride.OVERRIDE_VALUE,
3407 mUidPriorityOverride.valueAt(i));
3408 proto.end(pToken);
3409 }
3410 }
3411 for (int i = 0; i < mBackingUpUids.size(); i++) {
3412 int uid = mBackingUpUids.keyAt(i);
3413 if (filterUidFinal == -1 || filterUidFinal == UserHandle.getAppId(uid)) {
3414 proto.write(JobSchedulerServiceDumpProto.BACKING_UP_UIDS, uid);
3415 }
3416 }
3417
3418 mJobPackageTracker.dump(proto, JobSchedulerServiceDumpProto.PACKAGE_TRACKER,
3419 filterUidFinal);
3420 mJobPackageTracker.dumpHistory(proto, JobSchedulerServiceDumpProto.HISTORY,
3421 filterUidFinal);
3422
3423 for (JobStatus job : mPendingJobs) {
3424 final long pjToken = proto.start(JobSchedulerServiceDumpProto.PENDING_JOBS);
3425
3426 job.writeToShortProto(proto, PendingJob.INFO);
3427 job.dump(proto, PendingJob.DUMP, false, nowElapsed);
Makoto Onukiec8b14d2018-12-05 13:22:24 -08003428 proto.write(PendingJob.EVALUATED_PRIORITY, evaluateJobPriorityLocked(job));
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003429 proto.write(PendingJob.ENQUEUED_DURATION_MS, nowUptime - job.madePending);
3430
3431 proto.end(pjToken);
3432 }
3433 for (JobServiceContext jsc : mActiveServices) {
3434 final long ajToken = proto.start(JobSchedulerServiceDumpProto.ACTIVE_JOBS);
3435 final JobStatus job = jsc.getRunningJobLocked();
3436
3437 if (job == null) {
3438 final long ijToken = proto.start(ActiveJob.INACTIVE);
3439
3440 proto.write(ActiveJob.InactiveJob.TIME_SINCE_STOPPED_MS,
3441 nowElapsed - jsc.mStoppedTime);
3442 if (jsc.mStoppedReason != null) {
3443 proto.write(ActiveJob.InactiveJob.STOPPED_REASON,
3444 jsc.mStoppedReason);
3445 }
3446
3447 proto.end(ijToken);
3448 } else {
3449 final long rjToken = proto.start(ActiveJob.RUNNING);
3450
3451 job.writeToShortProto(proto, ActiveJob.RunningJob.INFO);
3452
3453 proto.write(ActiveJob.RunningJob.RUNNING_DURATION_MS,
3454 nowElapsed - jsc.getExecutionStartTimeElapsed());
3455 proto.write(ActiveJob.RunningJob.TIME_UNTIL_TIMEOUT_MS,
3456 jsc.getTimeoutElapsed() - nowElapsed);
3457
3458 job.dump(proto, ActiveJob.RunningJob.DUMP, false, nowElapsed);
3459
Makoto Onukiec8b14d2018-12-05 13:22:24 -08003460 proto.write(ActiveJob.RunningJob.EVALUATED_PRIORITY,
3461 evaluateJobPriorityLocked(jsc.getRunningJobLocked()));
Kweku Adams85f2fbc2017-12-18 12:04:12 -08003462
3463 proto.write(ActiveJob.RunningJob.TIME_SINCE_MADE_ACTIVE_MS,
3464 nowUptime - job.madeActive);
3465 proto.write(ActiveJob.RunningJob.PENDING_DURATION_MS,
3466 job.madeActive - job.madePending);
3467
3468 proto.end(rjToken);
3469 }
3470 proto.end(ajToken);
3471 }
3472 if (filterUid == -1) {
3473 proto.write(JobSchedulerServiceDumpProto.IS_READY_TO_ROCK, mReadyToRock);
3474 proto.write(JobSchedulerServiceDumpProto.REPORTED_ACTIVE, mReportedActive);
3475 proto.write(JobSchedulerServiceDumpProto.MAX_ACTIVE_JOBS, mMaxActiveJobs);
3476 }
3477 }
3478
3479 proto.flush();
3480 }
Christopher Tate7060b042014-06-09 19:50:00 -07003481}