blob: b8940cf9f02e86ce69f70265015c0ae96487f713 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006-2007 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.internal.os;
18
Sudheer Shanka9b735c52017-05-09 18:26:18 -070019import android.annotation.NonNull;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070020import android.annotation.Nullable;
Dianne Hackborn61659e52014-07-09 16:13:01 -070021import android.app.ActivityManager;
Adam Lesinski33dac552015-03-09 15:24:48 -070022import android.bluetooth.BluetoothActivityEnergyInfo;
Adam Lesinski50e47602015-12-04 17:04:54 -080023import android.bluetooth.UidTraffic;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080024import android.content.Context;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070025import android.content.Intent;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070026import android.net.ConnectivityManager;
27import android.net.NetworkStats;
Adam Lesinski33dac552015-03-09 15:24:48 -070028import android.net.wifi.WifiActivityEnergyInfo;
Dianne Hackborn3251b902014-06-20 14:40:53 -070029import android.net.wifi.WifiManager;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070030import android.os.BatteryManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.os.BatteryStats;
Dianne Hackborncd0e3352014-08-07 17:08:09 -070032import android.os.Build;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070033import android.os.FileUtils;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070034import android.os.Handler;
Adam Lesinskie1f480d2017-02-15 18:51:23 -080035import android.os.IBatteryPropertiesRegistrar;
Jeff Brown6f357d32014-01-15 20:40:55 -080036import android.os.Looper;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070037import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.os.Parcel;
39import android.os.ParcelFormatException;
40import android.os.Parcelable;
Evan Millarc64edde2009-04-18 12:26:32 -070041import android.os.Process;
Adam Lesinskie1f480d2017-02-15 18:51:23 -080042import android.os.RemoteException;
43import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.os.SystemClock;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070045import android.os.UserHandle;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070046import android.os.WorkSource;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070047import android.telephony.DataConnectionRealTimeInfo;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080048import android.telephony.ModemActivityInfo;
Amith Yamasanif37447b2009-10-08 18:28:01 -070049import android.telephony.ServiceState;
Wink Savillee9b06d72009-05-18 21:47:50 -070050import android.telephony.SignalStrength;
Dianne Hackborn627bba72009-03-24 22:32:56 -070051import android.telephony.TelephonyManager;
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -070052import android.text.TextUtils;
Dianne Hackborn61659e52014-07-09 16:13:01 -070053import android.util.ArrayMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.util.Log;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070055import android.util.LogWriter;
James Carr3a226052016-07-01 14:49:52 -070056import android.util.LongSparseArray;
57import android.util.LongSparseLongArray;
Dianne Hackbornd953c532014-08-16 18:17:38 -070058import android.util.MutableInt;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070059import android.util.Pools;
Dianne Hackborn1d442e02009-04-20 18:14:05 -070060import android.util.PrintWriterPrinter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.util.Printer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070062import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.util.SparseArray;
Dianne Hackborn099bc622014-01-22 13:39:16 -080064import android.util.SparseIntArray;
Adam Lesinskie08af192015-03-25 16:42:59 -070065import android.util.SparseLongArray;
Bookatzc1a050a2017-10-10 15:49:28 -070066import android.util.StatsLog;
Dianne Hackbornae384452011-06-28 12:33:48 -070067import android.util.TimeUtils;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080068import android.util.Xml;
Jeff Browne95c3cd2014-05-02 16:59:26 -070069import android.view.Display;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070
Adam Lesinski14ae39a2017-05-26 11:50:40 -070071import com.android.internal.annotations.GuardedBy;
Adam Lesinski98f0d462016-04-19 16:46:20 -070072import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070073import com.android.internal.net.NetworkStatsFactory;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080074import com.android.internal.util.ArrayUtils;
Dianne Hackborn8c841092013-06-24 13:46:13 -070075import com.android.internal.util.FastPrintWriter;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080076import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070077import com.android.internal.util.JournaledFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080078import com.android.internal.util.XmlUtils;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070079
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070080import libcore.util.EmptyArray;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080081import org.xmlpull.v1.XmlPullParser;
82import org.xmlpull.v1.XmlPullParserException;
83import org.xmlpull.v1.XmlSerializer;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070084
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080085import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import java.io.File;
87import java.io.FileInputStream;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080088import java.io.FileNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import java.io.FileOutputStream;
90import java.io.IOException;
Dianne Hackborn1d442e02009-04-20 18:14:05 -070091import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010092import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093import java.util.ArrayList;
Sudheer Shanka9b735c52017-05-09 18:26:18 -070094import java.util.Arrays;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080095import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096import java.util.HashMap;
Evan Millarc64edde2009-04-18 12:26:32 -070097import java.util.Iterator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098import java.util.Map;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070099import java.util.concurrent.Future;
Christopher Tate4cee7252010-03-19 14:50:40 -0700100import java.util.concurrent.atomic.AtomicInteger;
Dianne Hackbornce2ef762010-09-20 11:39:14 -0700101import java.util.concurrent.locks.ReentrantLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102
103/**
104 * All information we are collecting about things that can happen that impact
105 * battery life. All times are represented in microseconds except where indicated
106 * otherwise.
107 */
Joe Onoratoabded112016-02-08 16:49:39 -0800108public class BatteryStatsImpl extends BatteryStats {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 private static final String TAG = "BatteryStatsImpl";
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800110 private static final boolean DEBUG = false;
Adam Lesinskia7c90c82015-06-18 14:52:24 -0700111 public static final boolean DEBUG_ENERGY = false;
Adam Lesinski50e47602015-12-04 17:04:54 -0800112 private static final boolean DEBUG_ENERGY_CPU = DEBUG_ENERGY;
James Carr3a226052016-07-01 14:49:52 -0700113 private static final boolean DEBUG_MEMORY = false;
Dianne Hackborn32907cf2010-06-10 17:50:20 -0700114 private static final boolean DEBUG_HISTORY = false;
Dianne Hackborne8c88e62011-08-17 19:09:09 -0700115 private static final boolean USE_OLD_HISTORY = false; // for debugging.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700116
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700117 // TODO: remove "tcp" from network methods, since we measure total stats.
118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 // In-memory Parcel magic number, used to detect attempts to unmarshall bad data
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700120 private static final int MAGIC = 0xBA757475; // 'BATSTATS'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121
122 // Current on-disk Parcel version
Bookatzba78b2b2017-10-10 11:06:33 -0700123 private static final int VERSION = 168 + (USE_OLD_HISTORY ? 1000 : 0);
Amith Yamasanie43530a2009-08-21 13:11:37 -0700124
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700125 // Maximum number of items we will record in the history.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100126 private static final int MAX_HISTORY_ITEMS;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700127
Dianne Hackbornf47d8f22010-10-08 10:46:55 -0700128 // No, really, THIS is the maximum number of items we will record in the history.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100129 private static final int MAX_MAX_HISTORY_ITEMS;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -0700130
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800131 // The maximum number of names wakelocks we will keep track of
132 // per uid; once the limit is reached, we batch the remaining wakelocks
133 // in to one common name.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100134 private static final int MAX_WAKELOCKS_PER_UID;
135
136 static final int MAX_HISTORY_BUFFER; // 256KB
137 static final int MAX_MAX_HISTORY_BUFFER; // 320KB
138
139 static {
140 if (ActivityManager.isLowRamDeviceStatic()) {
141 MAX_HISTORY_ITEMS = 800;
142 MAX_MAX_HISTORY_ITEMS = 1200;
143 MAX_WAKELOCKS_PER_UID = 40;
144 MAX_HISTORY_BUFFER = 96*1024; // 96KB
145 MAX_MAX_HISTORY_BUFFER = 128*1024; // 128KB
146 } else {
147 MAX_HISTORY_ITEMS = 2000;
148 MAX_MAX_HISTORY_ITEMS = 3000;
149 MAX_WAKELOCKS_PER_UID = 100;
150 MAX_HISTORY_BUFFER = 256*1024; // 256KB
151 MAX_MAX_HISTORY_BUFFER = 320*1024; // 256KB
152 }
153 }
Dianne Hackbornc24ab862011-10-18 15:55:03 -0700154
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800155 // Number of transmit power states the Wifi controller can be in.
156 private static final int NUM_WIFI_TX_LEVELS = 1;
157
158 // Number of transmit power states the Bluetooth controller can be in.
159 private static final int NUM_BT_TX_LEVELS = 1;
160
Sudheer Shanka38383232017-07-25 09:55:03 -0700161 /**
162 * Holding a wakelock costs more than just using the cpu.
163 * Currently, we assign only half the cpu time to an app that is running but
164 * not holding a wakelock. The apps holding wakelocks get the rest of the blame.
165 * If no app is holding a wakelock, then the distribution is normal.
166 */
167 @VisibleForTesting
168 public static final int WAKE_LOCK_WEIGHT = 50;
169
Joe Onoratoabded112016-02-08 16:49:39 -0800170 protected Clocks mClocks;
171
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700172 private final JournaledFile mFile;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700173 public final AtomicFile mCheckinFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800174 public final AtomicFile mDailyFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700176 static final int MSG_UPDATE_WAKELOCKS = 1;
177 static final int MSG_REPORT_POWER_CHANGE = 2;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700178 static final int MSG_REPORT_CHARGING = 3;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700179 static final long DELAY_UPDATE_WAKELOCKS = 5*1000;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700180
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700181 private final KernelWakelockReader mKernelWakelockReader = new KernelWakelockReader();
182 private final KernelWakelockStats mTmpWakelockStats = new KernelWakelockStats();
183
Sudheer Shanka38383232017-07-25 09:55:03 -0700184 @VisibleForTesting
185 protected KernelUidCpuTimeReader mKernelUidCpuTimeReader = new KernelUidCpuTimeReader();
186 @VisibleForTesting
187 protected KernelCpuSpeedReader[] mKernelCpuSpeedReaders;
188 @VisibleForTesting
189 protected KernelUidCpuFreqTimeReader mKernelUidCpuFreqTimeReader =
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700190 new KernelUidCpuFreqTimeReader();
Adam Lesinski06af1fa2015-05-05 17:35:35 -0700191
James Carr3a226052016-07-01 14:49:52 -0700192 private final KernelMemoryBandwidthStats mKernelMemoryBandwidthStats
193 = new KernelMemoryBandwidthStats();
194 private final LongSparseArray<SamplingTimer> mKernelMemoryStats = new LongSparseArray<>();
195 public LongSparseArray<SamplingTimer> getKernelMemoryStats() {
196 return mKernelMemoryStats;
197 }
198
Bookatz0b8a0502017-09-13 11:51:52 -0700199 /** Container for Resource Power Manager stats. Updated by updateRpmStatsLocked. */
Bookatz50df7112017-08-04 14:53:26 -0700200 private final RpmStats mTmpRpmStats = new RpmStats();
Bookatz0b8a0502017-09-13 11:51:52 -0700201 /** The soonest the RPM stats can be updated after it was last updated. */
202 private static final long RPM_STATS_UPDATE_FREQ_MS = 1000;
203 /** Last time that RPM stats were updated by updateRpmStatsLocked. */
204 private long mLastRpmStatsUpdateTimeMs = -RPM_STATS_UPDATE_FREQ_MS;
Bookatz50df7112017-08-04 14:53:26 -0700205
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700206 public interface BatteryCallback {
207 public void batteryNeedsCpuUpdate();
208 public void batteryPowerChanged(boolean onBattery);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700209 public void batterySendBroadcast(Intent intent);
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700210 }
211
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700212 public interface PlatformIdleStateCallback {
Bookatz50df7112017-08-04 14:53:26 -0700213 public void fillLowPowerStats(RpmStats rpmStats);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700214 public String getPlatformLowPowerStats();
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +0000215 public String getSubsystemLowPowerStats();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700216 }
217
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700218 public static abstract class UserInfoProvider {
219 private int[] userIds;
220 protected abstract @Nullable int[] getUserIds();
Sudheer Shanka38383232017-07-25 09:55:03 -0700221 @VisibleForTesting
222 public final void refreshUserIds() {
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700223 userIds = getUserIds();
224 }
Sudheer Shanka38383232017-07-25 09:55:03 -0700225 @VisibleForTesting
226 public boolean exists(int userId) {
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700227 return userIds != null ? ArrayUtils.contains(userIds, userId) : true;
228 }
229 }
230
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700231 private final PlatformIdleStateCallback mPlatformIdleStateCallback;
232
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700233 final class MyHandler extends Handler {
Jeff Brown6f357d32014-01-15 20:40:55 -0800234 public MyHandler(Looper looper) {
235 super(looper, null, true);
236 }
237
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700238 @Override
239 public void handleMessage(Message msg) {
240 BatteryCallback cb = mCallback;
241 switch (msg.what) {
242 case MSG_UPDATE_WAKELOCKS:
Adam Lesinski72478f02015-06-17 15:39:43 -0700243 synchronized (BatteryStatsImpl.this) {
Sudheer Shankab8ad5942017-08-08 12:16:09 -0700244 updateCpuTimeLocked();
Adam Lesinski72478f02015-06-17 15:39:43 -0700245 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700246 if (cb != null) {
247 cb.batteryNeedsCpuUpdate();
248 }
249 break;
250 case MSG_REPORT_POWER_CHANGE:
251 if (cb != null) {
252 cb.batteryPowerChanged(msg.arg1 != 0);
253 }
254 break;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700255 case MSG_REPORT_CHARGING:
256 if (cb != null) {
257 final String action;
258 synchronized (BatteryStatsImpl.this) {
259 action = mCharging ? BatteryManager.ACTION_CHARGING
260 : BatteryManager.ACTION_DISCHARGING;
261 }
262 Intent intent = new Intent(action);
263 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
264 cb.batterySendBroadcast(intent);
265 }
266 break;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700267 }
268 }
269 }
270
Joe Onoratoabded112016-02-08 16:49:39 -0800271 public interface Clocks {
272 public long elapsedRealtime();
273 public long uptimeMillis();
274 }
275
276 public static class SystemClocks implements Clocks {
277 public long elapsedRealtime() {
278 return SystemClock.elapsedRealtime();
279 }
280
281 public long uptimeMillis() {
282 return SystemClock.uptimeMillis();
283 }
284 }
285
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700286 public interface ExternalStatsSync {
Adam Lesinski14ae39a2017-05-26 11:50:40 -0700287 int UPDATE_CPU = 0x01;
288 int UPDATE_WIFI = 0x02;
289 int UPDATE_RADIO = 0x04;
290 int UPDATE_BT = 0x08;
Bookatz50df7112017-08-04 14:53:26 -0700291 int UPDATE_RPM = 0x10; // 16
292 int UPDATE_ALL = UPDATE_CPU | UPDATE_WIFI | UPDATE_RADIO | UPDATE_BT | UPDATE_RPM;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800293
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700294 Future<?> scheduleSync(String reason, int flags);
295 Future<?> scheduleCpuSyncDueToRemovedUid(int uid);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700296 }
297
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700298 public final MyHandler mHandler;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700299 private ExternalStatsSync mExternalSync = null;
Sudheer Shanka38383232017-07-25 09:55:03 -0700300 @VisibleForTesting
301 protected UserInfoProvider mUserInfoProvider = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700302
303 private BatteryCallback mCallback;
304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800305 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -0800306 * Mapping isolated uids to the actual owning app uid.
307 */
308 final SparseIntArray mIsolatedUids = new SparseIntArray();
309
310 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 * The statistics we have collected organized by uids.
312 */
Adam Lesinski50e47602015-12-04 17:04:54 -0800313 final SparseArray<BatteryStatsImpl.Uid> mUidStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314
315 // A set of pools of currently active timers. When a timer is queried, we will divide the
316 // elapsed time by the number of active timers to arrive at that timer's share of the time.
317 // In order to do this, we must refresh each timer whenever the number of active timers
318 // changes.
Sudheer Shanka38383232017-07-25 09:55:03 -0700319 @VisibleForTesting
320 protected ArrayList<StopwatchTimer> mPartialTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700321 final ArrayList<StopwatchTimer> mFullTimers = new ArrayList<>();
322 final ArrayList<StopwatchTimer> mWindowTimers = new ArrayList<>();
Jeff Brown6a8bd7b2015-06-19 15:07:51 -0700323 final ArrayList<StopwatchTimer> mDrawTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700324 final SparseArray<ArrayList<StopwatchTimer>> mSensorTimers = new SparseArray<>();
325 final ArrayList<StopwatchTimer> mWifiRunningTimers = new ArrayList<>();
326 final ArrayList<StopwatchTimer> mFullWifiLockTimers = new ArrayList<>();
327 final ArrayList<StopwatchTimer> mWifiMulticastTimers = new ArrayList<>();
328 final ArrayList<StopwatchTimer> mWifiScanTimers = new ArrayList<>();
329 final SparseArray<ArrayList<StopwatchTimer>> mWifiBatchedScanTimers = new SparseArray<>();
330 final ArrayList<StopwatchTimer> mAudioTurnedOnTimers = new ArrayList<>();
331 final ArrayList<StopwatchTimer> mVideoTurnedOnTimers = new ArrayList<>();
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700332 final ArrayList<StopwatchTimer> mFlashlightTurnedOnTimers = new ArrayList<>();
333 final ArrayList<StopwatchTimer> mCameraTurnedOnTimers = new ArrayList<>();
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800334 final ArrayList<StopwatchTimer> mBluetoothScanOnTimers = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700336 // Last partial timers we use for distributing CPU usage.
Sudheer Shanka38383232017-07-25 09:55:03 -0700337 @VisibleForTesting
338 protected ArrayList<StopwatchTimer> mLastPartialTimers = new ArrayList<>();
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800340 // These are the objects that will want to do something when the device
341 // is unplugged from power.
Joe Onoratoabded112016-02-08 16:49:39 -0800342 protected final TimeBase mOnBatteryTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800343
344 // These are the objects that will want to do something when the device
Mike Mac2f518a2017-09-19 16:06:03 -0700345 // is unplugged from power *and* the screen is off or doze.
346 protected final TimeBase mOnBatteryScreenOffTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800347
348 // Set to true when we want to distribute CPU across wakelocks for the next
349 // CPU update, even if we aren't currently running wake locks.
350 boolean mDistributeWakelockCpu;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700351
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700352 boolean mShuttingDown;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700353
Dianne Hackborn37de0982014-05-09 09:32:18 -0700354 final HistoryEventTracker mActiveEvents = new HistoryEventTracker();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800355
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700356 long mHistoryBaseTime;
357 boolean mHaveBatteryLevel = false;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700358 boolean mRecordingHistory = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700359 int mNumHistoryItems;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700360
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700361 final Parcel mHistoryBuffer = Parcel.obtain();
362 final HistoryItem mHistoryLastWritten = new HistoryItem();
363 final HistoryItem mHistoryLastLastWritten = new HistoryItem();
Dianne Hackborn1fadab52011-04-14 17:57:33 -0700364 final HistoryItem mHistoryReadTmp = new HistoryItem();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700365 final HistoryItem mHistoryAddTmp = new HistoryItem();
Adam Lesinskie08af192015-03-25 16:42:59 -0700366 final HashMap<HistoryTag, Integer> mHistoryTagPool = new HashMap<>();
Dianne Hackborn099bc622014-01-22 13:39:16 -0800367 String[] mReadHistoryStrings;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -0800368 int[] mReadHistoryUids;
369 int mReadHistoryChars;
370 int mNextHistoryTagIdx = 0;
371 int mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700372 int mHistoryBufferLastPos = -1;
373 boolean mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700374 int mActiveHistoryStates = 0xffffffff;
375 int mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn40c87252014-03-19 16:55:40 -0700376 long mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700377 long mTrackRunningHistoryElapsedRealtime = 0;
378 long mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700379
380 final HistoryItem mHistoryCur = new HistoryItem();
381
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700382 HistoryItem mHistory;
383 HistoryItem mHistoryEnd;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700384 HistoryItem mHistoryLastEnd;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700385 HistoryItem mHistoryCache;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700386
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800387 // Used by computeHistoryStepDetails
388 HistoryStepDetails mLastHistoryStepDetails = null;
389 byte mLastHistoryStepLevel = 0;
390 final HistoryStepDetails mCurHistoryStepDetails = new HistoryStepDetails();
391 final HistoryStepDetails mReadHistoryStepDetails = new HistoryStepDetails();
392 final HistoryStepDetails mTmpHistoryStepDetails = new HistoryStepDetails();
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700393
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800394 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700395 * Total time (in milliseconds) spent executing in user code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800396 */
397 long mLastStepCpuUserTime;
398 long mCurStepCpuUserTime;
399 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700400 * Total time (in milliseconds) spent executing in kernel code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800401 */
402 long mLastStepCpuSystemTime;
403 long mCurStepCpuSystemTime;
404 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700405 * Times from /proc/stat (but measured in milliseconds).
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800406 */
407 long mLastStepStatUserTime;
408 long mLastStepStatSystemTime;
409 long mLastStepStatIOWaitTime;
410 long mLastStepStatIrqTime;
411 long mLastStepStatSoftIrqTime;
412 long mLastStepStatIdleTime;
413 long mCurStepStatUserTime;
414 long mCurStepStatSystemTime;
415 long mCurStepStatIOWaitTime;
416 long mCurStepStatIrqTime;
417 long mCurStepStatSoftIrqTime;
418 long mCurStepStatIdleTime;
419
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700420 private HistoryItem mHistoryIterator;
421 private boolean mReadOverflow;
422 private boolean mIteratingHistory;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 int mStartCount;
425
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800426 long mStartClockTime;
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700427 String mStartPlatformVersion;
428 String mEndPlatformVersion;
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 long mUptime;
431 long mUptimeStart;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800432 long mRealtime;
433 long mRealtimeStart;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700434
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800435 int mWakeLockNesting;
436 boolean mWakeLockImportant;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700437 public boolean mRecordAllHistory;
Dianne Hackborn9a755432014-05-15 17:05:22 -0700438 boolean mNoAutoReset;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800439
Mike Mac2f518a2017-09-19 16:06:03 -0700440 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
441 protected int mScreenState = Display.STATE_UNKNOWN;
442 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
443 protected StopwatchTimer mScreenOnTimer;
444 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
445 protected StopwatchTimer mScreenDozeTimer;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700446
Dianne Hackborn617f8772009-03-31 15:04:46 -0700447 int mScreenBrightnessBin = -1;
Evan Millarc64edde2009-04-18 12:26:32 -0700448 final StopwatchTimer[] mScreenBrightnessTimer = new StopwatchTimer[NUM_SCREEN_BRIGHTNESS_BINS];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700449
Amith Yamasani674c9bb2017-02-01 09:45:17 -0800450 boolean mPretendScreenOff;
451
Jeff Browne95c3cd2014-05-02 16:59:26 -0700452 boolean mInteractive;
453 StopwatchTimer mInteractiveTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700454
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700455 boolean mPowerSaveModeEnabled;
456 StopwatchTimer mPowerSaveModeEnabledTimer;
457
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700458 boolean mDeviceIdling;
459 StopwatchTimer mDeviceIdlingTimer;
460
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700461 boolean mDeviceLightIdling;
462 StopwatchTimer mDeviceLightIdlingTimer;
463
464 int mDeviceIdleMode;
465 long mLastIdleTimeStart;
466 long mLongestLightIdleTime;
467 long mLongestFullIdleTime;
468 StopwatchTimer mDeviceIdleModeLightTimer;
469 StopwatchTimer mDeviceIdleModeFullTimer;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700470
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 boolean mPhoneOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700472 StopwatchTimer mPhoneOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700473
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700474 int mAudioOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700475 StopwatchTimer mAudioOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700476
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700477 int mVideoOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700478 StopwatchTimer mVideoOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700479
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700480 int mFlashlightOnNesting;
Dianne Hackbornabc7c492014-06-30 16:57:46 -0700481 StopwatchTimer mFlashlightOnTimer;
482
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700483 int mCameraOnNesting;
484 StopwatchTimer mCameraOnTimer;
485
Dianne Hackborn627bba72009-03-24 22:32:56 -0700486 int mPhoneSignalStrengthBin = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800487 int mPhoneSignalStrengthBinRaw = -1;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700488 final StopwatchTimer[] mPhoneSignalStrengthsTimer =
Wink Saville52840902011-02-18 12:40:47 -0800489 new StopwatchTimer[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
Amith Yamasanif37447b2009-10-08 18:28:01 -0700490
491 StopwatchTimer mPhoneSignalScanningTimer;
492
Dianne Hackborn627bba72009-03-24 22:32:56 -0700493 int mPhoneDataConnectionType = -1;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700494 final StopwatchTimer[] mPhoneDataConnectionsTimer =
Evan Millarc64edde2009-04-18 12:26:32 -0700495 new StopwatchTimer[NUM_DATA_CONNECTION_TYPES];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700496
Dianne Hackborn57ed6a62013-12-09 18:15:56 -0800497 final LongSamplingCounter[] mNetworkByteActivityCounters =
498 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
499 final LongSamplingCounter[] mNetworkPacketActivityCounters =
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700500 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
501
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800502 /**
503 * The WiFi controller activity (time in tx, rx, idle, and power consumed) for the device.
504 */
505 ControllerActivityCounterImpl mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -0700506
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800507 /**
508 * The Bluetooth controller activity (time in tx, rx, idle, and power consumed) for the device.
509 */
510 ControllerActivityCounterImpl mBluetoothActivity;
511
512 /**
513 * The Modem controller activity (time in tx, rx, idle, and power consumed) for the device.
514 */
515 ControllerActivityCounterImpl mModemActivity;
516
517 /**
518 * Whether the device supports WiFi controller energy reporting. This is set to true on
519 * the first WiFi energy report. See {@link #mWifiActivity}.
520 */
521 boolean mHasWifiReporting = false;
522
523 /**
524 * Whether the device supports Bluetooth controller energy reporting. This is set to true on
525 * the first Bluetooth energy report. See {@link #mBluetoothActivity}.
526 */
527 boolean mHasBluetoothReporting = false;
528
529 /**
530 * Whether the device supports Modem controller energy reporting. This is set to true on
531 * the first Modem energy report. See {@link #mModemActivity}.
532 */
533 boolean mHasModemReporting = false;
Adam Lesinski33dac552015-03-09 15:24:48 -0700534
The Android Open Source Project10592532009-03-18 17:39:46 -0700535 boolean mWifiOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700536 StopwatchTimer mWifiOnTimer;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -0700537
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700538 boolean mGlobalWifiRunning;
539 StopwatchTimer mGlobalWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700540
Dianne Hackbornca1bf212014-02-14 14:18:36 -0800541 int mWifiState = -1;
542 final StopwatchTimer[] mWifiStateTimer = new StopwatchTimer[NUM_WIFI_STATES];
543
Dianne Hackborn3251b902014-06-20 14:40:53 -0700544 int mWifiSupplState = -1;
545 final StopwatchTimer[] mWifiSupplStateTimer = new StopwatchTimer[NUM_WIFI_SUPPL_STATES];
546
547 int mWifiSignalStrengthBin = -1;
548 final StopwatchTimer[] mWifiSignalStrengthsTimer =
549 new StopwatchTimer[NUM_WIFI_SIGNAL_STRENGTH_BINS];
550
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800551 int mBluetoothScanNesting;
Bookatz867c0d72017-03-07 18:23:42 -0800552 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
553 protected StopwatchTimer mBluetoothScanTimer;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800554
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700555 int mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackbornf7097a52014-05-13 09:56:14 -0700556 long mMobileRadioActiveStartTime;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800557 StopwatchTimer mMobileRadioActiveTimer;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800558 StopwatchTimer mMobileRadioActivePerAppTimer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700559 LongSamplingCounter mMobileRadioActiveAdjustedTime;
Dianne Hackbornd45665b2014-02-26 12:35:32 -0800560 LongSamplingCounter mMobileRadioActiveUnknownTime;
561 LongSamplingCounter mMobileRadioActiveUnknownCount;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800562
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700563 int mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800565 /**
566 * These provide time bases that discount the time the device is plugged
567 * in to power.
568 */
569 boolean mOnBattery;
Sudheer Shanka38383232017-07-25 09:55:03 -0700570 @VisibleForTesting
571 protected boolean mOnBatteryInternal;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700572
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700573 /**
574 * External reporting of whether the device is actually charging.
575 */
576 boolean mCharging = true;
577 int mLastChargingStateLevel;
578
The Android Open Source Project10592532009-03-18 17:39:46 -0700579 /*
580 * These keep track of battery levels (1-100) at the last plug event and the last unplug event.
581 */
Evan Millar633a1742009-04-02 16:36:33 -0700582 int mDischargeStartLevel;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700583 int mDischargeUnplugLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700584 int mDischargePlugLevel;
Evan Millar633a1742009-04-02 16:36:33 -0700585 int mDischargeCurrentLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700586 int mCurrentBatteryLevel;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -0700587 int mLowDischargeAmountSinceCharge;
588 int mHighDischargeAmountSinceCharge;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800589 int mDischargeScreenOnUnplugLevel;
590 int mDischargeScreenOffUnplugLevel;
Mike Mac2f518a2017-09-19 16:06:03 -0700591 int mDischargeScreenDozeUnplugLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800592 int mDischargeAmountScreenOn;
593 int mDischargeAmountScreenOnSinceCharge;
594 int mDischargeAmountScreenOff;
595 int mDischargeAmountScreenOffSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -0700596 int mDischargeAmountScreenDoze;
597 int mDischargeAmountScreenDozeSinceCharge;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700598
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700599 private LongSamplingCounter mDischargeScreenOffCounter;
Mike Mac2f518a2017-09-19 16:06:03 -0700600 private LongSamplingCounter mDischargeScreenDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700601 private LongSamplingCounter mDischargeCounter;
602
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700603 static final int MAX_LEVEL_STEPS = 200;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700604
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700605 int mInitStepMode = 0;
606 int mCurStepMode = 0;
607 int mModStepMode = 0;
608
Dianne Hackborn260c5022014-04-29 11:23:16 -0700609 int mLastDischargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700610 int mMinDischargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800611 final LevelStepTracker mDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
612 final LevelStepTracker mDailyDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700613 ArrayList<PackageChange> mDailyPackageChanges;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700614
615 int mLastChargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700616 int mMaxChargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800617 final LevelStepTracker mChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
618 final LevelStepTracker mDailyChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
619
620 static final int MAX_DAILY_ITEMS = 10;
621
622 long mDailyStartTime = 0;
623 long mNextMinDailyDeadline = 0;
624 long mNextMaxDailyDeadline = 0;
625
626 final ArrayList<DailyItem> mDailyItems = new ArrayList<>();
Dianne Hackborn260c5022014-04-29 11:23:16 -0700627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628 long mLastWriteTime = 0; // Milliseconds
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700629
Amith Yamasanif37447b2009-10-08 18:28:01 -0700630 private int mPhoneServiceState = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800631 private int mPhoneServiceStateRaw = -1;
632 private int mPhoneSimStateRaw = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -0700633
Dianne Hackborn1e01d162014-12-04 17:46:42 -0800634 private int mNumConnectivityChange;
635 private int mLoadedNumConnectivityChange;
636 private int mUnpluggedNumConnectivityChange;
637
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700638 private int mEstimatedBatteryCapacity = -1;
639
Jocelyn Dangc627d102017-04-14 13:15:14 -0700640 private int mMinLearnedBatteryCapacity = -1;
641 private int mMaxLearnedBatteryCapacity = -1;
Adam Lesinski041d9172016-12-12 12:03:56 -0800642
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700643 private long[] mCpuFreqs;
644
Sudheer Shanka38383232017-07-25 09:55:03 -0700645 @VisibleForTesting
646 protected PowerProfile mPowerProfile;
Adam Lesinskie08af192015-03-25 16:42:59 -0700647
Evan Millarc64edde2009-04-18 12:26:32 -0700648 /*
Bookatz50df7112017-08-04 14:53:26 -0700649 * Holds a SamplingTimer associated with each Resource Power Manager state and voter,
650 * recording their times when on-battery (regardless of screen state).
651 */
652 private final HashMap<String, SamplingTimer> mRpmStats = new HashMap<>();
653 /** Times for each Resource Power Manager state and voter when screen-off and on-battery. */
654 private final HashMap<String, SamplingTimer> mScreenOffRpmStats = new HashMap<>();
655
656 @Override
657 public Map<String, ? extends Timer> getRpmStats() {
658 return mRpmStats;
659 }
660
Bookatz82b341172017-09-07 19:06:08 -0700661 // TODO: Note: screenOffRpmStats has been disabled via SCREEN_OFF_RPM_STATS_ENABLED.
Bookatz50df7112017-08-04 14:53:26 -0700662 @Override
663 public Map<String, ? extends Timer> getScreenOffRpmStats() {
664 return mScreenOffRpmStats;
665 }
666
667 /*
Evan Millarc64edde2009-04-18 12:26:32 -0700668 * Holds a SamplingTimer associated with each kernel wakelock name being tracked.
669 */
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700670 private final HashMap<String, SamplingTimer> mKernelWakelockStats = new HashMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700671
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700672 public Map<String, ? extends Timer> getKernelWakelockStats() {
Evan Millarc64edde2009-04-18 12:26:32 -0700673 return mKernelWakelockStats;
674 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700675
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700676 String mLastWakeupReason = null;
677 long mLastWakeupUptimeMs = 0;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700678 private final HashMap<String, SamplingTimer> mWakeupReasonStats = new HashMap<>();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700679
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700680 public Map<String, ? extends Timer> getWakeupReasonStats() {
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700681 return mWakeupReasonStats;
682 }
683
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700684 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700685 public long getUahDischarge(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700686 return mDischargeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700687 }
688
689 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700690 public long getUahDischargeScreenOff(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700691 return mDischargeScreenOffCounter.getCountLocked(which);
692 }
693
694 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700695 public long getUahDischargeScreenDoze(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700696 return mDischargeScreenDozeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700697 }
698
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700699 @Override
700 public int getEstimatedBatteryCapacity() {
701 return mEstimatedBatteryCapacity;
702 }
703
Jocelyn Dangc627d102017-04-14 13:15:14 -0700704 @Override
705 public int getMinLearnedBatteryCapacity() {
706 return mMinLearnedBatteryCapacity;
707 }
708
709 @Override
710 public int getMaxLearnedBatteryCapacity() {
711 return mMaxLearnedBatteryCapacity;
712 }
713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 public BatteryStatsImpl() {
Joe Onoratoabded112016-02-08 16:49:39 -0800715 this(new SystemClocks());
716 }
717
718 public BatteryStatsImpl(Clocks clocks) {
719 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700720 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700721 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800722 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700723 mHandler = null;
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700724 mPlatformIdleStateCallback = null;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700725 mUserInfoProvider = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700726 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 }
728
Joe Onoratoabded112016-02-08 16:49:39 -0800729 private void init(Clocks clocks) {
730 mClocks = clocks;
Joe Onoratoabded112016-02-08 16:49:39 -0800731 }
732
Adam Lesinski14ae39a2017-05-26 11:50:40 -0700733 public interface TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800734 void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime);
735 void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime);
736 }
737
Joe Onoratoabded112016-02-08 16:49:39 -0800738 // methods are protected not private to be VisibleForTesting
739 public static class TimeBase {
740 protected final ArrayList<TimeBaseObs> mObservers = new ArrayList<>();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800741
Joe Onoratoabded112016-02-08 16:49:39 -0800742 protected long mUptime;
743 protected long mRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800744
Joe Onoratoabded112016-02-08 16:49:39 -0800745 protected boolean mRunning;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800746
Joe Onoratoabded112016-02-08 16:49:39 -0800747 protected long mPastUptime;
748 protected long mUptimeStart;
749 protected long mPastRealtime;
750 protected long mRealtimeStart;
751 protected long mUnpluggedUptime;
752 protected long mUnpluggedRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800753
754 public void dump(PrintWriter pw, String prefix) {
755 StringBuilder sb = new StringBuilder(128);
756 pw.print(prefix); pw.print("mRunning="); pw.println(mRunning);
757 sb.setLength(0);
758 sb.append(prefix);
759 sb.append("mUptime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -0700760 formatTimeMs(sb, mUptime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800761 pw.println(sb.toString());
762 sb.setLength(0);
763 sb.append(prefix);
764 sb.append("mRealtime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -0700765 formatTimeMs(sb, mRealtime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800766 pw.println(sb.toString());
767 sb.setLength(0);
768 sb.append(prefix);
769 sb.append("mPastUptime=");
770 formatTimeMs(sb, mPastUptime / 1000); sb.append("mUptimeStart=");
771 formatTimeMs(sb, mUptimeStart / 1000);
772 sb.append("mUnpluggedUptime="); formatTimeMs(sb, mUnpluggedUptime / 1000);
773 pw.println(sb.toString());
774 sb.setLength(0);
775 sb.append(prefix);
776 sb.append("mPastRealtime=");
777 formatTimeMs(sb, mPastRealtime / 1000); sb.append("mRealtimeStart=");
778 formatTimeMs(sb, mRealtimeStart / 1000);
779 sb.append("mUnpluggedRealtime="); formatTimeMs(sb, mUnpluggedRealtime / 1000);
780 pw.println(sb.toString());
781 }
782
783 public void add(TimeBaseObs observer) {
784 mObservers.add(observer);
785 }
786
787 public void remove(TimeBaseObs observer) {
788 if (!mObservers.remove(observer)) {
789 Slog.wtf(TAG, "Removed unknown observer: " + observer);
790 }
791 }
792
Joe Onoratoabded112016-02-08 16:49:39 -0800793 public boolean hasObserver(TimeBaseObs observer) {
794 return mObservers.contains(observer);
795 }
796
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800797 public void init(long uptime, long realtime) {
798 mRealtime = 0;
799 mUptime = 0;
800 mPastUptime = 0;
801 mPastRealtime = 0;
802 mUptimeStart = uptime;
803 mRealtimeStart = realtime;
804 mUnpluggedUptime = getUptime(mUptimeStart);
805 mUnpluggedRealtime = getRealtime(mRealtimeStart);
806 }
807
808 public void reset(long uptime, long realtime) {
809 if (!mRunning) {
810 mPastUptime = 0;
811 mPastRealtime = 0;
812 } else {
813 mUptimeStart = uptime;
814 mRealtimeStart = realtime;
Joe Onoratoabded112016-02-08 16:49:39 -0800815 // TODO: Since mUptimeStart was just reset and we are running, getUptime will
816 // just return mPastUptime. Also, are we sure we don't want to reset that?
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800817 mUnpluggedUptime = getUptime(uptime);
Joe Onoratoabded112016-02-08 16:49:39 -0800818 // TODO: likewise.
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800819 mUnpluggedRealtime = getRealtime(realtime);
820 }
821 }
822
823 public long computeUptime(long curTime, int which) {
824 switch (which) {
825 case STATS_SINCE_CHARGED:
826 return mUptime + getUptime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800827 case STATS_CURRENT:
828 return getUptime(curTime);
829 case STATS_SINCE_UNPLUGGED:
830 return getUptime(curTime) - mUnpluggedUptime;
831 }
832 return 0;
833 }
834
835 public long computeRealtime(long curTime, int which) {
836 switch (which) {
837 case STATS_SINCE_CHARGED:
838 return mRealtime + getRealtime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800839 case STATS_CURRENT:
840 return getRealtime(curTime);
841 case STATS_SINCE_UNPLUGGED:
842 return getRealtime(curTime) - mUnpluggedRealtime;
843 }
844 return 0;
845 }
846
847 public long getUptime(long curTime) {
848 long time = mPastUptime;
849 if (mRunning) {
850 time += curTime - mUptimeStart;
851 }
852 return time;
853 }
854
855 public long getRealtime(long curTime) {
856 long time = mPastRealtime;
857 if (mRunning) {
858 time += curTime - mRealtimeStart;
859 }
860 return time;
861 }
862
863 public long getUptimeStart() {
864 return mUptimeStart;
865 }
866
867 public long getRealtimeStart() {
868 return mRealtimeStart;
869 }
870
871 public boolean isRunning() {
872 return mRunning;
873 }
874
875 public boolean setRunning(boolean running, long uptime, long realtime) {
876 if (mRunning != running) {
877 mRunning = running;
878 if (running) {
879 mUptimeStart = uptime;
880 mRealtimeStart = realtime;
881 long batteryUptime = mUnpluggedUptime = getUptime(uptime);
882 long batteryRealtime = mUnpluggedRealtime = getRealtime(realtime);
883
884 for (int i = mObservers.size() - 1; i >= 0; i--) {
885 mObservers.get(i).onTimeStarted(realtime, batteryUptime, batteryRealtime);
886 }
887 } else {
888 mPastUptime += uptime - mUptimeStart;
889 mPastRealtime += realtime - mRealtimeStart;
890
891 long batteryUptime = getUptime(uptime);
892 long batteryRealtime = getRealtime(realtime);
893
894 for (int i = mObservers.size() - 1; i >= 0; i--) {
895 mObservers.get(i).onTimeStopped(realtime, batteryUptime, batteryRealtime);
896 }
897 }
898 return true;
899 }
900 return false;
901 }
902
903 public void readSummaryFromParcel(Parcel in) {
904 mUptime = in.readLong();
905 mRealtime = in.readLong();
906 }
907
908 public void writeSummaryToParcel(Parcel out, long uptime, long realtime) {
909 out.writeLong(computeUptime(uptime, STATS_SINCE_CHARGED));
910 out.writeLong(computeRealtime(realtime, STATS_SINCE_CHARGED));
911 }
912
913 public void readFromParcel(Parcel in) {
914 mRunning = false;
915 mUptime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800916 mPastUptime = in.readLong();
917 mUptimeStart = in.readLong();
Dianne Hackbornef640cd2014-03-25 14:41:05 -0700918 mRealtime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800919 mPastRealtime = in.readLong();
920 mRealtimeStart = in.readLong();
921 mUnpluggedUptime = in.readLong();
922 mUnpluggedRealtime = in.readLong();
923 }
924
925 public void writeToParcel(Parcel out, long uptime, long realtime) {
926 final long runningUptime = getUptime(uptime);
927 final long runningRealtime = getRealtime(realtime);
928 out.writeLong(mUptime);
929 out.writeLong(runningUptime);
930 out.writeLong(mUptimeStart);
Dianne Hackbornef640cd2014-03-25 14:41:05 -0700931 out.writeLong(mRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800932 out.writeLong(runningRealtime);
933 out.writeLong(mRealtimeStart);
934 out.writeLong(mUnpluggedUptime);
935 out.writeLong(mUnpluggedRealtime);
936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 /**
Dianne Hackborn617f8772009-03-31 15:04:46 -0700940 * State for keeping track of counting information.
941 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800942 public static class Counter extends BatteryStats.Counter implements TimeBaseObs {
Christopher Tate4cee7252010-03-19 14:50:40 -0700943 final AtomicInteger mCount = new AtomicInteger();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800944 final TimeBase mTimeBase;
Dianne Hackborn617f8772009-03-31 15:04:46 -0700945 int mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -0700946 int mUnpluggedCount;
947 int mPluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700948
Bookatz8c6f3c52017-05-24 12:00:17 -0700949 public Counter(TimeBase timeBase, Parcel in) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800950 mTimeBase = timeBase;
Christopher Tate4cee7252010-03-19 14:50:40 -0700951 mPluggedCount = in.readInt();
952 mCount.set(mPluggedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -0700953 mLoadedCount = in.readInt();
Dianne Hackborn617f8772009-03-31 15:04:46 -0700954 mUnpluggedCount = in.readInt();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800955 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -0700956 }
957
Bookatz8c6f3c52017-05-24 12:00:17 -0700958 public Counter(TimeBase timeBase) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800959 mTimeBase = timeBase;
960 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -0700961 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700962
Dianne Hackborn617f8772009-03-31 15:04:46 -0700963 public void writeToParcel(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -0700964 out.writeInt(mCount.get());
Dianne Hackborn617f8772009-03-31 15:04:46 -0700965 out.writeInt(mLoadedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -0700966 out.writeInt(mUnpluggedCount);
967 }
968
Bookatz8c6f3c52017-05-24 12:00:17 -0700969 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800970 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -0700971 mUnpluggedCount = mPluggedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -0700972 }
973
Bookatz8c6f3c52017-05-24 12:00:17 -0700974 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800975 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -0700976 mPluggedCount = mCount.get();
Dianne Hackborn617f8772009-03-31 15:04:46 -0700977 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700978
Dianne Hackborn617f8772009-03-31 15:04:46 -0700979 /**
980 * Writes a possibly null Counter to a Parcel.
981 *
982 * @param out the Parcel to be written to.
983 * @param counter a Counter, or null.
984 */
985 public static void writeCounterToParcel(Parcel out, Counter counter) {
986 if (counter == null) {
987 out.writeInt(0); // indicates null
988 return;
989 }
990 out.writeInt(1); // indicates non-null
991
992 counter.writeToParcel(out);
993 }
994
995 @Override
Evan Millarc64edde2009-04-18 12:26:32 -0700996 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -0700997 int val = mCount.get();
998 if (which == STATS_SINCE_UNPLUGGED) {
999 val -= mUnpluggedCount;
1000 } else if (which != STATS_SINCE_CHARGED) {
1001 val -= mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001002 }
1003
1004 return val;
1005 }
1006
1007 public void logState(Printer pw, String prefix) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001008 pw.println(prefix + "mCount=" + mCount.get()
Bookatz8c6f3c52017-05-24 12:00:17 -07001009 + " mLoadedCount=" + mLoadedCount
Dianne Hackborn617f8772009-03-31 15:04:46 -07001010 + " mUnpluggedCount=" + mUnpluggedCount
1011 + " mPluggedCount=" + mPluggedCount);
1012 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001013
Bookatz8c6f3c52017-05-24 12:00:17 -07001014 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1015 public void stepAtomic() {
1016 if (mTimeBase.isRunning()) {
1017 mCount.incrementAndGet();
1018 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001019 }
1020
Bookatz4ebc0642017-05-11 12:21:19 -07001021 void addAtomic(int delta) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001022 if (mTimeBase.isRunning()) {
1023 mCount.addAndGet(delta);
1024 }
Bookatz4ebc0642017-05-11 12:21:19 -07001025 }
1026
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001027 /**
1028 * Clear state of this counter.
1029 */
1030 void reset(boolean detachIfReset) {
1031 mCount.set(0);
Bookatz8c6f3c52017-05-24 12:00:17 -07001032 mLoadedCount = mPluggedCount = mUnpluggedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001033 if (detachIfReset) {
1034 detach();
1035 }
1036 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001037
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001038 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001039 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001040 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001041
Bookatz8c6f3c52017-05-24 12:00:17 -07001042 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1043 public void writeSummaryFromParcelLocked(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001044 int count = mCount.get();
1045 out.writeInt(count);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001046 }
1047
Bookatz8c6f3c52017-05-24 12:00:17 -07001048 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1049 public void readSummaryFromParcelLocked(Parcel in) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001050 mLoadedCount = in.readInt();
1051 mCount.set(mLoadedCount);
Christopher Tate4cee7252010-03-19 14:50:40 -07001052 mUnpluggedCount = mPluggedCount = mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001053 }
1054 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07001055
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001056 @VisibleForTesting
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001057 public static class LongSamplingCounterArray extends LongCounterArray implements TimeBaseObs {
1058 final TimeBase mTimeBase;
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001059 public long[] mCounts;
1060 public long[] mLoadedCounts;
1061 public long[] mUnpluggedCounts;
1062 public long[] mPluggedCounts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001063
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001064 private LongSamplingCounterArray(TimeBase timeBase, Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001065 mTimeBase = timeBase;
1066 mPluggedCounts = in.createLongArray();
1067 mCounts = copyArray(mPluggedCounts, mCounts);
1068 mLoadedCounts = in.createLongArray();
1069 mUnpluggedCounts = in.createLongArray();
1070 timeBase.add(this);
1071 }
1072
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001073 public LongSamplingCounterArray(TimeBase timeBase) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001074 mTimeBase = timeBase;
1075 timeBase.add(this);
1076 }
1077
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001078 private void writeToParcel(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001079 out.writeLongArray(mCounts);
1080 out.writeLongArray(mLoadedCounts);
1081 out.writeLongArray(mUnpluggedCounts);
1082 }
1083
1084 @Override
1085 public void onTimeStarted(long elapsedRealTime, long baseUptime, long baseRealtime) {
1086 mUnpluggedCounts = copyArray(mPluggedCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001087 }
1088
1089 @Override
1090 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
1091 mPluggedCounts = copyArray(mCounts, mPluggedCounts);
1092 }
1093
1094 @Override
1095 public long[] getCountsLocked(int which) {
1096 long[] val = copyArray(mTimeBase.isRunning() ? mCounts : mPluggedCounts, null);
1097 if (which == STATS_SINCE_UNPLUGGED) {
1098 subtract(val, mUnpluggedCounts);
1099 } else if (which != STATS_SINCE_CHARGED) {
1100 subtract(val, mLoadedCounts);
1101 }
1102 return val;
1103 }
1104
1105 @Override
1106 public void logState(Printer pw, String prefix) {
1107 pw.println(prefix + "mCounts=" + Arrays.toString(mCounts)
1108 + " mLoadedCounts=" + Arrays.toString(mLoadedCounts)
1109 + " mUnpluggedCounts=" + Arrays.toString(mUnpluggedCounts)
1110 + " mPluggedCounts=" + Arrays.toString(mPluggedCounts));
1111 }
1112
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001113 public void addCountLocked(long[] counts) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001114 if (counts == null) {
1115 return;
1116 }
Bookatz8c6f3c52017-05-24 12:00:17 -07001117 if (mTimeBase.isRunning()) {
1118 if (mCounts == null) {
1119 mCounts = new long[counts.length];
1120 }
1121 for (int i = 0; i < counts.length; ++i) {
1122 mCounts[i] += counts[i];
1123 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001124 }
1125 }
1126
Sudheer Shankab8ad5942017-08-08 12:16:09 -07001127 public int getSize() {
1128 return mCounts == null ? 0 : mCounts.length;
1129 }
1130
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001131 /**
1132 * Clear state of this counter.
1133 */
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001134 public void reset(boolean detachIfReset) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001135 fillArray(mCounts, 0);
1136 fillArray(mLoadedCounts, 0);
1137 fillArray(mPluggedCounts, 0);
1138 fillArray(mUnpluggedCounts, 0);
1139 if (detachIfReset) {
1140 detach();
1141 }
1142 }
1143
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001144 public void detach() {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001145 mTimeBase.remove(this);
1146 }
1147
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001148 private void writeSummaryToParcelLocked(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001149 out.writeLongArray(mCounts);
1150 }
1151
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001152 private void readSummaryFromParcelLocked(Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001153 mCounts = in.createLongArray();
1154 mLoadedCounts = copyArray(mCounts, mLoadedCounts);
1155 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
1156 mPluggedCounts = copyArray(mCounts, mPluggedCounts);
1157 }
1158
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001159 public static void writeToParcel(Parcel out, LongSamplingCounterArray counterArray) {
1160 if (counterArray != null) {
1161 out.writeInt(1);
1162 counterArray.writeToParcel(out);
1163 } else {
1164 out.writeInt(0);
1165 }
1166 }
1167
1168 public static LongSamplingCounterArray readFromParcel(Parcel in, TimeBase timeBase) {
1169 if (in.readInt() != 0) {
1170 return new LongSamplingCounterArray(timeBase, in);
1171 } else {
1172 return null;
1173 }
1174 }
1175
1176 public static void writeSummaryToParcelLocked(Parcel out,
1177 LongSamplingCounterArray counterArray) {
1178 if (counterArray != null) {
1179 out.writeInt(1);
1180 counterArray.writeSummaryToParcelLocked(out);
1181 } else {
1182 out.writeInt(0);
1183 }
1184 }
1185
1186 public static LongSamplingCounterArray readSummaryFromParcelLocked(Parcel in,
1187 TimeBase timeBase) {
1188 if (in.readInt() != 0) {
1189 final LongSamplingCounterArray counterArray
1190 = new LongSamplingCounterArray(timeBase);
1191 counterArray.readSummaryFromParcelLocked(in);
1192 return counterArray;
1193 } else {
1194 return null;
1195 }
1196 }
1197
Bookatz8c6f3c52017-05-24 12:00:17 -07001198 private static void fillArray(long[] a, long val) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001199 if (a != null) {
1200 Arrays.fill(a, val);
1201 }
1202 }
1203
Bookatz8c6f3c52017-05-24 12:00:17 -07001204 private static void subtract(@NonNull long[] val, long[] toSubtract) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001205 if (toSubtract == null) {
1206 return;
1207 }
1208 for (int i = 0; i < val.length; i++) {
1209 val[i] -= toSubtract[i];
1210 }
1211 }
1212
Bookatz8c6f3c52017-05-24 12:00:17 -07001213 private static long[] copyArray(long[] src, long[] dest) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001214 if (src == null) {
1215 return null;
1216 } else {
1217 if (dest == null) {
1218 dest = new long[src.length];
1219 }
1220 System.arraycopy(src, 0, dest, 0, src.length);
1221 return dest;
1222 }
1223 }
1224 }
1225
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001226 public static class LongSamplingCounter extends LongCounter implements TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001227 final TimeBase mTimeBase;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001228 long mCount;
1229 long mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001230 long mUnpluggedCount;
1231 long mPluggedCount;
1232
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001233 LongSamplingCounter(TimeBase timeBase, Parcel in) {
1234 mTimeBase = timeBase;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001235 mPluggedCount = in.readLong();
1236 mCount = mPluggedCount;
1237 mLoadedCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001238 mUnpluggedCount = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001239 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001240 }
1241
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001242 LongSamplingCounter(TimeBase timeBase) {
1243 mTimeBase = timeBase;
1244 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001245 }
1246
1247 public void writeToParcel(Parcel out) {
1248 out.writeLong(mCount);
1249 out.writeLong(mLoadedCount);
1250 out.writeLong(mUnpluggedCount);
1251 }
1252
1253 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001254 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001255 mUnpluggedCount = mPluggedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001256 }
1257
1258 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001259 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001260 mPluggedCount = mCount;
1261 }
1262
1263 public long getCountLocked(int which) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001264 long val = mTimeBase.isRunning() ? mCount : mPluggedCount;
Dianne Hackborn4590e522014-03-24 13:36:46 -07001265 if (which == STATS_SINCE_UNPLUGGED) {
1266 val -= mUnpluggedCount;
1267 } else if (which != STATS_SINCE_CHARGED) {
1268 val -= mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001269 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001270 return val;
1271 }
1272
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001273 @Override
1274 public void logState(Printer pw, String prefix) {
1275 pw.println(prefix + "mCount=" + mCount
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001276 + " mLoadedCount=" + mLoadedCount
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001277 + " mUnpluggedCount=" + mUnpluggedCount
1278 + " mPluggedCount=" + mPluggedCount);
1279 }
1280
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001281 void addCountLocked(long count) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001282 if (mTimeBase.isRunning()) {
1283 mCount += count;
1284 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001285 }
1286
1287 /**
1288 * Clear state of this counter.
1289 */
1290 void reset(boolean detachIfReset) {
1291 mCount = 0;
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001292 mLoadedCount = mPluggedCount = mUnpluggedCount = 0;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001293 if (detachIfReset) {
1294 detach();
1295 }
1296 }
1297
1298 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001299 mTimeBase.remove(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001300 }
1301
1302 void writeSummaryFromParcelLocked(Parcel out) {
1303 out.writeLong(mCount);
1304 }
1305
1306 void readSummaryFromParcelLocked(Parcel in) {
1307 mLoadedCount = in.readLong();
1308 mCount = mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001309 mUnpluggedCount = mPluggedCount = mLoadedCount;
1310 }
1311 }
1312
Dianne Hackborn617f8772009-03-31 15:04:46 -07001313 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 * State for keeping track of timing information.
1315 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001316 public static abstract class Timer extends BatteryStats.Timer implements TimeBaseObs {
Joe Onoratoabded112016-02-08 16:49:39 -08001317 protected final Clocks mClocks;
1318 protected final int mType;
1319 protected final TimeBase mTimeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001320
Joe Onoratoabded112016-02-08 16:49:39 -08001321 protected int mCount;
1322 protected int mLoadedCount;
1323 protected int mLastCount;
1324 protected int mUnpluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 // Times are in microseconds for better accuracy when dividing by the
1327 // lock count, and are in "battery realtime" units.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 /**
1330 * The total time we have accumulated since the start of the original
1331 * boot, to the last time something interesting happened in the
1332 * current run.
1333 */
Joe Onoratoabded112016-02-08 16:49:39 -08001334 protected long mTotalTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 /**
1337 * The total time we loaded for the previous runs. Subtract this from
1338 * mTotalTime to find the time for the current run of the system.
1339 */
Joe Onoratoabded112016-02-08 16:49:39 -08001340 protected long mLoadedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342 /**
1343 * The run time of the last run of the system, as loaded from the
1344 * saved data.
1345 */
Joe Onoratoabded112016-02-08 16:49:39 -08001346 protected long mLastTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 /**
1349 * The value of mTotalTime when unplug() was last called. Subtract
1350 * this from mTotalTime to find the time since the last unplug from
1351 * power.
1352 */
Joe Onoratoabded112016-02-08 16:49:39 -08001353 protected long mUnpluggedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001354
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001355 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07001356 * The total time this timer has been running until the latest mark has been set.
1357 * Subtract this from mTotalTime to get the time spent running since the mark was set.
1358 */
Joe Onoratoabded112016-02-08 16:49:39 -08001359 protected long mTimeBeforeMark;
Adam Lesinskie08af192015-03-25 16:42:59 -07001360
1361 /**
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001362 * Constructs from a parcel.
1363 * @param type
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001364 * @param timeBase
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001365 * @param in
1366 */
Joe Onoratoabded112016-02-08 16:49:39 -08001367 public Timer(Clocks clocks, int type, TimeBase timeBase, Parcel in) {
1368 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001370 mTimeBase = timeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 mCount = in.readInt();
1373 mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001374 mLastCount = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 mUnpluggedCount = in.readInt();
1376 mTotalTime = in.readLong();
1377 mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001378 mLastTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 mUnpluggedTime = in.readLong();
Adam Lesinskie08af192015-03-25 16:42:59 -07001380 mTimeBeforeMark = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001381 timeBase.add(this);
Dianne Hackborn29325132014-05-21 15:01:03 -07001382 if (DEBUG) Log.i(TAG, "**** READ TIMER #" + mType + ": mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 }
1384
Joe Onoratoabded112016-02-08 16:49:39 -08001385 public Timer(Clocks clocks, int type, TimeBase timeBase) {
1386 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001388 mTimeBase = timeBase;
1389 timeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 }
Evan Millarc64edde2009-04-18 12:26:32 -07001391
1392 protected abstract long computeRunTimeLocked(long curBatteryRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001393
Evan Millarc64edde2009-04-18 12:26:32 -07001394 protected abstract int computeCurrentCountLocked();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001395
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001396 /**
1397 * Clear state of this timer. Returns true if the timer is inactive
1398 * so can be completely dropped.
1399 */
Joe Onoratoabded112016-02-08 16:49:39 -08001400 public boolean reset(boolean detachIfReset) {
Adam Lesinskie08af192015-03-25 16:42:59 -07001401 mTotalTime = mLoadedTime = mLastTime = mTimeBeforeMark = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001402 mCount = mLoadedCount = mLastCount = 0;
1403 if (detachIfReset) {
1404 detach();
1405 }
1406 return true;
1407 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001408
Joe Onoratoabded112016-02-08 16:49:39 -08001409 public void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001410 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001411 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001412
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001413 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn29325132014-05-21 15:01:03 -07001414 if (DEBUG) Log.i(TAG, "**** WRITING TIMER #" + mType + ": mTotalTime="
1415 + computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
Adam Lesinski98f0d462016-04-19 16:46:20 -07001416 out.writeInt(computeCurrentCountLocked());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 out.writeInt(mLoadedCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 out.writeInt(mUnpluggedCount);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001419 out.writeLong(computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 out.writeLong(mLoadedTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 out.writeLong(mUnpluggedTime);
Adam Lesinskie08af192015-03-25 16:42:59 -07001422 out.writeLong(mTimeBeforeMark);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 }
1424
Adam Lesinskie08af192015-03-25 16:42:59 -07001425 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001426 public void onTimeStarted(long elapsedRealtime, long timeBaseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001428 Log.v(TAG, "unplug #" + mType + ": realtime=" + baseRealtime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 + " old mUnpluggedTime=" + mUnpluggedTime
1430 + " old mUnpluggedCount=" + mUnpluggedCount);
1431 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001432 mUnpluggedTime = computeRunTimeLocked(baseRealtime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001433 mUnpluggedCount = computeCurrentCountLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 if (DEBUG && mType < 0) {
1435 Log.v(TAG, "unplug #" + mType
1436 + ": new mUnpluggedTime=" + mUnpluggedTime
1437 + " new mUnpluggedCount=" + mUnpluggedCount);
1438 }
1439 }
1440
Adam Lesinskie08af192015-03-25 16:42:59 -07001441 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001442 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07001443 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001444 Log.v(TAG, "plug #" + mType + ": realtime=" + baseRealtime
Evan Millarc64edde2009-04-18 12:26:32 -07001445 + " old mTotalTime=" + mTotalTime);
1446 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001447 mTotalTime = computeRunTimeLocked(baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001448 mCount = computeCurrentCountLocked();
1449 if (DEBUG && mType < 0) {
1450 Log.v(TAG, "plug #" + mType
1451 + ": new mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 }
1453 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 /**
1456 * Writes a possibly null Timer to a Parcel.
1457 *
1458 * @param out the Parcel to be written to.
1459 * @param timer a Timer, or null.
1460 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001461 public static void writeTimerToParcel(Parcel out, Timer timer, long elapsedRealtimeUs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 if (timer == null) {
1463 out.writeInt(0); // indicates null
1464 return;
1465 }
1466 out.writeInt(1); // indicates non-null
1467
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001468 timer.writeToParcel(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 }
1470
1471 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001472 public long getTotalTimeLocked(long elapsedRealtimeUs, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001473 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1474 if (which == STATS_SINCE_UNPLUGGED) {
1475 val -= mUnpluggedTime;
1476 } else if (which != STATS_SINCE_CHARGED) {
1477 val -= mLoadedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 }
1479
1480 return val;
1481 }
1482
1483 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001484 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001485 int val = computeCurrentCountLocked();
1486 if (which == STATS_SINCE_UNPLUGGED) {
1487 val -= mUnpluggedCount;
1488 } else if (which != STATS_SINCE_CHARGED) {
1489 val -= mLoadedCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 }
1491
1492 return val;
1493 }
1494
Adam Lesinskie08af192015-03-25 16:42:59 -07001495 @Override
1496 public long getTimeSinceMarkLocked(long elapsedRealtimeUs) {
1497 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1498 return val - mTimeBeforeMark;
1499 }
1500
1501 @Override
Dianne Hackborn627bba72009-03-24 22:32:56 -07001502 public void logState(Printer pw, String prefix) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07001503 pw.println(prefix + "mCount=" + mCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 + " mLoadedCount=" + mLoadedCount + " mLastCount=" + mLastCount
1505 + " mUnpluggedCount=" + mUnpluggedCount);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001506 pw.println(prefix + "mTotalTime=" + mTotalTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 + " mLoadedTime=" + mLoadedTime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001508 pw.println(prefix + "mLastTime=" + mLastTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 + " mUnpluggedTime=" + mUnpluggedTime);
Evan Millarc64edde2009-04-18 12:26:32 -07001510 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001511
1512
Joe Onoratoabded112016-02-08 16:49:39 -08001513 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001514 long runTime = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1515 out.writeLong(runTime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001516 out.writeInt(computeCurrentCountLocked());
Evan Millarc64edde2009-04-18 12:26:32 -07001517 }
1518
Joe Onoratoabded112016-02-08 16:49:39 -08001519 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07001520 // Multiply by 1000 for backwards compatibility
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001521 mTotalTime = mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001522 mLastTime = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001523 mUnpluggedTime = mTotalTime;
1524 mCount = mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001525 mLastCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001526 mUnpluggedCount = mCount;
Adam Lesinskie08af192015-03-25 16:42:59 -07001527
1528 // When reading the summary, we set the mark to be the latest information.
1529 mTimeBeforeMark = mTotalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001530 }
1531 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001532
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001533 /**
1534 * A counter meant to accept monotonically increasing values to its {@link #update(long, int)}
1535 * method. The state of the timer according to its {@link TimeBase} will determine how much
1536 * of the value is recorded.
1537 *
1538 * If the value being recorded resets, {@link #endSample()} can be called in order to
1539 * account for the change. If the value passed in to {@link #update(long, int)} decreased
1540 * between calls, the {@link #endSample()} is automatically called and the new value is
1541 * expected to increase monotonically from that point on.
1542 */
Joe Onoratoabded112016-02-08 16:49:39 -08001543 public static class SamplingTimer extends Timer {
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001544
Evan Millarc64edde2009-04-18 12:26:32 -07001545 /**
1546 * The most recent reported count from /proc/wakelocks.
1547 */
1548 int mCurrentReportedCount;
1549
1550 /**
1551 * The reported count from /proc/wakelocks when unplug() was last
1552 * called.
1553 */
1554 int mUnpluggedReportedCount;
1555
1556 /**
1557 * The most recent reported total_time from /proc/wakelocks.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001558 */
Evan Millarc64edde2009-04-18 12:26:32 -07001559 long mCurrentReportedTotalTime;
1560
1561
1562 /**
1563 * The reported total_time from /proc/wakelocks when unplug() was last
1564 * called.
1565 */
1566 long mUnpluggedReportedTotalTime;
1567
1568 /**
1569 * Whether we are currently in a discharge cycle.
1570 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001571 boolean mTimeBaseRunning;
Evan Millarc64edde2009-04-18 12:26:32 -07001572
1573 /**
1574 * Whether we are currently recording reported values.
1575 */
1576 boolean mTrackingReportedValues;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001577
Evan Millarc64edde2009-04-18 12:26:32 -07001578 /*
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001579 * A sequence counter, incremented once for each update of the stats.
Evan Millarc64edde2009-04-18 12:26:32 -07001580 */
1581 int mUpdateVersion;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001582
Adam Lesinski98f0d462016-04-19 16:46:20 -07001583 @VisibleForTesting
1584 public SamplingTimer(Clocks clocks, TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08001585 super(clocks, 0, timeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -07001586 mCurrentReportedCount = in.readInt();
1587 mUnpluggedReportedCount = in.readInt();
1588 mCurrentReportedTotalTime = in.readLong();
1589 mUnpluggedReportedTotalTime = in.readLong();
1590 mTrackingReportedValues = in.readInt() == 1;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001591 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001592 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001593
Adam Lesinski98f0d462016-04-19 16:46:20 -07001594 @VisibleForTesting
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001595 public SamplingTimer(Clocks clocks, TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08001596 super(clocks, 0, timeBase);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001597 mTrackingReportedValues = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001598 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001599 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001600
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001601 /**
1602 * Ends the current sample, allowing subsequent values to {@link #update(long, int)} to
1603 * be less than the values used for a previous invocation.
1604 */
1605 public void endSample() {
1606 mTotalTime = computeRunTimeLocked(0 /* unused by us */);
1607 mCount = computeCurrentCountLocked();
1608 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime = 0;
1609 mUnpluggedReportedCount = mCurrentReportedCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001610 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001611
Evan Millarc64edde2009-04-18 12:26:32 -07001612 public void setUpdateVersion(int version) {
1613 mUpdateVersion = version;
1614 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001615
Evan Millarc64edde2009-04-18 12:26:32 -07001616 public int getUpdateVersion() {
1617 return mUpdateVersion;
1618 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001619
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001620 /**
1621 * Updates the current recorded values. These are meant to be monotonically increasing
1622 * and cumulative. If you are dealing with deltas, use {@link #add(long, int)}.
1623 *
1624 * If the values being recorded have been reset, the monotonically increasing requirement
1625 * will be broken. In this case, {@link #endSample()} is automatically called and
1626 * the total value of totalTime and count are recorded, starting a new monotonically
1627 * increasing sample.
1628 *
1629 * @param totalTime total time of sample in microseconds.
1630 * @param count total number of times the event being sampled occurred.
1631 */
1632 public void update(long totalTime, int count) {
1633 if (mTimeBaseRunning && !mTrackingReportedValues) {
Evan Millarc64edde2009-04-18 12:26:32 -07001634 // Updating the reported value for the first time.
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001635 mUnpluggedReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001636 mUnpluggedReportedCount = count;
Evan Millarc64edde2009-04-18 12:26:32 -07001637 }
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001638
1639 mTrackingReportedValues = true;
1640
1641 if (totalTime < mCurrentReportedTotalTime || count < mCurrentReportedCount) {
1642 endSample();
1643 }
1644
1645 mCurrentReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001646 mCurrentReportedCount = count;
1647 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001648
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001649 /**
1650 * Adds deltaTime and deltaCount to the current sample.
1651 *
1652 * @param deltaTime additional time recorded since the last sampled event, in microseconds.
1653 * @param deltaCount additional number of times the event being sampled occurred.
1654 */
1655 public void add(long deltaTime, int deltaCount) {
1656 update(mCurrentReportedTotalTime + deltaTime, mCurrentReportedCount + deltaCount);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07001657 }
1658
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001659 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001660 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
1661 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001662 if (mTrackingReportedValues) {
1663 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime;
1664 mUnpluggedReportedCount = mCurrentReportedCount;
1665 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001666 mTimeBaseRunning = true;
Evan Millarc64edde2009-04-18 12:26:32 -07001667 }
1668
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001669 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001670 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
1671 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
1672 mTimeBaseRunning = false;
Evan Millarc64edde2009-04-18 12:26:32 -07001673 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001674
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001675 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001676 public void logState(Printer pw, String prefix) {
1677 super.logState(pw, prefix);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001678 pw.println(prefix + "mCurrentReportedCount=" + mCurrentReportedCount
Evan Millarc64edde2009-04-18 12:26:32 -07001679 + " mUnpluggedReportedCount=" + mUnpluggedReportedCount
1680 + " mCurrentReportedTotalTime=" + mCurrentReportedTotalTime
1681 + " mUnpluggedReportedTotalTime=" + mUnpluggedReportedTotalTime);
1682 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001683
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001684 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001685 protected long computeRunTimeLocked(long curBatteryRealtime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001686 return mTotalTime + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07001687 ? mCurrentReportedTotalTime - mUnpluggedReportedTotalTime : 0);
1688 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001689
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001690 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001691 protected int computeCurrentCountLocked() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001692 return mCount + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07001693 ? mCurrentReportedCount - mUnpluggedReportedCount : 0);
1694 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001695
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001696 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001697 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1698 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07001699 out.writeInt(mCurrentReportedCount);
1700 out.writeInt(mUnpluggedReportedCount);
1701 out.writeLong(mCurrentReportedTotalTime);
1702 out.writeLong(mUnpluggedReportedTotalTime);
1703 out.writeInt(mTrackingReportedValues ? 1 : 0);
1704 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001705
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001706 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08001707 public boolean reset(boolean detachIfReset) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001708 super.reset(detachIfReset);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001709 mTrackingReportedValues = false;
1710 mUnpluggedReportedTotalTime = 0;
1711 mUnpluggedReportedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001712 return true;
1713 }
Evan Millarc64edde2009-04-18 12:26:32 -07001714 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001715
Evan Millarc64edde2009-04-18 12:26:32 -07001716 /**
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001717 * A timer that increments in batches. It does not run for durations, but just jumps
1718 * for a pre-determined amount.
1719 */
Joe Onoratoabded112016-02-08 16:49:39 -08001720 public static class BatchTimer extends Timer {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001721 final Uid mUid;
1722
1723 /**
1724 * The last time at which we updated the timer. This is in elapsed realtime microseconds.
1725 */
1726 long mLastAddedTime;
1727
1728 /**
1729 * The last duration that we added to the timer. This is in microseconds.
1730 */
1731 long mLastAddedDuration;
1732
1733 /**
1734 * Whether we are currently in a discharge cycle.
1735 */
1736 boolean mInDischarge;
1737
Joe Onoratoabded112016-02-08 16:49:39 -08001738 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase, Parcel in) {
1739 super(clocks, type, timeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001740 mUid = uid;
1741 mLastAddedTime = in.readLong();
1742 mLastAddedDuration = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001743 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001744 }
1745
Joe Onoratoabded112016-02-08 16:49:39 -08001746 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase) {
1747 super(clocks, type, timeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001748 mUid = uid;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001749 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001750 }
1751
1752 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001753 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1754 super.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001755 out.writeLong(mLastAddedTime);
1756 out.writeLong(mLastAddedDuration);
1757 }
1758
1759 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001760 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08001761 recomputeLastDuration(mClocks.elapsedRealtime() * 1000, false);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001762 mInDischarge = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001763 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001764 }
1765
1766 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001767 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001768 recomputeLastDuration(elapsedRealtime, false);
1769 mInDischarge = true;
1770 // If we are still within the last added duration, then re-added whatever remains.
1771 if (mLastAddedTime == elapsedRealtime) {
1772 mTotalTime += mLastAddedDuration;
1773 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001774 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001775 }
1776
1777 @Override
1778 public void logState(Printer pw, String prefix) {
1779 super.logState(pw, prefix);
1780 pw.println(prefix + "mLastAddedTime=" + mLastAddedTime
1781 + " mLastAddedDuration=" + mLastAddedDuration);
1782 }
1783
1784 private long computeOverage(long curTime) {
1785 if (mLastAddedTime > 0) {
1786 return mLastTime + mLastAddedDuration - curTime;
1787 }
1788 return 0;
1789 }
1790
1791 private void recomputeLastDuration(long curTime, boolean abort) {
1792 final long overage = computeOverage(curTime);
1793 if (overage > 0) {
1794 // Aborting before the duration ran out -- roll back the remaining
1795 // duration. Only do this if currently discharging; otherwise we didn't
1796 // actually add the time.
1797 if (mInDischarge) {
1798 mTotalTime -= overage;
1799 }
1800 if (abort) {
1801 mLastAddedTime = 0;
1802 } else {
1803 mLastAddedTime = curTime;
1804 mLastAddedDuration -= overage;
1805 }
1806 }
1807 }
1808
1809 public void addDuration(BatteryStatsImpl stats, long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08001810 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001811 recomputeLastDuration(now, true);
1812 mLastAddedTime = now;
1813 mLastAddedDuration = durationMillis * 1000;
1814 if (mInDischarge) {
1815 mTotalTime += mLastAddedDuration;
1816 mCount++;
1817 }
1818 }
1819
1820 public void abortLastDuration(BatteryStatsImpl stats) {
Joe Onoratoabded112016-02-08 16:49:39 -08001821 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001822 recomputeLastDuration(now, true);
1823 }
1824
1825 @Override
1826 protected int computeCurrentCountLocked() {
1827 return mCount;
1828 }
1829
1830 @Override
1831 protected long computeRunTimeLocked(long curBatteryRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08001832 final long overage = computeOverage(mClocks.elapsedRealtime() * 1000);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001833 if (overage > 0) {
1834 return mTotalTime = overage;
1835 }
1836 return mTotalTime;
1837 }
1838
1839 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08001840 public boolean reset(boolean detachIfReset) {
1841 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001842 recomputeLastDuration(now, true);
1843 boolean stillActive = mLastAddedTime == now;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001844 super.reset(!stillActive && detachIfReset);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001845 return !stillActive;
1846 }
1847 }
1848
Joe Onorato92fd23f2016-07-25 11:18:42 -07001849
1850 /**
1851 * A StopwatchTimer that also tracks the total and max individual
1852 * time spent active according to the given timebase. Whereas
1853 * StopwatchTimer apportions the time amongst all in the pool,
1854 * the total and max durations are not apportioned.
1855 */
1856 public static class DurationTimer extends StopwatchTimer {
1857 /**
1858 * The time (in ms) that the timer was last acquired or the time base
1859 * last (re-)started. Increasing the nesting depth does not reset this time.
1860 *
1861 * -1 if the timer is currently not running or the time base is not running.
1862 *
1863 * If written to a parcel, the start time is reset, as is mNesting in the base class
1864 * StopwatchTimer.
1865 */
1866 long mStartTimeMs = -1;
1867
1868 /**
Bookatz867c0d72017-03-07 18:23:42 -08001869 * The longest time period (in ms) that the timer has been active. Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07001870 */
1871 long mMaxDurationMs;
1872
1873 /**
Bookatz867c0d72017-03-07 18:23:42 -08001874 * The time (in ms) that that the timer has been active since most recent
1875 * stopRunningLocked() or reset(). Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07001876 */
1877 long mCurrentDurationMs;
1878
Bookatz867c0d72017-03-07 18:23:42 -08001879 /**
1880 * The total time (in ms) that that the timer has been active since most recent reset()
1881 * prior to the current startRunningLocked. This is the sum of all past currentDurations
1882 * (but not including the present currentDuration) since reset. Not pooled.
1883 */
1884 long mTotalDurationMs;
1885
Joe Onorato92fd23f2016-07-25 11:18:42 -07001886 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
1887 TimeBase timeBase, Parcel in) {
1888 super(clocks, uid, type, timerPool, timeBase, in);
1889 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08001890 mTotalDurationMs = in.readLong();
jackqdyulei610a0a02017-08-09 14:02:01 -07001891 mCurrentDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07001892 }
1893
1894 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
1895 TimeBase timeBase) {
1896 super(clocks, uid, type, timerPool, timeBase);
1897 }
1898
1899 @Override
1900 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1901 super.writeToParcel(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08001902 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
jackqdyulei610a0a02017-08-09 14:02:01 -07001903 out.writeLong(mTotalDurationMs);
1904 out.writeLong(getCurrentDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07001905 }
1906
1907 /**
1908 * Write the summary to the parcel.
1909 *
1910 * Since the time base is probably meaningless after we come back, reading
1911 * from this will have the effect of stopping the timer. So here all we write
Bookatz867c0d72017-03-07 18:23:42 -08001912 * is the max and total durations.
Joe Onorato92fd23f2016-07-25 11:18:42 -07001913 */
1914 @Override
1915 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
1916 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08001917 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
Bookatz867c0d72017-03-07 18:23:42 -08001918 out.writeLong(getTotalDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07001919 }
1920
1921 /**
1922 * Read the summary parcel.
1923 *
1924 * Has the side effect of stopping the timer.
1925 */
1926 @Override
1927 public void readSummaryFromParcelLocked(Parcel in) {
1928 super.readSummaryFromParcelLocked(in);
1929 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08001930 mTotalDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07001931 mStartTimeMs = -1;
1932 mCurrentDurationMs = 0;
1933 }
1934
1935 /**
1936 * The TimeBase time started (again).
1937 *
1938 * If the timer is also running, store the start time.
1939 */
1940 public void onTimeStarted(long elapsedRealtimeUs, long baseUptime, long baseRealtime) {
1941 super.onTimeStarted(elapsedRealtimeUs, baseUptime, baseRealtime);
1942 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08001943 mStartTimeMs = baseRealtime / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07001944 }
1945 }
1946
1947 /**
1948 * The TimeBase stopped running.
1949 *
1950 * If the timer is running, add the duration into mCurrentDurationMs.
1951 */
1952 @Override
Kweku Adams47db5a82016-12-09 19:04:50 -08001953 public void onTimeStopped(long elapsedRealtimeUs, long baseUptime, long baseRealtimeUs) {
1954 super.onTimeStopped(elapsedRealtimeUs, baseUptime, baseRealtimeUs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07001955 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08001956 // baseRealtimeUs has already been converted to the timebase's realtime.
1957 mCurrentDurationMs += (baseRealtimeUs / 1000) - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07001958 }
1959 mStartTimeMs = -1;
1960 }
1961
1962 @Override
1963 public void logState(Printer pw, String prefix) {
1964 super.logState(pw, prefix);
1965 }
1966
1967 @Override
1968 public void startRunningLocked(long elapsedRealtimeMs) {
1969 super.startRunningLocked(elapsedRealtimeMs);
1970 if (mNesting == 1 && mTimeBase.isRunning()) {
1971 // Just started
Kweku Adams47db5a82016-12-09 19:04:50 -08001972 mStartTimeMs = mTimeBase.getRealtime(elapsedRealtimeMs * 1000) / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07001973 }
1974 }
1975
1976 /**
1977 * Decrements the mNesting ref-count on this timer.
1978 *
1979 * If it actually stopped (mNesting went to 0), then possibly update
1980 * mMaxDuration if the current duration was the longest ever.
1981 */
1982 @Override
1983 public void stopRunningLocked(long elapsedRealtimeMs) {
Kweku Adams47db5a82016-12-09 19:04:50 -08001984 if (mNesting == 1) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07001985 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08001986 mTotalDurationMs += durationMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07001987 if (durationMs > mMaxDurationMs) {
1988 mMaxDurationMs = durationMs;
1989 }
1990 mStartTimeMs = -1;
1991 mCurrentDurationMs = 0;
1992 }
Kweku Adams47db5a82016-12-09 19:04:50 -08001993 // super method decrements mNesting, which getCurrentDurationMsLocked relies on,
1994 // so call super.stopRunningLocked after calling getCurrentDurationMsLocked.
1995 super.stopRunningLocked(elapsedRealtimeMs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07001996 }
1997
1998 @Override
1999 public boolean reset(boolean detachIfReset) {
2000 boolean result = super.reset(detachIfReset);
2001 mMaxDurationMs = 0;
Bookatz867c0d72017-03-07 18:23:42 -08002002 mTotalDurationMs = 0;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002003 mCurrentDurationMs = 0;
2004 if (mNesting > 0) {
2005 mStartTimeMs = mTimeBase.getRealtime(mClocks.elapsedRealtime()*1000) / 1000;
2006 } else {
2007 mStartTimeMs = -1;
2008 }
2009 return result;
2010 }
2011
2012 /**
2013 * Returns the max duration that this timer has ever seen.
2014 *
2015 * Note that this time is NOT split between the timers in the timer group that
2016 * this timer is attached to. It is the TOTAL time.
2017 */
2018 @Override
2019 public long getMaxDurationMsLocked(long elapsedRealtimeMs) {
2020 if (mNesting > 0) {
2021 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
2022 if (durationMs > mMaxDurationMs) {
2023 return durationMs;
2024 }
2025 }
2026 return mMaxDurationMs;
2027 }
2028
2029 /**
2030 * Returns the time since the timer was started.
Bookatz867c0d72017-03-07 18:23:42 -08002031 * Returns 0 if the timer is not currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002032 *
2033 * Note that this time is NOT split between the timers in the timer group that
2034 * this timer is attached to. It is the TOTAL time.
jackqdyulei610a0a02017-08-09 14:02:01 -07002035 *
2036 * Note that if running timer is parceled and unparceled, this method will return
2037 * current duration value at the time of parceling even though timer may not be
2038 * currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002039 */
2040 @Override
2041 public long getCurrentDurationMsLocked(long elapsedRealtimeMs) {
2042 long durationMs = mCurrentDurationMs;
Kweku Adams47db5a82016-12-09 19:04:50 -08002043 if (mNesting > 0 && mTimeBase.isRunning()) {
2044 durationMs += (mTimeBase.getRealtime(elapsedRealtimeMs*1000)/1000)
2045 - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002046 }
2047 return durationMs;
2048 }
Bookatz867c0d72017-03-07 18:23:42 -08002049
2050 /**
2051 * Returns the total cumulative duration that this timer has been on since reset().
2052 * If mTimerPool == null, this should be the same
2053 * as getTotalTimeLocked(elapsedRealtimeMs*1000, STATS_SINCE_CHARGED)/1000.
2054 *
2055 * Note that this time is NOT split between the timers in the timer group that
2056 * this timer is attached to. It is the TOTAL time. For this reason, if mTimerPool != null,
2057 * the result will not be equivalent to getTotalTimeLocked.
2058 */
2059 @Override
2060 public long getTotalDurationMsLocked(long elapsedRealtimeMs) {
2061 return mTotalDurationMs + getCurrentDurationMsLocked(elapsedRealtimeMs);
2062 }
Joe Onorato92fd23f2016-07-25 11:18:42 -07002063 }
2064
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002065 /**
Evan Millarc64edde2009-04-18 12:26:32 -07002066 * State for keeping track of timing information.
2067 */
Joe Onoratoabded112016-02-08 16:49:39 -08002068 public static class StopwatchTimer extends Timer {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002069 final Uid mUid;
Evan Millarc64edde2009-04-18 12:26:32 -07002070 final ArrayList<StopwatchTimer> mTimerPool;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002071
Evan Millarc64edde2009-04-18 12:26:32 -07002072 int mNesting;
2073
Evan Millarc64edde2009-04-18 12:26:32 -07002074 /**
2075 * The last time at which we updated the timer. If mNesting is > 0,
2076 * subtract this from the current battery time to find the amount of
2077 * time we have been running since we last computed an update.
2078 */
2079 long mUpdateTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002080
Evan Millarc64edde2009-04-18 12:26:32 -07002081 /**
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002082 * The total time at which the timer was acquired, to determine if it
Bookatzceebafe2017-04-06 11:59:13 -07002083 * was actually held for an interesting duration. If time base was not running when timer
2084 * was acquired, will be -1.
Evan Millarc64edde2009-04-18 12:26:32 -07002085 */
Bookatzceebafe2017-04-06 11:59:13 -07002086 long mAcquireTime = -1;
Evan Millarc64edde2009-04-18 12:26:32 -07002087
Amith Yamasanif37447b2009-10-08 18:28:01 -07002088 long mTimeout;
2089
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002090 /**
2091 * For partial wake locks, keep track of whether we are in the list
2092 * to consume CPU cycles.
2093 */
Sudheer Shanka38383232017-07-25 09:55:03 -07002094 @VisibleForTesting
2095 public boolean mInList;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002096
Joe Onoratoabded112016-02-08 16:49:39 -08002097 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002098 TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08002099 super(clocks, type, timeBase, in);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002100 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002101 mTimerPool = timerPool;
2102 mUpdateTime = in.readLong();
2103 }
2104
Joe Onoratoabded112016-02-08 16:49:39 -08002105 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002106 TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08002107 super(clocks, type, timeBase);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002108 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002109 mTimerPool = timerPool;
2110 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002111
Joe Onoratoabded112016-02-08 16:49:39 -08002112 public void setTimeout(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002113 mTimeout = timeout;
2114 }
2115
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002116 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2117 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07002118 out.writeLong(mUpdateTime);
2119 }
2120
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002121 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07002122 if (mNesting > 0) {
2123 if (DEBUG && mType < 0) {
2124 Log.v(TAG, "old mUpdateTime=" + mUpdateTime);
2125 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002126 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
2127 mUpdateTime = baseRealtime;
Evan Millarc64edde2009-04-18 12:26:32 -07002128 if (DEBUG && mType < 0) {
2129 Log.v(TAG, "new mUpdateTime=" + mUpdateTime);
2130 }
2131 }
2132 }
2133
2134 public void logState(Printer pw, String prefix) {
2135 super.logState(pw, prefix);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07002136 pw.println(prefix + "mNesting=" + mNesting + " mUpdateTime=" + mUpdateTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002137 + " mAcquireTime=" + mAcquireTime);
2138 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002139
Joe Onoratoabded112016-02-08 16:49:39 -08002140 public void startRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141 if (mNesting++ == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002142 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002143 mUpdateTime = batteryRealtime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002144 if (mTimerPool != null) {
2145 // Accumulate time to all currently active timers before adding
2146 // this new one to the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002147 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002148 // Add this timer to the active pool
2149 mTimerPool.add(this);
2150 }
Bookatzceebafe2017-04-06 11:59:13 -07002151 if (mTimeBase.isRunning()) {
2152 // Increment the count
2153 mCount++;
2154 mAcquireTime = mTotalTime;
2155 } else {
2156 mAcquireTime = -1;
2157 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002158 if (DEBUG && mType < 0) {
2159 Log.v(TAG, "start #" + mType + ": mUpdateTime=" + mUpdateTime
2160 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2161 + " mAcquireTime=" + mAcquireTime);
2162 }
2163 }
2164 }
2165
Joe Onoratoabded112016-02-08 16:49:39 -08002166 public boolean isRunningLocked() {
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002167 return mNesting > 0;
2168 }
2169
Joe Onoratoabded112016-02-08 16:49:39 -08002170 public void stopRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002171 // Ignore attempt to stop a timer that isn't running
2172 if (mNesting == 0) {
2173 return;
2174 }
2175 if (--mNesting == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002176 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002177 if (mTimerPool != null) {
2178 // Accumulate time to all active counters, scaled by the total
2179 // active in the pool, before taking this one out of the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002180 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002181 // Remove this timer from the active pool
2182 mTimerPool.remove(this);
2183 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002184 mNesting = 1;
2185 mTotalTime = computeRunTimeLocked(batteryRealtime);
2186 mNesting = 0;
2187 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002188
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002189 if (DEBUG && mType < 0) {
2190 Log.v(TAG, "stop #" + mType + ": mUpdateTime=" + mUpdateTime
2191 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2192 + " mAcquireTime=" + mAcquireTime);
2193 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002194
Bookatzceebafe2017-04-06 11:59:13 -07002195 if (mAcquireTime >= 0 && mTotalTime == mAcquireTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002196 // If there was no change in the time, then discard this
2197 // count. A somewhat cheezy strategy, but hey.
2198 mCount--;
2199 }
2200 }
2201 }
2202
Joe Onoratoabded112016-02-08 16:49:39 -08002203 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07002204 if (mNesting > 0) {
2205 mNesting = 1;
2206 stopRunningLocked(elapsedRealtimeMs);
2207 }
2208 }
2209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002210 // Update the total time for all other running Timers with the same type as this Timer
2211 // due to a change in timer count
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002212 private static long refreshTimersLocked(long batteryRealtime,
2213 final ArrayList<StopwatchTimer> pool, StopwatchTimer self) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002214 long selfTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002215 final int N = pool.size();
2216 for (int i=N-1; i>= 0; i--) {
Evan Millarc64edde2009-04-18 12:26:32 -07002217 final StopwatchTimer t = pool.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218 long heldTime = batteryRealtime - t.mUpdateTime;
2219 if (heldTime > 0) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002220 final long myTime = heldTime / N;
2221 if (t == self) {
2222 selfTime = myTime;
2223 }
2224 t.mTotalTime += myTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002225 }
2226 t.mUpdateTime = batteryRealtime;
2227 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002228 return selfTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002229 }
2230
Evan Millarc64edde2009-04-18 12:26:32 -07002231 @Override
2232 protected long computeRunTimeLocked(long curBatteryRealtime) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002233 if (mTimeout > 0 && curBatteryRealtime > mUpdateTime + mTimeout) {
2234 curBatteryRealtime = mUpdateTime + mTimeout;
2235 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002236 return mTotalTime + (mNesting > 0
2237 ? (curBatteryRealtime - mUpdateTime)
2238 / (mTimerPool != null ? mTimerPool.size() : 1)
2239 : 0);
2240 }
2241
Evan Millarc64edde2009-04-18 12:26:32 -07002242 @Override
2243 protected int computeCurrentCountLocked() {
2244 return mCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002245 }
2246
Adam Lesinskie08af192015-03-25 16:42:59 -07002247 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002248 public boolean reset(boolean detachIfReset) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002249 boolean canDetach = mNesting <= 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002250 super.reset(canDetach && detachIfReset);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002251 if (mNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08002252 mUpdateTime = mTimeBase.getRealtime(mClocks.elapsedRealtime() * 1000);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002253 }
Bookatzceebafe2017-04-06 11:59:13 -07002254 mAcquireTime = -1; // to ensure mCount isn't decreased to -1 if timer is stopped later.
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002255 return canDetach;
2256 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002257
Adam Lesinskie08af192015-03-25 16:42:59 -07002258 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002259 public void detach() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002260 super.detach();
2261 if (mTimerPool != null) {
2262 mTimerPool.remove(this);
2263 }
2264 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002265
Adam Lesinskie08af192015-03-25 16:42:59 -07002266 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002267 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07002268 super.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 mNesting = 0;
2270 }
Adam Lesinskie08af192015-03-25 16:42:59 -07002271
2272 /**
2273 * Set the mark so that we can query later for the total time the timer has
2274 * accumulated since this point. The timer can be running or not.
2275 *
2276 * @param elapsedRealtimeMs the current elapsed realtime in milliseconds.
2277 */
2278 public void setMark(long elapsedRealtimeMs) {
2279 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
2280 if (mNesting > 0) {
2281 // We are running.
2282 if (mTimerPool != null) {
2283 refreshTimersLocked(batteryRealtime, mTimerPool, this);
2284 } else {
2285 mTotalTime += batteryRealtime - mUpdateTime;
2286 mUpdateTime = batteryRealtime;
2287 }
2288 }
2289 mTimeBeforeMark = mTotalTime;
2290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002291 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002292
Bookatz867c0d72017-03-07 18:23:42 -08002293 /**
2294 * State for keeping track of two DurationTimers with different TimeBases, presumably where one
2295 * TimeBase is effectively a subset of the other.
2296 */
Bookatzaa4594a2017-03-24 12:39:56 -07002297 public static class DualTimer extends DurationTimer {
2298 // This class both is a DurationTimer and also holds a second DurationTimer.
2299 // The main timer (this) typically tracks the total time. It may be pooled (but since it's a
2300 // durationTimer, it also has the unpooled getTotalDurationMsLocked() for
2301 // STATS_SINCE_CHARGED).
Bookatz867c0d72017-03-07 18:23:42 -08002302 // mSubTimer typically tracks only part of the total time, such as background time, as
2303 // determined by a subTimeBase. It is NOT pooled.
2304 private final DurationTimer mSubTimer;
2305
2306 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002307 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2308 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002309 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002310 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002311 */
2312 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2313 TimeBase timeBase, TimeBase subTimeBase, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002314 super(clocks, uid, type, timerPool, timeBase, in);
Bookatz867c0d72017-03-07 18:23:42 -08002315 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase, in);
2316 }
2317
2318 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002319 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2320 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002321 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002322 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002323 */
2324 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2325 TimeBase timeBase, TimeBase subTimeBase) {
Bookatzaa4594a2017-03-24 12:39:56 -07002326 super(clocks, uid, type, timerPool, timeBase);
Bookatz867c0d72017-03-07 18:23:42 -08002327 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase);
2328 }
2329
Bookatz867c0d72017-03-07 18:23:42 -08002330 /** Get the secondary timer. */
Bookatzaa4594a2017-03-24 12:39:56 -07002331 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002332 public DurationTimer getSubTimer() {
2333 return mSubTimer;
2334 }
2335
Bookatzaa4594a2017-03-24 12:39:56 -07002336 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002337 public void startRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002338 super.startRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002339 mSubTimer.startRunningLocked(elapsedRealtimeMs);
2340 }
2341
Bookatzaa4594a2017-03-24 12:39:56 -07002342 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002343 public void stopRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002344 super.stopRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002345 mSubTimer.stopRunningLocked(elapsedRealtimeMs);
2346 }
2347
Bookatzaa4594a2017-03-24 12:39:56 -07002348 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002349 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002350 super.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002351 mSubTimer.stopAllRunningLocked(elapsedRealtimeMs);
2352 }
2353
Bookatzaa4594a2017-03-24 12:39:56 -07002354 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002355 public boolean reset(boolean detachIfReset) {
2356 boolean active = false;
Bookatz4a3eda92017-04-10 13:10:46 -07002357 // Do not detach the subTimer explicitly since that'll be done by DualTimer.detach().
2358 active |= !mSubTimer.reset(false);
Bookatzaa4594a2017-03-24 12:39:56 -07002359 active |= !super.reset(detachIfReset);
Bookatz867c0d72017-03-07 18:23:42 -08002360 return !active;
2361 }
2362
Bookatzaa4594a2017-03-24 12:39:56 -07002363 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002364 public void detach() {
Bookatz867c0d72017-03-07 18:23:42 -08002365 mSubTimer.detach();
Bookatz4a3eda92017-04-10 13:10:46 -07002366 super.detach();
Bookatz867c0d72017-03-07 18:23:42 -08002367 }
2368
Bookatzaa4594a2017-03-24 12:39:56 -07002369 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002370 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002371 super.writeToParcel(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002372 mSubTimer.writeToParcel(out, elapsedRealtimeUs);
2373 }
2374
Bookatzaa4594a2017-03-24 12:39:56 -07002375 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002376 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002377 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002378 mSubTimer.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
2379 }
2380
Bookatzaa4594a2017-03-24 12:39:56 -07002381 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002382 public void readSummaryFromParcelLocked(Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002383 super.readSummaryFromParcelLocked(in);
Bookatz867c0d72017-03-07 18:23:42 -08002384 mSubTimer.readSummaryFromParcelLocked(in);
2385 }
2386 }
2387
2388
Dianne Hackbornd953c532014-08-16 18:17:38 -07002389 public abstract class OverflowArrayMap<T> {
2390 private static final String OVERFLOW_NAME = "*overflow*";
2391
Dianne Hackborn657153b2016-07-29 14:54:14 -07002392 final int mUid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002393 final ArrayMap<String, T> mMap = new ArrayMap<>();
2394 T mCurOverflow;
2395 ArrayMap<String, MutableInt> mActiveOverflow;
Dianne Hackborn657153b2016-07-29 14:54:14 -07002396 long mLastOverflowTime;
2397 long mLastOverflowFinishTime;
2398 long mLastClearTime;
2399 long mLastCleanupTime;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002400
Dianne Hackborn657153b2016-07-29 14:54:14 -07002401 public OverflowArrayMap(int uid) {
2402 mUid = uid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002403 }
2404
2405 public ArrayMap<String, T> getMap() {
2406 return mMap;
2407 }
2408
2409 public void clear() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002410 mLastClearTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002411 mMap.clear();
2412 mCurOverflow = null;
2413 mActiveOverflow = null;
2414 }
2415
2416 public void add(String name, T obj) {
Joe Onorato388fc332016-04-12 17:06:47 -07002417 if (name == null) {
2418 name = "";
2419 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002420 mMap.put(name, obj);
2421 if (OVERFLOW_NAME.equals(name)) {
2422 mCurOverflow = obj;
2423 }
2424 }
2425
2426 public void cleanup() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002427 mLastCleanupTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002428 if (mActiveOverflow != null) {
2429 if (mActiveOverflow.size() == 0) {
2430 mActiveOverflow = null;
2431 }
2432 }
2433 if (mActiveOverflow == null) {
2434 // There is no currently active overflow, so we should no longer have
2435 // an overflow entry.
2436 if (mMap.containsKey(OVERFLOW_NAME)) {
2437 Slog.wtf(TAG, "Cleaning up with no active overflow, but have overflow entry "
2438 + mMap.get(OVERFLOW_NAME));
2439 mMap.remove(OVERFLOW_NAME);
2440 }
2441 mCurOverflow = null;
2442 } else {
2443 // There is currently active overflow, so we should still have an overflow entry.
2444 if (mCurOverflow == null || !mMap.containsKey(OVERFLOW_NAME)) {
2445 Slog.wtf(TAG, "Cleaning up with active overflow, but no overflow entry: cur="
2446 + mCurOverflow + " map=" + mMap.get(OVERFLOW_NAME));
2447 }
2448 }
2449 }
2450
2451 public T startObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002452 if (name == null) {
2453 name = "";
2454 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002455 T obj = mMap.get(name);
2456 if (obj != null) {
2457 return obj;
2458 }
2459
2460 // No object exists for the given name, but do we currently have it
2461 // running as part of the overflow?
2462 if (mActiveOverflow != null) {
2463 MutableInt over = mActiveOverflow.get(name);
2464 if (over != null) {
2465 // We are already actively counting this name in the overflow object.
2466 obj = mCurOverflow;
2467 if (obj == null) {
2468 // Shouldn't be here, but we'll try to recover.
2469 Slog.wtf(TAG, "Have active overflow " + name + " but null overflow");
2470 obj = mCurOverflow = instantiateObject();
2471 mMap.put(OVERFLOW_NAME, obj);
2472 }
2473 over.value++;
2474 return obj;
2475 }
2476 }
2477
2478 // No object exists for given name nor in the overflow; we need to make
2479 // a new one.
2480 final int N = mMap.size();
2481 if (N >= MAX_WAKELOCKS_PER_UID) {
2482 // Went over the limit on number of objects to track; this one goes
2483 // in to the overflow.
2484 obj = mCurOverflow;
2485 if (obj == null) {
2486 // Need to start overflow now...
2487 obj = mCurOverflow = instantiateObject();
2488 mMap.put(OVERFLOW_NAME, obj);
2489 }
2490 if (mActiveOverflow == null) {
2491 mActiveOverflow = new ArrayMap<>();
2492 }
2493 mActiveOverflow.put(name, new MutableInt(1));
Dianne Hackborn657153b2016-07-29 14:54:14 -07002494 mLastOverflowTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002495 return obj;
2496 }
2497
2498 // Normal case where we just need to make a new object.
2499 obj = instantiateObject();
2500 mMap.put(name, obj);
2501 return obj;
2502 }
2503
2504 public T stopObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002505 if (name == null) {
2506 name = "";
2507 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002508 T obj = mMap.get(name);
2509 if (obj != null) {
2510 return obj;
2511 }
2512
2513 // No object exists for the given name, but do we currently have it
2514 // running as part of the overflow?
2515 if (mActiveOverflow != null) {
2516 MutableInt over = mActiveOverflow.get(name);
2517 if (over != null) {
2518 // We are already actively counting this name in the overflow object.
2519 obj = mCurOverflow;
2520 if (obj != null) {
2521 over.value--;
2522 if (over.value <= 0) {
2523 mActiveOverflow.remove(name);
Dianne Hackborn657153b2016-07-29 14:54:14 -07002524 mLastOverflowFinishTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002525 }
2526 return obj;
2527 }
2528 }
2529 }
2530
2531 // Huh, they are stopping an active operation but we can't find one!
2532 // That's not good.
Dianne Hackborn657153b2016-07-29 14:54:14 -07002533 StringBuilder sb = new StringBuilder();
2534 sb.append("Unable to find object for ");
2535 sb.append(name);
2536 sb.append(" in uid ");
2537 sb.append(mUid);
2538 sb.append(" mapsize=");
2539 sb.append(mMap.size());
2540 sb.append(" activeoverflow=");
2541 sb.append(mActiveOverflow);
2542 sb.append(" curoverflow=");
2543 sb.append(mCurOverflow);
2544 long now = SystemClock.elapsedRealtime();
2545 if (mLastOverflowTime != 0) {
2546 sb.append(" lastOverflowTime=");
2547 TimeUtils.formatDuration(mLastOverflowTime-now, sb);
2548 }
2549 if (mLastOverflowFinishTime != 0) {
2550 sb.append(" lastOverflowFinishTime=");
2551 TimeUtils.formatDuration(mLastOverflowFinishTime-now, sb);
2552 }
2553 if (mLastClearTime != 0) {
2554 sb.append(" lastClearTime=");
2555 TimeUtils.formatDuration(mLastClearTime-now, sb);
2556 }
2557 if (mLastCleanupTime != 0) {
2558 sb.append(" lastCleanupTime=");
2559 TimeUtils.formatDuration(mLastCleanupTime-now, sb);
2560 }
2561 Slog.wtf(TAG, sb.toString());
Dianne Hackbornd953c532014-08-16 18:17:38 -07002562 return null;
2563 }
2564
2565 public abstract T instantiateObject();
2566 }
2567
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002568 public static class ControllerActivityCounterImpl extends ControllerActivityCounter
2569 implements Parcelable {
2570 private final LongSamplingCounter mIdleTimeMillis;
2571 private final LongSamplingCounter mRxTimeMillis;
2572 private final LongSamplingCounter[] mTxTimeMillis;
2573 private final LongSamplingCounter mPowerDrainMaMs;
2574
2575 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates) {
2576 mIdleTimeMillis = new LongSamplingCounter(timeBase);
2577 mRxTimeMillis = new LongSamplingCounter(timeBase);
2578 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2579 for (int i = 0; i < numTxStates; i++) {
2580 mTxTimeMillis[i] = new LongSamplingCounter(timeBase);
2581 }
2582 mPowerDrainMaMs = new LongSamplingCounter(timeBase);
2583 }
2584
2585 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates, Parcel in) {
2586 mIdleTimeMillis = new LongSamplingCounter(timeBase, in);
2587 mRxTimeMillis = new LongSamplingCounter(timeBase, in);
2588 final int recordedTxStates = in.readInt();
2589 if (recordedTxStates != numTxStates) {
2590 throw new ParcelFormatException("inconsistent tx state lengths");
2591 }
2592
2593 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2594 for (int i = 0; i < numTxStates; i++) {
2595 mTxTimeMillis[i] = new LongSamplingCounter(timeBase, in);
2596 }
2597 mPowerDrainMaMs = new LongSamplingCounter(timeBase, in);
2598 }
2599
2600 public void readSummaryFromParcel(Parcel in) {
2601 mIdleTimeMillis.readSummaryFromParcelLocked(in);
2602 mRxTimeMillis.readSummaryFromParcelLocked(in);
2603 final int recordedTxStates = in.readInt();
2604 if (recordedTxStates != mTxTimeMillis.length) {
2605 throw new ParcelFormatException("inconsistent tx state lengths");
2606 }
2607 for (LongSamplingCounter counter : mTxTimeMillis) {
2608 counter.readSummaryFromParcelLocked(in);
2609 }
2610 mPowerDrainMaMs.readSummaryFromParcelLocked(in);
2611 }
2612
2613 @Override
2614 public int describeContents() {
2615 return 0;
2616 }
2617
2618 public void writeSummaryToParcel(Parcel dest) {
2619 mIdleTimeMillis.writeSummaryFromParcelLocked(dest);
2620 mRxTimeMillis.writeSummaryFromParcelLocked(dest);
2621 dest.writeInt(mTxTimeMillis.length);
2622 for (LongSamplingCounter counter : mTxTimeMillis) {
2623 counter.writeSummaryFromParcelLocked(dest);
2624 }
2625 mPowerDrainMaMs.writeSummaryFromParcelLocked(dest);
2626 }
2627
2628 @Override
2629 public void writeToParcel(Parcel dest, int flags) {
2630 mIdleTimeMillis.writeToParcel(dest);
2631 mRxTimeMillis.writeToParcel(dest);
2632 dest.writeInt(mTxTimeMillis.length);
2633 for (LongSamplingCounter counter : mTxTimeMillis) {
2634 counter.writeToParcel(dest);
2635 }
2636 mPowerDrainMaMs.writeToParcel(dest);
2637 }
2638
2639 public void reset(boolean detachIfReset) {
2640 mIdleTimeMillis.reset(detachIfReset);
2641 mRxTimeMillis.reset(detachIfReset);
2642 for (LongSamplingCounter counter : mTxTimeMillis) {
2643 counter.reset(detachIfReset);
2644 }
2645 mPowerDrainMaMs.reset(detachIfReset);
2646 }
2647
2648 public void detach() {
2649 mIdleTimeMillis.detach();
2650 mRxTimeMillis.detach();
2651 for (LongSamplingCounter counter : mTxTimeMillis) {
2652 counter.detach();
2653 }
2654 mPowerDrainMaMs.detach();
2655 }
2656
2657 /**
2658 * @return a LongSamplingCounter, measuring time spent in the idle state in
2659 * milliseconds.
2660 */
2661 @Override
2662 public LongSamplingCounter getIdleTimeCounter() {
Roshan Pius81643302016-03-14 16:45:55 -07002663 return mIdleTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002664 }
2665
2666 /**
2667 * @return a LongSamplingCounter, measuring time spent in the receive state in
2668 * milliseconds.
2669 */
2670 @Override
2671 public LongSamplingCounter getRxTimeCounter() {
2672 return mRxTimeMillis;
2673 }
2674
2675 /**
2676 * @return a LongSamplingCounter[], measuring time spent in various transmit states in
2677 * milliseconds.
2678 */
2679 @Override
2680 public LongSamplingCounter[] getTxTimeCounters() {
2681 return mTxTimeMillis;
2682 }
2683
2684 /**
2685 * @return a LongSamplingCounter, measuring power use in milli-ampere milliseconds (mAmS).
2686 */
2687 @Override
2688 public LongSamplingCounter getPowerCounter() {
2689 return mPowerDrainMaMs;
2690 }
2691 }
2692
Bookatz50df7112017-08-04 14:53:26 -07002693 /** Get Resource Power Manager stats. Create a new one if it doesn't already exist. */
2694 public SamplingTimer getRpmTimerLocked(String name) {
2695 SamplingTimer rpmt = mRpmStats.get(name);
2696 if (rpmt == null) {
2697 rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
2698 mRpmStats.put(name, rpmt);
2699 }
2700 return rpmt;
2701 }
2702
2703 /** Get Screen-off Resource Power Manager stats. Create new one if it doesn't already exist. */
2704 public SamplingTimer getScreenOffRpmTimerLocked(String name) {
2705 SamplingTimer rpmt = mScreenOffRpmStats.get(name);
2706 if (rpmt == null) {
2707 rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
2708 mScreenOffRpmStats.put(name, rpmt);
2709 }
2710 return rpmt;
2711 }
2712
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002713 /*
2714 * Get the wakeup reason counter, and create a new one if one
2715 * doesn't already exist.
2716 */
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002717 public SamplingTimer getWakeupReasonTimerLocked(String name) {
2718 SamplingTimer timer = mWakeupReasonStats.get(name);
2719 if (timer == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002720 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002721 mWakeupReasonStats.put(name, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002722 }
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002723 return timer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002724 }
2725
Evan Millarc64edde2009-04-18 12:26:32 -07002726 /*
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002727 * Get the KernelWakelockTimer associated with name, and create a new one if one
Evan Millarc64edde2009-04-18 12:26:32 -07002728 * doesn't already exist.
2729 */
2730 public SamplingTimer getKernelWakelockTimerLocked(String name) {
2731 SamplingTimer kwlt = mKernelWakelockStats.get(name);
2732 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002733 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Evan Millarc64edde2009-04-18 12:26:32 -07002734 mKernelWakelockStats.put(name, kwlt);
2735 }
2736 return kwlt;
2737 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07002738
James Carr3a226052016-07-01 14:49:52 -07002739 public SamplingTimer getKernelMemoryTimerLocked(long bucket) {
2740 SamplingTimer kmt = mKernelMemoryStats.get(bucket);
2741 if (kmt == null) {
2742 kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
2743 mKernelMemoryStats.put(bucket, kmt);
2744 }
2745 return kmt;
2746 }
2747
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002748 private int writeHistoryTag(HistoryTag tag) {
2749 Integer idxObj = mHistoryTagPool.get(tag);
2750 int idx;
2751 if (idxObj != null) {
2752 idx = idxObj;
2753 } else {
2754 idx = mNextHistoryTagIdx;
2755 HistoryTag key = new HistoryTag();
2756 key.setTo(tag);
2757 tag.poolIdx = idx;
2758 mHistoryTagPool.put(key, idx);
2759 mNextHistoryTagIdx++;
2760 mNumHistoryTagChars += key.string.length() + 1;
2761 }
2762 return idx;
2763 }
2764
2765 private void readHistoryTag(int index, HistoryTag tag) {
2766 tag.string = mReadHistoryStrings[index];
2767 tag.uid = mReadHistoryUids[index];
2768 tag.poolIdx = index;
2769 }
2770
Adam Lesinski926969b2016-04-28 17:31:12 -07002771 /*
2772 The history delta format uses flags to denote further data in subsequent ints in the parcel.
2773
2774 There is always the first token, which may contain the delta time, or an indicator of
2775 the length of the time (int or long) following this token.
2776
2777 First token: always present,
2778 31 23 15 7 0
2779 â–ˆM|L|K|J|I|H|G|Fâ–ˆE|D|C|B|A|T|T|Tâ–ˆT|T|T|T|T|T|T|Tâ–ˆT|T|T|T|T|T|T|Tâ–ˆ
2780
2781 T: the delta time if it is <= 0x7fffd. Otherwise 0x7fffe indicates an int immediately
2782 follows containing the time, and 0x7ffff indicates a long immediately follows with the
2783 delta time.
2784 A: battery level changed and an int follows with battery data.
2785 B: state changed and an int follows with state change data.
2786 C: state2 has changed and an int follows with state2 change data.
2787 D: wakelock/wakereason has changed and an wakelock/wakereason struct follows.
2788 E: event data has changed and an event struct follows.
2789 F: battery charge in coulombs has changed and an int with the charge follows.
2790 G: state flag denoting that the mobile radio was active.
2791 H: state flag denoting that the wifi radio was active.
2792 I: state flag denoting that a wifi scan occurred.
2793 J: state flag denoting that a wifi full lock was held.
2794 K: state flag denoting that the gps was on.
2795 L: state flag denoting that a wakelock was held.
2796 M: state flag denoting that the cpu was running.
2797
2798 Time int/long: if T in the first token is 0x7ffff or 0x7fffe, then an int or long follows
2799 with the time delta.
2800
2801 Battery level int: if A in the first token is set,
2802 31 23 15 7 0
2803 â–ˆL|L|L|L|L|L|L|Tâ–ˆT|T|T|T|T|T|T|Tâ–ˆT|V|V|V|V|V|V|Vâ–ˆV|V|V|V|V|V|V|Dâ–ˆ
2804
2805 D: indicates that extra history details follow.
2806 V: the battery voltage.
2807 T: the battery temperature.
2808 L: the battery level (out of 100).
2809
2810 State change int: if B in the first token is set,
2811 31 23 15 7 0
2812 â–ˆS|S|S|H|H|H|P|Pâ–ˆF|E|D|C|B| | |Aâ–ˆ | | | | | | | â–ˆ | | | | | | | â–ˆ
2813
2814 A: wifi multicast was on.
2815 B: battery was plugged in.
2816 C: screen was on.
2817 D: phone was scanning for signal.
2818 E: audio was on.
2819 F: a sensor was active.
2820
2821 State2 change int: if C in the first token is set,
2822 31 23 15 7 0
2823 â–ˆM|L|K|J|I|H|H|Gâ–ˆF|E|D|C| | | | â–ˆ | | | | | | | â–ˆ |B|B|B|A|A|A|Aâ–ˆ
2824
2825 A: 4 bits indicating the wifi supplicant state: {@link BatteryStats#WIFI_SUPPL_STATE_NAMES}.
2826 B: 3 bits indicating the wifi signal strength: 0, 1, 2, 3, 4.
2827 C: a bluetooth scan was active.
2828 D: the camera was active.
2829 E: bluetooth was on.
2830 F: a phone call was active.
2831 G: the device was charging.
2832 H: 2 bits indicating the device-idle (doze) state: off, light, full
2833 I: the flashlight was on.
2834 J: wifi was on.
2835 K: wifi was running.
2836 L: video was playing.
2837 M: power save mode was on.
2838
2839 Wakelock/wakereason struct: if D in the first token is set,
2840 TODO(adamlesinski): describe wakelock/wakereason struct.
2841
2842 Event struct: if E in the first token is set,
2843 TODO(adamlesinski): describe the event struct.
2844
2845 History step details struct: if D in the battery level int is set,
2846 TODO(adamlesinski): describe the history step details struct.
2847
2848 Battery charge int: if F in the first token is set, an int representing the battery charge
2849 in coulombs follows.
2850 */
2851
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002852 // Part of initial delta int that specifies the time delta.
Dianne Hackborne13c4c02014-02-11 17:18:35 -08002853 static final int DELTA_TIME_MASK = 0x7ffff;
2854 static final int DELTA_TIME_LONG = 0x7ffff; // The delta is a following long
2855 static final int DELTA_TIME_INT = 0x7fffe; // The delta is a following int
2856 static final int DELTA_TIME_ABS = 0x7fffd; // Following is an entire abs update.
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002857 // Flag in delta int: a new battery level int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07002858 static final int DELTA_BATTERY_LEVEL_FLAG = 0x00080000;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002859 // Flag in delta int: a new full state and battery status int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07002860 static final int DELTA_STATE_FLAG = 0x00100000;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08002861 // Flag in delta int: a new full state2 int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07002862 static final int DELTA_STATE2_FLAG = 0x00200000;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08002863 // Flag in delta int: contains a wakelock or wakeReason tag.
Adam Lesinski926969b2016-04-28 17:31:12 -07002864 static final int DELTA_WAKELOCK_FLAG = 0x00400000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002865 // Flag in delta int: contains an event description.
Adam Lesinski926969b2016-04-28 17:31:12 -07002866 static final int DELTA_EVENT_FLAG = 0x00800000;
Adam Lesinskia8018ac2016-05-03 10:18:10 -07002867 // Flag in delta int: contains the battery charge count in uAh.
2868 static final int DELTA_BATTERY_CHARGE_FLAG = 0x01000000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002869 // These upper bits are the frequently changing state bits.
Adam Lesinski926969b2016-04-28 17:31:12 -07002870 static final int DELTA_STATE_MASK = 0xfe000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08002871
2872 // These are the pieces of battery state that are packed in to the upper bits of
2873 // the state int that have been packed in to the first delta int. They must fit
Adam Lesinski926969b2016-04-28 17:31:12 -07002874 // in STATE_BATTERY_MASK.
2875 static final int STATE_BATTERY_MASK = 0xff000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08002876 static final int STATE_BATTERY_STATUS_MASK = 0x00000007;
2877 static final int STATE_BATTERY_STATUS_SHIFT = 29;
2878 static final int STATE_BATTERY_HEALTH_MASK = 0x00000007;
2879 static final int STATE_BATTERY_HEALTH_SHIFT = 26;
2880 static final int STATE_BATTERY_PLUG_MASK = 0x00000003;
2881 static final int STATE_BATTERY_PLUG_SHIFT = 24;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002882
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08002883 // We use the low bit of the battery state int to indicate that we have full details
2884 // from a battery level change.
2885 static final int BATTERY_DELTA_LEVEL_FLAG = 0x00000001;
2886
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002887 public void writeHistoryDelta(Parcel dest, HistoryItem cur, HistoryItem last) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002888 if (last == null || cur.cmd != HistoryItem.CMD_UPDATE) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002889 dest.writeInt(DELTA_TIME_ABS);
2890 cur.writeToParcel(dest, 0);
2891 return;
2892 }
2893
2894 final long deltaTime = cur.time - last.time;
2895 final int lastBatteryLevelInt = buildBatteryLevelInt(last);
2896 final int lastStateInt = buildStateInt(last);
2897
2898 int deltaTimeToken;
2899 if (deltaTime < 0 || deltaTime > Integer.MAX_VALUE) {
2900 deltaTimeToken = DELTA_TIME_LONG;
2901 } else if (deltaTime >= DELTA_TIME_ABS) {
2902 deltaTimeToken = DELTA_TIME_INT;
2903 } else {
2904 deltaTimeToken = (int)deltaTime;
2905 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002906 int firstToken = deltaTimeToken | (cur.states&DELTA_STATE_MASK);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08002907 final int includeStepDetails = mLastHistoryStepLevel > cur.batteryLevel
2908 ? BATTERY_DELTA_LEVEL_FLAG : 0;
2909 final boolean computeStepDetails = includeStepDetails != 0
2910 || mLastHistoryStepDetails == null;
2911 final int batteryLevelInt = buildBatteryLevelInt(cur) | includeStepDetails;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002912 final boolean batteryLevelIntChanged = batteryLevelInt != lastBatteryLevelInt;
2913 if (batteryLevelIntChanged) {
2914 firstToken |= DELTA_BATTERY_LEVEL_FLAG;
2915 }
2916 final int stateInt = buildStateInt(cur);
2917 final boolean stateIntChanged = stateInt != lastStateInt;
2918 if (stateIntChanged) {
2919 firstToken |= DELTA_STATE_FLAG;
2920 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002921 final boolean state2IntChanged = cur.states2 != last.states2;
2922 if (state2IntChanged) {
2923 firstToken |= DELTA_STATE2_FLAG;
2924 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08002925 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002926 firstToken |= DELTA_WAKELOCK_FLAG;
2927 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002928 if (cur.eventCode != HistoryItem.EVENT_NONE) {
2929 firstToken |= DELTA_EVENT_FLAG;
2930 }
Adam Lesinski926969b2016-04-28 17:31:12 -07002931
Adam Lesinskia8018ac2016-05-03 10:18:10 -07002932 final boolean batteryChargeChanged = cur.batteryChargeUAh != last.batteryChargeUAh;
2933 if (batteryChargeChanged) {
2934 firstToken |= DELTA_BATTERY_CHARGE_FLAG;
Adam Lesinski926969b2016-04-28 17:31:12 -07002935 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002936 dest.writeInt(firstToken);
2937 if (DEBUG) Slog.i(TAG, "WRITE DELTA: firstToken=0x" + Integer.toHexString(firstToken)
2938 + " deltaTime=" + deltaTime);
2939
2940 if (deltaTimeToken >= DELTA_TIME_INT) {
2941 if (deltaTimeToken == DELTA_TIME_INT) {
2942 if (DEBUG) Slog.i(TAG, "WRITE DELTA: int deltaTime=" + (int)deltaTime);
2943 dest.writeInt((int)deltaTime);
2944 } else {
2945 if (DEBUG) Slog.i(TAG, "WRITE DELTA: long deltaTime=" + deltaTime);
2946 dest.writeLong(deltaTime);
2947 }
2948 }
2949 if (batteryLevelIntChanged) {
2950 dest.writeInt(batteryLevelInt);
2951 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryToken=0x"
2952 + Integer.toHexString(batteryLevelInt)
2953 + " batteryLevel=" + cur.batteryLevel
2954 + " batteryTemp=" + cur.batteryTemperature
2955 + " batteryVolt=" + (int)cur.batteryVoltage);
2956 }
2957 if (stateIntChanged) {
2958 dest.writeInt(stateInt);
2959 if (DEBUG) Slog.i(TAG, "WRITE DELTA: stateToken=0x"
2960 + Integer.toHexString(stateInt)
2961 + " batteryStatus=" + cur.batteryStatus
2962 + " batteryHealth=" + cur.batteryHealth
2963 + " batteryPlugType=" + cur.batteryPlugType
2964 + " states=0x" + Integer.toHexString(cur.states));
2965 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002966 if (state2IntChanged) {
2967 dest.writeInt(cur.states2);
2968 if (DEBUG) Slog.i(TAG, "WRITE DELTA: states2=0x"
2969 + Integer.toHexString(cur.states2));
2970 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08002971 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
2972 int wakeLockIndex;
2973 int wakeReasonIndex;
2974 if (cur.wakelockTag != null) {
2975 wakeLockIndex = writeHistoryTag(cur.wakelockTag);
2976 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
2977 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
2978 } else {
2979 wakeLockIndex = 0xffff;
2980 }
2981 if (cur.wakeReasonTag != null) {
2982 wakeReasonIndex = writeHistoryTag(cur.wakeReasonTag);
2983 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
2984 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
2985 } else {
2986 wakeReasonIndex = 0xffff;
2987 }
2988 dest.writeInt((wakeReasonIndex<<16) | wakeLockIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002989 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002990 if (cur.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002991 int index = writeHistoryTag(cur.eventTag);
2992 int codeAndIndex = (cur.eventCode&0xffff) | (index<<16);
Dianne Hackborn099bc622014-01-22 13:39:16 -08002993 dest.writeInt(codeAndIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002994 if (DEBUG) Slog.i(TAG, "WRITE DELTA: event=" + cur.eventCode + " tag=#"
2995 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
2996 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002997 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08002998 if (computeStepDetails) {
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07002999 if (mPlatformIdleStateCallback != null) {
3000 mCurHistoryStepDetails.statPlatformIdleState =
3001 mPlatformIdleStateCallback.getPlatformLowPowerStats();
3002 if (DEBUG) Slog.i(TAG, "WRITE PlatformIdleState:" +
3003 mCurHistoryStepDetails.statPlatformIdleState);
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +00003004
3005 mCurHistoryStepDetails.statSubsystemPowerState =
3006 mPlatformIdleStateCallback.getSubsystemLowPowerStats();
3007 if (DEBUG) Slog.i(TAG, "WRITE SubsystemPowerState:" +
3008 mCurHistoryStepDetails.statSubsystemPowerState);
3009
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003010 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003011 computeHistoryStepDetails(mCurHistoryStepDetails, mLastHistoryStepDetails);
3012 if (includeStepDetails != 0) {
3013 mCurHistoryStepDetails.writeToParcel(dest);
3014 }
3015 cur.stepDetails = mCurHistoryStepDetails;
3016 mLastHistoryStepDetails = mCurHistoryStepDetails;
3017 } else {
3018 cur.stepDetails = null;
3019 }
3020 if (mLastHistoryStepLevel < cur.batteryLevel) {
3021 mLastHistoryStepDetails = null;
3022 }
3023 mLastHistoryStepLevel = cur.batteryLevel;
Adam Lesinski926969b2016-04-28 17:31:12 -07003024
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003025 if (batteryChargeChanged) {
3026 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryChargeUAh=" + cur.batteryChargeUAh);
3027 dest.writeInt(cur.batteryChargeUAh);
Adam Lesinski926969b2016-04-28 17:31:12 -07003028 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003029 }
3030
3031 private int buildBatteryLevelInt(HistoryItem h) {
3032 return ((((int)h.batteryLevel)<<25)&0xfe000000)
Adam Lesinski3944c812015-11-13 15:54:59 -08003033 | ((((int)h.batteryTemperature)<<15)&0x01ff8000)
3034 | ((((int)h.batteryVoltage)<<1)&0x00007ffe);
3035 }
3036
3037 private void readBatteryLevelInt(int batteryLevelInt, HistoryItem out) {
3038 out.batteryLevel = (byte)((batteryLevelInt & 0xfe000000) >>> 25);
3039 out.batteryTemperature = (short)((batteryLevelInt & 0x01ff8000) >>> 15);
3040 out.batteryVoltage = (char)((batteryLevelInt & 0x00007ffe) >>> 1);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003041 }
3042
3043 private int buildStateInt(HistoryItem h) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003044 int plugType = 0;
3045 if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_AC) != 0) {
3046 plugType = 1;
3047 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_USB) != 0) {
3048 plugType = 2;
3049 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_WIRELESS) != 0) {
3050 plugType = 3;
3051 }
3052 return ((h.batteryStatus&STATE_BATTERY_STATUS_MASK)<<STATE_BATTERY_STATUS_SHIFT)
3053 | ((h.batteryHealth&STATE_BATTERY_HEALTH_MASK)<<STATE_BATTERY_HEALTH_SHIFT)
3054 | ((plugType&STATE_BATTERY_PLUG_MASK)<<STATE_BATTERY_PLUG_SHIFT)
Adam Lesinski926969b2016-04-28 17:31:12 -07003055 | (h.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003056 }
3057
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003058 private void computeHistoryStepDetails(final HistoryStepDetails out,
3059 final HistoryStepDetails last) {
3060 final HistoryStepDetails tmp = last != null ? mTmpHistoryStepDetails : out;
3061
3062 // Perform a CPU update right after we do this collection, so we have started
3063 // collecting good data for the next step.
3064 requestImmediateCpuUpdate();
3065
3066 if (last == null) {
3067 // We are not generating a delta, so all we need to do is reset the stats
3068 // we will later be doing a delta from.
3069 final int NU = mUidStats.size();
3070 for (int i=0; i<NU; i++) {
3071 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3072 uid.mLastStepUserTime = uid.mCurStepUserTime;
3073 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3074 }
3075 mLastStepCpuUserTime = mCurStepCpuUserTime;
3076 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3077 mLastStepStatUserTime = mCurStepStatUserTime;
3078 mLastStepStatSystemTime = mCurStepStatSystemTime;
3079 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3080 mLastStepStatIrqTime = mCurStepStatIrqTime;
3081 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3082 mLastStepStatIdleTime = mCurStepStatIdleTime;
3083 tmp.clear();
3084 return;
3085 }
3086 if (DEBUG) {
3087 Slog.d(TAG, "Step stats last: user=" + mLastStepCpuUserTime + " sys="
3088 + mLastStepStatSystemTime + " io=" + mLastStepStatIOWaitTime
3089 + " irq=" + mLastStepStatIrqTime + " sirq="
3090 + mLastStepStatSoftIrqTime + " idle=" + mLastStepStatIdleTime);
3091 Slog.d(TAG, "Step stats cur: user=" + mCurStepCpuUserTime + " sys="
3092 + mCurStepStatSystemTime + " io=" + mCurStepStatIOWaitTime
3093 + " irq=" + mCurStepStatIrqTime + " sirq="
3094 + mCurStepStatSoftIrqTime + " idle=" + mCurStepStatIdleTime);
3095 }
3096 out.userTime = (int)(mCurStepCpuUserTime - mLastStepCpuUserTime);
3097 out.systemTime = (int)(mCurStepCpuSystemTime - mLastStepCpuSystemTime);
3098 out.statUserTime = (int)(mCurStepStatUserTime - mLastStepStatUserTime);
3099 out.statSystemTime = (int)(mCurStepStatSystemTime - mLastStepStatSystemTime);
3100 out.statIOWaitTime = (int)(mCurStepStatIOWaitTime - mLastStepStatIOWaitTime);
3101 out.statIrqTime = (int)(mCurStepStatIrqTime - mLastStepStatIrqTime);
3102 out.statSoftIrqTime = (int)(mCurStepStatSoftIrqTime - mLastStepStatSoftIrqTime);
3103 out.statIdlTime = (int)(mCurStepStatIdleTime - mLastStepStatIdleTime);
3104 out.appCpuUid1 = out.appCpuUid2 = out.appCpuUid3 = -1;
3105 out.appCpuUTime1 = out.appCpuUTime2 = out.appCpuUTime3 = 0;
3106 out.appCpuSTime1 = out.appCpuSTime2 = out.appCpuSTime3 = 0;
3107 final int NU = mUidStats.size();
3108 for (int i=0; i<NU; i++) {
3109 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3110 final int totalUTime = (int)(uid.mCurStepUserTime - uid.mLastStepUserTime);
3111 final int totalSTime = (int)(uid.mCurStepSystemTime - uid.mLastStepSystemTime);
3112 final int totalTime = totalUTime + totalSTime;
3113 uid.mLastStepUserTime = uid.mCurStepUserTime;
3114 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3115 if (totalTime <= (out.appCpuUTime3+out.appCpuSTime3)) {
3116 continue;
3117 }
3118 if (totalTime <= (out.appCpuUTime2+out.appCpuSTime2)) {
3119 out.appCpuUid3 = uid.mUid;
3120 out.appCpuUTime3 = totalUTime;
3121 out.appCpuSTime3 = totalSTime;
3122 } else {
3123 out.appCpuUid3 = out.appCpuUid2;
3124 out.appCpuUTime3 = out.appCpuUTime2;
3125 out.appCpuSTime3 = out.appCpuSTime2;
3126 if (totalTime <= (out.appCpuUTime1+out.appCpuSTime1)) {
3127 out.appCpuUid2 = uid.mUid;
3128 out.appCpuUTime2 = totalUTime;
3129 out.appCpuSTime2 = totalSTime;
3130 } else {
3131 out.appCpuUid2 = out.appCpuUid1;
3132 out.appCpuUTime2 = out.appCpuUTime1;
3133 out.appCpuSTime2 = out.appCpuSTime1;
3134 out.appCpuUid1 = uid.mUid;
3135 out.appCpuUTime1 = totalUTime;
3136 out.appCpuSTime1 = totalSTime;
3137 }
3138 }
3139 }
3140 mLastStepCpuUserTime = mCurStepCpuUserTime;
3141 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3142 mLastStepStatUserTime = mCurStepStatUserTime;
3143 mLastStepStatSystemTime = mCurStepStatSystemTime;
3144 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3145 mLastStepStatIrqTime = mCurStepStatIrqTime;
3146 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3147 mLastStepStatIdleTime = mCurStepStatIdleTime;
3148 }
3149
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003150 public void readHistoryDelta(Parcel src, HistoryItem cur) {
3151 int firstToken = src.readInt();
3152 int deltaTimeToken = firstToken&DELTA_TIME_MASK;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003153 cur.cmd = HistoryItem.CMD_UPDATE;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003154 cur.numReadInts = 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003155 if (DEBUG) Slog.i(TAG, "READ DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3156 + " deltaTimeToken=" + deltaTimeToken);
3157
3158 if (deltaTimeToken < DELTA_TIME_ABS) {
3159 cur.time += deltaTimeToken;
3160 } else if (deltaTimeToken == DELTA_TIME_ABS) {
3161 cur.time = src.readLong();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003162 cur.numReadInts += 2;
3163 if (DEBUG) Slog.i(TAG, "READ DELTA: ABS time=" + cur.time);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003164 cur.readFromParcel(src);
3165 return;
3166 } else if (deltaTimeToken == DELTA_TIME_INT) {
3167 int delta = src.readInt();
3168 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003169 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003170 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3171 } else {
3172 long delta = src.readLong();
3173 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3174 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003175 cur.numReadInts += 2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003176 }
3177
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003178 final int batteryLevelInt;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003179 if ((firstToken&DELTA_BATTERY_LEVEL_FLAG) != 0) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003180 batteryLevelInt = src.readInt();
Adam Lesinski3944c812015-11-13 15:54:59 -08003181 readBatteryLevelInt(batteryLevelInt, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003182 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003183 if (DEBUG) Slog.i(TAG, "READ DELTA: batteryToken=0x"
3184 + Integer.toHexString(batteryLevelInt)
3185 + " batteryLevel=" + cur.batteryLevel
3186 + " batteryTemp=" + cur.batteryTemperature
3187 + " batteryVolt=" + (int)cur.batteryVoltage);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003188 } else {
3189 batteryLevelInt = 0;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003190 }
3191
3192 if ((firstToken&DELTA_STATE_FLAG) != 0) {
3193 int stateInt = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003194 cur.states = (firstToken&DELTA_STATE_MASK) | (stateInt&(~STATE_BATTERY_MASK));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003195 cur.batteryStatus = (byte)((stateInt>>STATE_BATTERY_STATUS_SHIFT)
3196 & STATE_BATTERY_STATUS_MASK);
3197 cur.batteryHealth = (byte)((stateInt>>STATE_BATTERY_HEALTH_SHIFT)
3198 & STATE_BATTERY_HEALTH_MASK);
3199 cur.batteryPlugType = (byte)((stateInt>>STATE_BATTERY_PLUG_SHIFT)
3200 & STATE_BATTERY_PLUG_MASK);
3201 switch (cur.batteryPlugType) {
3202 case 1:
3203 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_AC;
3204 break;
3205 case 2:
3206 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_USB;
3207 break;
3208 case 3:
3209 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS;
3210 break;
3211 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003212 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003213 if (DEBUG) Slog.i(TAG, "READ DELTA: stateToken=0x"
3214 + Integer.toHexString(stateInt)
3215 + " batteryStatus=" + cur.batteryStatus
3216 + " batteryHealth=" + cur.batteryHealth
3217 + " batteryPlugType=" + cur.batteryPlugType
3218 + " states=0x" + Integer.toHexString(cur.states));
3219 } else {
Adam Lesinski926969b2016-04-28 17:31:12 -07003220 cur.states = (firstToken&DELTA_STATE_MASK) | (cur.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003221 }
3222
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003223 if ((firstToken&DELTA_STATE2_FLAG) != 0) {
3224 cur.states2 = src.readInt();
3225 if (DEBUG) Slog.i(TAG, "READ DELTA: states2=0x"
3226 + Integer.toHexString(cur.states2));
3227 }
3228
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003229 if ((firstToken&DELTA_WAKELOCK_FLAG) != 0) {
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003230 int indexes = src.readInt();
3231 int wakeLockIndex = indexes&0xffff;
3232 int wakeReasonIndex = (indexes>>16)&0xffff;
3233 if (wakeLockIndex != 0xffff) {
3234 cur.wakelockTag = cur.localWakelockTag;
3235 readHistoryTag(wakeLockIndex, cur.wakelockTag);
3236 if (DEBUG) Slog.i(TAG, "READ DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3237 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3238 } else {
3239 cur.wakelockTag = null;
3240 }
3241 if (wakeReasonIndex != 0xffff) {
3242 cur.wakeReasonTag = cur.localWakeReasonTag;
3243 readHistoryTag(wakeReasonIndex, cur.wakeReasonTag);
3244 if (DEBUG) Slog.i(TAG, "READ DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3245 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3246 } else {
3247 cur.wakeReasonTag = null;
3248 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003249 cur.numReadInts += 1;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003250 } else {
3251 cur.wakelockTag = null;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003252 cur.wakeReasonTag = null;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003253 }
3254
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003255 if ((firstToken&DELTA_EVENT_FLAG) != 0) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003256 cur.eventTag = cur.localEventTag;
3257 final int codeAndIndex = src.readInt();
Dianne Hackborn099bc622014-01-22 13:39:16 -08003258 cur.eventCode = (codeAndIndex&0xffff);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003259 final int index = ((codeAndIndex>>16)&0xffff);
3260 readHistoryTag(index, cur.eventTag);
3261 cur.numReadInts += 1;
3262 if (DEBUG) Slog.i(TAG, "READ DELTA: event=" + cur.eventCode + " tag=#"
3263 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3264 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003265 } else {
3266 cur.eventCode = HistoryItem.EVENT_NONE;
3267 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003268
3269 if ((batteryLevelInt&BATTERY_DELTA_LEVEL_FLAG) != 0) {
3270 cur.stepDetails = mReadHistoryStepDetails;
3271 cur.stepDetails.readFromParcel(src);
3272 } else {
3273 cur.stepDetails = null;
3274 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003275
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003276 if ((firstToken&DELTA_BATTERY_CHARGE_FLAG) != 0) {
3277 cur.batteryChargeUAh = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003278 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003279 }
3280
Dianne Hackbornfc064132014-06-02 12:42:12 -07003281 @Override
3282 public void commitCurrentHistoryBatchLocked() {
3283 mHistoryLastWritten.cmd = HistoryItem.CMD_NULL;
3284 }
3285
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003286 void addHistoryBufferLocked(long elapsedRealtimeMs, long uptimeMs, HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003287 if (!mHaveBatteryLevel || !mRecordingHistory) {
3288 return;
3289 }
3290
Dianne Hackborn40c87252014-03-19 16:55:40 -07003291 final long timeDiff = (mHistoryBaseTime+elapsedRealtimeMs) - mHistoryLastWritten.time;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003292 final int diffStates = mHistoryLastWritten.states^(cur.states&mActiveHistoryStates);
3293 final int diffStates2 = mHistoryLastWritten.states2^(cur.states2&mActiveHistoryStates2);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003294 final int lastDiffStates = mHistoryLastWritten.states^mHistoryLastLastWritten.states;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003295 final int lastDiffStates2 = mHistoryLastWritten.states2^mHistoryLastLastWritten.states2;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003296 if (DEBUG) Slog.i(TAG, "ADD: tdelta=" + timeDiff + " diff="
3297 + Integer.toHexString(diffStates) + " lastDiff="
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003298 + Integer.toHexString(lastDiffStates) + " diff2="
3299 + Integer.toHexString(diffStates2) + " lastDiff2="
3300 + Integer.toHexString(lastDiffStates2));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003301 if (mHistoryBufferLastPos >= 0 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003302 && timeDiff < 1000 && (diffStates&lastDiffStates) == 0
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003303 && (diffStates2&lastDiffStates2) == 0
3304 && (mHistoryLastWritten.wakelockTag == null || cur.wakelockTag == null)
3305 && (mHistoryLastWritten.wakeReasonTag == null || cur.wakeReasonTag == null)
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003306 && mHistoryLastWritten.stepDetails == null
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003307 && (mHistoryLastWritten.eventCode == HistoryItem.EVENT_NONE
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003308 || cur.eventCode == HistoryItem.EVENT_NONE)
3309 && mHistoryLastWritten.batteryLevel == cur.batteryLevel
3310 && mHistoryLastWritten.batteryStatus == cur.batteryStatus
3311 && mHistoryLastWritten.batteryHealth == cur.batteryHealth
3312 && mHistoryLastWritten.batteryPlugType == cur.batteryPlugType
3313 && mHistoryLastWritten.batteryTemperature == cur.batteryTemperature
3314 && mHistoryLastWritten.batteryVoltage == cur.batteryVoltage) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003315 // We can merge this new change in with the last one. Merging is
Dianne Hackborn40c87252014-03-19 16:55:40 -07003316 // allowed as long as only the states have changed, and within those states
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003317 // as long as no bit has changed both between now and the last entry, as
3318 // well as the last entry and the one before it (so we capture any toggles).
3319 if (DEBUG) Slog.i(TAG, "ADD: rewinding back to " + mHistoryBufferLastPos);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003320 mHistoryBuffer.setDataSize(mHistoryBufferLastPos);
3321 mHistoryBuffer.setDataPosition(mHistoryBufferLastPos);
3322 mHistoryBufferLastPos = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003323 elapsedRealtimeMs = mHistoryLastWritten.time - mHistoryBaseTime;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003324 // If the last written history had a wakelock tag, we need to retain it.
3325 // Note that the condition above made sure that we aren't in a case where
3326 // both it and the current history item have a wakelock tag.
3327 if (mHistoryLastWritten.wakelockTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003328 cur.wakelockTag = cur.localWakelockTag;
3329 cur.wakelockTag.setTo(mHistoryLastWritten.wakelockTag);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003330 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003331 // If the last written history had a wake reason tag, we need to retain it.
3332 // Note that the condition above made sure that we aren't in a case where
3333 // both it and the current history item have a wakelock tag.
3334 if (mHistoryLastWritten.wakeReasonTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003335 cur.wakeReasonTag = cur.localWakeReasonTag;
3336 cur.wakeReasonTag.setTo(mHistoryLastWritten.wakeReasonTag);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003337 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003338 // If the last written history had an event, we need to retain it.
3339 // Note that the condition above made sure that we aren't in a case where
3340 // both it and the current history item have an event.
3341 if (mHistoryLastWritten.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003342 cur.eventCode = mHistoryLastWritten.eventCode;
3343 cur.eventTag = cur.localEventTag;
3344 cur.eventTag.setTo(mHistoryLastWritten.eventTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003345 }
Dianne Hackborn1fadab52011-04-14 17:57:33 -07003346 mHistoryLastWritten.setTo(mHistoryLastLastWritten);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003347 }
3348
Adam Lesinski45489782016-12-15 23:45:17 -08003349 boolean recordResetDueToOverflow = false;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003350 final int dataSize = mHistoryBuffer.dataSize();
Adam Lesinski45489782016-12-15 23:45:17 -08003351 if (dataSize >= MAX_MAX_HISTORY_BUFFER*3) {
3352 // Clients can't deal with history buffers this large. This only
3353 // really happens when the device is on charger and interacted with
3354 // for long periods of time, like in retail mode. Since the device is
3355 // most likely charged, when unplugged, stats would have reset anyways.
3356 // Reset the stats and mark that we overflowed.
3357 // b/32540341
3358 resetAllStatsLocked();
3359
3360 // Mark that we want to set *OVERFLOW* event and the RESET:START
3361 // events.
3362 recordResetDueToOverflow = true;
3363
3364 } else if (dataSize >= MAX_HISTORY_BUFFER) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003365 if (!mHistoryOverflow) {
3366 mHistoryOverflow = true;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003367 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur);
3368 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_OVERFLOW, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003369 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003370 }
3371
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003372 // After overflow, we allow various bit-wise states to settle to 0.
3373 boolean writeAnyway = false;
3374 final int curStates = cur.states & HistoryItem.SETTLE_TO_ZERO_STATES
3375 & mActiveHistoryStates;
3376 if (mHistoryLastWritten.states != curStates) {
3377 // mActiveHistoryStates keeps track of which bits in .states are now being
3378 // forced to 0.
3379 int old = mActiveHistoryStates;
3380 mActiveHistoryStates &= curStates | ~HistoryItem.SETTLE_TO_ZERO_STATES;
3381 writeAnyway |= old != mActiveHistoryStates;
3382 }
3383 final int curStates2 = cur.states2 & HistoryItem.SETTLE_TO_ZERO_STATES2
3384 & mActiveHistoryStates2;
3385 if (mHistoryLastWritten.states2 != curStates2) {
3386 // mActiveHistoryStates2 keeps track of which bits in .states2 are now being
3387 // forced to 0.
3388 int old = mActiveHistoryStates2;
3389 mActiveHistoryStates2 &= curStates2 | ~HistoryItem.SETTLE_TO_ZERO_STATES2;
3390 writeAnyway |= old != mActiveHistoryStates2;
3391 }
3392
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003393 // Once we've reached the maximum number of items, we only
3394 // record changes to the battery level and the most interesting states.
3395 // Once we've reached the maximum maximum number of items, we only
3396 // record changes to the battery level.
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003397 if (!writeAnyway && mHistoryLastWritten.batteryLevel == cur.batteryLevel &&
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003398 (dataSize >= MAX_MAX_HISTORY_BUFFER
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003399 || ((mHistoryLastWritten.states^cur.states)
Dianne Hackborn3251b902014-06-20 14:40:53 -07003400 & HistoryItem.MOST_INTERESTING_STATES) == 0
3401 || ((mHistoryLastWritten.states2^cur.states2)
3402 & HistoryItem.MOST_INTERESTING_STATES2) == 0)) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003403 return;
3404 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003405
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003406 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003407 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003408 }
3409
Adam Lesinski45489782016-12-15 23:45:17 -08003410 if (dataSize == 0 || recordResetDueToOverflow) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003411 // The history is currently empty; we need it to start with a time stamp.
3412 cur.currentTime = System.currentTimeMillis();
Adam Lesinski45489782016-12-15 23:45:17 -08003413 if (recordResetDueToOverflow) {
3414 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_OVERFLOW, cur);
3415 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003416 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_RESET, cur);
3417 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003418 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003419 }
3420
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003421 private void addHistoryBufferLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd,
3422 HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003423 if (mIteratingHistory) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003424 throw new IllegalStateException("Can't do this while iterating history!");
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003425 }
3426 mHistoryBufferLastPos = mHistoryBuffer.dataPosition();
3427 mHistoryLastLastWritten.setTo(mHistoryLastWritten);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003428 mHistoryLastWritten.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003429 mHistoryLastWritten.states &= mActiveHistoryStates;
3430 mHistoryLastWritten.states2 &= mActiveHistoryStates2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003431 writeHistoryDelta(mHistoryBuffer, mHistoryLastWritten, mHistoryLastLastWritten);
Dianne Hackborn40c87252014-03-19 16:55:40 -07003432 mLastHistoryElapsedRealtime = elapsedRealtimeMs;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003433 cur.wakelockTag = null;
3434 cur.wakeReasonTag = null;
3435 cur.eventCode = HistoryItem.EVENT_NONE;
3436 cur.eventTag = null;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003437 if (DEBUG_HISTORY) Slog.i(TAG, "Writing history buffer: was " + mHistoryBufferLastPos
3438 + " now " + mHistoryBuffer.dataPosition()
3439 + " size is now " + mHistoryBuffer.dataSize());
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003440 }
3441
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003442 int mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003443 int mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003444
Dianne Hackborn40c87252014-03-19 16:55:40 -07003445 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003446 if (mTrackRunningHistoryElapsedRealtime != 0) {
3447 final long diffElapsed = elapsedRealtimeMs - mTrackRunningHistoryElapsedRealtime;
3448 final long diffUptime = uptimeMs - mTrackRunningHistoryUptime;
3449 if (diffUptime < (diffElapsed-20)) {
3450 final long wakeElapsedTime = elapsedRealtimeMs - (diffElapsed - diffUptime);
3451 mHistoryAddTmp.setTo(mHistoryLastWritten);
3452 mHistoryAddTmp.wakelockTag = null;
3453 mHistoryAddTmp.wakeReasonTag = null;
3454 mHistoryAddTmp.eventCode = HistoryItem.EVENT_NONE;
3455 mHistoryAddTmp.states &= ~HistoryItem.STATE_CPU_RUNNING_FLAG;
3456 addHistoryRecordInnerLocked(wakeElapsedTime, uptimeMs, mHistoryAddTmp);
3457 }
3458 }
3459 mHistoryCur.states |= HistoryItem.STATE_CPU_RUNNING_FLAG;
3460 mTrackRunningHistoryElapsedRealtime = elapsedRealtimeMs;
3461 mTrackRunningHistoryUptime = uptimeMs;
3462 addHistoryRecordInnerLocked(elapsedRealtimeMs, uptimeMs, mHistoryCur);
3463 }
3464
3465 void addHistoryRecordInnerLocked(long elapsedRealtimeMs, long uptimeMs, HistoryItem cur) {
3466 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003467
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003468 if (!USE_OLD_HISTORY) {
3469 return;
3470 }
3471
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003472 if (!mHaveBatteryLevel || !mRecordingHistory) {
3473 return;
3474 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003475
3476 // If the current time is basically the same as the last time,
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003477 // and no states have since the last recorded entry changed and
3478 // are now resetting back to their original value, then just collapse
3479 // into one record.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003480 if (mHistoryEnd != null && mHistoryEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003481 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+1000)
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003482 && ((mHistoryEnd.states^cur.states)&mChangedStates&mActiveHistoryStates) == 0
3483 && ((mHistoryEnd.states2^cur.states2)&mChangedStates2&mActiveHistoryStates2) == 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003484 // If the current is the same as the one before, then we no
3485 // longer need the entry.
3486 if (mHistoryLastEnd != null && mHistoryLastEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003487 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+500)
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003488 && mHistoryLastEnd.sameNonEvent(cur)) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003489 mHistoryLastEnd.next = null;
3490 mHistoryEnd.next = mHistoryCache;
3491 mHistoryCache = mHistoryEnd;
3492 mHistoryEnd = mHistoryLastEnd;
3493 mHistoryLastEnd = null;
3494 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003495 mChangedStates |= mHistoryEnd.states^(cur.states&mActiveHistoryStates);
3496 mChangedStates2 |= mHistoryEnd.states^(cur.states2&mActiveHistoryStates2);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003497 mHistoryEnd.setTo(mHistoryEnd.time, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003498 }
3499 return;
3500 }
3501
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003502 mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003503 mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003504
3505 if (mNumHistoryItems == MAX_HISTORY_ITEMS
3506 || mNumHistoryItems == MAX_MAX_HISTORY_ITEMS) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07003507 addHistoryRecordLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003508 }
3509
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003510 if (mNumHistoryItems >= MAX_HISTORY_ITEMS) {
3511 // Once we've reached the maximum number of items, we only
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003512 // record changes to the battery level and the most interesting states.
3513 // Once we've reached the maximum maximum number of items, we only
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003514 // record changes to the battery level.
3515 if (mHistoryEnd != null && mHistoryEnd.batteryLevel
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003516 == cur.batteryLevel &&
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003517 (mNumHistoryItems >= MAX_MAX_HISTORY_ITEMS
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003518 || ((mHistoryEnd.states^(cur.states&mActiveHistoryStates))
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003519 & HistoryItem.MOST_INTERESTING_STATES) == 0)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003520 return;
3521 }
3522 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003523
Dianne Hackborn40c87252014-03-19 16:55:40 -07003524 addHistoryRecordLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003525 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003526
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003527 public void addHistoryEventLocked(long elapsedRealtimeMs, long uptimeMs, int code,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003528 String name, int uid) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003529 mHistoryCur.eventCode = code;
3530 mHistoryCur.eventTag = mHistoryCur.localEventTag;
3531 mHistoryCur.eventTag.string = name;
3532 mHistoryCur.eventTag.uid = uid;
Dianne Hackborn4590e522014-03-24 13:36:46 -07003533 addHistoryRecordLocked(elapsedRealtimeMs, uptimeMs);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003534 }
3535
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003536 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd, HistoryItem cur) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003537 HistoryItem rec = mHistoryCache;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003538 if (rec != null) {
3539 mHistoryCache = rec.next;
3540 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003541 rec = new HistoryItem();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003542 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003543 rec.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003544
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003545 addHistoryRecordLocked(rec);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003546 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003547
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003548 void addHistoryRecordLocked(HistoryItem rec) {
3549 mNumHistoryItems++;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003550 rec.next = null;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003551 mHistoryLastEnd = mHistoryEnd;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003552 if (mHistoryEnd != null) {
3553 mHistoryEnd.next = rec;
3554 mHistoryEnd = rec;
3555 } else {
3556 mHistory = mHistoryEnd = rec;
3557 }
3558 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003559
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003560 void clearHistoryLocked() {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003561 if (DEBUG_HISTORY) Slog.i(TAG, "********** CLEARING HISTORY!");
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003562 if (USE_OLD_HISTORY) {
3563 if (mHistory != null) {
3564 mHistoryEnd.next = mHistoryCache;
3565 mHistoryCache = mHistory;
3566 mHistory = mHistoryLastEnd = mHistoryEnd = null;
3567 }
3568 mNumHistoryItems = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003569 }
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003570
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003571 mHistoryBaseTime = 0;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003572 mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003573 mTrackRunningHistoryElapsedRealtime = 0;
3574 mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003575
3576 mHistoryBuffer.setDataSize(0);
3577 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003578 mHistoryBuffer.setDataCapacity(MAX_HISTORY_BUFFER / 2);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003579 mHistoryLastLastWritten.clear();
3580 mHistoryLastWritten.clear();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003581 mHistoryTagPool.clear();
3582 mNextHistoryTagIdx = 0;
3583 mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003584 mHistoryBufferLastPos = -1;
3585 mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003586 mActiveHistoryStates = 0xffffffff;
3587 mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003588 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003589
Mike Mac2f518a2017-09-19 16:06:03 -07003590 public void updateTimeBasesLocked(boolean unplugged, int screenState, long uptime,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003591 long realtime) {
Mike Maa7724752017-10-10 15:29:25 -07003592 final boolean screenOff = !isScreenOn(screenState);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003593 final boolean updateOnBatteryTimeBase = unplugged != mOnBatteryTimeBase.isRunning();
3594 final boolean updateOnBatteryScreenOffTimeBase =
3595 (unplugged && screenOff) != mOnBatteryScreenOffTimeBase.isRunning();
Bookatz867c0d72017-03-07 18:23:42 -08003596
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003597 if (updateOnBatteryScreenOffTimeBase || updateOnBatteryTimeBase) {
3598 if (updateOnBatteryScreenOffTimeBase) {
3599 updateKernelWakelocksLocked();
3600 updateBatteryPropertiesLocked();
Bookatz867c0d72017-03-07 18:23:42 -08003601 }
Bookatz82b341172017-09-07 19:06:08 -07003602 // This if{} is only necessary due to SCREEN_OFF_RPM_STATS_ENABLED, which exists because
3603 // updateRpmStatsLocked is too slow to run each screen change. When the speed is
3604 // improved, remove the surrounding if{}.
3605 if (SCREEN_OFF_RPM_STATS_ENABLED || updateOnBatteryTimeBase) {
3606 updateRpmStatsLocked(); // if either OnBattery or OnBatteryScreenOff timebase changes.
3607 }
Adam Lesinski72478f02015-06-17 15:39:43 -07003608 if (DEBUG_ENERGY_CPU) {
Mike Mac2f518a2017-09-19 16:06:03 -07003609 Slog.d(TAG, "Updating cpu time because screen is now "
3610 + Display.stateToString(screenState)
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003611 + " and battery is " + (unplugged ? "on" : "off"));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003612 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -07003613 updateCpuTimeLocked();
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003614
3615 mOnBatteryTimeBase.setRunning(unplugged, uptime, realtime);
Mike Mac2f518a2017-09-19 16:06:03 -07003616 if (updateOnBatteryTimeBase) {
3617 for (int i = mUidStats.size() - 1; i >= 0; --i) {
3618 mUidStats.valueAt(i).updateOnBatteryBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003619 }
Mike Mac2f518a2017-09-19 16:06:03 -07003620 }
3621 if (updateOnBatteryScreenOffTimeBase) {
3622 mOnBatteryScreenOffTimeBase.setRunning(unplugged && screenOff, uptime, realtime);
3623 for (int i = mUidStats.size() - 1; i >= 0; --i) {
3624 mUidStats.valueAt(i).updateOnBatteryScreenOffBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003625 }
Bookatzc8c44962017-05-11 12:12:54 -07003626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003627 }
3628 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07003629
Adam Lesinskie1f480d2017-02-15 18:51:23 -08003630 private void updateBatteryPropertiesLocked() {
3631 try {
3632 IBatteryPropertiesRegistrar registrar = IBatteryPropertiesRegistrar.Stub.asInterface(
3633 ServiceManager.getService("batteryproperties"));
3634 registrar.scheduleUpdate();
3635 } catch (RemoteException e) {
3636 // Ignore.
3637 }
3638 }
3639
Dianne Hackborn099bc622014-01-22 13:39:16 -08003640 public void addIsolatedUidLocked(int isolatedUid, int appUid) {
3641 mIsolatedUids.put(isolatedUid, appUid);
3642 }
3643
Adam Lesinski61db88f2015-07-01 15:05:07 -07003644 /**
3645 * Schedules a read of the latest cpu times before removing the isolated UID.
3646 * @see #removeIsolatedUidLocked(int)
3647 */
3648 public void scheduleRemoveIsolatedUidLocked(int isolatedUid, int appUid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003649 int curUid = mIsolatedUids.get(isolatedUid, -1);
3650 if (curUid == appUid) {
Adam Lesinski61db88f2015-07-01 15:05:07 -07003651 if (mExternalSync != null) {
3652 mExternalSync.scheduleCpuSyncDueToRemovedUid(isolatedUid);
3653 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08003654 }
3655 }
3656
Adam Lesinski61db88f2015-07-01 15:05:07 -07003657 /**
3658 * This should only be called after the cpu times have been read.
3659 * @see #scheduleRemoveIsolatedUidLocked(int, int)
3660 */
3661 public void removeIsolatedUidLocked(int isolatedUid) {
3662 mIsolatedUids.delete(isolatedUid);
3663 mKernelUidCpuTimeReader.removeUid(isolatedUid);
Sudheer Shanka6d8dcec2017-06-01 12:09:03 -07003664 mKernelUidCpuFreqTimeReader.removeUid(isolatedUid);
Adam Lesinski61db88f2015-07-01 15:05:07 -07003665 }
3666
Dianne Hackborn099bc622014-01-22 13:39:16 -08003667 public int mapUid(int uid) {
3668 int isolated = mIsolatedUids.get(uid, -1);
3669 return isolated > 0 ? isolated : uid;
3670 }
3671
3672 public void noteEventLocked(int code, String name, int uid) {
3673 uid = mapUid(uid);
Dianne Hackborn37de0982014-05-09 09:32:18 -07003674 if (!mActiveEvents.updateState(code, name, uid, 0)) {
3675 return;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003676 }
Joe Onoratoabded112016-02-08 16:49:39 -08003677 final long elapsedRealtime = mClocks.elapsedRealtime();
3678 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -07003679 addHistoryEventLocked(elapsedRealtime, uptime, code, name, uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003680 }
3681
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003682 boolean ensureStartClockTime(final long currentTime) {
3683 final long ABOUT_ONE_YEAR = 365*24*60*60*1000L;
3684 if (currentTime > ABOUT_ONE_YEAR && mStartClockTime < (currentTime-ABOUT_ONE_YEAR)) {
3685 // If the start clock time has changed by more than a year, then presumably
3686 // the previous time was completely bogus. So we are going to figure out a
3687 // new time based on how much time has elapsed since we started counting.
Joe Onoratoabded112016-02-08 16:49:39 -08003688 mStartClockTime = currentTime - (mClocks.elapsedRealtime()-(mRealtimeStart/1000));
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003689 return true;
3690 }
3691 return false;
3692 }
3693
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003694 public void noteCurrentTimeChangedLocked() {
3695 final long currentTime = System.currentTimeMillis();
Joe Onoratoabded112016-02-08 16:49:39 -08003696 final long elapsedRealtime = mClocks.elapsedRealtime();
3697 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003698 recordCurrentTimeChangeLocked(currentTime, elapsedRealtime, uptime);
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003699 ensureStartClockTime(currentTime);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003700 }
3701
Dianne Hackborn61659e52014-07-09 16:13:01 -07003702 public void noteProcessStartLocked(String name, int uid) {
3703 uid = mapUid(uid);
3704 if (isOnBattery()) {
3705 Uid u = getUidStatsLocked(uid);
3706 u.getProcessStatsLocked(name).incStartsLocked();
3707 }
3708 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_START, name, uid, 0)) {
3709 return;
3710 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003711 if (!mRecordAllHistory) {
3712 return;
3713 }
Joe Onoratoabded112016-02-08 16:49:39 -08003714 final long elapsedRealtime = mClocks.elapsedRealtime();
3715 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn61659e52014-07-09 16:13:01 -07003716 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_START, name, uid);
3717 }
3718
Dianne Hackborn1e01d162014-12-04 17:46:42 -08003719 public void noteProcessCrashLocked(String name, int uid) {
3720 uid = mapUid(uid);
3721 if (isOnBattery()) {
3722 Uid u = getUidStatsLocked(uid);
3723 u.getProcessStatsLocked(name).incNumCrashesLocked();
3724 }
3725 }
3726
3727 public void noteProcessAnrLocked(String name, int uid) {
3728 uid = mapUid(uid);
3729 if (isOnBattery()) {
3730 Uid u = getUidStatsLocked(uid);
3731 u.getProcessStatsLocked(name).incNumAnrsLocked();
3732 }
3733 }
3734
Dianne Hackborna8d10942015-11-19 17:55:19 -08003735 public void noteUidProcessStateLocked(int uid, int state) {
Amith Yamasanifd3caf62017-07-26 11:48:35 -07003736 int parentUid = mapUid(uid);
3737 if (uid != parentUid) {
3738 // Isolated UIDs process state is already rolled up into parent, so no need to track
3739 // Otherwise the parent's process state will get downgraded incorrectly
3740 return;
3741 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08003742 getUidStatsLocked(uid).updateUidProcessStateLocked(state);
Dianne Hackborn61659e52014-07-09 16:13:01 -07003743 }
3744
3745 public void noteProcessFinishLocked(String name, int uid) {
3746 uid = mapUid(uid);
3747 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_FINISH, name, uid, 0)) {
3748 return;
3749 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003750 if (!mRecordAllHistory) {
3751 return;
3752 }
Joe Onoratoabded112016-02-08 16:49:39 -08003753 final long elapsedRealtime = mClocks.elapsedRealtime();
3754 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003755 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_FINISH, name, uid);
Dianne Hackborn61659e52014-07-09 16:13:01 -07003756 }
3757
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003758 public void noteSyncStartLocked(String name, int uid) {
3759 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003760 final long elapsedRealtime = mClocks.elapsedRealtime();
3761 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003762 getUidStatsLocked(uid).noteStartSyncLocked(name, elapsedRealtime);
3763 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_START, name, uid, 0)) {
3764 return;
3765 }
3766 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_START, name, uid);
3767 }
3768
3769 public void noteSyncFinishLocked(String name, int uid) {
3770 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003771 final long elapsedRealtime = mClocks.elapsedRealtime();
3772 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003773 getUidStatsLocked(uid).noteStopSyncLocked(name, elapsedRealtime);
3774 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_FINISH, name, uid, 0)) {
3775 return;
3776 }
3777 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_FINISH, name, uid);
3778 }
3779
3780 public void noteJobStartLocked(String name, int uid) {
3781 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003782 final long elapsedRealtime = mClocks.elapsedRealtime();
3783 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003784 getUidStatsLocked(uid).noteStartJobLocked(name, elapsedRealtime);
3785 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_START, name, uid, 0)) {
3786 return;
3787 }
3788 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_START, name, uid);
3789 }
3790
Dianne Hackborn94326cb2017-06-28 16:17:20 -07003791 public void noteJobFinishLocked(String name, int uid, int stopReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003792 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003793 final long elapsedRealtime = mClocks.elapsedRealtime();
3794 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07003795 getUidStatsLocked(uid).noteStopJobLocked(name, elapsedRealtime, stopReason);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003796 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_FINISH, name, uid, 0)) {
3797 return;
3798 }
3799 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_FINISH, name, uid);
3800 }
3801
Dianne Hackborn1e383822015-04-10 14:02:33 -07003802 public void noteAlarmStartLocked(String name, int uid) {
3803 if (!mRecordAllHistory) {
3804 return;
3805 }
3806 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003807 final long elapsedRealtime = mClocks.elapsedRealtime();
3808 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e383822015-04-10 14:02:33 -07003809 if (!mActiveEvents.updateState(HistoryItem.EVENT_ALARM_START, name, uid, 0)) {
3810 return;
3811 }
3812 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ALARM_START, name, uid);
3813 }
3814
3815 public void noteAlarmFinishLocked(String name, int uid) {
3816 if (!mRecordAllHistory) {
3817 return;
3818 }
3819 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003820 final long elapsedRealtime = mClocks.elapsedRealtime();
3821 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e383822015-04-10 14:02:33 -07003822 if (!mActiveEvents.updateState(HistoryItem.EVENT_ALARM_FINISH, name, uid, 0)) {
3823 return;
3824 }
3825 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ALARM_FINISH, name, uid);
3826 }
3827
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003828 private void requestWakelockCpuUpdate() {
3829 if (!mHandler.hasMessages(MSG_UPDATE_WAKELOCKS)) {
3830 Message m = mHandler.obtainMessage(MSG_UPDATE_WAKELOCKS);
3831 mHandler.sendMessageDelayed(m, DELAY_UPDATE_WAKELOCKS);
3832 }
3833 }
3834
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003835 private void requestImmediateCpuUpdate() {
3836 mHandler.removeMessages(MSG_UPDATE_WAKELOCKS);
3837 mHandler.sendEmptyMessage(MSG_UPDATE_WAKELOCKS);
3838 }
3839
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003840 public void setRecordAllHistoryLocked(boolean enabled) {
3841 mRecordAllHistory = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003842 if (!enabled) {
3843 // Clear out any existing state.
3844 mActiveEvents.removeEvents(HistoryItem.EVENT_WAKE_LOCK);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003845 mActiveEvents.removeEvents(HistoryItem.EVENT_ALARM);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003846 // Record the currently running processes as stopping, now that we are no
3847 // longer tracking them.
3848 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
3849 HistoryItem.EVENT_PROC);
3850 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08003851 long mSecRealtime = mClocks.elapsedRealtime();
3852 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003853 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
3854 SparseIntArray uids = ent.getValue();
3855 for (int j=0; j<uids.size(); j++) {
3856 addHistoryEventLocked(mSecRealtime, mSecUptime,
3857 HistoryItem.EVENT_PROC_FINISH, ent.getKey(), uids.keyAt(j));
3858 }
3859 }
3860 }
3861 } else {
3862 // Record the currently running processes as starting, now that we are tracking them.
3863 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
3864 HistoryItem.EVENT_PROC);
3865 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08003866 long mSecRealtime = mClocks.elapsedRealtime();
3867 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003868 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
3869 SparseIntArray uids = ent.getValue();
3870 for (int j=0; j<uids.size(); j++) {
3871 addHistoryEventLocked(mSecRealtime, mSecUptime,
3872 HistoryItem.EVENT_PROC_START, ent.getKey(), uids.keyAt(j));
3873 }
3874 }
3875 }
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003876 }
3877 }
3878
Dianne Hackborn9a755432014-05-15 17:05:22 -07003879 public void setNoAutoReset(boolean enabled) {
3880 mNoAutoReset = enabled;
3881 }
3882
Amith Yamasani674c9bb2017-02-01 09:45:17 -08003883 public void setPretendScreenOff(boolean pretendScreenOff) {
Mike Mac2f518a2017-09-19 16:06:03 -07003884 if (mPretendScreenOff != pretendScreenOff) {
3885 mPretendScreenOff = pretendScreenOff;
3886 noteScreenStateLocked(pretendScreenOff ? Display.STATE_OFF : Display.STATE_ON);
3887 }
Amith Yamasani674c9bb2017-02-01 09:45:17 -08003888 }
3889
Dianne Hackborn9a755432014-05-15 17:05:22 -07003890 private String mInitialAcquireWakeName;
3891 private int mInitialAcquireWakeUid = -1;
3892
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003893 public void noteStartWakeLocked(int uid, int pid, String name, String historyName, int type,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003894 boolean unimportantForLogging, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003895 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07003896 if (type == WAKE_TYPE_PARTIAL) {
3897 // Only care about partial wake locks, since full wake locks
3898 // will be canceled when the user puts the screen to sleep.
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003899 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07003900 if (historyName == null) {
3901 historyName = name;
3902 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003903 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07003904 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_START, historyName,
3905 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07003906 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07003907 HistoryItem.EVENT_WAKE_LOCK_START, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07003908 }
3909 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07003910 if (mWakeLockNesting == 0) {
3911 mHistoryCur.states |= HistoryItem.STATE_WAKE_LOCK_FLAG;
3912 if (DEBUG_HISTORY) Slog.v(TAG, "Start wake lock to: "
3913 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003914 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003915 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07003916 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003917 mWakeLockImportant = !unimportantForLogging;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003918 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07003919 } else if (!mWakeLockImportant && !unimportantForLogging
3920 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003921 if (mHistoryLastWritten.wakelockTag != null) {
3922 // We'll try to update the last tag.
3923 mHistoryLastWritten.wakelockTag = null;
3924 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003925 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07003926 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003927 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003928 }
3929 mWakeLockImportant = true;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07003930 }
3931 mWakeLockNesting++;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003932 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003933 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07003934 if (mOnBatteryScreenOffTimeBase.isRunning()) {
3935 // We only update the cpu time when a wake lock is acquired if the screen is off.
3936 // If the screen is on, we don't distribute the power amongst partial wakelocks.
3937 if (DEBUG_ENERGY_CPU) {
3938 Slog.d(TAG, "Updating cpu time because of +wake_lock");
3939 }
3940 requestWakelockCpuUpdate();
3941 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08003942 getUidStatsLocked(uid).noteStartWakeLocked(pid, name, type, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003943 }
3944 }
3945
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003946 public void noteStopWakeLocked(int uid, int pid, String name, String historyName, int type,
3947 long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003948 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07003949 if (type == WAKE_TYPE_PARTIAL) {
3950 mWakeLockNesting--;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003951 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07003952 if (historyName == null) {
3953 historyName = name;
3954 }
3955 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName,
3956 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07003957 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07003958 HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07003959 }
3960 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07003961 if (mWakeLockNesting == 0) {
3962 mHistoryCur.states &= ~HistoryItem.STATE_WAKE_LOCK_FLAG;
3963 if (DEBUG_HISTORY) Slog.v(TAG, "Stop wake lock to: "
3964 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn37de0982014-05-09 09:32:18 -07003965 mInitialAcquireWakeName = null;
3966 mInitialAcquireWakeUid = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003967 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07003968 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003969 }
3970 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07003971 if (mOnBatteryScreenOffTimeBase.isRunning()) {
3972 if (DEBUG_ENERGY_CPU) {
3973 Slog.d(TAG, "Updating cpu time because of -wake_lock");
3974 }
3975 requestWakelockCpuUpdate();
3976 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08003977 getUidStatsLocked(uid).noteStopWakeLocked(pid, name, type, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003978 }
3979 }
3980
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003981 public void noteStartWakeFromSourceLocked(WorkSource ws, int pid, String name,
3982 String historyName, int type, boolean unimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08003983 final long elapsedRealtime = mClocks.elapsedRealtime();
3984 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003985 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003986 for (int i=0; i<N; i++) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003987 noteStartWakeLocked(ws.get(i), pid, name, historyName, type, unimportantForLogging,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003988 elapsedRealtime, uptime);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003989 }
3990 }
3991
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003992 public void noteChangeWakelockFromSourceLocked(WorkSource ws, int pid, String name,
3993 String historyName, int type, WorkSource newWs, int newPid, String newName,
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003994 String newHistoryName, int newType, boolean newUnimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08003995 final long elapsedRealtime = mClocks.elapsedRealtime();
3996 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003997 // For correct semantics, we start the need worksources first, so that we won't
3998 // make inappropriate history items as if all wake locks went away and new ones
3999 // appeared. This is okay because tracking of wake locks allows nesting.
Dianne Hackborn40c87252014-03-19 16:55:40 -07004000 final int NN = newWs.size();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004001 for (int i=0; i<NN; i++) {
4002 noteStartWakeLocked(newWs.get(i), newPid, newName, newHistoryName, newType,
Dianne Hackborn40c87252014-03-19 16:55:40 -07004003 newUnimportantForLogging, elapsedRealtime, uptime);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004004 }
4005 final int NO = ws.size();
4006 for (int i=0; i<NO; i++) {
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004007 noteStopWakeLocked(ws.get(i), pid, name, historyName, type, elapsedRealtime, uptime);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004008 }
4009 }
4010
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004011 public void noteStopWakeFromSourceLocked(WorkSource ws, int pid, String name,
4012 String historyName, int type) {
Joe Onoratoabded112016-02-08 16:49:39 -08004013 final long elapsedRealtime = mClocks.elapsedRealtime();
4014 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004015 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004016 for (int i=0; i<N; i++) {
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004017 noteStopWakeLocked(ws.get(i), pid, name, historyName, type, elapsedRealtime, uptime);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004018 }
4019 }
4020
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004021 public void noteLongPartialWakelockStart(String name, String historyName, int uid) {
4022 uid = mapUid(uid);
4023 final long elapsedRealtime = mClocks.elapsedRealtime();
4024 final long uptime = mClocks.uptimeMillis();
4025 if (historyName == null) {
4026 historyName = name;
4027 }
4028 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_START, historyName, uid,
4029 0)) {
4030 return;
4031 }
4032 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_START,
4033 historyName, uid);
Bookatzc1a050a2017-10-10 15:49:28 -07004034 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED, uid, name, historyName, 1);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004035 }
4036
4037 public void noteLongPartialWakelockFinish(String name, String historyName, int uid) {
4038 uid = mapUid(uid);
4039 final long elapsedRealtime = mClocks.elapsedRealtime();
4040 final long uptime = mClocks.uptimeMillis();
4041 if (historyName == null) {
4042 historyName = name;
4043 }
4044 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH, historyName, uid,
4045 0)) {
4046 return;
4047 }
4048 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH,
4049 historyName, uid);
Bookatzc1a050a2017-10-10 15:49:28 -07004050 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED, uid, name, historyName, 0);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004051 }
4052
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004053 void aggregateLastWakeupUptimeLocked(long uptimeMs) {
4054 if (mLastWakeupReason != null) {
4055 long deltaUptime = uptimeMs - mLastWakeupUptimeMs;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004056 SamplingTimer timer = getWakeupReasonTimerLocked(mLastWakeupReason);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07004057 timer.add(deltaUptime * 1000, 1); // time in in microseconds
Bookatz8c6571b2017-10-24 15:04:41 -07004058 StatsLog.write(StatsLog.KERNEL_WAKEUP_REPORTED, mLastWakeupReason, deltaUptime * 1000);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004059 mLastWakeupReason = null;
4060 }
4061 }
4062
4063 public void noteWakeupReasonLocked(String reason) {
Joe Onoratoabded112016-02-08 16:49:39 -08004064 final long elapsedRealtime = mClocks.elapsedRealtime();
4065 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004066 if (DEBUG_HISTORY) Slog.v(TAG, "Wakeup reason \"" + reason +"\": "
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004067 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004068 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004069 mHistoryCur.wakeReasonTag = mHistoryCur.localWakeReasonTag;
4070 mHistoryCur.wakeReasonTag.string = reason;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004071 mHistoryCur.wakeReasonTag.uid = 0;
4072 mLastWakeupReason = reason;
4073 mLastWakeupUptimeMs = uptime;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004074 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004075 }
4076
Adam Lesinski72478f02015-06-17 15:39:43 -07004077 public boolean startAddingCpuLocked() {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004078 mHandler.removeMessages(MSG_UPDATE_WAKELOCKS);
Adam Lesinski72478f02015-06-17 15:39:43 -07004079 return mOnBatteryInternal;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004080 }
4081
Adam Lesinski72478f02015-06-17 15:39:43 -07004082 public void finishAddingCpuLocked(int totalUTime, int totalSTime, int statUserTime,
4083 int statSystemTime, int statIOWaitTime, int statIrqTime,
4084 int statSoftIrqTime, int statIdleTime) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004085 if (DEBUG) Slog.d(TAG, "Adding cpu: tuser=" + totalUTime + " tsys=" + totalSTime
4086 + " user=" + statUserTime + " sys=" + statSystemTime
4087 + " io=" + statIOWaitTime + " irq=" + statIrqTime
4088 + " sirq=" + statSoftIrqTime + " idle=" + statIdleTime);
4089 mCurStepCpuUserTime += totalUTime;
4090 mCurStepCpuSystemTime += totalSTime;
4091 mCurStepStatUserTime += statUserTime;
4092 mCurStepStatSystemTime += statSystemTime;
4093 mCurStepStatIOWaitTime += statIOWaitTime;
4094 mCurStepStatIrqTime += statIrqTime;
4095 mCurStepStatSoftIrqTime += statSoftIrqTime;
4096 mCurStepStatIdleTime += statIdleTime;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004097 }
4098
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004099 public void noteProcessDiedLocked(int uid, int pid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004100 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004101 Uid u = mUidStats.get(uid);
4102 if (u != null) {
4103 u.mPids.remove(pid);
4104 }
4105 }
4106
4107 public long getProcessWakeTime(int uid, int pid, long realtime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004108 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004109 Uid u = mUidStats.get(uid);
4110 if (u != null) {
4111 Uid.Pid p = u.mPids.get(pid);
4112 if (p != null) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004113 return p.mWakeSumMs + (p.mWakeNesting > 0 ? (realtime - p.mWakeStartMs) : 0);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004114 }
4115 }
4116 return 0;
4117 }
4118
Dianne Hackborn287952c2010-09-22 22:34:31 -07004119 public void reportExcessiveCpuLocked(int uid, String proc, long overTime, long usedTime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004120 uid = mapUid(uid);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004121 Uid u = mUidStats.get(uid);
4122 if (u != null) {
4123 u.reportExcessiveCpuLocked(proc, overTime, usedTime);
4124 }
4125 }
4126
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004127 int mSensorNesting;
4128
4129 public void noteStartSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004130 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004131 final long elapsedRealtime = mClocks.elapsedRealtime();
4132 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004133 if (mSensorNesting == 0) {
4134 mHistoryCur.states |= HistoryItem.STATE_SENSOR_ON_FLAG;
4135 if (DEBUG_HISTORY) Slog.v(TAG, "Start sensor to: "
4136 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004137 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004138 }
4139 mSensorNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004140 getUidStatsLocked(uid).noteStartSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004141 }
4142
4143 public void noteStopSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004144 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004145 final long elapsedRealtime = mClocks.elapsedRealtime();
4146 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004147 mSensorNesting--;
4148 if (mSensorNesting == 0) {
4149 mHistoryCur.states &= ~HistoryItem.STATE_SENSOR_ON_FLAG;
4150 if (DEBUG_HISTORY) Slog.v(TAG, "Stop sensor to: "
4151 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004152 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004153 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004154 getUidStatsLocked(uid).noteStopSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004155 }
4156
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004157 int mGpsNesting;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004158
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004159 public void noteStartGpsLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004160 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004161 final long elapsedRealtime = mClocks.elapsedRealtime();
4162 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004163 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004164 mHistoryCur.states |= HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004165 if (DEBUG_HISTORY) Slog.v(TAG, "Start GPS to: "
4166 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004167 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004168 }
4169 mGpsNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004170 getUidStatsLocked(uid).noteStartGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004171 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004172
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004173 public void noteStopGpsLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004174 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004175 final long elapsedRealtime = mClocks.elapsedRealtime();
4176 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004177 mGpsNesting--;
4178 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004179 mHistoryCur.states &= ~HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004180 if (DEBUG_HISTORY) Slog.v(TAG, "Stop GPS to: "
4181 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004182 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004183 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004184 getUidStatsLocked(uid).noteStopGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004185 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004186
Jeff Browne95c3cd2014-05-02 16:59:26 -07004187 public void noteScreenStateLocked(int state) {
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004188 state = mPretendScreenOff ? Display.STATE_OFF : state;
Santos Cordone94f0502017-02-24 12:31:20 -08004189
4190 // Battery stats relies on there being 4 states. To accommodate this, new states beyond the
4191 // original 4 are mapped to one of the originals.
4192 if (state > MAX_TRACKED_SCREEN_STATE) {
4193 switch (state) {
4194 case Display.STATE_VR:
4195 state = Display.STATE_ON;
4196 break;
4197 default:
4198 Slog.wtf(TAG, "Unknown screen state (not mapped): " + state);
4199 break;
4200 }
4201 }
4202
Jeff Browne95c3cd2014-05-02 16:59:26 -07004203 if (mScreenState != state) {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08004204 recordDailyStatsIfNeededLocked(true);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004205 final int oldState = mScreenState;
4206 mScreenState = state;
4207 if (DEBUG) Slog.v(TAG, "Screen state: oldState=" + Display.stateToString(oldState)
4208 + ", newState=" + Display.stateToString(state));
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004209
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004210 if (state != Display.STATE_UNKNOWN) {
4211 int stepState = state-1;
Santos Cordone94f0502017-02-24 12:31:20 -08004212 if ((stepState & STEP_LEVEL_MODE_SCREEN_STATE) == stepState) {
4213 mModStepMode |= (mCurStepMode & STEP_LEVEL_MODE_SCREEN_STATE) ^ stepState;
4214 mCurStepMode = (mCurStepMode & ~STEP_LEVEL_MODE_SCREEN_STATE) | stepState;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004215 } else {
4216 Slog.wtf(TAG, "Unexpected screen state: " + state);
4217 }
4218 }
4219
Mike Mac2f518a2017-09-19 16:06:03 -07004220 final long elapsedRealtime = mClocks.elapsedRealtime();
4221 final long uptime = mClocks.uptimeMillis();
4222
4223 boolean updateHistory = false;
4224 if (isScreenDoze(state)) {
4225 mHistoryCur.states |= HistoryItem.STATE_SCREEN_DOZE_FLAG;
4226 mScreenDozeTimer.startRunningLocked(elapsedRealtime);
4227 updateHistory = true;
4228 } else if (isScreenDoze(oldState)) {
4229 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_DOZE_FLAG;
4230 mScreenDozeTimer.stopRunningLocked(elapsedRealtime);
4231 updateHistory = true;
4232 }
4233 if (isScreenOn(state)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004234 mHistoryCur.states |= HistoryItem.STATE_SCREEN_ON_FLAG;
4235 if (DEBUG_HISTORY) Slog.v(TAG, "Screen on to: "
4236 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004237 mScreenOnTimer.startRunningLocked(elapsedRealtime);
4238 if (mScreenBrightnessBin >= 0) {
4239 mScreenBrightnessTimer[mScreenBrightnessBin].startRunningLocked(elapsedRealtime);
4240 }
Mike Mac2f518a2017-09-19 16:06:03 -07004241 updateHistory = true;
4242 } else if (isScreenOn(oldState)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004243 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_ON_FLAG;
4244 if (DEBUG_HISTORY) Slog.v(TAG, "Screen off to: "
4245 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004246 mScreenOnTimer.stopRunningLocked(elapsedRealtime);
4247 if (mScreenBrightnessBin >= 0) {
4248 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
4249 }
Mike Mac2f518a2017-09-19 16:06:03 -07004250 updateHistory = true;
4251 }
4252 if (updateHistory) {
4253 if (DEBUG_HISTORY) Slog.v(TAG, "Screen state to: "
4254 + Display.stateToString(state));
4255 addHistoryRecordLocked(elapsedRealtime, uptime);
4256 }
4257 if (isScreenOn(state)) {
4258 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
4259 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
4260 // Fake a wake lock, so we consider the device waked as long as the screen is on.
4261 noteStartWakeLocked(-1, -1, "screen", null, WAKE_TYPE_PARTIAL, false,
4262 elapsedRealtime, uptime);
4263 } else if (isScreenOn(oldState)) {
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004264 noteStopWakeLocked(-1, -1, "screen", "screen", WAKE_TYPE_PARTIAL,
Jeff Browne95c3cd2014-05-02 16:59:26 -07004265 elapsedRealtime, uptime);
Mike Mac2f518a2017-09-19 16:06:03 -07004266 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
Joe Onoratoabded112016-02-08 16:49:39 -08004267 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
Mike Mac2f518a2017-09-19 16:06:03 -07004268 }
4269 // Update discharge amounts.
4270 if (mOnBatteryInternal) {
4271 updateDischargeScreenLevelsLocked(oldState, state);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08004272 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07004273 }
4274 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004275
Dianne Hackborn617f8772009-03-31 15:04:46 -07004276 public void noteScreenBrightnessLocked(int brightness) {
4277 // Bin the brightness.
4278 int bin = brightness / (256/NUM_SCREEN_BRIGHTNESS_BINS);
4279 if (bin < 0) bin = 0;
4280 else if (bin >= NUM_SCREEN_BRIGHTNESS_BINS) bin = NUM_SCREEN_BRIGHTNESS_BINS-1;
4281 if (mScreenBrightnessBin != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08004282 final long elapsedRealtime = mClocks.elapsedRealtime();
4283 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004284 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_BRIGHTNESS_MASK)
4285 | (bin << HistoryItem.STATE_BRIGHTNESS_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004286 if (DEBUG_HISTORY) Slog.v(TAG, "Screen brightness " + bin + " to: "
4287 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004288 addHistoryRecordLocked(elapsedRealtime, uptime);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004289 if (mScreenState == Display.STATE_ON) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07004290 if (mScreenBrightnessBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004291 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004292 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004293 mScreenBrightnessTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004294 }
4295 mScreenBrightnessBin = bin;
4296 }
4297 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004298
Dianne Hackborn617f8772009-03-31 15:04:46 -07004299 public void noteUserActivityLocked(int uid, int event) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08004300 if (mOnBatteryInternal) {
4301 uid = mapUid(uid);
4302 getUidStatsLocked(uid).noteUserActivityLocked(event);
4303 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004304 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004305
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004306 public void noteWakeUpLocked(String reason, int reasonUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004307 final long elapsedRealtime = mClocks.elapsedRealtime();
4308 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004309 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SCREEN_WAKE_UP,
4310 reason, reasonUid);
4311 }
4312
Jeff Browne95c3cd2014-05-02 16:59:26 -07004313 public void noteInteractiveLocked(boolean interactive) {
4314 if (mInteractive != interactive) {
Joe Onoratoabded112016-02-08 16:49:39 -08004315 final long elapsedRealtime = mClocks.elapsedRealtime();
Jeff Browne95c3cd2014-05-02 16:59:26 -07004316 mInteractive = interactive;
4317 if (DEBUG) Slog.v(TAG, "Interactive: " + interactive);
4318 if (interactive) {
4319 mInteractiveTimer.startRunningLocked(elapsedRealtime);
4320 } else {
4321 mInteractiveTimer.stopRunningLocked(elapsedRealtime);
4322 }
4323 }
4324 }
4325
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004326 public void noteConnectivityChangedLocked(int type, String extra) {
Joe Onoratoabded112016-02-08 16:49:39 -08004327 final long elapsedRealtime = mClocks.elapsedRealtime();
4328 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004329 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_CONNECTIVITY_CHANGED,
4330 extra, type);
4331 mNumConnectivityChange++;
4332 }
4333
Adam Lesinski5f056f62016-07-14 16:56:08 -07004334 private void noteMobileRadioApWakeupLocked(final long elapsedRealtimeMillis,
4335 final long uptimeMillis, int uid) {
4336 uid = mapUid(uid);
4337 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
4338 uid);
4339 getUidStatsLocked(uid).noteMobileRadioApWakeupLocked();
4340 }
4341
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004342 /**
4343 * Updates the radio power state and returns true if an external stats collection should occur.
4344 */
4345 public boolean noteMobileRadioPowerStateLocked(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004346 final long elapsedRealtime = mClocks.elapsedRealtime();
4347 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004348 if (mMobileRadioPowerState != powerState) {
4349 long realElapsedRealtimeMs;
4350 final boolean active =
4351 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
4352 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
4353 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07004354 if (uid > 0) {
4355 noteMobileRadioApWakeupLocked(elapsedRealtime, uptime, uid);
4356 }
4357
Adam Lesinski9acfd812016-04-19 18:29:50 -07004358 mMobileRadioActiveStartTime = realElapsedRealtimeMs = timestampNs / (1000 * 1000);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004359 mHistoryCur.states |= HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
4360 } else {
4361 realElapsedRealtimeMs = timestampNs / (1000*1000);
Dianne Hackbornf7097a52014-05-13 09:56:14 -07004362 long lastUpdateTimeMs = mMobileRadioActiveStartTime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004363 if (realElapsedRealtimeMs < lastUpdateTimeMs) {
4364 Slog.wtf(TAG, "Data connection inactive timestamp " + realElapsedRealtimeMs
4365 + " is before start time " + lastUpdateTimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004366 realElapsedRealtimeMs = elapsedRealtime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004367 } else if (realElapsedRealtimeMs < elapsedRealtime) {
4368 mMobileRadioActiveAdjustedTime.addCountLocked(elapsedRealtime
4369 - realElapsedRealtimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004370 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004371 mHistoryCur.states &= ~HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
4372 }
4373 if (DEBUG_HISTORY) Slog.v(TAG, "Mobile network active " + active + " to: "
4374 + Integer.toHexString(mHistoryCur.states));
4375 addHistoryRecordLocked(elapsedRealtime, uptime);
4376 mMobileRadioPowerState = powerState;
4377 if (active) {
4378 mMobileRadioActiveTimer.startRunningLocked(elapsedRealtime);
4379 mMobileRadioActivePerAppTimer.startRunningLocked(elapsedRealtime);
4380 } else {
4381 mMobileRadioActiveTimer.stopRunningLocked(realElapsedRealtimeMs);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004382 mMobileRadioActivePerAppTimer.stopRunningLocked(realElapsedRealtimeMs);
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004383 // Tell the caller to collect radio network/power stats.
4384 return true;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004385 }
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004386 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004387 return false;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004388 }
4389
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004390 public void notePowerSaveModeLocked(boolean enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004391 if (mPowerSaveModeEnabled != enabled) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004392 int stepState = enabled ? STEP_LEVEL_MODE_POWER_SAVE : 0;
4393 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_POWER_SAVE) ^ stepState;
4394 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_POWER_SAVE) | stepState;
Joe Onoratoabded112016-02-08 16:49:39 -08004395 final long elapsedRealtime = mClocks.elapsedRealtime();
4396 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004397 mPowerSaveModeEnabled = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004398 if (enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004399 mHistoryCur.states2 |= HistoryItem.STATE2_POWER_SAVE_FLAG;
4400 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode enabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004401 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004402 mPowerSaveModeEnabledTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004403 } else {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004404 mHistoryCur.states2 &= ~HistoryItem.STATE2_POWER_SAVE_FLAG;
4405 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode disabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004406 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004407 mPowerSaveModeEnabledTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004408 }
4409 addHistoryRecordLocked(elapsedRealtime, uptime);
Bookatzc1a050a2017-10-10 15:49:28 -07004410 StatsLog.write(StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED, enabled ? 1 : 0);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004411 }
4412 }
4413
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004414 public void noteDeviceIdleModeLocked(int mode, String activeReason, int activeUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004415 final long elapsedRealtime = mClocks.elapsedRealtime();
4416 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004417 boolean nowIdling = mode == DEVICE_IDLE_MODE_DEEP;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004418 if (mDeviceIdling && !nowIdling && activeReason == null) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004419 // We don't go out of general idling mode until explicitly taken out of
4420 // device idle through going active or significant motion.
4421 nowIdling = true;
4422 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004423 boolean nowLightIdling = mode == DEVICE_IDLE_MODE_LIGHT;
4424 if (mDeviceLightIdling && !nowLightIdling && !nowIdling && activeReason == null) {
4425 // We don't go out of general light idling mode until explicitly taken out of
4426 // device idle through going active or significant motion.
4427 nowLightIdling = true;
4428 }
4429 if (activeReason != null && (mDeviceIdling || mDeviceLightIdling)) {
4430 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ACTIVE,
4431 activeReason, activeUid);
4432 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004433 if (mDeviceIdling != nowIdling) {
4434 mDeviceIdling = nowIdling;
4435 int stepState = nowIdling ? STEP_LEVEL_MODE_DEVICE_IDLE : 0;
4436 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_DEVICE_IDLE) ^ stepState;
4437 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_DEVICE_IDLE) | stepState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004438 if (nowIdling) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004439 mDeviceIdlingTimer.startRunningLocked(elapsedRealtime);
4440 } else {
4441 mDeviceIdlingTimer.stopRunningLocked(elapsedRealtime);
4442 }
4443 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004444 if (mDeviceLightIdling != nowLightIdling) {
4445 mDeviceLightIdling = nowLightIdling;
4446 if (nowLightIdling) {
4447 mDeviceLightIdlingTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004448 } else {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004449 mDeviceLightIdlingTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004450 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004451 }
4452 if (mDeviceIdleMode != mode) {
4453 mHistoryCur.states2 = (mHistoryCur.states2 & ~HistoryItem.STATE2_DEVICE_IDLE_MASK)
4454 | (mode << HistoryItem.STATE2_DEVICE_IDLE_SHIFT);
4455 if (DEBUG_HISTORY) Slog.v(TAG, "Device idle mode changed to: "
4456 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004457 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004458 long lastDuration = elapsedRealtime - mLastIdleTimeStart;
4459 mLastIdleTimeStart = elapsedRealtime;
4460 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
4461 if (lastDuration > mLongestLightIdleTime) {
4462 mLongestLightIdleTime = lastDuration;
4463 }
4464 mDeviceIdleModeLightTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004465 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004466 if (lastDuration > mLongestFullIdleTime) {
4467 mLongestFullIdleTime = lastDuration;
4468 }
4469 mDeviceIdleModeFullTimer.stopRunningLocked(elapsedRealtime);
4470 }
4471 if (mode == DEVICE_IDLE_MODE_LIGHT) {
4472 mDeviceIdleModeLightTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004473 } else if (mode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004474 mDeviceIdleModeFullTimer.startRunningLocked(elapsedRealtime);
4475 }
4476 mDeviceIdleMode = mode;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004477 }
4478 }
4479
4480 public void notePackageInstalledLocked(String pkgName, int versionCode) {
Joe Onoratoabded112016-02-08 16:49:39 -08004481 final long elapsedRealtime = mClocks.elapsedRealtime();
4482 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004483 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_INSTALLED,
4484 pkgName, versionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004485 PackageChange pc = new PackageChange();
4486 pc.mPackageName = pkgName;
4487 pc.mUpdate = true;
4488 pc.mVersionCode = versionCode;
4489 addPackageChange(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004490 }
4491
4492 public void notePackageUninstalledLocked(String pkgName) {
Joe Onoratoabded112016-02-08 16:49:39 -08004493 final long elapsedRealtime = mClocks.elapsedRealtime();
4494 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004495 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_UNINSTALLED,
4496 pkgName, 0);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004497 PackageChange pc = new PackageChange();
4498 pc.mPackageName = pkgName;
4499 pc.mUpdate = true;
4500 addPackageChange(pc);
4501 }
4502
4503 private void addPackageChange(PackageChange pc) {
4504 if (mDailyPackageChanges == null) {
4505 mDailyPackageChanges = new ArrayList<>();
4506 }
4507 mDailyPackageChanges.add(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004508 }
4509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004510 public void notePhoneOnLocked() {
4511 if (!mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08004512 final long elapsedRealtime = mClocks.elapsedRealtime();
4513 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07004514 mHistoryCur.states2 |= HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004515 if (DEBUG_HISTORY) Slog.v(TAG, "Phone on to: "
4516 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004517 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004518 mPhoneOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004519 mPhoneOnTimer.startRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004520 }
4521 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004523 public void notePhoneOffLocked() {
4524 if (mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08004525 final long elapsedRealtime = mClocks.elapsedRealtime();
4526 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07004527 mHistoryCur.states2 &= ~HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004528 if (DEBUG_HISTORY) Slog.v(TAG, "Phone off to: "
4529 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004530 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004531 mPhoneOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004532 mPhoneOnTimer.stopRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004533 }
4534 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07004535
Dianne Hackborn3251b902014-06-20 14:40:53 -07004536 void stopAllPhoneSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08004537 final long elapsedRealtime = mClocks.elapsedRealtime();
Wink Saville52840902011-02-18 12:40:47 -08004538 for (int i = 0; i < SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004539 if (i == except) {
4540 continue;
4541 }
4542 while (mPhoneSignalStrengthsTimer[i].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004543 mPhoneSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004544 }
4545 }
4546 }
4547
Dianne Hackborne4a59512010-12-07 11:08:07 -08004548 private int fixPhoneServiceState(int state, int signalBin) {
4549 if (mPhoneSimStateRaw == TelephonyManager.SIM_STATE_ABSENT) {
4550 // In this case we will always be STATE_OUT_OF_SERVICE, so need
4551 // to infer that we are scanning from other data.
4552 if (state == ServiceState.STATE_OUT_OF_SERVICE
Wink Saville52840902011-02-18 12:40:47 -08004553 && signalBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08004554 state = ServiceState.STATE_IN_SERVICE;
4555 }
4556 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004557
Dianne Hackborne4a59512010-12-07 11:08:07 -08004558 return state;
4559 }
4560
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004561 private void updateAllPhoneStateLocked(int state, int simState, int strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08004562 boolean scanning = false;
4563 boolean newHistory = false;
4564
4565 mPhoneServiceStateRaw = state;
4566 mPhoneSimStateRaw = simState;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004567 mPhoneSignalStrengthBinRaw = strengthBin;
4568
Joe Onoratoabded112016-02-08 16:49:39 -08004569 final long elapsedRealtime = mClocks.elapsedRealtime();
4570 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne4a59512010-12-07 11:08:07 -08004571
4572 if (simState == TelephonyManager.SIM_STATE_ABSENT) {
4573 // In this case we will always be STATE_OUT_OF_SERVICE, so need
4574 // to infer that we are scanning from other data.
4575 if (state == ServiceState.STATE_OUT_OF_SERVICE
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004576 && strengthBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08004577 state = ServiceState.STATE_IN_SERVICE;
4578 }
4579 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004580
4581 // If the phone is powered off, stop all timers.
4582 if (state == ServiceState.STATE_POWER_OFF) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004583 strengthBin = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -07004584
Dianne Hackborne4a59512010-12-07 11:08:07 -08004585 // If we are in service, make sure the correct signal string timer is running.
4586 } else if (state == ServiceState.STATE_IN_SERVICE) {
4587 // Bin will be changed below.
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004588
4589 // If we're out of service, we are in the lowest signal strength
4590 // bin and have the scanning bit set.
Amith Yamasanif37447b2009-10-08 18:28:01 -07004591 } else if (state == ServiceState.STATE_OUT_OF_SERVICE) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004592 scanning = true;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004593 strengthBin = SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN;
Amith Yamasanif37447b2009-10-08 18:28:01 -07004594 if (!mPhoneSignalScanningTimer.isRunningLocked()) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004595 mHistoryCur.states |= HistoryItem.STATE_PHONE_SCANNING_FLAG;
Dianne Hackborne4a59512010-12-07 11:08:07 -08004596 newHistory = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004597 if (DEBUG_HISTORY) Slog.v(TAG, "Phone started scanning to: "
4598 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004599 mPhoneSignalScanningTimer.startRunningLocked(elapsedRealtime);
Amith Yamasanif37447b2009-10-08 18:28:01 -07004600 }
4601 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004602
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004603 if (!scanning) {
4604 // If we are no longer scanning, then stop the scanning timer.
4605 if (mPhoneSignalScanningTimer.isRunningLocked()) {
4606 mHistoryCur.states &= ~HistoryItem.STATE_PHONE_SCANNING_FLAG;
4607 if (DEBUG_HISTORY) Slog.v(TAG, "Phone stopped scanning to: "
4608 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08004609 newHistory = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004610 mPhoneSignalScanningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004611 }
4612 }
4613
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004614 if (mPhoneServiceState != state) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004615 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_STATE_MASK)
4616 | (state << HistoryItem.STATE_PHONE_STATE_SHIFT);
Dianne Hackborne4a59512010-12-07 11:08:07 -08004617 if (DEBUG_HISTORY) Slog.v(TAG, "Phone state " + state + " to: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004618 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08004619 newHistory = true;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004620 mPhoneServiceState = state;
4621 }
Dianne Hackborne4a59512010-12-07 11:08:07 -08004622
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004623 if (mPhoneSignalStrengthBin != strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08004624 if (mPhoneSignalStrengthBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004625 mPhoneSignalStrengthsTimer[mPhoneSignalStrengthBin].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004626 elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08004627 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004628 if (strengthBin >= 0) {
4629 if (!mPhoneSignalStrengthsTimer[strengthBin].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004630 mPhoneSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08004631 }
Dianne Hackborn3251b902014-06-20 14:40:53 -07004632 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_MASK)
4633 | (strengthBin << HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_SHIFT);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004634 if (DEBUG_HISTORY) Slog.v(TAG, "Signal strength " + strengthBin + " to: "
Dianne Hackborne4a59512010-12-07 11:08:07 -08004635 + Integer.toHexString(mHistoryCur.states));
4636 newHistory = true;
4637 } else {
Dianne Hackborn3251b902014-06-20 14:40:53 -07004638 stopAllPhoneSignalStrengthTimersLocked(-1);
Dianne Hackborne4a59512010-12-07 11:08:07 -08004639 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004640 mPhoneSignalStrengthBin = strengthBin;
Dianne Hackborne4a59512010-12-07 11:08:07 -08004641 }
4642
4643 if (newHistory) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07004644 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08004645 }
4646 }
4647
4648 /**
4649 * Telephony stack updates the phone state.
4650 * @param state phone state from ServiceState.getState()
4651 */
4652 public void notePhoneStateLocked(int state, int simState) {
4653 updateAllPhoneStateLocked(state, simState, mPhoneSignalStrengthBinRaw);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07004654 }
4655
Wink Savillee9b06d72009-05-18 21:47:50 -07004656 public void notePhoneSignalStrengthLocked(SignalStrength signalStrength) {
Dianne Hackborn627bba72009-03-24 22:32:56 -07004657 // Bin the strength.
Wink Saville52840902011-02-18 12:40:47 -08004658 int bin = signalStrength.getLevel();
Dianne Hackborne4a59512010-12-07 11:08:07 -08004659 updateAllPhoneStateLocked(mPhoneServiceStateRaw, mPhoneSimStateRaw, bin);
Dianne Hackborn627bba72009-03-24 22:32:56 -07004660 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004661
Dianne Hackborn627bba72009-03-24 22:32:56 -07004662 public void notePhoneDataConnectionStateLocked(int dataType, boolean hasData) {
4663 int bin = DATA_CONNECTION_NONE;
4664 if (hasData) {
4665 switch (dataType) {
4666 case TelephonyManager.NETWORK_TYPE_EDGE:
4667 bin = DATA_CONNECTION_EDGE;
4668 break;
4669 case TelephonyManager.NETWORK_TYPE_GPRS:
4670 bin = DATA_CONNECTION_GPRS;
4671 break;
4672 case TelephonyManager.NETWORK_TYPE_UMTS:
4673 bin = DATA_CONNECTION_UMTS;
4674 break;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004675 case TelephonyManager.NETWORK_TYPE_CDMA:
4676 bin = DATA_CONNECTION_CDMA;
4677 break;
4678 case TelephonyManager.NETWORK_TYPE_EVDO_0:
4679 bin = DATA_CONNECTION_EVDO_0;
4680 break;
4681 case TelephonyManager.NETWORK_TYPE_EVDO_A:
4682 bin = DATA_CONNECTION_EVDO_A;
4683 break;
4684 case TelephonyManager.NETWORK_TYPE_1xRTT:
4685 bin = DATA_CONNECTION_1xRTT;
4686 break;
4687 case TelephonyManager.NETWORK_TYPE_HSDPA:
4688 bin = DATA_CONNECTION_HSDPA;
4689 break;
4690 case TelephonyManager.NETWORK_TYPE_HSUPA:
4691 bin = DATA_CONNECTION_HSUPA;
4692 break;
4693 case TelephonyManager.NETWORK_TYPE_HSPA:
4694 bin = DATA_CONNECTION_HSPA;
4695 break;
4696 case TelephonyManager.NETWORK_TYPE_IDEN:
4697 bin = DATA_CONNECTION_IDEN;
4698 break;
4699 case TelephonyManager.NETWORK_TYPE_EVDO_B:
4700 bin = DATA_CONNECTION_EVDO_B;
4701 break;
Robert Greenwalt962a9902010-11-02 11:10:25 -07004702 case TelephonyManager.NETWORK_TYPE_LTE:
4703 bin = DATA_CONNECTION_LTE;
4704 break;
4705 case TelephonyManager.NETWORK_TYPE_EHRPD:
4706 bin = DATA_CONNECTION_EHRPD;
4707 break;
Patrick Tjinb71703c2013-11-06 09:27:03 -08004708 case TelephonyManager.NETWORK_TYPE_HSPAP:
4709 bin = DATA_CONNECTION_HSPAP;
4710 break;
Dianne Hackborn627bba72009-03-24 22:32:56 -07004711 default:
4712 bin = DATA_CONNECTION_OTHER;
4713 break;
4714 }
4715 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004716 if (DEBUG) Log.i(TAG, "Phone Data Connection -> " + dataType + " = " + hasData);
Dianne Hackborn627bba72009-03-24 22:32:56 -07004717 if (mPhoneDataConnectionType != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08004718 final long elapsedRealtime = mClocks.elapsedRealtime();
4719 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004720 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_DATA_CONNECTION_MASK)
4721 | (bin << HistoryItem.STATE_DATA_CONNECTION_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004722 if (DEBUG_HISTORY) Slog.v(TAG, "Data connection " + bin + " to: "
4723 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004724 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07004725 if (mPhoneDataConnectionType >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004726 mPhoneDataConnectionsTimer[mPhoneDataConnectionType].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004727 elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07004728 }
4729 mPhoneDataConnectionType = bin;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004730 mPhoneDataConnectionsTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07004731 }
4732 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004733
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07004734 public void noteWifiOnLocked() {
The Android Open Source Project10592532009-03-18 17:39:46 -07004735 if (!mWifiOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08004736 final long elapsedRealtime = mClocks.elapsedRealtime();
4737 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07004738 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004739 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI on to: "
4740 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004741 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07004742 mWifiOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004743 mWifiOnTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004744 scheduleSyncExternalStatsLocked("wifi-off", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07004745 }
4746 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004747
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07004748 public void noteWifiOffLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08004749 final long elapsedRealtime = mClocks.elapsedRealtime();
4750 final long uptime = mClocks.uptimeMillis();
The Android Open Source Project10592532009-03-18 17:39:46 -07004751 if (mWifiOn) {
Dianne Hackborn3251b902014-06-20 14:40:53 -07004752 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004753 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI off to: "
4754 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004755 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07004756 mWifiOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004757 mWifiOnTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004758 scheduleSyncExternalStatsLocked("wifi-on", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07004759 }
4760 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004761
4762 public void noteAudioOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004763 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004764 final long elapsedRealtime = mClocks.elapsedRealtime();
4765 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004766 if (mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004767 mHistoryCur.states |= HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004768 if (DEBUG_HISTORY) Slog.v(TAG, "Audio on to: "
4769 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004770 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004771 mAudioOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004772 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004773 mAudioOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004774 getUidStatsLocked(uid).noteAudioTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004775 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004776
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004777 public void noteAudioOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004778 if (mAudioOnNesting == 0) {
4779 return;
4780 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08004781 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004782 final long elapsedRealtime = mClocks.elapsedRealtime();
4783 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004784 if (--mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004785 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004786 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
4787 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004788 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004789 mAudioOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004790 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004791 getUidStatsLocked(uid).noteAudioTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004792 }
4793
4794 public void noteVideoOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004795 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004796 final long elapsedRealtime = mClocks.elapsedRealtime();
4797 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004798 if (mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004799 mHistoryCur.states2 |= HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004800 if (DEBUG_HISTORY) Slog.v(TAG, "Video on to: "
4801 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004802 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004803 mVideoOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004804 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004805 mVideoOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004806 getUidStatsLocked(uid).noteVideoTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004807 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004808
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004809 public void noteVideoOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004810 if (mVideoOnNesting == 0) {
4811 return;
4812 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08004813 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004814 final long elapsedRealtime = mClocks.elapsedRealtime();
4815 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004816 if (--mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004817 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004818 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
4819 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004820 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004821 mVideoOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004822 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004823 getUidStatsLocked(uid).noteVideoTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004824 }
4825
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004826 public void noteResetAudioLocked() {
4827 if (mAudioOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08004828 final long elapsedRealtime = mClocks.elapsedRealtime();
4829 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004830 mAudioOnNesting = 0;
4831 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
4832 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
4833 + Integer.toHexString(mHistoryCur.states));
4834 addHistoryRecordLocked(elapsedRealtime, uptime);
4835 mAudioOnTimer.stopAllRunningLocked(elapsedRealtime);
4836 for (int i=0; i<mUidStats.size(); i++) {
4837 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
4838 uid.noteResetAudioLocked(elapsedRealtime);
4839 }
4840 }
4841 }
4842
4843 public void noteResetVideoLocked() {
4844 if (mVideoOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08004845 final long elapsedRealtime = mClocks.elapsedRealtime();
4846 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004847 mAudioOnNesting = 0;
4848 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
4849 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
4850 + Integer.toHexString(mHistoryCur.states));
4851 addHistoryRecordLocked(elapsedRealtime, uptime);
4852 mVideoOnTimer.stopAllRunningLocked(elapsedRealtime);
4853 for (int i=0; i<mUidStats.size(); i++) {
4854 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
4855 uid.noteResetVideoLocked(elapsedRealtime);
4856 }
4857 }
4858 }
4859
Jeff Sharkey3e013e82013-04-25 14:48:19 -07004860 public void noteActivityResumedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004861 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004862 getUidStatsLocked(uid).noteActivityResumedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07004863 }
4864
4865 public void noteActivityPausedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004866 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004867 getUidStatsLocked(uid).noteActivityPausedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07004868 }
4869
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004870 public void noteVibratorOnLocked(int uid, long durationMillis) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004871 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004872 getUidStatsLocked(uid).noteVibratorOnLocked(durationMillis);
4873 }
4874
4875 public void noteVibratorOffLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004876 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004877 getUidStatsLocked(uid).noteVibratorOffLocked();
4878 }
4879
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004880 public void noteFlashlightOnLocked(int uid) {
4881 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004882 final long elapsedRealtime = mClocks.elapsedRealtime();
4883 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004884 if (mFlashlightOnNesting++ == 0) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004885 mHistoryCur.states2 |= HistoryItem.STATE2_FLASHLIGHT_FLAG;
4886 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight on to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004887 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004888 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004889 mFlashlightOnTimer.startRunningLocked(elapsedRealtime);
4890 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004891 getUidStatsLocked(uid).noteFlashlightTurnedOnLocked(elapsedRealtime);
4892 }
4893
4894 public void noteFlashlightOffLocked(int uid) {
4895 if (mFlashlightOnNesting == 0) {
4896 return;
4897 }
4898 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004899 final long elapsedRealtime = mClocks.elapsedRealtime();
4900 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004901 if (--mFlashlightOnNesting == 0) {
4902 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
4903 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
4904 + Integer.toHexString(mHistoryCur.states2));
4905 addHistoryRecordLocked(elapsedRealtime, uptime);
4906 mFlashlightOnTimer.stopRunningLocked(elapsedRealtime);
4907 }
4908 getUidStatsLocked(uid).noteFlashlightTurnedOffLocked(elapsedRealtime);
4909 }
4910
4911 public void noteCameraOnLocked(int uid) {
4912 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004913 final long elapsedRealtime = mClocks.elapsedRealtime();
4914 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004915 if (mCameraOnNesting++ == 0) {
4916 mHistoryCur.states2 |= HistoryItem.STATE2_CAMERA_FLAG;
4917 if (DEBUG_HISTORY) Slog.v(TAG, "Camera on to: "
4918 + Integer.toHexString(mHistoryCur.states2));
4919 addHistoryRecordLocked(elapsedRealtime, uptime);
4920 mCameraOnTimer.startRunningLocked(elapsedRealtime);
4921 }
4922 getUidStatsLocked(uid).noteCameraTurnedOnLocked(elapsedRealtime);
4923 }
4924
4925 public void noteCameraOffLocked(int uid) {
4926 if (mCameraOnNesting == 0) {
4927 return;
4928 }
4929 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004930 final long elapsedRealtime = mClocks.elapsedRealtime();
4931 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004932 if (--mCameraOnNesting == 0) {
4933 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
4934 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
4935 + Integer.toHexString(mHistoryCur.states2));
4936 addHistoryRecordLocked(elapsedRealtime, uptime);
4937 mCameraOnTimer.stopRunningLocked(elapsedRealtime);
4938 }
4939 getUidStatsLocked(uid).noteCameraTurnedOffLocked(elapsedRealtime);
4940 }
4941
4942 public void noteResetCameraLocked() {
4943 if (mCameraOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08004944 final long elapsedRealtime = mClocks.elapsedRealtime();
4945 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004946 mCameraOnNesting = 0;
4947 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
4948 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
4949 + Integer.toHexString(mHistoryCur.states2));
4950 addHistoryRecordLocked(elapsedRealtime, uptime);
4951 mCameraOnTimer.stopAllRunningLocked(elapsedRealtime);
4952 for (int i=0; i<mUidStats.size(); i++) {
4953 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
4954 uid.noteResetCameraLocked(elapsedRealtime);
4955 }
4956 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004957 }
4958
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004959 public void noteResetFlashlightLocked() {
4960 if (mFlashlightOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08004961 final long elapsedRealtime = mClocks.elapsedRealtime();
4962 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004963 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004964 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
4965 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004966 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004967 addHistoryRecordLocked(elapsedRealtime, uptime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004968 mFlashlightOnTimer.stopAllRunningLocked(elapsedRealtime);
4969 for (int i=0; i<mUidStats.size(); i++) {
4970 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
4971 uid.noteResetFlashlightLocked(elapsedRealtime);
4972 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004973 }
4974 }
4975
Bookatzb1f04f32017-05-19 13:57:32 -07004976 private void noteBluetoothScanStartedLocked(int uid, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004977 uid = mapUid(uid);
Bookatz867c0d72017-03-07 18:23:42 -08004978 final long elapsedRealtime = mClocks.elapsedRealtime();
4979 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004980 if (mBluetoothScanNesting == 0) {
4981 mHistoryCur.states2 |= HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
4982 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan started for: "
4983 + Integer.toHexString(mHistoryCur.states2));
4984 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07004985 mBluetoothScanTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004986 }
4987 mBluetoothScanNesting++;
Bookatzb1f04f32017-05-19 13:57:32 -07004988 getUidStatsLocked(uid).noteBluetoothScanStartedLocked(elapsedRealtime, isUnoptimized);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004989 }
4990
Bookatzb1f04f32017-05-19 13:57:32 -07004991 public void noteBluetoothScanStartedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004992 final int N = ws.size();
4993 for (int i = 0; i < N; i++) {
Bookatzb1f04f32017-05-19 13:57:32 -07004994 noteBluetoothScanStartedLocked(ws.get(i), isUnoptimized);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004995 }
4996 }
4997
Bookatz94c5a312017-07-11 16:49:17 -07004998 private void noteBluetoothScanStoppedLocked(int uid, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004999 uid = mapUid(uid);
Bookatz867c0d72017-03-07 18:23:42 -08005000 final long elapsedRealtime = mClocks.elapsedRealtime();
5001 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005002 mBluetoothScanNesting--;
5003 if (mBluetoothScanNesting == 0) {
5004 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5005 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan stopped for: "
5006 + Integer.toHexString(mHistoryCur.states2));
5007 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005008 mBluetoothScanTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005009 }
Bookatz94c5a312017-07-11 16:49:17 -07005010 getUidStatsLocked(uid).noteBluetoothScanStoppedLocked(elapsedRealtime, isUnoptimized);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005011 }
5012
Bookatz94c5a312017-07-11 16:49:17 -07005013 public void noteBluetoothScanStoppedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005014 final int N = ws.size();
5015 for (int i = 0; i < N; i++) {
Bookatz94c5a312017-07-11 16:49:17 -07005016 noteBluetoothScanStoppedLocked(ws.get(i), isUnoptimized);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005017 }
5018 }
5019
5020 public void noteResetBluetoothScanLocked() {
5021 if (mBluetoothScanNesting > 0) {
Bookatz867c0d72017-03-07 18:23:42 -08005022 final long elapsedRealtime = mClocks.elapsedRealtime();
5023 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005024 mBluetoothScanNesting = 0;
5025 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5026 if (DEBUG_HISTORY) Slog.v(TAG, "BLE can stopped for: "
5027 + Integer.toHexString(mHistoryCur.states2));
5028 addHistoryRecordLocked(elapsedRealtime, uptime);
5029 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtime);
5030 for (int i=0; i<mUidStats.size(); i++) {
5031 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5032 uid.noteResetBluetoothScanLocked(elapsedRealtime);
5033 }
5034 }
5035 }
5036
Bookatz4ebc0642017-05-11 12:21:19 -07005037 public void noteBluetoothScanResultsFromSourceLocked(WorkSource ws, int numNewResults) {
Bookatz956f36bf2017-04-28 09:48:17 -07005038 final int N = ws.size();
5039 for (int i = 0; i < N; i++) {
5040 int uid = mapUid(ws.get(i));
Bookatz4ebc0642017-05-11 12:21:19 -07005041 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Bookatz956f36bf2017-04-28 09:48:17 -07005042 }
5043 }
5044
Adam Lesinski5f056f62016-07-14 16:56:08 -07005045 private void noteWifiRadioApWakeupLocked(final long elapsedRealtimeMillis,
5046 final long uptimeMillis, int uid) {
5047 uid = mapUid(uid);
5048 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
5049 uid);
5050 getUidStatsLocked(uid).noteWifiRadioApWakeupLocked();
5051 }
5052
5053 public void noteWifiRadioPowerState(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005054 final long elapsedRealtime = mClocks.elapsedRealtime();
5055 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005056 if (mWifiRadioPowerState != powerState) {
5057 final boolean active =
5058 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
5059 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
5060 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07005061 if (uid > 0) {
5062 noteWifiRadioApWakeupLocked(elapsedRealtime, uptime, uid);
5063 }
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005064 mHistoryCur.states |= HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
5065 } else {
5066 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
5067 }
5068 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi network active " + active + " to: "
5069 + Integer.toHexString(mHistoryCur.states));
5070 addHistoryRecordLocked(elapsedRealtime, uptime);
5071 mWifiRadioPowerState = powerState;
5072 }
5073 }
5074
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005075 public void noteWifiRunningLocked(WorkSource ws) {
5076 if (!mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005077 final long elapsedRealtime = mClocks.elapsedRealtime();
5078 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005079 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005080 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI running to: "
5081 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005082 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005083 mGlobalWifiRunning = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005084 mGlobalWifiRunningTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005085 int N = ws.size();
5086 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005087 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005088 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005089 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005090 scheduleSyncExternalStatsLocked("wifi-running", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005091 } else {
5092 Log.w(TAG, "noteWifiRunningLocked -- called while WIFI running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005093 }
5094 }
5095
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005096 public void noteWifiRunningChangedLocked(WorkSource oldWs, WorkSource newWs) {
5097 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005098 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005099 int N = oldWs.size();
5100 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005101 int uid = mapUid(oldWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005102 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005103 }
5104 N = newWs.size();
5105 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005106 int uid = mapUid(newWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005107 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005108 }
5109 } else {
5110 Log.w(TAG, "noteWifiRunningChangedLocked -- called while WIFI not running");
5111 }
5112 }
5113
5114 public void noteWifiStoppedLocked(WorkSource ws) {
5115 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005116 final long elapsedRealtime = mClocks.elapsedRealtime();
5117 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005118 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005119 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI stopped to: "
5120 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005121 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005122 mGlobalWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005123 mGlobalWifiRunningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005124 int N = ws.size();
5125 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005126 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005127 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005128 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005129 scheduleSyncExternalStatsLocked("wifi-stopped", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005130 } else {
5131 Log.w(TAG, "noteWifiStoppedLocked -- called while WIFI not running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005132 }
5133 }
5134
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005135 public void noteWifiStateLocked(int wifiState, String accessPoint) {
5136 if (DEBUG) Log.i(TAG, "WiFi state -> " + wifiState);
5137 if (mWifiState != wifiState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005138 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005139 if (mWifiState >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005140 mWifiStateTimer[mWifiState].stopRunningLocked(elapsedRealtime);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005141 }
5142 mWifiState = wifiState;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005143 mWifiStateTimer[wifiState].startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005144 scheduleSyncExternalStatsLocked("wifi-state", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005145 }
5146 }
5147
Dianne Hackborn3251b902014-06-20 14:40:53 -07005148 public void noteWifiSupplicantStateChangedLocked(int supplState, boolean failedAuth) {
5149 if (DEBUG) Log.i(TAG, "WiFi suppl state -> " + supplState);
5150 if (mWifiSupplState != supplState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005151 final long elapsedRealtime = mClocks.elapsedRealtime();
5152 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005153 if (mWifiSupplState >= 0) {
5154 mWifiSupplStateTimer[mWifiSupplState].stopRunningLocked(elapsedRealtime);
5155 }
5156 mWifiSupplState = supplState;
5157 mWifiSupplStateTimer[supplState].startRunningLocked(elapsedRealtime);
5158 mHistoryCur.states2 =
5159 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SUPPL_STATE_MASK)
5160 | (supplState << HistoryItem.STATE2_WIFI_SUPPL_STATE_SHIFT);
5161 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi suppl state " + supplState + " to: "
5162 + Integer.toHexString(mHistoryCur.states2));
5163 addHistoryRecordLocked(elapsedRealtime, uptime);
5164 }
5165 }
5166
5167 void stopAllWifiSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005168 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005169 for (int i = 0; i < NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
5170 if (i == except) {
5171 continue;
5172 }
5173 while (mWifiSignalStrengthsTimer[i].isRunningLocked()) {
5174 mWifiSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
5175 }
5176 }
5177 }
5178
5179 public void noteWifiRssiChangedLocked(int newRssi) {
5180 int strengthBin = WifiManager.calculateSignalLevel(newRssi, NUM_WIFI_SIGNAL_STRENGTH_BINS);
5181 if (DEBUG) Log.i(TAG, "WiFi rssi -> " + newRssi + " bin=" + strengthBin);
5182 if (mWifiSignalStrengthBin != strengthBin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005183 final long elapsedRealtime = mClocks.elapsedRealtime();
5184 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005185 if (mWifiSignalStrengthBin >= 0) {
5186 mWifiSignalStrengthsTimer[mWifiSignalStrengthBin].stopRunningLocked(
5187 elapsedRealtime);
5188 }
5189 if (strengthBin >= 0) {
5190 if (!mWifiSignalStrengthsTimer[strengthBin].isRunningLocked()) {
5191 mWifiSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
5192 }
5193 mHistoryCur.states2 =
5194 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_MASK)
5195 | (strengthBin << HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_SHIFT);
5196 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi signal strength " + strengthBin + " to: "
5197 + Integer.toHexString(mHistoryCur.states2));
5198 addHistoryRecordLocked(elapsedRealtime, uptime);
5199 } else {
5200 stopAllWifiSignalStrengthTimersLocked(-1);
5201 }
5202 mWifiSignalStrengthBin = strengthBin;
5203 }
5204 }
5205
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005206 int mWifiFullLockNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005207
The Android Open Source Project10592532009-03-18 17:39:46 -07005208 public void noteFullWifiLockAcquiredLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005209 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005210 final long elapsedRealtime = mClocks.elapsedRealtime();
5211 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005212 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005213 mHistoryCur.states |= HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005214 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock on to: "
5215 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005216 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005217 }
5218 mWifiFullLockNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005219 getUidStatsLocked(uid).noteFullWifiLockAcquiredLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005220 }
5221
5222 public void noteFullWifiLockReleasedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005223 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005224 final long elapsedRealtime = mClocks.elapsedRealtime();
5225 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005226 mWifiFullLockNesting--;
5227 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005228 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005229 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock off to: "
5230 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005231 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005232 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005233 getUidStatsLocked(uid).noteFullWifiLockReleasedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005234 }
5235
Nick Pelly6ccaa542012-06-15 15:22:47 -07005236 int mWifiScanNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005237
Nick Pelly6ccaa542012-06-15 15:22:47 -07005238 public void noteWifiScanStartedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005239 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005240 final long elapsedRealtime = mClocks.elapsedRealtime();
5241 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07005242 if (mWifiScanNesting == 0) {
5243 mHistoryCur.states |= HistoryItem.STATE_WIFI_SCAN_FLAG;
5244 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan started for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005245 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005246 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005247 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07005248 mWifiScanNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005249 getUidStatsLocked(uid).noteWifiScanStartedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005250 }
5251
Nick Pelly6ccaa542012-06-15 15:22:47 -07005252 public void noteWifiScanStoppedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005253 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005254 final long elapsedRealtime = mClocks.elapsedRealtime();
5255 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07005256 mWifiScanNesting--;
5257 if (mWifiScanNesting == 0) {
5258 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_SCAN_FLAG;
5259 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan stopped for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005260 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005261 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005262 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005263 getUidStatsLocked(uid).noteWifiScanStoppedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005264 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005265
Robert Greenwalta029ea12013-09-25 16:38:12 -07005266 public void noteWifiBatchedScanStartedLocked(int uid, int csph) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005267 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005268 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005269 getUidStatsLocked(uid).noteWifiBatchedScanStartedLocked(csph, elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005270 }
5271
5272 public void noteWifiBatchedScanStoppedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005273 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005274 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005275 getUidStatsLocked(uid).noteWifiBatchedScanStoppedLocked(elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005276 }
5277
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005278 int mWifiMulticastNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005279
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005280 public void noteWifiMulticastEnabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005281 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005282 final long elapsedRealtime = mClocks.elapsedRealtime();
5283 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005284 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005285 mHistoryCur.states |= HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005286 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast on to: "
5287 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005288 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005289 }
5290 mWifiMulticastNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005291 getUidStatsLocked(uid).noteWifiMulticastEnabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005292 }
5293
5294 public void noteWifiMulticastDisabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005295 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005296 final long elapsedRealtime = mClocks.elapsedRealtime();
5297 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005298 mWifiMulticastNesting--;
5299 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005300 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005301 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast off to: "
5302 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005303 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005304 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005305 getUidStatsLocked(uid).noteWifiMulticastDisabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005306 }
5307
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005308 public void noteFullWifiLockAcquiredFromSourceLocked(WorkSource ws) {
5309 int N = ws.size();
5310 for (int i=0; i<N; i++) {
5311 noteFullWifiLockAcquiredLocked(ws.get(i));
5312 }
5313 }
5314
5315 public void noteFullWifiLockReleasedFromSourceLocked(WorkSource ws) {
5316 int N = ws.size();
5317 for (int i=0; i<N; i++) {
5318 noteFullWifiLockReleasedLocked(ws.get(i));
5319 }
5320 }
5321
Nick Pelly6ccaa542012-06-15 15:22:47 -07005322 public void noteWifiScanStartedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005323 int N = ws.size();
5324 for (int i=0; i<N; i++) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07005325 noteWifiScanStartedLocked(ws.get(i));
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005326 }
5327 }
5328
Nick Pelly6ccaa542012-06-15 15:22:47 -07005329 public void noteWifiScanStoppedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005330 int N = ws.size();
5331 for (int i=0; i<N; i++) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07005332 noteWifiScanStoppedLocked(ws.get(i));
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005333 }
5334 }
5335
Robert Greenwalta029ea12013-09-25 16:38:12 -07005336 public void noteWifiBatchedScanStartedFromSourceLocked(WorkSource ws, int csph) {
5337 int N = ws.size();
5338 for (int i=0; i<N; i++) {
5339 noteWifiBatchedScanStartedLocked(ws.get(i), csph);
5340 }
5341 }
5342
5343 public void noteWifiBatchedScanStoppedFromSourceLocked(WorkSource ws) {
5344 int N = ws.size();
5345 for (int i=0; i<N; i++) {
5346 noteWifiBatchedScanStoppedLocked(ws.get(i));
5347 }
5348 }
5349
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005350 public void noteWifiMulticastEnabledFromSourceLocked(WorkSource ws) {
5351 int N = ws.size();
5352 for (int i=0; i<N; i++) {
5353 noteWifiMulticastEnabledLocked(ws.get(i));
5354 }
5355 }
5356
5357 public void noteWifiMulticastDisabledFromSourceLocked(WorkSource ws) {
5358 int N = ws.size();
5359 for (int i=0; i<N; i++) {
5360 noteWifiMulticastDisabledLocked(ws.get(i));
5361 }
5362 }
5363
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08005364 private static String[] includeInStringArray(String[] array, String str) {
5365 if (ArrayUtils.indexOf(array, str) >= 0) {
5366 return array;
5367 }
5368 String[] newArray = new String[array.length+1];
5369 System.arraycopy(array, 0, newArray, 0, array.length);
5370 newArray[array.length] = str;
5371 return newArray;
5372 }
5373
5374 private static String[] excludeFromStringArray(String[] array, String str) {
5375 int index = ArrayUtils.indexOf(array, str);
5376 if (index >= 0) {
5377 String[] newArray = new String[array.length-1];
5378 if (index > 0) {
5379 System.arraycopy(array, 0, newArray, 0, index);
5380 }
5381 if (index < array.length-1) {
5382 System.arraycopy(array, index+1, newArray, index, array.length-index-1);
5383 }
5384 return newArray;
5385 }
5386 return array;
5387 }
5388
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07005389 public void noteNetworkInterfaceTypeLocked(String iface, int networkType) {
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07005390 if (TextUtils.isEmpty(iface)) return;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07005391
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005392 synchronized (mModemNetworkLock) {
5393 if (ConnectivityManager.isNetworkTypeMobile(networkType)) {
5394 mModemIfaces = includeInStringArray(mModemIfaces, iface);
5395 if (DEBUG) Slog.d(TAG, "Note mobile iface " + iface + ": " + mModemIfaces);
5396 } else {
5397 mModemIfaces = excludeFromStringArray(mModemIfaces, iface);
5398 if (DEBUG) Slog.d(TAG, "Note non-mobile iface " + iface + ": " + mModemIfaces);
5399 }
5400 }
5401
5402 synchronized (mWifiNetworkLock) {
5403 if (ConnectivityManager.isNetworkTypeWifi(networkType)) {
5404 mWifiIfaces = includeInStringArray(mWifiIfaces, iface);
5405 if (DEBUG) Slog.d(TAG, "Note wifi iface " + iface + ": " + mWifiIfaces);
5406 } else {
5407 mWifiIfaces = excludeFromStringArray(mWifiIfaces, iface);
5408 if (DEBUG) Slog.d(TAG, "Note non-wifi iface " + iface + ": " + mWifiIfaces);
5409 }
5410 }
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07005411 }
5412
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005413 @Override public long getScreenOnTime(long elapsedRealtimeUs, int which) {
5414 return mScreenOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005415 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005416
Dianne Hackborn77b987f2014-02-26 16:20:52 -08005417 @Override public int getScreenOnCount(int which) {
5418 return mScreenOnTimer.getCountLocked(which);
5419 }
5420
Mike Mac2f518a2017-09-19 16:06:03 -07005421 @Override public long getScreenDozeTime(long elapsedRealtimeUs, int which) {
5422 return mScreenDozeTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
5423 }
5424
5425 @Override public int getScreenDozeCount(int which) {
5426 return mScreenDozeTimer.getCountLocked(which);
5427 }
5428
Dianne Hackborn617f8772009-03-31 15:04:46 -07005429 @Override public long getScreenBrightnessTime(int brightnessBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005430 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07005431 return mScreenBrightnessTimer[brightnessBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005432 elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005433 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005434
Kweku Adams87b19ec2017-10-09 12:40:03 -07005435 @Override public Timer getScreenBrightnessTimer(int brightnessBin) {
5436 return mScreenBrightnessTimer[brightnessBin];
5437 }
5438
Jeff Browne95c3cd2014-05-02 16:59:26 -07005439 @Override public long getInteractiveTime(long elapsedRealtimeUs, int which) {
5440 return mInteractiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005441 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005442
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005443 @Override public long getPowerSaveModeEnabledTime(long elapsedRealtimeUs, int which) {
5444 return mPowerSaveModeEnabledTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005445 }
5446
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005447 @Override public int getPowerSaveModeEnabledCount(int which) {
5448 return mPowerSaveModeEnabledTimer.getCountLocked(which);
5449 }
5450
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005451 @Override public long getDeviceIdleModeTime(int mode, long elapsedRealtimeUs,
5452 int which) {
5453 switch (mode) {
5454 case DEVICE_IDLE_MODE_LIGHT:
5455 return mDeviceIdleModeLightTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005456 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005457 return mDeviceIdleModeFullTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
5458 }
5459 return 0;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005460 }
5461
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005462 @Override public int getDeviceIdleModeCount(int mode, int which) {
5463 switch (mode) {
5464 case DEVICE_IDLE_MODE_LIGHT:
5465 return mDeviceIdleModeLightTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005466 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005467 return mDeviceIdleModeFullTimer.getCountLocked(which);
5468 }
5469 return 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005470 }
5471
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005472 @Override public long getLongestDeviceIdleModeTime(int mode) {
5473 switch (mode) {
5474 case DEVICE_IDLE_MODE_LIGHT:
5475 return mLongestLightIdleTime;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005476 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005477 return mLongestFullIdleTime;
5478 }
5479 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005480 }
5481
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005482 @Override public long getDeviceIdlingTime(int mode, long elapsedRealtimeUs, int which) {
5483 switch (mode) {
5484 case DEVICE_IDLE_MODE_LIGHT:
5485 return mDeviceLightIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005486 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005487 return mDeviceIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
5488 }
5489 return 0;
5490 }
5491
5492 @Override public int getDeviceIdlingCount(int mode, int which) {
5493 switch (mode) {
5494 case DEVICE_IDLE_MODE_LIGHT:
5495 return mDeviceLightIdlingTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005496 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005497 return mDeviceIdlingTimer.getCountLocked(which);
5498 }
5499 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005500 }
5501
Dianne Hackborn1e01d162014-12-04 17:46:42 -08005502 @Override public int getNumConnectivityChange(int which) {
5503 int val = mNumConnectivityChange;
5504 if (which == STATS_CURRENT) {
5505 val -= mLoadedNumConnectivityChange;
5506 } else if (which == STATS_SINCE_UNPLUGGED) {
5507 val -= mUnpluggedNumConnectivityChange;
5508 }
5509 return val;
5510 }
5511
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005512 @Override public long getPhoneOnTime(long elapsedRealtimeUs, int which) {
5513 return mPhoneOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005514 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005515
Dianne Hackborn77b987f2014-02-26 16:20:52 -08005516 @Override public int getPhoneOnCount(int which) {
5517 return mPhoneOnTimer.getCountLocked(which);
5518 }
5519
Dianne Hackborn627bba72009-03-24 22:32:56 -07005520 @Override public long getPhoneSignalStrengthTime(int strengthBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005521 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07005522 return mPhoneSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005523 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005524 }
Amith Yamasanif37447b2009-10-08 18:28:01 -07005525
5526 @Override public long getPhoneSignalScanningTime(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005527 long elapsedRealtimeUs, int which) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07005528 return mPhoneSignalScanningTimer.getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005529 elapsedRealtimeUs, which);
Amith Yamasanif37447b2009-10-08 18:28:01 -07005530 }
5531
Kweku Adams87b19ec2017-10-09 12:40:03 -07005532 @Override public Timer getPhoneSignalScanningTimer() {
5533 return mPhoneSignalScanningTimer;
5534 }
5535
Catherine Liufb900812012-07-17 14:12:56 -05005536 @Override public int getPhoneSignalStrengthCount(int strengthBin, int which) {
5537 return mPhoneSignalStrengthsTimer[strengthBin].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005538 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005539
Kweku Adams87b19ec2017-10-09 12:40:03 -07005540 @Override public Timer getPhoneSignalStrengthTimer(int strengthBin) {
5541 return mPhoneSignalStrengthsTimer[strengthBin];
5542 }
5543
Dianne Hackborn627bba72009-03-24 22:32:56 -07005544 @Override public long getPhoneDataConnectionTime(int dataType,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005545 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07005546 return mPhoneDataConnectionsTimer[dataType].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005547 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005548 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005549
Dianne Hackborn617f8772009-03-31 15:04:46 -07005550 @Override public int getPhoneDataConnectionCount(int dataType, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07005551 return mPhoneDataConnectionsTimer[dataType].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005552 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005553
Kweku Adams87b19ec2017-10-09 12:40:03 -07005554 @Override public Timer getPhoneDataConnectionTimer(int dataType) {
5555 return mPhoneDataConnectionsTimer[dataType];
5556 }
5557
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005558 @Override public long getMobileRadioActiveTime(long elapsedRealtimeUs, int which) {
5559 return mMobileRadioActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborne13c4c02014-02-11 17:18:35 -08005560 }
5561
Dianne Hackbornd45665b2014-02-26 12:35:32 -08005562 @Override public int getMobileRadioActiveCount(int which) {
5563 return mMobileRadioActiveTimer.getCountLocked(which);
5564 }
5565
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005566 @Override public long getMobileRadioActiveAdjustedTime(int which) {
5567 return mMobileRadioActiveAdjustedTime.getCountLocked(which);
5568 }
5569
Dianne Hackbornd45665b2014-02-26 12:35:32 -08005570 @Override public long getMobileRadioActiveUnknownTime(int which) {
5571 return mMobileRadioActiveUnknownTime.getCountLocked(which);
5572 }
5573
5574 @Override public int getMobileRadioActiveUnknownCount(int which) {
5575 return (int)mMobileRadioActiveUnknownCount.getCountLocked(which);
5576 }
5577
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005578 @Override public long getWifiOnTime(long elapsedRealtimeUs, int which) {
5579 return mWifiOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07005580 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005581
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005582 @Override public long getGlobalWifiRunningTime(long elapsedRealtimeUs, int which) {
5583 return mGlobalWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005584 }
5585
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005586 @Override public long getWifiStateTime(int wifiState,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005587 long elapsedRealtimeUs, int which) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005588 return mWifiStateTimer[wifiState].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005589 elapsedRealtimeUs, which);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005590 }
5591
5592 @Override public int getWifiStateCount(int wifiState, int which) {
5593 return mWifiStateTimer[wifiState].getCountLocked(which);
5594 }
5595
Kweku Adams87b19ec2017-10-09 12:40:03 -07005596 @Override public Timer getWifiStateTimer(int wifiState) {
5597 return mWifiStateTimer[wifiState];
5598 }
5599
Dianne Hackborn3251b902014-06-20 14:40:53 -07005600 @Override public long getWifiSupplStateTime(int state,
5601 long elapsedRealtimeUs, int which) {
5602 return mWifiSupplStateTimer[state].getTotalTimeLocked(
5603 elapsedRealtimeUs, which);
5604 }
5605
5606 @Override public int getWifiSupplStateCount(int state, int which) {
5607 return mWifiSupplStateTimer[state].getCountLocked(which);
5608 }
5609
Kweku Adams87b19ec2017-10-09 12:40:03 -07005610 @Override public Timer getWifiSupplStateTimer(int state) {
5611 return mWifiSupplStateTimer[state];
5612 }
5613
Dianne Hackborn3251b902014-06-20 14:40:53 -07005614 @Override public long getWifiSignalStrengthTime(int strengthBin,
5615 long elapsedRealtimeUs, int which) {
5616 return mWifiSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
5617 elapsedRealtimeUs, which);
5618 }
5619
5620 @Override public int getWifiSignalStrengthCount(int strengthBin, int which) {
5621 return mWifiSignalStrengthsTimer[strengthBin].getCountLocked(which);
5622 }
5623
Kweku Adams87b19ec2017-10-09 12:40:03 -07005624 @Override public Timer getWifiSignalStrengthTimer(int strengthBin) {
5625 return mWifiSignalStrengthsTimer[strengthBin];
5626 }
5627
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005628 @Override
5629 public ControllerActivityCounter getBluetoothControllerActivity() {
5630 return mBluetoothActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07005631 }
5632
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005633 @Override
5634 public ControllerActivityCounter getWifiControllerActivity() {
5635 return mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -07005636 }
5637
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005638 @Override
5639 public ControllerActivityCounter getModemControllerActivity() {
5640 return mModemActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07005641 }
5642
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005643 @Override
5644 public boolean hasBluetoothActivityReporting() {
5645 return mHasBluetoothReporting;
5646 }
5647
5648 @Override
5649 public boolean hasWifiActivityReporting() {
5650 return mHasWifiReporting;
5651 }
5652
5653 @Override
5654 public boolean hasModemActivityReporting() {
5655 return mHasModemReporting;
Adam Lesinski33dac552015-03-09 15:24:48 -07005656 }
5657
Ruben Brunk5b1308f2015-06-03 18:49:27 -07005658 @Override
5659 public long getFlashlightOnTime(long elapsedRealtimeUs, int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005660 return mFlashlightOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
5661 }
5662
Ruben Brunk5b1308f2015-06-03 18:49:27 -07005663 @Override
5664 public long getFlashlightOnCount(int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005665 return mFlashlightOnTimer.getCountLocked(which);
5666 }
5667
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07005668 @Override
Ruben Brunk5b1308f2015-06-03 18:49:27 -07005669 public long getCameraOnTime(long elapsedRealtimeUs, int which) {
5670 return mCameraOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
5671 }
5672
5673 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005674 public long getBluetoothScanTime(long elapsedRealtimeUs, int which) {
5675 return mBluetoothScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
5676 }
5677
5678 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08005679 public long getNetworkActivityBytes(int type, int which) {
5680 if (type >= 0 && type < mNetworkByteActivityCounters.length) {
5681 return mNetworkByteActivityCounters[type].getCountLocked(which);
5682 } else {
5683 return 0;
5684 }
5685 }
5686
5687 @Override
5688 public long getNetworkActivityPackets(int type, int which) {
5689 if (type >= 0 && type < mNetworkPacketActivityCounters.length) {
5690 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07005691 } else {
5692 return 0;
5693 }
5694 }
5695
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08005696 @Override public long getStartClockTime() {
Dianne Hackbornd48954f2015-07-22 17:20:33 -07005697 final long currentTime = System.currentTimeMillis();
5698 if (ensureStartClockTime(currentTime)) {
Joe Onoratoabded112016-02-08 16:49:39 -08005699 recordCurrentTimeChangeLocked(currentTime, mClocks.elapsedRealtime(),
5700 mClocks.uptimeMillis());
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07005701 }
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08005702 return mStartClockTime;
5703 }
5704
Dianne Hackborncd0e3352014-08-07 17:08:09 -07005705 @Override public String getStartPlatformVersion() {
5706 return mStartPlatformVersion;
5707 }
5708
5709 @Override public String getEndPlatformVersion() {
5710 return mEndPlatformVersion;
5711 }
5712
5713 @Override public int getParcelVersion() {
5714 return VERSION;
5715 }
5716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005717 @Override public boolean getIsOnBattery() {
5718 return mOnBattery;
5719 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005721 @Override public SparseArray<? extends BatteryStats.Uid> getUidStats() {
5722 return mUidStats;
5723 }
5724
Adam Lesinski5f056f62016-07-14 16:56:08 -07005725 private static void detachTimerIfNotNull(BatteryStatsImpl.Timer timer) {
5726 if (timer != null) {
5727 timer.detach();
5728 }
5729 }
5730
5731 private static boolean resetTimerIfNotNull(BatteryStatsImpl.Timer timer,
5732 boolean detachIfReset) {
5733 if (timer != null) {
5734 return timer.reset(detachIfReset);
5735 }
5736 return true;
5737 }
5738
Bookatz867c0d72017-03-07 18:23:42 -08005739 private static boolean resetTimerIfNotNull(DualTimer timer, boolean detachIfReset) {
5740 if (timer != null) {
5741 return timer.reset(detachIfReset);
5742 }
5743 return true;
5744 }
5745
Adam Lesinski5f056f62016-07-14 16:56:08 -07005746 private static void detachLongCounterIfNotNull(LongSamplingCounter counter) {
5747 if (counter != null) {
5748 counter.detach();
5749 }
5750 }
5751
5752 private static void resetLongCounterIfNotNull(LongSamplingCounter counter,
5753 boolean detachIfReset) {
5754 if (counter != null) {
5755 counter.reset(detachIfReset);
5756 }
5757 }
5758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005759 /**
5760 * The statistics associated with a particular uid.
5761 */
Joe Onoratoabded112016-02-08 16:49:39 -08005762 public static class Uid extends BatteryStats.Uid {
5763 /**
5764 * BatteryStatsImpl that we are associated with.
5765 */
5766 protected BatteryStatsImpl mBsi;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005768 final int mUid;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005769
Bookatz867c0d72017-03-07 18:23:42 -08005770 /** TimeBase for when uid is in background and device is on battery. */
5771 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
5772 public final TimeBase mOnBatteryBackgroundTimeBase;
Bookatzc8c44962017-05-11 12:12:54 -07005773 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
5774 public final TimeBase mOnBatteryScreenOffBackgroundTimeBase;
Bookatz867c0d72017-03-07 18:23:42 -08005775
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005776 boolean mWifiRunning;
5777 StopwatchTimer mWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005778
The Android Open Source Project10592532009-03-18 17:39:46 -07005779 boolean mFullWifiLockOut;
Evan Millarc64edde2009-04-18 12:26:32 -07005780 StopwatchTimer mFullWifiLockTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005781
Nick Pelly6ccaa542012-06-15 15:22:47 -07005782 boolean mWifiScanStarted;
Bookatz867c0d72017-03-07 18:23:42 -08005783 DualTimer mWifiScanTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005784
Dianne Hackborn61659e52014-07-09 16:13:01 -07005785 static final int NO_BATCHED_SCAN_STARTED = -1;
Robert Greenwalta029ea12013-09-25 16:38:12 -07005786 int mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
5787 StopwatchTimer[] mWifiBatchedScanTimer;
5788
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005789 boolean mWifiMulticastEnabled;
5790 StopwatchTimer mWifiMulticastTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005791
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005792 StopwatchTimer mAudioTurnedOnTimer;
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005793 StopwatchTimer mVideoTurnedOnTimer;
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005794 StopwatchTimer mFlashlightTurnedOnTimer;
5795 StopwatchTimer mCameraTurnedOnTimer;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005796 StopwatchTimer mForegroundActivityTimer;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07005797 StopwatchTimer mForegroundServiceTimer;
Bookatzc8c44962017-05-11 12:12:54 -07005798 /** Total time spent by the uid holding any partial wakelocks. */
5799 DualTimer mAggregatedPartialWakelockTimer;
Bookatz867c0d72017-03-07 18:23:42 -08005800 DualTimer mBluetoothScanTimer;
Bookatzb1f04f32017-05-19 13:57:32 -07005801 DualTimer mBluetoothUnoptimizedScanTimer;
Bookatz956f36bf2017-04-28 09:48:17 -07005802 Counter mBluetoothScanResultCounter;
Bookatzb1f04f32017-05-19 13:57:32 -07005803 Counter mBluetoothScanResultBgCounter;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005804
Dianne Hackborna8d10942015-11-19 17:55:19 -08005805 int mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07005806 StopwatchTimer[] mProcessStateTimer;
5807
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07005808 boolean mInForegroundService = false;
5809
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005810 BatchTimer mVibratorOnTimer;
5811
Dianne Hackborn617f8772009-03-31 15:04:46 -07005812 Counter[] mUserActivityCounters;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005813
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08005814 LongSamplingCounter[] mNetworkByteActivityCounters;
5815 LongSamplingCounter[] mNetworkPacketActivityCounters;
Dianne Hackbornd45665b2014-02-26 12:35:32 -08005816 LongSamplingCounter mMobileRadioActiveTime;
5817 LongSamplingCounter mMobileRadioActiveCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07005818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005819 /**
Adam Lesinski5f056f62016-07-14 16:56:08 -07005820 * How many times this UID woke up the Application Processor due to a Mobile radio packet.
5821 */
5822 private LongSamplingCounter mMobileRadioApWakeupCount;
5823
5824 /**
5825 * How many times this UID woke up the Application Processor due to a Wifi packet.
5826 */
5827 private LongSamplingCounter mWifiRadioApWakeupCount;
5828
5829 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07005830 * The amount of time this uid has kept the WiFi controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005831 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07005832 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005833 private ControllerActivityCounterImpl mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07005834
5835 /**
5836 * The amount of time this uid has kept the Bluetooth controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005837 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07005838 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005839 private ControllerActivityCounterImpl mBluetoothControllerActivity;
5840
5841 /**
5842 * The amount of time this uid has kept the Modem controller in idle, tx, and rx mode.
5843 * Can be null if the UID has had no such activity.
5844 */
5845 private ControllerActivityCounterImpl mModemControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07005846
5847 /**
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08005848 * The CPU times we had at the last history details update.
5849 */
5850 long mLastStepUserTime;
5851 long mLastStepSystemTime;
5852 long mCurStepUserTime;
5853 long mCurStepSystemTime;
5854
Joe Onoratoabded112016-02-08 16:49:39 -08005855 LongSamplingCounter mUserCpuTime;
5856 LongSamplingCounter mSystemCpuTime;
Sudheer Shankaaf857412017-07-21 00:14:24 -07005857 LongSamplingCounter[][] mCpuClusterSpeedTimesUs;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07005858
Sudheer Shanka9b735c52017-05-09 18:26:18 -07005859 LongSamplingCounterArray mCpuFreqTimeMs;
5860 LongSamplingCounterArray mScreenOffCpuFreqTimeMs;
5861
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08005862 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005863 * The statistics we have collected for this uid's wake locks.
5864 */
Joe Onoratoabded112016-02-08 16:49:39 -08005865 final OverflowArrayMap<Wakelock> mWakelockStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005866
5867 /**
Dianne Hackbornfdb19562014-07-11 16:03:36 -07005868 * The statistics we have collected for this uid's syncs.
5869 */
Bookatz2bffb5b2017-04-13 11:59:33 -07005870 final OverflowArrayMap<DualTimer> mSyncStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07005871
5872 /**
5873 * The statistics we have collected for this uid's jobs.
5874 */
Bookatzaa4594a2017-03-24 12:39:56 -07005875 final OverflowArrayMap<DualTimer> mJobStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07005876
5877 /**
Dianne Hackborn94326cb2017-06-28 16:17:20 -07005878 * Count of the jobs that have completed and the reasons why they completed.
5879 */
5880 final ArrayMap<String, SparseIntArray> mJobCompletions = new ArrayMap<>();
5881
5882 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005883 * The statistics we have collected for this uid's sensor activations.
5884 */
Adam Lesinskie08af192015-03-25 16:42:59 -07005885 final SparseArray<Sensor> mSensorStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005886
5887 /**
5888 * The statistics we have collected for this uid's processes.
5889 */
Adam Lesinskie08af192015-03-25 16:42:59 -07005890 final ArrayMap<String, Proc> mProcessStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005891
5892 /**
5893 * The statistics we have collected for this uid's processes.
5894 */
Adam Lesinskie08af192015-03-25 16:42:59 -07005895 final ArrayMap<String, Pkg> mPackageStats = new ArrayMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005896
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07005897 /**
5898 * The transient wake stats we have collected for this uid's pids.
5899 */
Adam Lesinskie08af192015-03-25 16:42:59 -07005900 final SparseArray<Pid> mPids = new SparseArray<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07005901
Joe Onoratoabded112016-02-08 16:49:39 -08005902 public Uid(BatteryStatsImpl bsi, int uid) {
5903 mBsi = bsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005904 mUid = uid;
Joe Onoratoabded112016-02-08 16:49:39 -08005905
Bookatz867c0d72017-03-07 18:23:42 -08005906 mOnBatteryBackgroundTimeBase = new TimeBase();
5907 mOnBatteryBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
5908 mBsi.mClocks.elapsedRealtime() * 1000);
5909
Bookatzc8c44962017-05-11 12:12:54 -07005910 mOnBatteryScreenOffBackgroundTimeBase = new TimeBase();
5911 mOnBatteryScreenOffBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
5912 mBsi.mClocks.elapsedRealtime() * 1000);
5913
Joe Onoratoabded112016-02-08 16:49:39 -08005914 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
5915 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08005916
Dianne Hackborn657153b2016-07-29 14:54:14 -07005917 mWakelockStats = mBsi.new OverflowArrayMap<Wakelock>(uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005918 @Override public Wakelock instantiateObject() {
5919 return new Wakelock(mBsi, Uid.this);
5920 }
5921 };
Bookatz2bffb5b2017-04-13 11:59:33 -07005922 mSyncStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
5923 @Override public DualTimer instantiateObject() {
5924 return new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
5925 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08005926 }
5927 };
Bookatzaa4594a2017-03-24 12:39:56 -07005928 mJobStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
5929 @Override public DualTimer instantiateObject() {
5930 return new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
5931 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08005932 }
5933 };
5934
5935 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_RUNNING,
5936 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
5937 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, this, FULL_WIFI_LOCK,
5938 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Bookatz867c0d72017-03-07 18:23:42 -08005939 mWifiScanTimer = new DualTimer(mBsi.mClocks, this, WIFI_SCAN,
5940 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005941 mWifiBatchedScanTimer = new StopwatchTimer[NUM_WIFI_BATCHED_SCAN_BINS];
Joe Onoratoabded112016-02-08 16:49:39 -08005942 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_MULTICAST_ENABLED,
5943 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07005944 mProcessStateTimer = new StopwatchTimer[NUM_PROCESS_STATE];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005945 }
5946
5947 @Override
Sudheer Shanka9b735c52017-05-09 18:26:18 -07005948 public long[] getCpuFreqTimes(int which) {
5949 if (mCpuFreqTimeMs == null) {
5950 return null;
5951 }
5952 final long[] cpuFreqTimes = mCpuFreqTimeMs.getCountsLocked(which);
5953 if (cpuFreqTimes == null) {
5954 return null;
5955 }
5956 // Return cpuFreqTimes only if atleast one of the elements in non-zero.
5957 for (int i = 0; i < cpuFreqTimes.length; ++i) {
5958 if (cpuFreqTimes[i] != 0) {
5959 return cpuFreqTimes;
5960 }
5961 }
5962 return null;
5963 }
5964
5965 @Override
5966 public long[] getScreenOffCpuFreqTimes(int which) {
5967 if (mScreenOffCpuFreqTimeMs == null) {
5968 return null;
5969 }
5970 final long[] cpuFreqTimes = mScreenOffCpuFreqTimeMs.getCountsLocked(which);
5971 if (cpuFreqTimes == null) {
5972 return null;
5973 }
5974 // Return cpuFreqTimes only if atleast one of the elements in non-zero.
5975 for (int i = 0; i < cpuFreqTimes.length; ++i) {
5976 if (cpuFreqTimes[i] != 0) {
5977 return cpuFreqTimes;
5978 }
5979 }
5980 return null;
5981 }
5982
5983 @Override
Bookatzc8c44962017-05-11 12:12:54 -07005984 public Timer getAggregatedPartialWakelockTimer() {
5985 return mAggregatedPartialWakelockTimer;
5986 }
5987
5988 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07005989 public ArrayMap<String, ? extends BatteryStats.Uid.Wakelock> getWakelockStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07005990 return mWakelockStats.getMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005991 }
5992
5993 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07005994 public ArrayMap<String, ? extends BatteryStats.Timer> getSyncStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07005995 return mSyncStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07005996 }
5997
5998 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07005999 public ArrayMap<String, ? extends BatteryStats.Timer> getJobStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006000 return mJobStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006001 }
6002
6003 @Override
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006004 public ArrayMap<String, SparseIntArray> getJobCompletionStats() {
6005 return mJobCompletions;
6006 }
6007
6008 @Override
Dianne Hackborn61659e52014-07-09 16:13:01 -07006009 public SparseArray<? extends BatteryStats.Uid.Sensor> getSensorStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006010 return mSensorStats;
6011 }
6012
6013 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006014 public ArrayMap<String, ? extends BatteryStats.Uid.Proc> getProcessStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006015 return mProcessStats;
6016 }
6017
6018 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006019 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg> getPackageStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006020 return mPackageStats;
6021 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07006022
6023 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006024 public int getUid() {
6025 return mUid;
6026 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07006027
6028 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006029 public void noteWifiRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006030 if (!mWifiRunning) {
6031 mWifiRunning = true;
6032 if (mWifiRunningTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006033 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
6034 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006035 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006036 mWifiRunningTimer.startRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006037 }
6038 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006039
Dianne Hackborn617f8772009-03-31 15:04:46 -07006040 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006041 public void noteWifiStoppedLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006042 if (mWifiRunning) {
6043 mWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006044 mWifiRunningTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006045 }
6046 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006047
Dianne Hackborn617f8772009-03-31 15:04:46 -07006048 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006049 public void noteFullWifiLockAcquiredLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07006050 if (!mFullWifiLockOut) {
6051 mFullWifiLockOut = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006052 if (mFullWifiLockTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006053 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
6054 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006055 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006056 mFullWifiLockTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07006057 }
6058 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006059
The Android Open Source Project10592532009-03-18 17:39:46 -07006060 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006061 public void noteFullWifiLockReleasedLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07006062 if (mFullWifiLockOut) {
6063 mFullWifiLockOut = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006064 mFullWifiLockTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07006065 }
6066 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006067
The Android Open Source Project10592532009-03-18 17:39:46 -07006068 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006069 public void noteWifiScanStartedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07006070 if (!mWifiScanStarted) {
6071 mWifiScanStarted = true;
6072 if (mWifiScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08006073 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
6074 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase,
6075 mOnBatteryBackgroundTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006076 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006077 mWifiScanTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07006078 }
6079 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006080
The Android Open Source Project10592532009-03-18 17:39:46 -07006081 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006082 public void noteWifiScanStoppedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07006083 if (mWifiScanStarted) {
6084 mWifiScanStarted = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006085 mWifiScanTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07006086 }
6087 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006088
6089 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006090 public void noteWifiBatchedScanStartedLocked(int csph, long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07006091 int bin = 0;
Navtej Singh Mann3c0ce5c2015-06-11 16:53:11 -07006092 while (csph > 8 && bin < NUM_WIFI_BATCHED_SCAN_BINS-1) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07006093 csph = csph >> 3;
6094 bin++;
6095 }
6096
6097 if (mWifiBatchedScanBinStarted == bin) return;
6098
6099 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
6100 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006101 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006102 }
6103 mWifiBatchedScanBinStarted = bin;
6104 if (mWifiBatchedScanTimer[bin] == null) {
6105 makeWifiBatchedScanBin(bin, null);
6106 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006107 mWifiBatchedScanTimer[bin].startRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006108 }
6109
6110 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006111 public void noteWifiBatchedScanStoppedLocked(long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07006112 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
6113 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006114 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006115 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
6116 }
6117 }
6118
6119 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006120 public void noteWifiMulticastEnabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006121 if (!mWifiMulticastEnabled) {
6122 mWifiMulticastEnabled = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006123 if (mWifiMulticastTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006124 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
6125 WIFI_MULTICAST_ENABLED, mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006126 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006127 mWifiMulticastTimer.startRunningLocked(elapsedRealtimeMs);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006128 }
6129 }
6130
6131 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006132 public void noteWifiMulticastDisabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006133 if (mWifiMulticastEnabled) {
6134 mWifiMulticastEnabled = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006135 mWifiMulticastTimer.stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006136 }
6137 }
6138
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006139 @Override
6140 public ControllerActivityCounter getWifiControllerActivity() {
6141 return mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006142 }
6143
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006144 @Override
6145 public ControllerActivityCounter getBluetoothControllerActivity() {
6146 return mBluetoothControllerActivity;
6147 }
6148
6149 @Override
6150 public ControllerActivityCounter getModemControllerActivity() {
6151 return mModemControllerActivity;
6152 }
6153
6154 public ControllerActivityCounterImpl getOrCreateWifiControllerActivityLocked() {
6155 if (mWifiControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006156 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006157 NUM_BT_TX_LEVELS);
Adam Lesinski50e47602015-12-04 17:04:54 -08006158 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006159 return mWifiControllerActivity;
6160 }
6161
6162 public ControllerActivityCounterImpl getOrCreateBluetoothControllerActivityLocked() {
6163 if (mBluetoothControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006164 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006165 NUM_BT_TX_LEVELS);
6166 }
6167 return mBluetoothControllerActivity;
6168 }
6169
6170 public ControllerActivityCounterImpl getOrCreateModemControllerActivityLocked() {
6171 if (mModemControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006172 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006173 ModemActivityInfo.TX_POWER_LEVELS);
6174 }
6175 return mModemControllerActivity;
Adam Lesinski50e47602015-12-04 17:04:54 -08006176 }
6177
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006178 public StopwatchTimer createAudioTurnedOnTimerLocked() {
6179 if (mAudioTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006180 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
6181 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006182 }
6183 return mAudioTurnedOnTimer;
6184 }
6185
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006186 public void noteAudioTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07006187 createAudioTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07006188 // TODO(statsd): Possibly use a worksource instead of a uid.
6189 StatsLog.write(StatsLog.AUDIO_STATE_CHANGED, getUid(), 1);
Dianne Hackborn10eaa852014-07-22 22:54:55 -07006190 }
6191
6192 public void noteAudioTurnedOffLocked(long elapsedRealtimeMs) {
6193 if (mAudioTurnedOnTimer != null) {
6194 mAudioTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07006195 if (!mAudioTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
6196 // TODO(statsd): Possibly use a worksource instead of a uid.
6197 StatsLog.write(StatsLog.AUDIO_STATE_CHANGED, getUid(), 0);
6198 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006199 }
6200 }
6201
Dianne Hackborn10eaa852014-07-22 22:54:55 -07006202 public void noteResetAudioLocked(long elapsedRealtimeMs) {
6203 if (mAudioTurnedOnTimer != null) {
6204 mAudioTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07006205 // TODO(statsd): Possibly use a worksource instead of a uid.
6206 StatsLog.write(StatsLog.AUDIO_STATE_CHANGED, getUid(), 0);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006207 }
6208 }
6209
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006210 public StopwatchTimer createVideoTurnedOnTimerLocked() {
6211 if (mVideoTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006212 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
6213 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006214 }
6215 return mVideoTurnedOnTimer;
6216 }
6217
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006218 public void noteVideoTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07006219 createVideoTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07006220 // TODO(statsd): Possibly use a worksource instead of a uid.
6221 StatsLog.write(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(), 1);
Dianne Hackborn10eaa852014-07-22 22:54:55 -07006222 }
6223
6224 public void noteVideoTurnedOffLocked(long elapsedRealtimeMs) {
6225 if (mVideoTurnedOnTimer != null) {
6226 mVideoTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07006227 if (!mVideoTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
6228 // TODO(statsd): Possibly use a worksource instead of a uid.
6229 StatsLog.write(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(), 0);
6230 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006231 }
6232 }
6233
Dianne Hackborn10eaa852014-07-22 22:54:55 -07006234 public void noteResetVideoLocked(long elapsedRealtimeMs) {
6235 if (mVideoTurnedOnTimer != null) {
6236 mVideoTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07006237 // TODO(statsd): Possibly use a worksource instead of a uid.
6238 StatsLog.write(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(), 0);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006239 }
6240 }
6241
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006242 public StopwatchTimer createFlashlightTurnedOnTimerLocked() {
6243 if (mFlashlightTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006244 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
6245 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006246 }
6247 return mFlashlightTurnedOnTimer;
6248 }
6249
6250 public void noteFlashlightTurnedOnLocked(long elapsedRealtimeMs) {
6251 createFlashlightTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07006252 // TODO(statsd): Possibly use a worksource instead of a uid.
6253 StatsLog.write(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), 1);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006254 }
6255
6256 public void noteFlashlightTurnedOffLocked(long elapsedRealtimeMs) {
6257 if (mFlashlightTurnedOnTimer != null) {
6258 mFlashlightTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07006259 if (!mFlashlightTurnedOnTimer.isRunningLocked()) {
6260 // TODO(statsd): Possibly use a worksource instead of a uid.
6261 StatsLog.write(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), 0);
6262 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006263 }
6264 }
6265
6266 public void noteResetFlashlightLocked(long elapsedRealtimeMs) {
6267 if (mFlashlightTurnedOnTimer != null) {
6268 mFlashlightTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07006269 // TODO(statsd): Possibly use a worksource instead of a uid.
6270 StatsLog.write(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), 0);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006271 }
6272 }
6273
6274 public StopwatchTimer createCameraTurnedOnTimerLocked() {
6275 if (mCameraTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006276 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
6277 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006278 }
6279 return mCameraTurnedOnTimer;
6280 }
6281
6282 public void noteCameraTurnedOnLocked(long elapsedRealtimeMs) {
6283 createCameraTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07006284 // TODO(statsd): Possibly use a worksource instead of a uid.
6285 StatsLog.write(StatsLog.CAMERA_STATE_CHANGED, getUid(), 1);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006286 }
6287
6288 public void noteCameraTurnedOffLocked(long elapsedRealtimeMs) {
6289 if (mCameraTurnedOnTimer != null) {
6290 mCameraTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07006291 if (!mCameraTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
6292 // TODO(statsd): Possibly use a worksource instead of a uid.
6293 StatsLog.write(StatsLog.CAMERA_STATE_CHANGED, getUid(), 0);
6294 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006295 }
6296 }
6297
6298 public void noteResetCameraLocked(long elapsedRealtimeMs) {
6299 if (mCameraTurnedOnTimer != null) {
6300 mCameraTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07006301 // TODO(statsd): Possibly use a worksource instead of a uid.
6302 StatsLog.write(StatsLog.CAMERA_STATE_CHANGED, getUid(), 0);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006303 }
6304 }
6305
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006306 public StopwatchTimer createForegroundActivityTimerLocked() {
6307 if (mForegroundActivityTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006308 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
6309 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006310 }
6311 return mForegroundActivityTimer;
6312 }
6313
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006314 public StopwatchTimer createForegroundServiceTimerLocked() {
6315 if (mForegroundServiceTimer == null) {
6316 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
6317 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase);
6318 }
6319 return mForegroundServiceTimer;
6320 }
6321
Bookatzc8c44962017-05-11 12:12:54 -07006322 public DualTimer createAggregatedPartialWakelockTimerLocked() {
6323 if (mAggregatedPartialWakelockTimer == null) {
6324 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
6325 AGGREGATED_WAKE_TYPE_PARTIAL, null,
6326 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase);
6327 }
6328 return mAggregatedPartialWakelockTimer;
6329 }
6330
Bookatz867c0d72017-03-07 18:23:42 -08006331 public DualTimer createBluetoothScanTimerLocked() {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006332 if (mBluetoothScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08006333 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
6334 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
6335 mOnBatteryBackgroundTimeBase);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006336 }
6337 return mBluetoothScanTimer;
6338 }
6339
Bookatzb1f04f32017-05-19 13:57:32 -07006340 public DualTimer createBluetoothUnoptimizedScanTimerLocked() {
6341 if (mBluetoothUnoptimizedScanTimer == null) {
6342 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
6343 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
6344 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
6345 }
6346 return mBluetoothUnoptimizedScanTimer;
6347 }
6348
6349 public void noteBluetoothScanStartedLocked(long elapsedRealtimeMs, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006350 createBluetoothScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07006351 // TODO(statsd): Possibly use a worksource instead of a uid.
6352 StatsLog.write(StatsLog.BLE_SCAN_STATE_CHANGED, getUid(), 1);
Bookatzb1f04f32017-05-19 13:57:32 -07006353 if (isUnoptimized) {
6354 createBluetoothUnoptimizedScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07006355 // TODO(statsd): Possibly use a worksource instead of a uid.
6356 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED, getUid(), 1);
Bookatzb1f04f32017-05-19 13:57:32 -07006357 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006358 }
6359
Bookatz94c5a312017-07-11 16:49:17 -07006360 public void noteBluetoothScanStoppedLocked(long elapsedRealtimeMs, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006361 if (mBluetoothScanTimer != null) {
6362 mBluetoothScanTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07006363 if (!mBluetoothScanTimer.isRunningLocked()) { // only tell statsd if truly stopped
6364 // TODO(statsd): Possibly use a worksource instead of a uid.
6365 StatsLog.write(StatsLog.BLE_SCAN_STATE_CHANGED, getUid(), 0);
6366 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006367 }
Bookatz94c5a312017-07-11 16:49:17 -07006368 if (isUnoptimized && mBluetoothUnoptimizedScanTimer != null) {
Bookatzb1f04f32017-05-19 13:57:32 -07006369 mBluetoothUnoptimizedScanTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07006370 if (!mBluetoothUnoptimizedScanTimer.isRunningLocked()) {
6371 // TODO(statsd): Possibly use a worksource instead of a uid.
6372 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED, getUid(), 0);
6373 }
Bookatzb1f04f32017-05-19 13:57:32 -07006374 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006375 }
6376
6377 public void noteResetBluetoothScanLocked(long elapsedRealtimeMs) {
6378 if (mBluetoothScanTimer != null) {
6379 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07006380 // TODO(statsd): Possibly use a worksource instead of a uid.
6381 StatsLog.write(StatsLog.BLE_SCAN_STATE_CHANGED, getUid(), 0);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006382 }
Bookatzb1f04f32017-05-19 13:57:32 -07006383 if (mBluetoothUnoptimizedScanTimer != null) {
6384 mBluetoothUnoptimizedScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07006385 // TODO(statsd): Possibly use a worksource instead of a uid.
6386 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED, getUid(), 0);
Bookatzb1f04f32017-05-19 13:57:32 -07006387 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006388 }
6389
Bookatz956f36bf2017-04-28 09:48:17 -07006390 public Counter createBluetoothScanResultCounterLocked() {
6391 if (mBluetoothScanResultCounter == null) {
6392 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase);
6393 }
6394 return mBluetoothScanResultCounter;
6395 }
6396
Bookatzb1f04f32017-05-19 13:57:32 -07006397 public Counter createBluetoothScanResultBgCounterLocked() {
6398 if (mBluetoothScanResultBgCounter == null) {
6399 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase);
6400 }
6401 return mBluetoothScanResultBgCounter;
6402 }
6403
Bookatz4ebc0642017-05-11 12:21:19 -07006404 public void noteBluetoothScanResultsLocked(int numNewResults) {
6405 createBluetoothScanResultCounterLocked().addAtomic(numNewResults);
Bookatzb1f04f32017-05-19 13:57:32 -07006406 // Uses background timebase, so the count will only be incremented if uid in background.
6407 createBluetoothScanResultBgCounterLocked().addAtomic(numNewResults);
Bookatzc1a050a2017-10-10 15:49:28 -07006408 // TODO(statsd): Possibly use a worksource instead of a uid.
6409 // TODO(statsd): This could be in AppScanStats instead, if desired.
6410 StatsLog.write(StatsLog.BLE_SCAN_RESULT_RECEIVED, getUid(), numNewResults);
Bookatz956f36bf2017-04-28 09:48:17 -07006411 }
6412
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006413 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006414 public void noteActivityResumedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006415 // We always start, since we want multiple foreground PIDs to nest
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006416 createForegroundActivityTimerLocked().startRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006417 }
6418
6419 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006420 public void noteActivityPausedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006421 if (mForegroundActivityTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006422 mForegroundActivityTimer.stopRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006423 }
6424 }
6425
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006426 public void noteForegroundServiceResumedLocked(long elapsedRealtimeMs) {
6427 createForegroundServiceTimerLocked().startRunningLocked(elapsedRealtimeMs);
6428 }
6429
6430 public void noteForegroundServicePausedLocked(long elapsedRealtimeMs) {
6431 if (mForegroundServiceTimer != null) {
6432 mForegroundServiceTimer.stopRunningLocked(elapsedRealtimeMs);
6433 }
6434 }
6435
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006436 public BatchTimer createVibratorOnTimerLocked() {
6437 if (mVibratorOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006438 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
6439 mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006440 }
6441 return mVibratorOnTimer;
6442 }
6443
6444 public void noteVibratorOnLocked(long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08006445 createVibratorOnTimerLocked().addDuration(mBsi, durationMillis);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006446 }
6447
6448 public void noteVibratorOffLocked() {
6449 if (mVibratorOnTimer != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006450 mVibratorOnTimer.abortLastDuration(mBsi);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006451 }
6452 }
6453
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006454 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006455 public long getWifiRunningTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006456 if (mWifiRunningTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006457 return 0;
6458 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006459 return mWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006460 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006461
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006462 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006463 public long getFullWifiLockTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006464 if (mFullWifiLockTimer == null) {
6465 return 0;
6466 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006467 return mFullWifiLockTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07006468 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006469
6470 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006471 public long getWifiScanTime(long elapsedRealtimeUs, int which) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07006472 if (mWifiScanTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006473 return 0;
6474 }
Bookatzaa4594a2017-03-24 12:39:56 -07006475 return mWifiScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07006476 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006477
6478 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07006479 public int getWifiScanCount(int which) {
6480 if (mWifiScanTimer == null) {
6481 return 0;
6482 }
Bookatzaa4594a2017-03-24 12:39:56 -07006483 return mWifiScanTimer.getCountLocked(which);
Bookatz867c0d72017-03-07 18:23:42 -08006484 }
6485
6486 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07006487 public Timer getWifiScanTimer() {
6488 return mWifiScanTimer;
6489 }
6490
6491 @Override
Bookatz867c0d72017-03-07 18:23:42 -08006492 public int getWifiScanBackgroundCount(int which) {
Bookatzaa4594a2017-03-24 12:39:56 -07006493 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08006494 return 0;
6495 }
6496 return mWifiScanTimer.getSubTimer().getCountLocked(which);
6497 }
6498
6499 @Override
6500 public long getWifiScanActualTime(final long elapsedRealtimeUs) {
6501 if (mWifiScanTimer == null) {
6502 return 0;
6503 }
6504 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
Bookatzaa4594a2017-03-24 12:39:56 -07006505 return mWifiScanTimer.getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Bookatz867c0d72017-03-07 18:23:42 -08006506 }
6507
6508 @Override
6509 public long getWifiScanBackgroundTime(final long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07006510 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08006511 return 0;
6512 }
6513 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
6514 return mWifiScanTimer.getSubTimer().getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Dianne Hackborn62793e42015-03-09 11:15:41 -07006515 }
6516
6517 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07006518 public Timer getWifiScanBackgroundTimer() {
6519 if (mWifiScanTimer == null) {
6520 return null;
6521 }
6522 return mWifiScanTimer.getSubTimer();
6523 }
6524
6525 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006526 public long getWifiBatchedScanTime(int csphBin, long elapsedRealtimeUs, int which) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07006527 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
6528 if (mWifiBatchedScanTimer[csphBin] == null) {
6529 return 0;
6530 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006531 return mWifiBatchedScanTimer[csphBin].getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006532 }
6533
6534 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07006535 public int getWifiBatchedScanCount(int csphBin, int which) {
6536 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
6537 if (mWifiBatchedScanTimer[csphBin] == null) {
6538 return 0;
6539 }
6540 return mWifiBatchedScanTimer[csphBin].getCountLocked(which);
6541 }
6542
6543 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006544 public long getWifiMulticastTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006545 if (mWifiMulticastTimer == null) {
6546 return 0;
6547 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006548 return mWifiMulticastTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006549 }
6550
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006551 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006552 public Timer getAudioTurnedOnTimer() {
6553 return mAudioTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006554 }
6555
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006556 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006557 public Timer getVideoTurnedOnTimer() {
6558 return mVideoTurnedOnTimer;
6559 }
6560
6561 @Override
6562 public Timer getFlashlightTurnedOnTimer() {
6563 return mFlashlightTurnedOnTimer;
6564 }
6565
6566 @Override
6567 public Timer getCameraTurnedOnTimer() {
6568 return mCameraTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006569 }
6570
Dianne Hackborn617f8772009-03-31 15:04:46 -07006571 @Override
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006572 public Timer getForegroundActivityTimer() {
6573 return mForegroundActivityTimer;
6574 }
6575
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006576 @Override
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006577 public Timer getForegroundServiceTimer() {
6578 return mForegroundServiceTimer;
6579 }
6580
6581 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006582 public Timer getBluetoothScanTimer() {
Bookatzaa4594a2017-03-24 12:39:56 -07006583 return mBluetoothScanTimer;
Bookatz867c0d72017-03-07 18:23:42 -08006584 }
6585
6586 @Override
6587 public Timer getBluetoothScanBackgroundTimer() {
6588 if (mBluetoothScanTimer == null) {
6589 return null;
6590 }
6591 return mBluetoothScanTimer.getSubTimer();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006592 }
6593
Bookatz956f36bf2017-04-28 09:48:17 -07006594 @Override
Bookatzb1f04f32017-05-19 13:57:32 -07006595 public Timer getBluetoothUnoptimizedScanTimer() {
6596 return mBluetoothUnoptimizedScanTimer;
6597 }
6598
6599 @Override
6600 public Timer getBluetoothUnoptimizedScanBackgroundTimer() {
6601 if (mBluetoothUnoptimizedScanTimer == null) {
6602 return null;
6603 }
6604 return mBluetoothUnoptimizedScanTimer.getSubTimer();
6605 }
6606
6607 @Override
Bookatz956f36bf2017-04-28 09:48:17 -07006608 public Counter getBluetoothScanResultCounter() {
6609 return mBluetoothScanResultCounter;
6610 }
6611
Bookatzb1f04f32017-05-19 13:57:32 -07006612 @Override
6613 public Counter getBluetoothScanResultBgCounter() {
6614 return mBluetoothScanResultBgCounter;
6615 }
6616
Dianne Hackborn61659e52014-07-09 16:13:01 -07006617 void makeProcessState(int i, Parcel in) {
6618 if (i < 0 || i >= NUM_PROCESS_STATE) return;
6619
6620 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006621 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
6622 mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006623 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08006624 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
6625 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006626 }
6627 }
6628
6629 @Override
6630 public long getProcessStateTime(int state, long elapsedRealtimeUs, int which) {
6631 if (state < 0 || state >= NUM_PROCESS_STATE) return 0;
6632 if (mProcessStateTimer[state] == null) {
6633 return 0;
6634 }
6635 return mProcessStateTimer[state].getTotalTimeLocked(elapsedRealtimeUs, which);
6636 }
6637
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006638 @Override
Joe Onorato713fec82016-03-04 10:34:02 -08006639 public Timer getProcessStateTimer(int state) {
6640 if (state < 0 || state >= NUM_PROCESS_STATE) return null;
6641 return mProcessStateTimer[state];
6642 }
6643
6644 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006645 public Timer getVibratorOnTimer() {
6646 return mVibratorOnTimer;
6647 }
6648
6649 @Override
Dianne Hackborn617f8772009-03-31 15:04:46 -07006650 public void noteUserActivityLocked(int type) {
6651 if (mUserActivityCounters == null) {
6652 initUserActivityLocked();
6653 }
Jeff Browndf693de2012-07-27 12:03:38 -07006654 if (type >= 0 && type < NUM_USER_ACTIVITY_TYPES) {
6655 mUserActivityCounters[type].stepAtomic();
6656 } else {
6657 Slog.w(TAG, "Unknown user activity type " + type + " was specified.",
6658 new Throwable());
6659 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07006660 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006661
Dianne Hackborn617f8772009-03-31 15:04:46 -07006662 @Override
6663 public boolean hasUserActivity() {
6664 return mUserActivityCounters != null;
6665 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006666
Dianne Hackborn617f8772009-03-31 15:04:46 -07006667 @Override
6668 public int getUserActivityCount(int type, int which) {
6669 if (mUserActivityCounters == null) {
6670 return 0;
6671 }
Evan Millarc64edde2009-04-18 12:26:32 -07006672 return mUserActivityCounters[type].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006673 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006674
Robert Greenwalta029ea12013-09-25 16:38:12 -07006675 void makeWifiBatchedScanBin(int i, Parcel in) {
6676 if (i < 0 || i >= NUM_WIFI_BATCHED_SCAN_BINS) return;
6677
Joe Onoratoabded112016-02-08 16:49:39 -08006678 ArrayList<StopwatchTimer> collected = mBsi.mWifiBatchedScanTimers.get(i);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006679 if (collected == null) {
6680 collected = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08006681 mBsi.mWifiBatchedScanTimers.put(i, collected);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006682 }
6683 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006684 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
6685 collected, mBsi.mOnBatteryTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006686 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08006687 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
6688 collected, mBsi.mOnBatteryTimeBase, in);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006689 }
6690 }
6691
6692
Dianne Hackborn617f8772009-03-31 15:04:46 -07006693 void initUserActivityLocked() {
6694 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
6695 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08006696 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006697 }
6698 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006699
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006700 void noteNetworkActivityLocked(int type, long deltaBytes, long deltaPackets) {
6701 if (mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006702 initNetworkActivityLocked();
6703 }
6704 if (type >= 0 && type < NUM_NETWORK_ACTIVITY_TYPES) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006705 mNetworkByteActivityCounters[type].addCountLocked(deltaBytes);
6706 mNetworkPacketActivityCounters[type].addCountLocked(deltaPackets);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006707 } else {
6708 Slog.w(TAG, "Unknown network activity type " + type + " was specified.",
6709 new Throwable());
6710 }
6711 }
6712
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006713 void noteMobileRadioActiveTimeLocked(long batteryUptime) {
6714 if (mNetworkByteActivityCounters == null) {
6715 initNetworkActivityLocked();
6716 }
6717 mMobileRadioActiveTime.addCountLocked(batteryUptime);
6718 mMobileRadioActiveCount.addCountLocked(1);
6719 }
6720
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006721 @Override
6722 public boolean hasNetworkActivity() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006723 return mNetworkByteActivityCounters != null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006724 }
6725
6726 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006727 public long getNetworkActivityBytes(int type, int which) {
6728 if (mNetworkByteActivityCounters != null && type >= 0
6729 && type < mNetworkByteActivityCounters.length) {
6730 return mNetworkByteActivityCounters[type].getCountLocked(which);
6731 } else {
6732 return 0;
6733 }
6734 }
6735
6736 @Override
6737 public long getNetworkActivityPackets(int type, int which) {
6738 if (mNetworkPacketActivityCounters != null && type >= 0
6739 && type < mNetworkPacketActivityCounters.length) {
6740 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006741 } else {
6742 return 0;
6743 }
6744 }
6745
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006746 @Override
6747 public long getMobileRadioActiveTime(int which) {
6748 return mMobileRadioActiveTime != null
6749 ? mMobileRadioActiveTime.getCountLocked(which) : 0;
6750 }
6751
6752 @Override
6753 public int getMobileRadioActiveCount(int which) {
6754 return mMobileRadioActiveCount != null
6755 ? (int)mMobileRadioActiveCount.getCountLocked(which) : 0;
6756 }
6757
Adam Lesinskie08af192015-03-25 16:42:59 -07006758 @Override
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006759 public long getUserCpuTimeUs(int which) {
6760 return mUserCpuTime.getCountLocked(which);
6761 }
6762
6763 @Override
6764 public long getSystemCpuTimeUs(int which) {
6765 return mSystemCpuTime.getCountLocked(which);
6766 }
6767
6768 @Override
Adam Lesinski6832f392015-09-05 18:05:40 -07006769 public long getTimeAtCpuSpeed(int cluster, int step, int which) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07006770 if (mCpuClusterSpeedTimesUs != null) {
6771 if (cluster >= 0 && cluster < mCpuClusterSpeedTimesUs.length) {
6772 final LongSamplingCounter[] cpuSpeedTimesUs = mCpuClusterSpeedTimesUs[cluster];
6773 if (cpuSpeedTimesUs != null) {
6774 if (step >= 0 && step < cpuSpeedTimesUs.length) {
6775 final LongSamplingCounter c = cpuSpeedTimesUs[step];
Adam Lesinski6832f392015-09-05 18:05:40 -07006776 if (c != null) {
6777 return c.getCountLocked(which);
6778 }
6779 }
6780 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006781 }
6782 }
6783 return 0;
6784 }
6785
Adam Lesinski5f056f62016-07-14 16:56:08 -07006786 public void noteMobileRadioApWakeupLocked() {
6787 if (mMobileRadioApWakeupCount == null) {
6788 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6789 }
6790 mMobileRadioApWakeupCount.addCountLocked(1);
6791 }
6792
6793 @Override
6794 public long getMobileRadioApWakeupCount(int which) {
6795 if (mMobileRadioApWakeupCount != null) {
6796 return mMobileRadioApWakeupCount.getCountLocked(which);
6797 }
6798 return 0;
6799 }
6800
6801 public void noteWifiRadioApWakeupLocked() {
6802 if (mWifiRadioApWakeupCount == null) {
6803 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6804 }
6805 mWifiRadioApWakeupCount.addCountLocked(1);
6806 }
6807
6808 @Override
6809 public long getWifiRadioApWakeupCount(int which) {
6810 if (mWifiRadioApWakeupCount != null) {
6811 return mWifiRadioApWakeupCount.getCountLocked(which);
6812 }
6813 return 0;
6814 }
6815
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006816 void initNetworkActivityLocked() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006817 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
6818 mNetworkPacketActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006819 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08006820 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6821 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006822 }
Joe Onoratoabded112016-02-08 16:49:39 -08006823 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6824 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006825 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006826
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006827 /**
6828 * Clear all stats for this uid. Returns true if the uid is completely
6829 * inactive so can be dropped.
6830 */
Adam Lesinski5f212c82017-03-13 12:25:13 -07006831 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
Bookatz993a0be2017-07-21 09:03:23 -07006832 public boolean reset(long uptime, long realtime) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006833 boolean active = false;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006834
Bookatz993a0be2017-07-21 09:03:23 -07006835 mOnBatteryBackgroundTimeBase.init(uptime, realtime);
6836 mOnBatteryScreenOffBackgroundTimeBase.init(uptime, realtime);
6837
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006838 if (mWifiRunningTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006839 active |= !mWifiRunningTimer.reset(false);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006840 active |= mWifiRunning;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006841 }
6842 if (mFullWifiLockTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006843 active |= !mFullWifiLockTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006844 active |= mFullWifiLockOut;
6845 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07006846 if (mWifiScanTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006847 active |= !mWifiScanTimer.reset(false);
Nick Pelly6ccaa542012-06-15 15:22:47 -07006848 active |= mWifiScanStarted;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006849 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006850 if (mWifiBatchedScanTimer != null) {
6851 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
6852 if (mWifiBatchedScanTimer[i] != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006853 active |= !mWifiBatchedScanTimer[i].reset(false);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006854 }
6855 }
6856 active |= (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED);
6857 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006858 if (mWifiMulticastTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006859 active |= !mWifiMulticastTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006860 active |= mWifiMulticastEnabled;
6861 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07006862
6863 active |= !resetTimerIfNotNull(mAudioTurnedOnTimer, false);
6864 active |= !resetTimerIfNotNull(mVideoTurnedOnTimer, false);
6865 active |= !resetTimerIfNotNull(mFlashlightTurnedOnTimer, false);
6866 active |= !resetTimerIfNotNull(mCameraTurnedOnTimer, false);
6867 active |= !resetTimerIfNotNull(mForegroundActivityTimer, false);
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006868 active |= !resetTimerIfNotNull(mForegroundServiceTimer, false);
Bookatzc8c44962017-05-11 12:12:54 -07006869 active |= !resetTimerIfNotNull(mAggregatedPartialWakelockTimer, false);
Adam Lesinski5f056f62016-07-14 16:56:08 -07006870 active |= !resetTimerIfNotNull(mBluetoothScanTimer, false);
Bookatzb1f04f32017-05-19 13:57:32 -07006871 active |= !resetTimerIfNotNull(mBluetoothUnoptimizedScanTimer, false);
Bookatz956f36bf2017-04-28 09:48:17 -07006872 if (mBluetoothScanResultCounter != null) {
6873 mBluetoothScanResultCounter.reset(false);
6874 }
Bookatzb1f04f32017-05-19 13:57:32 -07006875 if (mBluetoothScanResultBgCounter != null) {
6876 mBluetoothScanResultBgCounter.reset(false);
6877 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07006878
Dianne Hackborn61659e52014-07-09 16:13:01 -07006879 if (mProcessStateTimer != null) {
6880 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
6881 if (mProcessStateTimer[i] != null) {
6882 active |= !mProcessStateTimer[i].reset(false);
6883 }
6884 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08006885 active |= (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006886 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006887 if (mVibratorOnTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006888 if (mVibratorOnTimer.reset(false)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006889 mVibratorOnTimer.detach();
6890 mVibratorOnTimer = null;
6891 } else {
6892 active = true;
6893 }
6894 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006895
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006896 if (mUserActivityCounters != null) {
6897 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
6898 mUserActivityCounters[i].reset(false);
6899 }
6900 }
6901
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006902 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006903 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006904 mNetworkByteActivityCounters[i].reset(false);
6905 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006906 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006907 mMobileRadioActiveTime.reset(false);
6908 mMobileRadioActiveCount.reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006909 }
6910
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006911 if (mWifiControllerActivity != null) {
6912 mWifiControllerActivity.reset(false);
6913 }
Adam Lesinskie08af192015-03-25 16:42:59 -07006914
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07006915 if (mBluetoothControllerActivity != null) {
6916 mBluetoothControllerActivity.reset(false);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006917 }
6918
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07006919 if (mModemControllerActivity != null) {
6920 mModemControllerActivity.reset(false);
Adam Lesinskie08af192015-03-25 16:42:59 -07006921 }
6922
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006923 mUserCpuTime.reset(false);
6924 mSystemCpuTime.reset(false);
Adam Lesinski6832f392015-09-05 18:05:40 -07006925
Sudheer Shankaaf857412017-07-21 00:14:24 -07006926 if (mCpuClusterSpeedTimesUs != null) {
6927 for (LongSamplingCounter[] speeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07006928 if (speeds != null) {
6929 for (LongSamplingCounter speed : speeds) {
6930 if (speed != null) {
6931 speed.reset(false);
6932 }
6933 }
6934 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006935 }
6936 }
6937
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006938 if (mCpuFreqTimeMs != null) {
6939 mCpuFreqTimeMs.reset(false);
6940 }
6941 if (mScreenOffCpuFreqTimeMs != null) {
6942 mScreenOffCpuFreqTimeMs.reset(false);
6943 }
6944
Adam Lesinski5f056f62016-07-14 16:56:08 -07006945 resetLongCounterIfNotNull(mMobileRadioApWakeupCount, false);
6946 resetLongCounterIfNotNull(mWifiRadioApWakeupCount, false);
6947
Dianne Hackbornd953c532014-08-16 18:17:38 -07006948 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
6949 for (int iw=wakeStats.size()-1; iw>=0; iw--) {
6950 Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006951 if (wl.reset()) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006952 wakeStats.removeAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006953 } else {
6954 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006955 }
6956 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07006957 mWakelockStats.cleanup();
Bookatz2bffb5b2017-04-13 11:59:33 -07006958 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07006959 for (int is=syncStats.size()-1; is>=0; is--) {
Bookatz2bffb5b2017-04-13 11:59:33 -07006960 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006961 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006962 syncStats.removeAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006963 timer.detach();
6964 } else {
6965 active = true;
6966 }
6967 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07006968 mSyncStats.cleanup();
Bookatzaa4594a2017-03-24 12:39:56 -07006969 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07006970 for (int ij=jobStats.size()-1; ij>=0; ij--) {
Bookatzaa4594a2017-03-24 12:39:56 -07006971 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006972 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006973 jobStats.removeAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006974 timer.detach();
6975 } else {
6976 active = true;
6977 }
6978 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07006979 mJobStats.cleanup();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006980 mJobCompletions.clear();
Dianne Hackborn61659e52014-07-09 16:13:01 -07006981 for (int ise=mSensorStats.size()-1; ise>=0; ise--) {
6982 Sensor s = mSensorStats.valueAt(ise);
6983 if (s.reset()) {
6984 mSensorStats.removeAt(ise);
6985 } else {
6986 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006987 }
6988 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07006989 for (int ip=mProcessStats.size()-1; ip>=0; ip--) {
6990 Proc proc = mProcessStats.valueAt(ip);
Dianne Hackborna8d10942015-11-19 17:55:19 -08006991 proc.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006992 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08006993 mProcessStats.clear();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006994 if (mPids.size() > 0) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08006995 for (int i=mPids.size()-1; i>=0; i--) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006996 Pid pid = mPids.valueAt(i);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08006997 if (pid.mWakeNesting > 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006998 active = true;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08006999 } else {
7000 mPids.removeAt(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007001 }
7002 }
7003 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007004 if (mPackageStats.size() > 0) {
7005 Iterator<Map.Entry<String, Pkg>> it = mPackageStats.entrySet().iterator();
7006 while (it.hasNext()) {
7007 Map.Entry<String, Pkg> pkgEntry = it.next();
7008 Pkg p = pkgEntry.getValue();
7009 p.detach();
7010 if (p.mServiceStats.size() > 0) {
7011 Iterator<Map.Entry<String, Pkg.Serv>> it2
7012 = p.mServiceStats.entrySet().iterator();
7013 while (it2.hasNext()) {
7014 Map.Entry<String, Pkg.Serv> servEntry = it2.next();
7015 servEntry.getValue().detach();
7016 }
7017 }
7018 }
7019 mPackageStats.clear();
7020 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007021
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08007022 mLastStepUserTime = mLastStepSystemTime = 0;
7023 mCurStepUserTime = mCurStepSystemTime = 0;
7024
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007025 if (!active) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007026 if (mWifiRunningTimer != null) {
7027 mWifiRunningTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007028 }
7029 if (mFullWifiLockTimer != null) {
7030 mFullWifiLockTimer.detach();
7031 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007032 if (mWifiScanTimer != null) {
7033 mWifiScanTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007034 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007035 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7036 if (mWifiBatchedScanTimer[i] != null) {
7037 mWifiBatchedScanTimer[i].detach();
7038 }
7039 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007040 if (mWifiMulticastTimer != null) {
7041 mWifiMulticastTimer.detach();
7042 }
7043 if (mAudioTurnedOnTimer != null) {
7044 mAudioTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007045 mAudioTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007046 }
7047 if (mVideoTurnedOnTimer != null) {
7048 mVideoTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007049 mVideoTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007050 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007051 if (mFlashlightTurnedOnTimer != null) {
7052 mFlashlightTurnedOnTimer.detach();
7053 mFlashlightTurnedOnTimer = null;
7054 }
7055 if (mCameraTurnedOnTimer != null) {
7056 mCameraTurnedOnTimer.detach();
7057 mCameraTurnedOnTimer = null;
7058 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007059 if (mForegroundActivityTimer != null) {
7060 mForegroundActivityTimer.detach();
7061 mForegroundActivityTimer = null;
7062 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007063 if (mForegroundServiceTimer != null) {
7064 mForegroundServiceTimer.detach();
7065 mForegroundServiceTimer = null;
7066 }
Bookatzc8c44962017-05-11 12:12:54 -07007067 if (mAggregatedPartialWakelockTimer != null) {
7068 mAggregatedPartialWakelockTimer.detach();
7069 mAggregatedPartialWakelockTimer = null;
7070 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007071 if (mBluetoothScanTimer != null) {
7072 mBluetoothScanTimer.detach();
7073 mBluetoothScanTimer = null;
7074 }
Bookatzb1f04f32017-05-19 13:57:32 -07007075 if (mBluetoothUnoptimizedScanTimer != null) {
7076 mBluetoothUnoptimizedScanTimer.detach();
7077 mBluetoothUnoptimizedScanTimer = null;
7078 }
Bookatz956f36bf2017-04-28 09:48:17 -07007079 if (mBluetoothScanResultCounter != null) {
7080 mBluetoothScanResultCounter.detach();
7081 mBluetoothScanResultCounter = null;
7082 }
Bookatzb1f04f32017-05-19 13:57:32 -07007083 if (mBluetoothScanResultBgCounter != null) {
7084 mBluetoothScanResultBgCounter.detach();
7085 mBluetoothScanResultBgCounter = null;
7086 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007087 if (mUserActivityCounters != null) {
7088 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
7089 mUserActivityCounters[i].detach();
7090 }
7091 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007092 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007093 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007094 mNetworkByteActivityCounters[i].detach();
7095 mNetworkPacketActivityCounters[i].detach();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007096 }
7097 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007098
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007099 if (mWifiControllerActivity != null) {
7100 mWifiControllerActivity.detach();
Adam Lesinskie08af192015-03-25 16:42:59 -07007101 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007102
7103 if (mBluetoothControllerActivity != null) {
7104 mBluetoothControllerActivity.detach();
7105 }
7106
7107 if (mModemControllerActivity != null) {
7108 mModemControllerActivity.detach();
7109 }
7110
Dianne Hackborne5167ca2014-03-08 14:39:10 -08007111 mPids.clear();
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007112
7113 mUserCpuTime.detach();
7114 mSystemCpuTime.detach();
Adam Lesinski6832f392015-09-05 18:05:40 -07007115
Sudheer Shankaaf857412017-07-21 00:14:24 -07007116 if (mCpuClusterSpeedTimesUs != null) {
7117 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007118 if (cpuSpeeds != null) {
7119 for (LongSamplingCounter c : cpuSpeeds) {
7120 if (c != null) {
7121 c.detach();
7122 }
7123 }
7124 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007125 }
7126 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007127
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007128 if (mCpuFreqTimeMs != null) {
7129 mCpuFreqTimeMs.detach();
7130 }
7131 if (mScreenOffCpuFreqTimeMs != null) {
7132 mScreenOffCpuFreqTimeMs.detach();
7133 }
7134
Adam Lesinski5f056f62016-07-14 16:56:08 -07007135 detachLongCounterIfNotNull(mMobileRadioApWakeupCount);
7136 detachLongCounterIfNotNull(mWifiRadioApWakeupCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007137 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007138
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007139 return !active;
7140 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007141
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007142 void writeJobCompletionsToParcelLocked(Parcel out) {
7143 int NJC = mJobCompletions.size();
7144 out.writeInt(NJC);
7145 for (int ijc=0; ijc<NJC; ijc++) {
7146 out.writeString(mJobCompletions.keyAt(ijc));
7147 SparseIntArray types = mJobCompletions.valueAt(ijc);
7148 int NT = types.size();
7149 out.writeInt(NT);
7150 for (int it=0; it<NT; it++) {
7151 out.writeInt(types.keyAt(it));
7152 out.writeInt(types.valueAt(it));
7153 }
7154 }
7155 }
7156
Bookatz867c0d72017-03-07 18:23:42 -08007157 void writeToParcelLocked(Parcel out, long uptimeUs, long elapsedRealtimeUs) {
7158 mOnBatteryBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatzc8c44962017-05-11 12:12:54 -07007159 mOnBatteryScreenOffBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08007160
Dianne Hackbornd953c532014-08-16 18:17:38 -07007161 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
7162 int NW = wakeStats.size();
Dianne Hackborn61659e52014-07-09 16:13:01 -07007163 out.writeInt(NW);
7164 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007165 out.writeString(wakeStats.keyAt(iw));
7166 Uid.Wakelock wakelock = wakeStats.valueAt(iw);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007167 wakelock.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007168 }
7169
Bookatz2bffb5b2017-04-13 11:59:33 -07007170 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07007171 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007172 out.writeInt(NS);
7173 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007174 out.writeString(syncStats.keyAt(is));
Bookatz2bffb5b2017-04-13 11:59:33 -07007175 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007176 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
7177 }
7178
Bookatzaa4594a2017-03-24 12:39:56 -07007179 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07007180 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007181 out.writeInt(NJ);
7182 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007183 out.writeString(jobStats.keyAt(ij));
Bookatzaa4594a2017-03-24 12:39:56 -07007184 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007185 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
7186 }
7187
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007188 writeJobCompletionsToParcelLocked(out);
7189
Dianne Hackborn61659e52014-07-09 16:13:01 -07007190 int NSE = mSensorStats.size();
7191 out.writeInt(NSE);
7192 for (int ise=0; ise<NSE; ise++) {
7193 out.writeInt(mSensorStats.keyAt(ise));
7194 Uid.Sensor sensor = mSensorStats.valueAt(ise);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007195 sensor.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007196 }
7197
Dianne Hackborn61659e52014-07-09 16:13:01 -07007198 int NP = mProcessStats.size();
7199 out.writeInt(NP);
7200 for (int ip=0; ip<NP; ip++) {
7201 out.writeString(mProcessStats.keyAt(ip));
7202 Uid.Proc proc = mProcessStats.valueAt(ip);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007203 proc.writeToParcelLocked(out);
7204 }
7205
7206 out.writeInt(mPackageStats.size());
7207 for (Map.Entry<String, Uid.Pkg> pkgEntry : mPackageStats.entrySet()) {
7208 out.writeString(pkgEntry.getKey());
7209 Uid.Pkg pkg = pkgEntry.getValue();
7210 pkg.writeToParcelLocked(out);
7211 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007212
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007213 if (mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007214 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007215 mWifiRunningTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007216 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007217 out.writeInt(0);
7218 }
7219 if (mFullWifiLockTimer != null) {
7220 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007221 mFullWifiLockTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007222 } else {
7223 out.writeInt(0);
7224 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007225 if (mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007226 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007227 mWifiScanTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007228 } else {
7229 out.writeInt(0);
7230 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007231 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7232 if (mWifiBatchedScanTimer[i] != null) {
7233 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007234 mWifiBatchedScanTimer[i].writeToParcel(out, elapsedRealtimeUs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007235 } else {
7236 out.writeInt(0);
7237 }
7238 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007239 if (mWifiMulticastTimer != null) {
7240 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007241 mWifiMulticastTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007242 } else {
7243 out.writeInt(0);
7244 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007245
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007246 if (mAudioTurnedOnTimer != null) {
7247 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007248 mAudioTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007249 } else {
7250 out.writeInt(0);
7251 }
7252 if (mVideoTurnedOnTimer != null) {
7253 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007254 mVideoTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007255 } else {
7256 out.writeInt(0);
7257 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007258 if (mFlashlightTurnedOnTimer != null) {
7259 out.writeInt(1);
7260 mFlashlightTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
7261 } else {
7262 out.writeInt(0);
7263 }
7264 if (mCameraTurnedOnTimer != null) {
7265 out.writeInt(1);
7266 mCameraTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
7267 } else {
7268 out.writeInt(0);
7269 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007270 if (mForegroundActivityTimer != null) {
7271 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007272 mForegroundActivityTimer.writeToParcel(out, elapsedRealtimeUs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007273 } else {
7274 out.writeInt(0);
7275 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007276 if (mForegroundServiceTimer != null) {
7277 out.writeInt(1);
7278 mForegroundServiceTimer.writeToParcel(out, elapsedRealtimeUs);
7279 } else {
7280 out.writeInt(0);
7281 }
Bookatzc8c44962017-05-11 12:12:54 -07007282 if (mAggregatedPartialWakelockTimer != null) {
7283 out.writeInt(1);
7284 mAggregatedPartialWakelockTimer.writeToParcel(out, elapsedRealtimeUs);
7285 } else {
7286 out.writeInt(0);
7287 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007288 if (mBluetoothScanTimer != null) {
7289 out.writeInt(1);
7290 mBluetoothScanTimer.writeToParcel(out, elapsedRealtimeUs);
7291 } else {
7292 out.writeInt(0);
7293 }
Bookatzb1f04f32017-05-19 13:57:32 -07007294 if (mBluetoothUnoptimizedScanTimer != null) {
7295 out.writeInt(1);
7296 mBluetoothUnoptimizedScanTimer.writeToParcel(out, elapsedRealtimeUs);
7297 } else {
7298 out.writeInt(0);
7299 }
Bookatz956f36bf2017-04-28 09:48:17 -07007300 if (mBluetoothScanResultCounter != null) {
7301 out.writeInt(1);
7302 mBluetoothScanResultCounter.writeToParcel(out);
7303 } else {
7304 out.writeInt(0);
7305 }
Bookatzb1f04f32017-05-19 13:57:32 -07007306 if (mBluetoothScanResultBgCounter != null) {
7307 out.writeInt(1);
7308 mBluetoothScanResultBgCounter.writeToParcel(out);
7309 } else {
7310 out.writeInt(0);
7311 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07007312 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
7313 if (mProcessStateTimer[i] != null) {
7314 out.writeInt(1);
7315 mProcessStateTimer[i].writeToParcel(out, elapsedRealtimeUs);
7316 } else {
7317 out.writeInt(0);
7318 }
7319 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007320 if (mVibratorOnTimer != null) {
7321 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007322 mVibratorOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007323 } else {
7324 out.writeInt(0);
7325 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007326 if (mUserActivityCounters != null) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07007327 out.writeInt(1);
7328 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
7329 mUserActivityCounters[i].writeToParcel(out);
7330 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007331 } else {
7332 out.writeInt(0);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007333 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007334 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007335 out.writeInt(1);
7336 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007337 mNetworkByteActivityCounters[i].writeToParcel(out);
7338 mNetworkPacketActivityCounters[i].writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007339 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007340 mMobileRadioActiveTime.writeToParcel(out);
7341 mMobileRadioActiveCount.writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007342 } else {
7343 out.writeInt(0);
7344 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007345
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007346 if (mWifiControllerActivity != null) {
7347 out.writeInt(1);
7348 mWifiControllerActivity.writeToParcel(out, 0);
7349 } else {
7350 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07007351 }
7352
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007353 if (mBluetoothControllerActivity != null) {
7354 out.writeInt(1);
7355 mBluetoothControllerActivity.writeToParcel(out, 0);
7356 } else {
7357 out.writeInt(0);
7358 }
7359
7360 if (mModemControllerActivity != null) {
7361 out.writeInt(1);
7362 mModemControllerActivity.writeToParcel(out, 0);
7363 } else {
7364 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07007365 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007366
7367 mUserCpuTime.writeToParcel(out);
7368 mSystemCpuTime.writeToParcel(out);
7369
Sudheer Shankaaf857412017-07-21 00:14:24 -07007370 if (mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007371 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -07007372 out.writeInt(mCpuClusterSpeedTimesUs.length);
7373 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007374 if (cpuSpeeds != null) {
7375 out.writeInt(1);
7376 out.writeInt(cpuSpeeds.length);
7377 for (LongSamplingCounter c : cpuSpeeds) {
7378 if (c != null) {
7379 out.writeInt(1);
7380 c.writeToParcel(out);
7381 } else {
7382 out.writeInt(0);
7383 }
7384 }
7385 } else {
7386 out.writeInt(0);
7387 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007388 }
Adam Lesinski6832f392015-09-05 18:05:40 -07007389 } else {
7390 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007391 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007392
Sudheer Shanka59f5c002017-05-15 10:57:15 -07007393 LongSamplingCounterArray.writeToParcel(out, mCpuFreqTimeMs);
7394 LongSamplingCounterArray.writeToParcel(out, mScreenOffCpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007395
Adam Lesinski5f056f62016-07-14 16:56:08 -07007396 if (mMobileRadioApWakeupCount != null) {
7397 out.writeInt(1);
7398 mMobileRadioApWakeupCount.writeToParcel(out);
7399 } else {
7400 out.writeInt(0);
7401 }
7402
7403 if (mWifiRadioApWakeupCount != null) {
7404 out.writeInt(1);
7405 mWifiRadioApWakeupCount.writeToParcel(out);
7406 } else {
7407 out.writeInt(0);
7408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007409 }
7410
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007411 void readJobCompletionsFromParcelLocked(Parcel in) {
7412 int numJobCompletions = in.readInt();
7413 mJobCompletions.clear();
7414 for (int j = 0; j < numJobCompletions; j++) {
7415 String jobName = in.readString();
7416 int numTypes = in.readInt();
7417 if (numTypes > 0) {
7418 SparseIntArray types = new SparseIntArray();
7419 for (int k = 0; k < numTypes; k++) {
7420 int type = in.readInt();
7421 int count = in.readInt();
7422 types.put(type, count);
7423 }
7424 mJobCompletions.put(jobName, types);
7425 }
7426 }
7427 }
7428
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007429 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase, Parcel in) {
Bookatz867c0d72017-03-07 18:23:42 -08007430 mOnBatteryBackgroundTimeBase.readFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -07007431 mOnBatteryScreenOffBackgroundTimeBase.readFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -08007432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007433 int numWakelocks = in.readInt();
7434 mWakelockStats.clear();
7435 for (int j = 0; j < numWakelocks; j++) {
7436 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08007437 Uid.Wakelock wakelock = new Wakelock(mBsi, this);
Bookatz5b5ec322017-05-26 09:40:38 -07007438 wakelock.readFromParcelLocked(
7439 timeBase, screenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase, in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07007440 mWakelockStats.add(wakelockName, wakelock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007441 }
7442
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007443 int numSyncs = in.readInt();
7444 mSyncStats.clear();
7445 for (int j = 0; j < numSyncs; j++) {
7446 String syncName = in.readString();
7447 if (in.readInt() != 0) {
Bookatz2bffb5b2017-04-13 11:59:33 -07007448 mSyncStats.add(syncName, new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
7449 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007450 }
7451 }
7452
7453 int numJobs = in.readInt();
7454 mJobStats.clear();
7455 for (int j = 0; j < numJobs; j++) {
7456 String jobName = in.readString();
7457 if (in.readInt() != 0) {
Bookatzaa4594a2017-03-24 12:39:56 -07007458 mJobStats.add(jobName, new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
7459 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007460 }
7461 }
7462
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007463 readJobCompletionsFromParcelLocked(in);
7464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007465 int numSensors = in.readInt();
7466 mSensorStats.clear();
7467 for (int k = 0; k < numSensors; k++) {
7468 int sensorNumber = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08007469 Uid.Sensor sensor = new Sensor(mBsi, this, sensorNumber);
Bookatz867c0d72017-03-07 18:23:42 -08007470 sensor.readFromParcelLocked(mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
7471 in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007472 mSensorStats.put(sensorNumber, sensor);
7473 }
7474
7475 int numProcs = in.readInt();
7476 mProcessStats.clear();
7477 for (int k = 0; k < numProcs; k++) {
7478 String processName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08007479 Uid.Proc proc = new Proc(mBsi, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007480 proc.readFromParcelLocked(in);
7481 mProcessStats.put(processName, proc);
7482 }
7483
7484 int numPkgs = in.readInt();
7485 mPackageStats.clear();
7486 for (int l = 0; l < numPkgs; l++) {
7487 String packageName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08007488 Uid.Pkg pkg = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007489 pkg.readFromParcelLocked(in);
7490 mPackageStats.put(packageName, pkg);
7491 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007492
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007493 mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007494 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007495 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
7496 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007497 } else {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007498 mWifiRunningTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007499 }
7500 mFullWifiLockOut = false;
7501 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007502 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
7503 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007504 } else {
7505 mFullWifiLockTimer = null;
7506 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007507 mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007508 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08007509 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
7510 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
7511 in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007512 } else {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007513 mWifiScanTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007514 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007515 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
7516 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7517 if (in.readInt() != 0) {
7518 makeWifiBatchedScanBin(i, in);
7519 } else {
7520 mWifiBatchedScanTimer[i] = null;
7521 }
7522 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007523 mWifiMulticastEnabled = false;
7524 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007525 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_MULTICAST_ENABLED,
7526 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007527 } else {
7528 mWifiMulticastTimer = null;
7529 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007530 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007531 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
7532 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007533 } else {
7534 mAudioTurnedOnTimer = null;
7535 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007536 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007537 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
7538 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007539 } else {
7540 mVideoTurnedOnTimer = null;
7541 }
7542 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007543 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7544 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007545 } else {
7546 mFlashlightTurnedOnTimer = null;
7547 }
7548 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007549 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
7550 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007551 } else {
7552 mCameraTurnedOnTimer = null;
7553 }
7554 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007555 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7556 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007557 } else {
7558 mForegroundActivityTimer = null;
7559 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007560 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007561 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7562 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase, in);
7563 } else {
7564 mForegroundServiceTimer = null;
7565 }
7566 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -07007567 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
7568 AGGREGATED_WAKE_TYPE_PARTIAL, null,
7569 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase,
7570 in);
7571 } else {
7572 mAggregatedPartialWakelockTimer = null;
7573 }
7574 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08007575 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
7576 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
7577 mOnBatteryBackgroundTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007578 } else {
7579 mBluetoothScanTimer = null;
7580 }
Bookatz956f36bf2017-04-28 09:48:17 -07007581 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -07007582 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
7583 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
7584 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in);
7585 } else {
7586 mBluetoothUnoptimizedScanTimer = null;
7587 }
7588 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -07007589 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase, in);
7590 } else {
7591 mBluetoothScanResultCounter = null;
7592 }
Bookatzb1f04f32017-05-19 13:57:32 -07007593 if (in.readInt() != 0) {
7594 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase, in);
7595 } else {
7596 mBluetoothScanResultBgCounter = null;
7597 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08007598 mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07007599 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
7600 if (in.readInt() != 0) {
7601 makeProcessState(i, in);
7602 } else {
7603 mProcessStateTimer[i] = null;
7604 }
7605 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007606 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007607 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
7608 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007609 } else {
7610 mVibratorOnTimer = null;
7611 }
7612 if (in.readInt() != 0) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07007613 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
7614 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007615 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007616 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007617 } else {
7618 mUserActivityCounters = null;
Dianne Hackborn617f8772009-03-31 15:04:46 -07007619 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007620 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007621 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
7622 mNetworkPacketActivityCounters
7623 = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007624 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007625 mNetworkByteActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08007626 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007627 mNetworkPacketActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08007628 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007629 }
Joe Onoratoabded112016-02-08 16:49:39 -08007630 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
7631 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007632 } else {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007633 mNetworkByteActivityCounters = null;
7634 mNetworkPacketActivityCounters = null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007635 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007636
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007637 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007638 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007639 NUM_WIFI_TX_LEVELS, in);
7640 } else {
7641 mWifiControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07007642 }
7643
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007644 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007645 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007646 NUM_BT_TX_LEVELS, in);
7647 } else {
7648 mBluetoothControllerActivity = null;
7649 }
7650
7651 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007652 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007653 ModemActivityInfo.TX_POWER_LEVELS, in);
7654 } else {
7655 mModemControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07007656 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007657
Joe Onoratoabded112016-02-08 16:49:39 -08007658 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
7659 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007660
Adam Lesinski6832f392015-09-05 18:05:40 -07007661 if (in.readInt() != 0) {
7662 int numCpuClusters = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08007663 if (mBsi.mPowerProfile != null && mBsi.mPowerProfile.getNumCpuClusters() != numCpuClusters) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007664 throw new ParcelFormatException("Incompatible number of cpu clusters");
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007665 }
Adam Lesinski6832f392015-09-05 18:05:40 -07007666
Sudheer Shankaaf857412017-07-21 00:14:24 -07007667 mCpuClusterSpeedTimesUs = new LongSamplingCounter[numCpuClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -07007668 for (int cluster = 0; cluster < numCpuClusters; cluster++) {
7669 if (in.readInt() != 0) {
7670 int numSpeeds = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08007671 if (mBsi.mPowerProfile != null &&
7672 mBsi.mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != numSpeeds) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007673 throw new ParcelFormatException("Incompatible number of cpu speeds");
7674 }
7675
7676 final LongSamplingCounter[] cpuSpeeds = new LongSamplingCounter[numSpeeds];
Sudheer Shankaaf857412017-07-21 00:14:24 -07007677 mCpuClusterSpeedTimesUs[cluster] = cpuSpeeds;
Adam Lesinski6832f392015-09-05 18:05:40 -07007678 for (int speed = 0; speed < numSpeeds; speed++) {
7679 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07007680 cpuSpeeds[speed] = new LongSamplingCounter(
7681 mBsi.mOnBatteryTimeBase, in);
Adam Lesinski6832f392015-09-05 18:05:40 -07007682 }
7683 }
Adam Lesinskia57a5402015-09-28 10:21:33 -07007684 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07007685 mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -07007686 }
7687 }
7688 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07007689 mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007690 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007691
Sudheer Shanka59f5c002017-05-15 10:57:15 -07007692 mCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(in, mBsi.mOnBatteryTimeBase);
7693 mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(
7694 in, mBsi.mOnBatteryScreenOffTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007695
7696 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07007697 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
7698 } else {
7699 mMobileRadioApWakeupCount = null;
7700 }
7701
7702 if (in.readInt() != 0) {
7703 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
7704 } else {
7705 mWifiRadioApWakeupCount = null;
7706 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007707 }
7708
7709 /**
7710 * The statistics associated with a particular wake lock.
7711 */
Joe Onoratoabded112016-02-08 16:49:39 -08007712 public static class Wakelock extends BatteryStats.Uid.Wakelock {
7713 /**
7714 * BatteryStatsImpl that we are associated with.
7715 */
7716 protected BatteryStatsImpl mBsi;
7717
7718 /**
7719 * BatteryStatsImpl that we are associated with.
7720 */
7721 protected Uid mUid;
7722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007723 /**
7724 * How long (in ms) this uid has been keeping the device partially awake.
Bookatz5b5ec322017-05-26 09:40:38 -07007725 * Tracks both the total time and the time while the app was in the background.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007726 */
Bookatz5b5ec322017-05-26 09:40:38 -07007727 DualTimer mTimerPartial;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007728
7729 /**
7730 * How long (in ms) this uid has been keeping the device fully awake.
7731 */
Evan Millarc64edde2009-04-18 12:26:32 -07007732 StopwatchTimer mTimerFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007733
7734 /**
7735 * How long (in ms) this uid has had a window keeping the device awake.
7736 */
Evan Millarc64edde2009-04-18 12:26:32 -07007737 StopwatchTimer mTimerWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007738
7739 /**
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07007740 * How long (in ms) this uid has had a draw wake lock.
Adam Lesinski9425fe22015-06-19 12:02:13 -07007741 */
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07007742 StopwatchTimer mTimerDraw;
Adam Lesinski9425fe22015-06-19 12:02:13 -07007743
Joe Onoratoabded112016-02-08 16:49:39 -08007744 public Wakelock(BatteryStatsImpl bsi, Uid uid) {
7745 mBsi = bsi;
7746 mUid = uid;
7747 }
7748
Adam Lesinski9425fe22015-06-19 12:02:13 -07007749 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007750 * Reads a possibly null Timer from a Parcel. The timer is associated with the
7751 * proper timer pool from the given BatteryStatsImpl object.
7752 *
7753 * @param in the Parcel to be read from.
7754 * return a new Timer, or null.
7755 */
Joe Onorato92fd23f2016-07-25 11:18:42 -07007756 private StopwatchTimer readStopwatchTimerFromParcel(int type,
7757 ArrayList<StopwatchTimer> pool, TimeBase timeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007758 if (in.readInt() == 0) {
7759 return null;
7760 }
7761
Joe Onoratoabded112016-02-08 16:49:39 -08007762 return new StopwatchTimer(mBsi.mClocks, mUid, type, pool, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007763 }
7764
Joe Onorato92fd23f2016-07-25 11:18:42 -07007765 /**
7766 * Reads a possibly null Timer from a Parcel. The timer is associated with the
7767 * proper timer pool from the given BatteryStatsImpl object.
7768 *
7769 * @param in the Parcel to be read from.
7770 * return a new Timer, or null.
7771 */
Bookatz5b5ec322017-05-26 09:40:38 -07007772 private DualTimer readDualTimerFromParcel(int type, ArrayList<StopwatchTimer> pool,
7773 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07007774 if (in.readInt() == 0) {
7775 return null;
7776 }
7777
Bookatz5b5ec322017-05-26 09:40:38 -07007778 return new DualTimer(mBsi.mClocks, mUid, type, pool, timeBase, bgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07007779 }
7780
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007781 boolean reset() {
7782 boolean wlactive = false;
7783 if (mTimerFull != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007784 wlactive |= !mTimerFull.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007785 }
7786 if (mTimerPartial != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007787 wlactive |= !mTimerPartial.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007788 }
7789 if (mTimerWindow != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007790 wlactive |= !mTimerWindow.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007791 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07007792 if (mTimerDraw != null) {
7793 wlactive |= !mTimerDraw.reset(false);
Adam Lesinski9425fe22015-06-19 12:02:13 -07007794 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007795 if (!wlactive) {
7796 if (mTimerFull != null) {
7797 mTimerFull.detach();
7798 mTimerFull = null;
7799 }
7800 if (mTimerPartial != null) {
7801 mTimerPartial.detach();
7802 mTimerPartial = null;
7803 }
7804 if (mTimerWindow != null) {
7805 mTimerWindow.detach();
7806 mTimerWindow = null;
7807 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07007808 if (mTimerDraw != null) {
7809 mTimerDraw.detach();
7810 mTimerDraw = null;
Adam Lesinski9425fe22015-06-19 12:02:13 -07007811 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007812 }
7813 return !wlactive;
7814 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007815
Bookatz5b5ec322017-05-26 09:40:38 -07007816 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase,
7817 TimeBase screenOffBgTimeBase, Parcel in) {
7818 mTimerPartial = readDualTimerFromParcel(WAKE_TYPE_PARTIAL,
7819 mBsi.mPartialTimers, screenOffTimeBase, screenOffBgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07007820 mTimerFull = readStopwatchTimerFromParcel(WAKE_TYPE_FULL,
7821 mBsi.mFullTimers, timeBase, in);
7822 mTimerWindow = readStopwatchTimerFromParcel(WAKE_TYPE_WINDOW,
7823 mBsi.mWindowTimers, timeBase, in);
7824 mTimerDraw = readStopwatchTimerFromParcel(WAKE_TYPE_DRAW,
7825 mBsi.mDrawTimers, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007826 }
7827
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007828 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
7829 Timer.writeTimerToParcel(out, mTimerPartial, elapsedRealtimeUs);
7830 Timer.writeTimerToParcel(out, mTimerFull, elapsedRealtimeUs);
7831 Timer.writeTimerToParcel(out, mTimerWindow, elapsedRealtimeUs);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07007832 Timer.writeTimerToParcel(out, mTimerDraw, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007833 }
7834
7835 @Override
7836 public Timer getWakeTime(int type) {
7837 switch (type) {
7838 case WAKE_TYPE_FULL: return mTimerFull;
7839 case WAKE_TYPE_PARTIAL: return mTimerPartial;
7840 case WAKE_TYPE_WINDOW: return mTimerWindow;
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07007841 case WAKE_TYPE_DRAW: return mTimerDraw;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007842 default: throw new IllegalArgumentException("type = " + type);
7843 }
7844 }
7845 }
7846
Joe Onoratoabded112016-02-08 16:49:39 -08007847 public static class Sensor extends BatteryStats.Uid.Sensor {
7848 /**
7849 * BatteryStatsImpl that we are associated with.
7850 */
7851 protected BatteryStatsImpl mBsi;
7852
7853 /**
Bookatz867c0d72017-03-07 18:23:42 -08007854 * Uid that we are associated with.
Joe Onoratoabded112016-02-08 16:49:39 -08007855 */
7856 protected Uid mUid;
7857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007858 final int mHandle;
Bookatz867c0d72017-03-07 18:23:42 -08007859 DualTimer mTimer;
Amith Yamasaniab9ad192016-12-06 12:46:59 -08007860
Joe Onoratoabded112016-02-08 16:49:39 -08007861 public Sensor(BatteryStatsImpl bsi, Uid uid, int handle) {
7862 mBsi = bsi;
7863 mUid = uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007864 mHandle = handle;
7865 }
7866
Bookatz867c0d72017-03-07 18:23:42 -08007867 private DualTimer readTimersFromParcel(
7868 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007869 if (in.readInt() == 0) {
7870 return null;
7871 }
7872
Joe Onoratoabded112016-02-08 16:49:39 -08007873 ArrayList<StopwatchTimer> pool = mBsi.mSensorTimers.get(mHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007874 if (pool == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07007875 pool = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08007876 mBsi.mSensorTimers.put(mHandle, pool);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007877 }
Bookatz867c0d72017-03-07 18:23:42 -08007878 return new DualTimer(mBsi.mClocks, mUid, 0, pool, timeBase, bgTimeBase, in);
Amith Yamasaniab9ad192016-12-06 12:46:59 -08007879 }
7880
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007881 boolean reset() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007882 if (mTimer.reset(true)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007883 mTimer = null;
7884 return true;
7885 }
7886 return false;
7887 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007888
Bookatz867c0d72017-03-07 18:23:42 -08007889 void readFromParcelLocked(TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
7890 mTimer = readTimersFromParcel(timeBase, bgTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007891 }
7892
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007893 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07007894 Timer.writeTimerToParcel(out, mTimer, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007895 }
7896
7897 @Override
7898 public Timer getSensorTime() {
Bookatzaa4594a2017-03-24 12:39:56 -07007899 return mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007900 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007901
7902 @Override
Bookatz867c0d72017-03-07 18:23:42 -08007903 public Timer getSensorBackgroundTime() {
7904 if (mTimer == null) {
7905 return null;
7906 }
7907 return mTimer.getSubTimer();
Amith Yamasaniab9ad192016-12-06 12:46:59 -08007908 }
7909
7910 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007911 public int getHandle() {
7912 return mHandle;
7913 }
7914 }
7915
7916 /**
7917 * The statistics associated with a particular process.
7918 */
Joe Onoratoabded112016-02-08 16:49:39 -08007919 public static class Proc extends BatteryStats.Uid.Proc implements TimeBaseObs {
7920 /**
7921 * BatteryStatsImpl that we are associated with.
7922 */
7923 protected BatteryStatsImpl mBsi;
7924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007925 /**
Dianne Hackborncd0e3352014-08-07 17:08:09 -07007926 * The name of this process.
7927 */
7928 final String mName;
7929
7930 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -08007931 * Remains true until removed from the stats.
7932 */
7933 boolean mActive = true;
7934
7935 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07007936 * Total time (in ms) spent executing in user code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007937 */
7938 long mUserTime;
7939
7940 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07007941 * Total time (in ms) spent executing in kernel code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007942 */
7943 long mSystemTime;
7944
7945 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07007946 * Amount of time (in ms) the process was running in the foreground.
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007947 */
7948 long mForegroundTime;
7949
7950 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007951 * Number of times the process has been started.
7952 */
7953 int mStarts;
7954
7955 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007956 * Number of times the process has crashed.
7957 */
7958 int mNumCrashes;
7959
7960 /**
7961 * Number of times the process has had an ANR.
7962 */
7963 int mNumAnrs;
7964
7965 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007966 * The amount of user time loaded from a previous save.
7967 */
7968 long mLoadedUserTime;
7969
7970 /**
7971 * The amount of system time loaded from a previous save.
7972 */
7973 long mLoadedSystemTime;
7974
7975 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007976 * The amount of foreground time loaded from a previous save.
7977 */
7978 long mLoadedForegroundTime;
7979
7980 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007981 * The number of times the process has started from a previous save.
7982 */
7983 int mLoadedStarts;
7984
7985 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007986 * Number of times the process has crashed from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007987 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007988 int mLoadedNumCrashes;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007989
7990 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007991 * Number of times the process has had an ANR from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007992 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007993 int mLoadedNumAnrs;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007994
7995 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007996 * The amount of user time when last unplugged.
7997 */
7998 long mUnpluggedUserTime;
7999
8000 /**
8001 * The amount of system time when last unplugged.
8002 */
8003 long mUnpluggedSystemTime;
8004
8005 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008006 * The amount of foreground time since unplugged.
8007 */
8008 long mUnpluggedForegroundTime;
8009
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008010 /**
8011 * The number of times the process has started before unplugged.
8012 */
8013 int mUnpluggedStarts;
8014
Dianne Hackborn61659e52014-07-09 16:13:01 -07008015 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008016 * Number of times the process has crashed before unplugged.
8017 */
8018 int mUnpluggedNumCrashes;
8019
8020 /**
8021 * Number of times the process has had an ANR before unplugged.
8022 */
8023 int mUnpluggedNumAnrs;
8024
Dianne Hackborn287952c2010-09-22 22:34:31 -07008025 ArrayList<ExcessivePower> mExcessivePower;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008026
Joe Onoratoabded112016-02-08 16:49:39 -08008027 public Proc(BatteryStatsImpl bsi, String name) {
8028 mBsi = bsi;
Dianne Hackborncd0e3352014-08-07 17:08:09 -07008029 mName = name;
Joe Onoratoabded112016-02-08 16:49:39 -08008030 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008031 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07008032
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008033 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008034 mUnpluggedUserTime = mUserTime;
8035 mUnpluggedSystemTime = mSystemTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008036 mUnpluggedForegroundTime = mForegroundTime;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008037 mUnpluggedStarts = mStarts;
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008038 mUnpluggedNumCrashes = mNumCrashes;
8039 mUnpluggedNumAnrs = mNumAnrs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008040 }
8041
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008042 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008043 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008044
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008045 void detach() {
Dianne Hackborn099bc622014-01-22 13:39:16 -08008046 mActive = false;
Joe Onoratoabded112016-02-08 16:49:39 -08008047 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008048 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008049
Dianne Hackborn287952c2010-09-22 22:34:31 -07008050 public int countExcessivePowers() {
8051 return mExcessivePower != null ? mExcessivePower.size() : 0;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008052 }
8053
Dianne Hackborn287952c2010-09-22 22:34:31 -07008054 public ExcessivePower getExcessivePower(int i) {
8055 if (mExcessivePower != null) {
8056 return mExcessivePower.get(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008057 }
8058 return null;
8059 }
8060
Dianne Hackborn287952c2010-09-22 22:34:31 -07008061 public void addExcessiveCpu(long overTime, long usedTime) {
8062 if (mExcessivePower == null) {
8063 mExcessivePower = new ArrayList<ExcessivePower>();
8064 }
8065 ExcessivePower ew = new ExcessivePower();
8066 ew.type = ExcessivePower.TYPE_CPU;
8067 ew.overTime = overTime;
8068 ew.usedTime = usedTime;
8069 mExcessivePower.add(ew);
8070 }
8071
8072 void writeExcessivePowerToParcelLocked(Parcel out) {
8073 if (mExcessivePower == null) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008074 out.writeInt(0);
8075 return;
8076 }
8077
Dianne Hackborn287952c2010-09-22 22:34:31 -07008078 final int N = mExcessivePower.size();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008079 out.writeInt(N);
8080 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008081 ExcessivePower ew = mExcessivePower.get(i);
8082 out.writeInt(ew.type);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008083 out.writeLong(ew.overTime);
8084 out.writeLong(ew.usedTime);
8085 }
8086 }
8087
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07008088 void readExcessivePowerFromParcelLocked(Parcel in) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008089 final int N = in.readInt();
8090 if (N == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008091 mExcessivePower = null;
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07008092 return;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008093 }
8094
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08008095 if (N > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07008096 throw new ParcelFormatException(
8097 "File corrupt: too many excessive power entries " + N);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08008098 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07008099
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07008100 mExcessivePower = new ArrayList<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008101 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008102 ExcessivePower ew = new ExcessivePower();
8103 ew.type = in.readInt();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008104 ew.overTime = in.readLong();
8105 ew.usedTime = in.readLong();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008106 mExcessivePower.add(ew);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008107 }
8108 }
8109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008110 void writeToParcelLocked(Parcel out) {
8111 out.writeLong(mUserTime);
8112 out.writeLong(mSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008113 out.writeLong(mForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008114 out.writeInt(mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008115 out.writeInt(mNumCrashes);
8116 out.writeInt(mNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008117 out.writeLong(mLoadedUserTime);
8118 out.writeLong(mLoadedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008119 out.writeLong(mLoadedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008120 out.writeInt(mLoadedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008121 out.writeInt(mLoadedNumCrashes);
8122 out.writeInt(mLoadedNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008123 out.writeLong(mUnpluggedUserTime);
8124 out.writeLong(mUnpluggedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008125 out.writeLong(mUnpluggedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008126 out.writeInt(mUnpluggedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008127 out.writeInt(mUnpluggedNumCrashes);
8128 out.writeInt(mUnpluggedNumAnrs);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008129 writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008130 }
8131
8132 void readFromParcelLocked(Parcel in) {
8133 mUserTime = in.readLong();
8134 mSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008135 mForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008136 mStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008137 mNumCrashes = in.readInt();
8138 mNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008139 mLoadedUserTime = in.readLong();
8140 mLoadedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008141 mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008142 mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008143 mLoadedNumCrashes = in.readInt();
8144 mLoadedNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008145 mUnpluggedUserTime = in.readLong();
8146 mUnpluggedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008147 mUnpluggedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008148 mUnpluggedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008149 mUnpluggedNumCrashes = in.readInt();
8150 mUnpluggedNumAnrs = in.readInt();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008151 readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008152 }
8153
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008154 public void addCpuTimeLocked(int utime, int stime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008155 mUserTime += utime;
8156 mSystemTime += stime;
8157 }
8158
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008159 public void addForegroundTimeLocked(long ttime) {
8160 mForegroundTime += ttime;
8161 }
8162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008163 public void incStartsLocked() {
8164 mStarts++;
8165 }
8166
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008167 public void incNumCrashesLocked() {
8168 mNumCrashes++;
8169 }
8170
8171 public void incNumAnrsLocked() {
8172 mNumAnrs++;
8173 }
8174
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008175 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -08008176 public boolean isActive() {
8177 return mActive;
8178 }
8179
8180 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008181 public long getUserTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07008182 long val = mUserTime;
8183 if (which == STATS_CURRENT) {
8184 val -= mLoadedUserTime;
8185 } else if (which == STATS_SINCE_UNPLUGGED) {
8186 val -= mUnpluggedUserTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008187 }
8188 return val;
8189 }
8190
8191 @Override
8192 public long getSystemTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07008193 long val = mSystemTime;
8194 if (which == STATS_CURRENT) {
8195 val -= mLoadedSystemTime;
8196 } else if (which == STATS_SINCE_UNPLUGGED) {
8197 val -= mUnpluggedSystemTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008198 }
8199 return val;
8200 }
8201
8202 @Override
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008203 public long getForegroundTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07008204 long val = mForegroundTime;
8205 if (which == STATS_CURRENT) {
8206 val -= mLoadedForegroundTime;
8207 } else if (which == STATS_SINCE_UNPLUGGED) {
8208 val -= mUnpluggedForegroundTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008209 }
8210 return val;
8211 }
8212
8213 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008214 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07008215 int val = mStarts;
8216 if (which == STATS_CURRENT) {
8217 val -= mLoadedStarts;
8218 } else if (which == STATS_SINCE_UNPLUGGED) {
8219 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008220 }
8221 return val;
8222 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07008223
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008224 @Override
8225 public int getNumCrashes(int which) {
8226 int val = mNumCrashes;
8227 if (which == STATS_CURRENT) {
8228 val -= mLoadedNumCrashes;
8229 } else if (which == STATS_SINCE_UNPLUGGED) {
8230 val -= mUnpluggedNumCrashes;
8231 }
8232 return val;
8233 }
8234
8235 @Override
8236 public int getNumAnrs(int which) {
8237 int val = mNumAnrs;
8238 if (which == STATS_CURRENT) {
8239 val -= mLoadedNumAnrs;
8240 } else if (which == STATS_SINCE_UNPLUGGED) {
8241 val -= mUnpluggedNumAnrs;
8242 }
8243 return val;
8244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008245 }
8246
8247 /**
8248 * The statistics associated with a particular package.
8249 */
Joe Onoratoabded112016-02-08 16:49:39 -08008250 public static class Pkg extends BatteryStats.Uid.Pkg implements TimeBaseObs {
8251 /**
8252 * BatteryStatsImpl that we are associated with.
8253 */
8254 protected BatteryStatsImpl mBsi;
8255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008256 /**
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008257 * Number of times wakeup alarms have occurred for this app.
Bookatz98d4d5c2017-08-01 19:07:54 -07008258 * On screen-off timebase starting in report v25.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008259 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008260 ArrayMap<String, Counter> mWakeupAlarms = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008261
8262 /**
8263 * The statics we have collected for this package's services.
8264 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008265 final ArrayMap<String, Serv> mServiceStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008266
Joe Onoratoabded112016-02-08 16:49:39 -08008267 public Pkg(BatteryStatsImpl bsi) {
8268 mBsi = bsi;
8269 mBsi.mOnBatteryScreenOffTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008270 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008271
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008272 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008273 }
8274
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008275 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008276 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008277
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008278 void detach() {
Joe Onoratoabded112016-02-08 16:49:39 -08008279 mBsi.mOnBatteryScreenOffTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008280 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008282 void readFromParcelLocked(Parcel in) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008283 int numWA = in.readInt();
8284 mWakeupAlarms.clear();
8285 for (int i=0; i<numWA; i++) {
8286 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -07008287 mWakeupAlarms.put(tag, new Counter(mBsi.mOnBatteryScreenOffTimeBase, in));
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008289
8290 int numServs = in.readInt();
8291 mServiceStats.clear();
8292 for (int m = 0; m < numServs; m++) {
8293 String serviceName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008294 Uid.Pkg.Serv serv = new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008295 mServiceStats.put(serviceName, serv);
8296
8297 serv.readFromParcelLocked(in);
8298 }
8299 }
8300
8301 void writeToParcelLocked(Parcel out) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008302 int numWA = mWakeupAlarms.size();
8303 out.writeInt(numWA);
8304 for (int i=0; i<numWA; i++) {
8305 out.writeString(mWakeupAlarms.keyAt(i));
8306 mWakeupAlarms.valueAt(i).writeToParcel(out);
8307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008308
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008309 final int NS = mServiceStats.size();
8310 out.writeInt(NS);
8311 for (int i=0; i<NS; i++) {
8312 out.writeString(mServiceStats.keyAt(i));
8313 Uid.Pkg.Serv serv = mServiceStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008314 serv.writeToParcelLocked(out);
8315 }
8316 }
8317
8318 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008319 public ArrayMap<String, ? extends BatteryStats.Counter> getWakeupAlarmStats() {
8320 return mWakeupAlarms;
8321 }
8322
8323 public void noteWakeupAlarmLocked(String tag) {
8324 Counter c = mWakeupAlarms.get(tag);
8325 if (c == null) {
Bookatz98d4d5c2017-08-01 19:07:54 -07008326 c = new Counter(mBsi.mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008327 mWakeupAlarms.put(tag, c);
8328 }
8329 c.stepAtomic();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008330 }
8331
8332 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008333 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg.Serv> getServiceStats() {
8334 return mServiceStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008335 }
8336
8337 /**
8338 * The statistics associated with a particular service.
8339 */
Joe Onoratoabded112016-02-08 16:49:39 -08008340 public static class Serv extends BatteryStats.Uid.Pkg.Serv implements TimeBaseObs {
8341 /**
8342 * BatteryStatsImpl that we are associated with.
8343 */
8344 protected BatteryStatsImpl mBsi;
8345
8346 /**
8347 * The android package in which this service resides.
8348 */
8349 protected Pkg mPkg;
8350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008351 /**
8352 * Total time (ms in battery uptime) the service has been left started.
8353 */
Joe Onoratoabded112016-02-08 16:49:39 -08008354 protected long mStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008355
8356 /**
8357 * If service has been started and not yet stopped, this is
8358 * when it was started.
8359 */
Joe Onoratoabded112016-02-08 16:49:39 -08008360 protected long mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008361
8362 /**
8363 * True if we are currently running.
8364 */
Joe Onoratoabded112016-02-08 16:49:39 -08008365 protected boolean mRunning;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008366
8367 /**
8368 * Total number of times startService() has been called.
8369 */
Joe Onoratoabded112016-02-08 16:49:39 -08008370 protected int mStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008371
8372 /**
8373 * Total time (ms in battery uptime) the service has been left launched.
8374 */
Joe Onoratoabded112016-02-08 16:49:39 -08008375 protected long mLaunchedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008376
8377 /**
8378 * If service has been launched and not yet exited, this is
8379 * when it was launched (ms in battery uptime).
8380 */
Joe Onoratoabded112016-02-08 16:49:39 -08008381 protected long mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008382
8383 /**
8384 * True if we are currently launched.
8385 */
Joe Onoratoabded112016-02-08 16:49:39 -08008386 protected boolean mLaunched;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008387
8388 /**
8389 * Total number times the service has been launched.
8390 */
Joe Onoratoabded112016-02-08 16:49:39 -08008391 protected int mLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008392
8393 /**
8394 * The amount of time spent started loaded from a previous save
8395 * (ms in battery uptime).
8396 */
Joe Onoratoabded112016-02-08 16:49:39 -08008397 protected long mLoadedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008398
8399 /**
8400 * The number of starts loaded from a previous save.
8401 */
Joe Onoratoabded112016-02-08 16:49:39 -08008402 protected int mLoadedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008403
8404 /**
8405 * The number of launches loaded from a previous save.
8406 */
Joe Onoratoabded112016-02-08 16:49:39 -08008407 protected int mLoadedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008408
8409 /**
8410 * The amount of time spent started as of the last run (ms
8411 * in battery uptime).
8412 */
Joe Onoratoabded112016-02-08 16:49:39 -08008413 protected long mLastStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008414
8415 /**
8416 * The number of starts as of the last run.
8417 */
Joe Onoratoabded112016-02-08 16:49:39 -08008418 protected int mLastStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008419
8420 /**
8421 * The number of launches as of the last run.
8422 */
Joe Onoratoabded112016-02-08 16:49:39 -08008423 protected int mLastLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008424
8425 /**
8426 * The amount of time spent started when last unplugged (ms
8427 * in battery uptime).
8428 */
Joe Onoratoabded112016-02-08 16:49:39 -08008429 protected long mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008430
8431 /**
8432 * The number of starts when last unplugged.
8433 */
Joe Onoratoabded112016-02-08 16:49:39 -08008434 protected int mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008435
8436 /**
8437 * The number of launches when last unplugged.
8438 */
Joe Onoratoabded112016-02-08 16:49:39 -08008439 protected int mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008440
Joe Onoratoabded112016-02-08 16:49:39 -08008441 /**
8442 * Construct a Serv. Also adds it to the on-battery time base as a listener.
8443 */
8444 public Serv(BatteryStatsImpl bsi) {
8445 mBsi = bsi;
8446 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008447 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008448
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008449 public void onTimeStarted(long elapsedRealtime, long baseUptime,
8450 long baseRealtime) {
8451 mUnpluggedStartTime = getStartTimeToNowLocked(baseUptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008452 mUnpluggedStarts = mStarts;
8453 mUnpluggedLaunches = mLaunches;
8454 }
8455
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008456 public void onTimeStopped(long elapsedRealtime, long baseUptime,
8457 long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008458 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008459
Joe Onoratoabded112016-02-08 16:49:39 -08008460 /**
8461 * Remove this Serv as a listener from the time base.
8462 */
8463 public void detach() {
8464 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008465 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008466
Joe Onoratoabded112016-02-08 16:49:39 -08008467 public void readFromParcelLocked(Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008468 mStartTime = in.readLong();
8469 mRunningSince = in.readLong();
8470 mRunning = in.readInt() != 0;
8471 mStarts = in.readInt();
8472 mLaunchedTime = in.readLong();
8473 mLaunchedSince = in.readLong();
8474 mLaunched = in.readInt() != 0;
8475 mLaunches = in.readInt();
8476 mLoadedStartTime = in.readLong();
8477 mLoadedStarts = in.readInt();
8478 mLoadedLaunches = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07008479 mLastStartTime = 0;
8480 mLastStarts = 0;
8481 mLastLaunches = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008482 mUnpluggedStartTime = in.readLong();
8483 mUnpluggedStarts = in.readInt();
8484 mUnpluggedLaunches = in.readInt();
8485 }
8486
Joe Onoratoabded112016-02-08 16:49:39 -08008487 public void writeToParcelLocked(Parcel out) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008488 out.writeLong(mStartTime);
8489 out.writeLong(mRunningSince);
8490 out.writeInt(mRunning ? 1 : 0);
8491 out.writeInt(mStarts);
8492 out.writeLong(mLaunchedTime);
8493 out.writeLong(mLaunchedSince);
8494 out.writeInt(mLaunched ? 1 : 0);
8495 out.writeInt(mLaunches);
8496 out.writeLong(mLoadedStartTime);
8497 out.writeInt(mLoadedStarts);
8498 out.writeInt(mLoadedLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008499 out.writeLong(mUnpluggedStartTime);
8500 out.writeInt(mUnpluggedStarts);
8501 out.writeInt(mUnpluggedLaunches);
8502 }
8503
Joe Onoratoabded112016-02-08 16:49:39 -08008504 public long getLaunchTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008505 if (!mLaunched) return mLaunchedTime;
8506 return mLaunchedTime + batteryUptime - mLaunchedSince;
8507 }
8508
Joe Onoratoabded112016-02-08 16:49:39 -08008509 public long getStartTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008510 if (!mRunning) return mStartTime;
8511 return mStartTime + batteryUptime - mRunningSince;
8512 }
8513
8514 public void startLaunchedLocked() {
8515 if (!mLaunched) {
8516 mLaunches++;
Joe Onoratoabded112016-02-08 16:49:39 -08008517 mLaunchedSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008518 mLaunched = true;
8519 }
8520 }
8521
8522 public void stopLaunchedLocked() {
8523 if (mLaunched) {
Joe Onoratoabded112016-02-08 16:49:39 -08008524 long time = mBsi.getBatteryUptimeLocked() - mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008525 if (time > 0) {
8526 mLaunchedTime += time;
8527 } else {
8528 mLaunches--;
8529 }
8530 mLaunched = false;
8531 }
8532 }
8533
8534 public void startRunningLocked() {
8535 if (!mRunning) {
8536 mStarts++;
Joe Onoratoabded112016-02-08 16:49:39 -08008537 mRunningSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008538 mRunning = true;
8539 }
8540 }
8541
8542 public void stopRunningLocked() {
8543 if (mRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08008544 long time = mBsi.getBatteryUptimeLocked() - mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008545 if (time > 0) {
8546 mStartTime += time;
8547 } else {
8548 mStarts--;
8549 }
8550 mRunning = false;
8551 }
8552 }
8553
8554 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08008555 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008556 }
8557
8558 @Override
8559 public int getLaunches(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07008560 int val = mLaunches;
8561 if (which == STATS_CURRENT) {
8562 val -= mLoadedLaunches;
8563 } else if (which == STATS_SINCE_UNPLUGGED) {
8564 val -= mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008566 return val;
8567 }
8568
8569 @Override
8570 public long getStartTime(long now, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07008571 long val = getStartTimeToNowLocked(now);
8572 if (which == STATS_CURRENT) {
8573 val -= mLoadedStartTime;
8574 } else if (which == STATS_SINCE_UNPLUGGED) {
8575 val -= mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008577 return val;
8578 }
8579
8580 @Override
8581 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07008582 int val = mStarts;
8583 if (which == STATS_CURRENT) {
8584 val -= mLoadedStarts;
8585 } else if (which == STATS_SINCE_UNPLUGGED) {
8586 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008587 }
8588
8589 return val;
8590 }
8591 }
8592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008593 final Serv newServiceStatsLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08008594 return new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008595 }
8596 }
8597
8598 /**
8599 * Retrieve the statistics object for a particular process, creating
8600 * if needed.
8601 */
8602 public Proc getProcessStatsLocked(String name) {
8603 Proc ps = mProcessStats.get(name);
8604 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08008605 ps = new Proc(mBsi, name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008606 mProcessStats.put(name, ps);
8607 }
8608
8609 return ps;
8610 }
8611
Dianne Hackborna8d10942015-11-19 17:55:19 -08008612 public void updateUidProcessStateLocked(int procState) {
8613 int uidRunningState;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008614 // Make special note of Foreground Services
8615 final boolean userAwareService =
8616 (procState == ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE);
Dianne Hackborna8d10942015-11-19 17:55:19 -08008617 if (procState == ActivityManager.PROCESS_STATE_NONEXISTENT) {
8618 uidRunningState = ActivityManager.PROCESS_STATE_NONEXISTENT;
8619 } else if (procState == ActivityManager.PROCESS_STATE_TOP) {
8620 uidRunningState = PROCESS_STATE_TOP;
8621 } else if (procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
8622 // Persistent and other foreground states go here.
8623 uidRunningState = PROCESS_STATE_FOREGROUND_SERVICE;
8624 } else if (procState <= ActivityManager.PROCESS_STATE_TOP_SLEEPING) {
8625 uidRunningState = PROCESS_STATE_TOP_SLEEPING;
8626 } else if (procState <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) {
8627 // Persistent and other foreground states go here.
8628 uidRunningState = PROCESS_STATE_FOREGROUND;
8629 } else if (procState <= ActivityManager.PROCESS_STATE_RECEIVER) {
8630 uidRunningState = PROCESS_STATE_BACKGROUND;
Dianne Hackborn61659e52014-07-09 16:13:01 -07008631 } else {
Dianne Hackborna8d10942015-11-19 17:55:19 -08008632 uidRunningState = PROCESS_STATE_CACHED;
Dianne Hackborn61659e52014-07-09 16:13:01 -07008633 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07008634
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008635 if (mProcessState == uidRunningState && userAwareService == mInForegroundService) {
8636 return;
8637 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008638
Bookatz867c0d72017-03-07 18:23:42 -08008639 final long elapsedRealtimeMs = mBsi.mClocks.elapsedRealtime();
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008640 if (mProcessState != uidRunningState) {
8641 final long uptimeMs = mBsi.mClocks.uptimeMillis();
Dianne Hackborna8d10942015-11-19 17:55:19 -08008642
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008643 if (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
8644 mProcessStateTimer[mProcessState].stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn61659e52014-07-09 16:13:01 -07008645 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008646 mProcessState = uidRunningState;
8647 if (uidRunningState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
8648 if (mProcessStateTimer[uidRunningState] == null) {
8649 makeProcessState(uidRunningState, null);
8650 }
8651 mProcessStateTimer[uidRunningState].startRunningLocked(elapsedRealtimeMs);
8652 }
8653
8654 updateOnBatteryBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
8655 updateOnBatteryScreenOffBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
Dianne Hackborn61659e52014-07-09 16:13:01 -07008656 }
Bookatz867c0d72017-03-07 18:23:42 -08008657
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008658 if (userAwareService != mInForegroundService) {
8659 if (userAwareService) {
8660 noteForegroundServiceResumedLocked(elapsedRealtimeMs);
8661 } else {
8662 noteForegroundServicePausedLocked(elapsedRealtimeMs);
8663 }
8664 mInForegroundService = userAwareService;
8665 }
Bookatz867c0d72017-03-07 18:23:42 -08008666 }
8667
Bookatzc8c44962017-05-11 12:12:54 -07008668 /** Whether to consider Uid to be in the background for background timebase purposes. */
8669 public boolean isInBackground() {
Bookatz867c0d72017-03-07 18:23:42 -08008670 // Note that PROCESS_STATE_CACHED and ActivityManager.PROCESS_STATE_NONEXISTENT is
8671 // also considered to be 'background' for our purposes, because it's not foreground.
Bookatzc8c44962017-05-11 12:12:54 -07008672 return mProcessState >= PROCESS_STATE_BACKGROUND;
8673 }
8674
8675 public boolean updateOnBatteryBgTimeBase(long uptimeUs, long realtimeUs) {
8676 boolean on = mBsi.mOnBatteryTimeBase.isRunning() && isInBackground();
8677 return mOnBatteryBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
8678 }
8679
8680 public boolean updateOnBatteryScreenOffBgTimeBase(long uptimeUs, long realtimeUs) {
8681 boolean on = mBsi.mOnBatteryScreenOffTimeBase.isRunning() && isInBackground();
8682 return mOnBatteryScreenOffBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
Dianne Hackborn61659e52014-07-09 16:13:01 -07008683 }
8684
Dianne Hackbornb5e31652010-09-07 12:13:55 -07008685 public SparseArray<? extends Pid> getPidStats() {
8686 return mPids;
8687 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008688
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008689 public Pid getPidStatsLocked(int pid) {
8690 Pid p = mPids.get(pid);
8691 if (p == null) {
8692 p = new Pid();
8693 mPids.put(pid, p);
8694 }
8695 return p;
8696 }
8697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008698 /**
8699 * Retrieve the statistics object for a particular service, creating
8700 * if needed.
8701 */
8702 public Pkg getPackageStatsLocked(String name) {
8703 Pkg ps = mPackageStats.get(name);
8704 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08008705 ps = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008706 mPackageStats.put(name, ps);
8707 }
8708
8709 return ps;
8710 }
8711
8712 /**
8713 * Retrieve the statistics object for a particular service, creating
8714 * if needed.
8715 */
8716 public Pkg.Serv getServiceStatsLocked(String pkg, String serv) {
8717 Pkg ps = getPackageStatsLocked(pkg);
8718 Pkg.Serv ss = ps.mServiceStats.get(serv);
8719 if (ss == null) {
8720 ss = ps.newServiceStatsLocked();
8721 ps.mServiceStats.put(serv, ss);
8722 }
8723
8724 return ss;
8725 }
8726
Dianne Hackbornd953c532014-08-16 18:17:38 -07008727 public void readSyncSummaryFromParcelLocked(String name, Parcel in) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008728 DualTimer timer = mSyncStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008729 timer.readSummaryFromParcelLocked(in);
8730 mSyncStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008731 }
8732
Dianne Hackbornd953c532014-08-16 18:17:38 -07008733 public void readJobSummaryFromParcelLocked(String name, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07008734 DualTimer timer = mJobStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008735 timer.readSummaryFromParcelLocked(in);
8736 mJobStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008737 }
8738
Dianne Hackbornd953c532014-08-16 18:17:38 -07008739 public void readWakeSummaryFromParcelLocked(String wlName, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08008740 Wakelock wl = new Wakelock(mBsi, this);
Dianne Hackbornd953c532014-08-16 18:17:38 -07008741 mWakelockStats.add(wlName, wl);
8742 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07008743 getWakelockTimerLocked(wl, WAKE_TYPE_FULL).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008744 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008745 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07008746 getWakelockTimerLocked(wl, WAKE_TYPE_PARTIAL).readSummaryFromParcelLocked(in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07008747 }
8748 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07008749 getWakelockTimerLocked(wl, WAKE_TYPE_WINDOW).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008750 }
Adam Lesinski9425fe22015-06-19 12:02:13 -07008751 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07008752 getWakelockTimerLocked(wl, WAKE_TYPE_DRAW).readSummaryFromParcelLocked(in);
Adam Lesinski9425fe22015-06-19 12:02:13 -07008753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008754 }
8755
Bookatz867c0d72017-03-07 18:23:42 -08008756 public DualTimer getSensorTimerLocked(int sensor, boolean create) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008757 Sensor se = mSensorStats.get(sensor);
8758 if (se == null) {
8759 if (!create) {
8760 return null;
8761 }
Joe Onoratoabded112016-02-08 16:49:39 -08008762 se = new Sensor(mBsi, this, sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008763 mSensorStats.put(sensor, se);
8764 }
Bookatz867c0d72017-03-07 18:23:42 -08008765 DualTimer t = se.mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008766 if (t != null) {
8767 return t;
8768 }
Joe Onoratoabded112016-02-08 16:49:39 -08008769 ArrayList<StopwatchTimer> timers = mBsi.mSensorTimers.get(sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008770 if (timers == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07008771 timers = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08008772 mBsi.mSensorTimers.put(sensor, timers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008773 }
Bookatz867c0d72017-03-07 18:23:42 -08008774 t = new DualTimer(mBsi.mClocks, this, BatteryStats.SENSOR, timers,
8775 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008776 se.mTimer = t;
8777 return t;
8778 }
8779
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008780 public void noteStartSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008781 DualTimer t = mSyncStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008782 if (t != null) {
8783 t.startRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07008784 // TODO(statsd): Possibly use a worksource instead of a uid.
8785 StatsLog.write(StatsLog.SYNC_STATE_CHANGED, getUid(), name, 1);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008786 }
8787 }
8788
8789 public void noteStopSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008790 DualTimer t = mSyncStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008791 if (t != null) {
8792 t.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07008793 if (!t.isRunningLocked()) { // only tell statsd if truly stopped
8794 // TODO(statsd): Possibly use a worksource instead of a uid.
8795 StatsLog.write(StatsLog.SYNC_STATE_CHANGED, getUid(), name, 0);
8796 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008797 }
8798 }
8799
8800 public void noteStartJobLocked(String name, long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07008801 DualTimer t = mJobStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008802 if (t != null) {
8803 t.startRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07008804 // TODO(statsd): Possibly use a worksource instead of a uid.
8805 StatsLog.write(StatsLog.SCHEDULED_JOB_STATE_CHANGED, getUid(), name, 1);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008806 }
8807 }
8808
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008809 public void noteStopJobLocked(String name, long elapsedRealtimeMs, int stopReason) {
Bookatzaa4594a2017-03-24 12:39:56 -07008810 DualTimer t = mJobStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008811 if (t != null) {
8812 t.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07008813 if (!t.isRunningLocked()) { // only tell statsd if truly stopped
8814 // TODO(statsd): Possibly use a worksource instead of a uid.
8815 StatsLog.write(StatsLog.SCHEDULED_JOB_STATE_CHANGED, getUid(), name, 0);
8816 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008817 }
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008818 if (mBsi.mOnBatteryTimeBase.isRunning()) {
8819 SparseIntArray types = mJobCompletions.get(name);
8820 if (types == null) {
8821 types = new SparseIntArray();
8822 mJobCompletions.put(name, types);
8823 }
8824 int last = types.get(stopReason, 0);
8825 types.put(stopReason, last + 1);
8826 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008827 }
8828
Bookatz5b5ec322017-05-26 09:40:38 -07008829 public StopwatchTimer getWakelockTimerLocked(Wakelock wl, int type) {
8830 if (wl == null) {
8831 return null;
8832 }
8833 switch (type) {
8834 case WAKE_TYPE_PARTIAL: {
8835 DualTimer t = wl.mTimerPartial;
8836 if (t == null) {
8837 t = new DualTimer(mBsi.mClocks, this, WAKE_TYPE_PARTIAL,
8838 mBsi.mPartialTimers, mBsi.mOnBatteryScreenOffTimeBase,
8839 mOnBatteryScreenOffBackgroundTimeBase);
8840 wl.mTimerPartial = t;
8841 }
8842 return t;
8843 }
8844 case WAKE_TYPE_FULL: {
8845 StopwatchTimer t = wl.mTimerFull;
8846 if (t == null) {
8847 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_FULL,
8848 mBsi.mFullTimers, mBsi.mOnBatteryTimeBase);
8849 wl.mTimerFull = t;
8850 }
8851 return t;
8852 }
8853 case WAKE_TYPE_WINDOW: {
8854 StopwatchTimer t = wl.mTimerWindow;
8855 if (t == null) {
8856 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_WINDOW,
8857 mBsi.mWindowTimers, mBsi.mOnBatteryTimeBase);
8858 wl.mTimerWindow = t;
8859 }
8860 return t;
8861 }
8862 case WAKE_TYPE_DRAW: {
8863 StopwatchTimer t = wl.mTimerDraw;
8864 if (t == null) {
8865 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_DRAW,
8866 mBsi.mDrawTimers, mBsi.mOnBatteryTimeBase);
8867 wl.mTimerDraw = t;
8868 }
8869 return t;
8870 }
8871 default:
8872 throw new IllegalArgumentException("type=" + type);
8873 }
8874 }
8875
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008876 public void noteStartWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008877 Wakelock wl = mWakelockStats.startObject(name);
8878 if (wl != null) {
Bookatz5b5ec322017-05-26 09:40:38 -07008879 getWakelockTimerLocked(wl, type).startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008880 }
Bookatzc8c44962017-05-11 12:12:54 -07008881 if (type == WAKE_TYPE_PARTIAL) {
8882 createAggregatedPartialWakelockTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07008883 // TODO(statsd): Possibly use a worksource instead of a uid.
8884 StatsLog.write(StatsLog.UID_WAKELOCK_STATE_CHANGED, getUid(), type, 1);
Bookatzc8c44962017-05-11 12:12:54 -07008885 if (pid >= 0) {
8886 Pid p = getPidStatsLocked(pid);
8887 if (p.mWakeNesting++ == 0) {
8888 p.mWakeStartMs = elapsedRealtimeMs;
8889 }
Dianne Hackbornb8071d792010-09-09 16:45:15 -07008890 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008892 }
8893
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008894 public void noteStopWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008895 Wakelock wl = mWakelockStats.stopObject(name);
8896 if (wl != null) {
Bookatz5b5ec322017-05-26 09:40:38 -07008897 getWakelockTimerLocked(wl, type).stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008898 }
Bookatzc8c44962017-05-11 12:12:54 -07008899 if (type == WAKE_TYPE_PARTIAL) {
8900 if (mAggregatedPartialWakelockTimer != null) {
8901 mAggregatedPartialWakelockTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07008902 if (!mAggregatedPartialWakelockTimer.isRunningLocked()) {
8903 // TODO(statsd): Possibly use a worksource instead of a uid.
8904 StatsLog.write(StatsLog.UID_WAKELOCK_STATE_CHANGED, getUid(), type,
8905 0);
8906 }
Bookatzc8c44962017-05-11 12:12:54 -07008907 }
8908 if (pid >= 0) {
8909 Pid p = mPids.get(pid);
8910 if (p != null && p.mWakeNesting > 0) {
8911 if (p.mWakeNesting-- == 1) {
8912 p.mWakeSumMs += elapsedRealtimeMs - p.mWakeStartMs;
8913 p.mWakeStartMs = 0;
8914 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008915 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008916 }
8917 }
8918 }
8919
Dianne Hackborn287952c2010-09-22 22:34:31 -07008920 public void reportExcessiveCpuLocked(String proc, long overTime, long usedTime) {
8921 Proc p = getProcessStatsLocked(proc);
8922 if (p != null) {
8923 p.addExcessiveCpu(overTime, usedTime);
8924 }
8925 }
8926
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008927 public void noteStartSensor(int sensor, long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08008928 DualTimer t = getSensorTimerLocked(sensor, /* create= */ true);
Amith Yamasani154d1242017-02-16 10:01:48 -08008929 t.startRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07008930 // TODO(statsd): Possibly use a worksource instead of a uid.
8931 if (sensor == Sensor.GPS) {
8932 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED, getUid(), 1);
8933 } else {
8934 StatsLog.write(StatsLog.SENSOR_STATE_CHANGED, getUid(), sensor, 1);
8935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008936 }
8937
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008938 public void noteStopSensor(int sensor, long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008939 // Don't create a timer if one doesn't already exist
Bookatz867c0d72017-03-07 18:23:42 -08008940 DualTimer t = getSensorTimerLocked(sensor, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008941 if (t != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008942 t.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07008943 if (!t.isRunningLocked()) { // only tell statsd if truly stopped
8944 // TODO(statsd): Possibly use a worksource instead of a uid.
8945 if (sensor == Sensor.GPS) {
8946 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED, getUid(), 0);
8947 } else {
8948 StatsLog.write(StatsLog.SENSOR_STATE_CHANGED, getUid(), sensor, 0);
8949 }
8950 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008951 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008952 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008953
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008954 public void noteStartGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08008955 noteStartSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008956 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008957
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008958 public void noteStopGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08008959 noteStopSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008960 }
8961
8962 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08008963 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008964 }
8965 }
8966
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008967 public long[] getCpuFreqs() {
8968 return mCpuFreqs;
8969 }
8970
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07008971 public BatteryStatsImpl(File systemDir, Handler handler, PlatformIdleStateCallback cb,
8972 UserInfoProvider userInfoProvider) {
8973 this(new SystemClocks(), systemDir, handler, cb, userInfoProvider);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07008974 }
8975
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07008976 private BatteryStatsImpl(Clocks clocks, File systemDir, Handler handler,
8977 PlatformIdleStateCallback cb,
8978 UserInfoProvider userInfoProvider) {
Joe Onoratoabded112016-02-08 16:49:39 -08008979 init(clocks);
8980
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07008981 if (systemDir != null) {
8982 mFile = new JournaledFile(new File(systemDir, "batterystats.bin"),
8983 new File(systemDir, "batterystats.bin.tmp"));
8984 } else {
8985 mFile = null;
8986 }
8987 mCheckinFile = new AtomicFile(new File(systemDir, "batterystats-checkin.bin"));
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08008988 mDailyFile = new AtomicFile(new File(systemDir, "batterystats-daily.xml"));
Jeff Brown6f357d32014-01-15 20:40:55 -08008989 mHandler = new MyHandler(handler.getLooper());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008990 mStartCount++;
Joe Onoratoabded112016-02-08 16:49:39 -08008991 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -07008992 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008993 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008994 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008995 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07008996 }
Joe Onoratoabded112016-02-08 16:49:39 -08008997 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase);
8998 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
8999 mOnBatteryTimeBase);
9000 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -11, null,
9001 mOnBatteryTimeBase);
9002 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
9003 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null, mOnBatteryTimeBase);
9004 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase);
9005 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase);
9006 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
9007 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i, null,
9008 mOnBatteryTimeBase);
9009 }
9010 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
9011 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07009012 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08009013 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009014 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07009015 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07009016 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009017 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
9018 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07009019 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009020 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase, NUM_WIFI_TX_LEVELS);
9021 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
9022 NUM_BT_TX_LEVELS);
9023 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
9024 ModemActivityInfo.TX_POWER_LEVELS);
Joe Onoratoabded112016-02-08 16:49:39 -08009025 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null, mOnBatteryTimeBase);
9026 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
9027 mOnBatteryTimeBase);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07009028 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009029 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase);
9030 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08009031 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase);
9032 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null, mOnBatteryTimeBase);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08009033 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08009034 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i, null,
Dianne Hackborn3251b902014-06-20 14:40:53 -07009035 mOnBatteryTimeBase);
9036 }
Joe Onoratoabded112016-02-08 16:49:39 -08009037 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
9038 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i, null,
9039 mOnBatteryTimeBase);
9040 }
9041 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
9042 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i, null,
9043 mOnBatteryTimeBase);
9044 }
9045 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
9046 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
9047 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase);
9048 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase);
9049 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -07009050 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -07009051 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -07009052 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009053 mOnBattery = mOnBatteryInternal = false;
Joe Onoratoabded112016-02-08 16:49:39 -08009054 long uptime = mClocks.uptimeMillis() * 1000;
9055 long realtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009056 initTimes(uptime, realtime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -07009057 mStartPlatformVersion = mEndPlatformVersion = Build.ID;
Evan Millar633a1742009-04-02 16:36:33 -07009058 mDischargeStartLevel = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009059 mDischargeUnplugLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07009060 mDischargePlugLevel = -1;
Evan Millar633a1742009-04-02 16:36:33 -07009061 mDischargeCurrentLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07009062 mCurrentBatteryLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08009063 initDischarge();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009064 clearHistoryLocked();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009065 updateDailyDeadlineLocked();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07009066 mPlatformIdleStateCallback = cb;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07009067 mUserInfoProvider = userInfoProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009068 }
9069
9070 public BatteryStatsImpl(Parcel p) {
Joe Onoratoabded112016-02-08 16:49:39 -08009071 this(new SystemClocks(), p);
9072 }
9073
9074 public BatteryStatsImpl(Clocks clocks, Parcel p) {
9075 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07009076 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07009077 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009078 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07009079 mHandler = null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009080 mExternalSync = null;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009081 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009082 readFromParcel(p);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07009083 mPlatformIdleStateCallback = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009084 }
9085
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009086 public void setPowerProfileLocked(PowerProfile profile) {
9087 mPowerProfile = profile;
Adam Lesinski6832f392015-09-05 18:05:40 -07009088
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009089 // We need to initialize the KernelCpuSpeedReaders to read from
9090 // the first cpu of each core. Once we have the PowerProfile, we have access to this
9091 // information.
9092 final int numClusters = mPowerProfile.getNumCpuClusters();
9093 mKernelCpuSpeedReaders = new KernelCpuSpeedReader[numClusters];
9094 int firstCpuOfCluster = 0;
9095 for (int i = 0; i < numClusters; i++) {
9096 final int numSpeedSteps = mPowerProfile.getNumSpeedStepsInCpuCluster(i);
9097 mKernelCpuSpeedReaders[i] = new KernelCpuSpeedReader(firstCpuOfCluster,
9098 numSpeedSteps);
9099 firstCpuOfCluster += mPowerProfile.getNumCoresInCpuCluster(i);
9100 }
Adam Lesinskif9b20a92016-06-17 17:30:01 -07009101
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009102 if (mEstimatedBatteryCapacity == -1) {
9103 // Initialize the estimated battery capacity to a known preset one.
9104 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
Adam Lesinskie08af192015-03-25 16:42:59 -07009105 }
9106 }
9107
Dianne Hackborn0d903a82010-09-07 23:51:03 -07009108 public void setCallback(BatteryCallback cb) {
9109 mCallback = cb;
9110 }
9111
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009112 public void setRadioScanningTimeoutLocked(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07009113 if (mPhoneSignalScanningTimer != null) {
9114 mPhoneSignalScanningTimer.setTimeout(timeout);
9115 }
9116 }
9117
Adam Lesinskib3a1bad2017-05-26 11:50:40 -07009118 public void setExternalStatsSyncLocked(ExternalStatsSync sync) {
9119 mExternalSync = sync;
9120 }
9121
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009122 public void updateDailyDeadlineLocked() {
9123 // Get the current time.
9124 long currentTime = mDailyStartTime = System.currentTimeMillis();
9125 Calendar calDeadline = Calendar.getInstance();
9126 calDeadline.setTimeInMillis(currentTime);
9127
9128 // Move time up to the next day, ranging from 1am to 3pm.
9129 calDeadline.set(Calendar.DAY_OF_YEAR, calDeadline.get(Calendar.DAY_OF_YEAR) + 1);
9130 calDeadline.set(Calendar.MILLISECOND, 0);
9131 calDeadline.set(Calendar.SECOND, 0);
9132 calDeadline.set(Calendar.MINUTE, 0);
9133 calDeadline.set(Calendar.HOUR_OF_DAY, 1);
9134 mNextMinDailyDeadline = calDeadline.getTimeInMillis();
9135 calDeadline.set(Calendar.HOUR_OF_DAY, 3);
9136 mNextMaxDailyDeadline = calDeadline.getTimeInMillis();
9137 }
9138
9139 public void recordDailyStatsIfNeededLocked(boolean settled) {
9140 long currentTime = System.currentTimeMillis();
9141 if (currentTime >= mNextMaxDailyDeadline) {
9142 recordDailyStatsLocked();
9143 } else if (settled && currentTime >= mNextMinDailyDeadline) {
9144 recordDailyStatsLocked();
9145 } else if (currentTime < (mDailyStartTime-(1000*60*60*24))) {
9146 recordDailyStatsLocked();
9147 }
9148 }
9149
9150 public void recordDailyStatsLocked() {
9151 DailyItem item = new DailyItem();
9152 item.mStartTime = mDailyStartTime;
9153 item.mEndTime = System.currentTimeMillis();
9154 boolean hasData = false;
9155 if (mDailyDischargeStepTracker.mNumStepDurations > 0) {
9156 hasData = true;
9157 item.mDischargeSteps = new LevelStepTracker(
9158 mDailyDischargeStepTracker.mNumStepDurations,
9159 mDailyDischargeStepTracker.mStepDurations);
9160 }
9161 if (mDailyChargeStepTracker.mNumStepDurations > 0) {
9162 hasData = true;
9163 item.mChargeSteps = new LevelStepTracker(
9164 mDailyChargeStepTracker.mNumStepDurations,
9165 mDailyChargeStepTracker.mStepDurations);
9166 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07009167 if (mDailyPackageChanges != null) {
9168 hasData = true;
9169 item.mPackageChanges = mDailyPackageChanges;
9170 mDailyPackageChanges = null;
9171 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009172 mDailyDischargeStepTracker.init();
9173 mDailyChargeStepTracker.init();
9174 updateDailyDeadlineLocked();
9175
9176 if (hasData) {
9177 mDailyItems.add(item);
9178 while (mDailyItems.size() > MAX_DAILY_ITEMS) {
9179 mDailyItems.remove(0);
9180 }
9181 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
9182 try {
9183 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01009184 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009185 writeDailyItemsLocked(out);
9186 BackgroundThread.getHandler().post(new Runnable() {
9187 @Override
9188 public void run() {
9189 synchronized (mCheckinFile) {
9190 FileOutputStream stream = null;
9191 try {
9192 stream = mDailyFile.startWrite();
9193 memStream.writeTo(stream);
9194 stream.flush();
9195 FileUtils.sync(stream);
9196 stream.close();
9197 mDailyFile.finishWrite(stream);
9198 } catch (IOException e) {
9199 Slog.w("BatteryStats",
9200 "Error writing battery daily items", e);
9201 mDailyFile.failWrite(stream);
9202 }
9203 }
9204 }
9205 });
9206 } catch (IOException e) {
9207 }
9208 }
9209 }
9210
9211 private void writeDailyItemsLocked(XmlSerializer out) throws IOException {
9212 StringBuilder sb = new StringBuilder(64);
9213 out.startDocument(null, true);
9214 out.startTag(null, "daily-items");
9215 for (int i=0; i<mDailyItems.size(); i++) {
9216 final DailyItem dit = mDailyItems.get(i);
9217 out.startTag(null, "item");
9218 out.attribute(null, "start", Long.toString(dit.mStartTime));
9219 out.attribute(null, "end", Long.toString(dit.mEndTime));
9220 writeDailyLevelSteps(out, "dis", dit.mDischargeSteps, sb);
9221 writeDailyLevelSteps(out, "chg", dit.mChargeSteps, sb);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07009222 if (dit.mPackageChanges != null) {
9223 for (int j=0; j<dit.mPackageChanges.size(); j++) {
9224 PackageChange pc = dit.mPackageChanges.get(j);
9225 if (pc.mUpdate) {
9226 out.startTag(null, "upd");
9227 out.attribute(null, "pkg", pc.mPackageName);
9228 out.attribute(null, "ver", Integer.toString(pc.mVersionCode));
9229 out.endTag(null, "upd");
9230 } else {
9231 out.startTag(null, "rem");
9232 out.attribute(null, "pkg", pc.mPackageName);
9233 out.endTag(null, "rem");
9234 }
9235 }
9236 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009237 out.endTag(null, "item");
9238 }
9239 out.endTag(null, "daily-items");
9240 out.endDocument();
9241 }
9242
9243 private void writeDailyLevelSteps(XmlSerializer out, String tag, LevelStepTracker steps,
9244 StringBuilder tmpBuilder) throws IOException {
9245 if (steps != null) {
9246 out.startTag(null, tag);
9247 out.attribute(null, "n", Integer.toString(steps.mNumStepDurations));
9248 for (int i=0; i<steps.mNumStepDurations; i++) {
9249 out.startTag(null, "s");
9250 tmpBuilder.setLength(0);
9251 steps.encodeEntryAt(i, tmpBuilder);
9252 out.attribute(null, "v", tmpBuilder.toString());
9253 out.endTag(null, "s");
9254 }
9255 out.endTag(null, tag);
9256 }
9257 }
9258
9259 public void readDailyStatsLocked() {
9260 Slog.d(TAG, "Reading daily items from " + mDailyFile.getBaseFile());
9261 mDailyItems.clear();
9262 FileInputStream stream;
9263 try {
9264 stream = mDailyFile.openRead();
9265 } catch (FileNotFoundException e) {
9266 return;
9267 }
9268 try {
9269 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01009270 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009271 readDailyItemsLocked(parser);
9272 } catch (XmlPullParserException e) {
9273 } finally {
9274 try {
9275 stream.close();
9276 } catch (IOException e) {
9277 }
9278 }
9279 }
9280
9281 private void readDailyItemsLocked(XmlPullParser parser) {
9282 try {
9283 int type;
9284 while ((type = parser.next()) != XmlPullParser.START_TAG
9285 && type != XmlPullParser.END_DOCUMENT) {
9286 ;
9287 }
9288
9289 if (type != XmlPullParser.START_TAG) {
9290 throw new IllegalStateException("no start tag found");
9291 }
9292
9293 int outerDepth = parser.getDepth();
9294 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
9295 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
9296 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
9297 continue;
9298 }
9299
9300 String tagName = parser.getName();
9301 if (tagName.equals("item")) {
9302 readDailyItemTagLocked(parser);
9303 } else {
9304 Slog.w(TAG, "Unknown element under <daily-items>: "
9305 + parser.getName());
9306 XmlUtils.skipCurrentTag(parser);
9307 }
9308 }
9309
9310 } catch (IllegalStateException e) {
9311 Slog.w(TAG, "Failed parsing daily " + e);
9312 } catch (NullPointerException e) {
9313 Slog.w(TAG, "Failed parsing daily " + e);
9314 } catch (NumberFormatException e) {
9315 Slog.w(TAG, "Failed parsing daily " + e);
9316 } catch (XmlPullParserException e) {
9317 Slog.w(TAG, "Failed parsing daily " + e);
9318 } catch (IOException e) {
9319 Slog.w(TAG, "Failed parsing daily " + e);
9320 } catch (IndexOutOfBoundsException e) {
9321 Slog.w(TAG, "Failed parsing daily " + e);
9322 }
9323 }
9324
9325 void readDailyItemTagLocked(XmlPullParser parser) throws NumberFormatException,
9326 XmlPullParserException, IOException {
9327 DailyItem dit = new DailyItem();
9328 String attr = parser.getAttributeValue(null, "start");
9329 if (attr != null) {
9330 dit.mStartTime = Long.parseLong(attr);
9331 }
9332 attr = parser.getAttributeValue(null, "end");
9333 if (attr != null) {
9334 dit.mEndTime = Long.parseLong(attr);
9335 }
9336 int outerDepth = parser.getDepth();
9337 int type;
9338 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
9339 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
9340 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
9341 continue;
9342 }
9343
9344 String tagName = parser.getName();
9345 if (tagName.equals("dis")) {
9346 readDailyItemTagDetailsLocked(parser, dit, false, "dis");
9347 } else if (tagName.equals("chg")) {
9348 readDailyItemTagDetailsLocked(parser, dit, true, "chg");
Dianne Hackborn88e98df2015-03-23 13:29:14 -07009349 } else if (tagName.equals("upd")) {
9350 if (dit.mPackageChanges == null) {
9351 dit.mPackageChanges = new ArrayList<>();
9352 }
9353 PackageChange pc = new PackageChange();
9354 pc.mUpdate = true;
9355 pc.mPackageName = parser.getAttributeValue(null, "pkg");
9356 String verStr = parser.getAttributeValue(null, "ver");
9357 pc.mVersionCode = verStr != null ? Integer.parseInt(verStr) : 0;
9358 dit.mPackageChanges.add(pc);
9359 XmlUtils.skipCurrentTag(parser);
9360 } else if (tagName.equals("rem")) {
9361 if (dit.mPackageChanges == null) {
9362 dit.mPackageChanges = new ArrayList<>();
9363 }
9364 PackageChange pc = new PackageChange();
9365 pc.mUpdate = false;
9366 pc.mPackageName = parser.getAttributeValue(null, "pkg");
9367 dit.mPackageChanges.add(pc);
9368 XmlUtils.skipCurrentTag(parser);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009369 } else {
9370 Slog.w(TAG, "Unknown element under <item>: "
9371 + parser.getName());
9372 XmlUtils.skipCurrentTag(parser);
9373 }
9374 }
9375 mDailyItems.add(dit);
9376 }
9377
9378 void readDailyItemTagDetailsLocked(XmlPullParser parser, DailyItem dit, boolean isCharge,
9379 String tag)
9380 throws NumberFormatException, XmlPullParserException, IOException {
9381 final String numAttr = parser.getAttributeValue(null, "n");
9382 if (numAttr == null) {
9383 Slog.w(TAG, "Missing 'n' attribute at " + parser.getPositionDescription());
9384 XmlUtils.skipCurrentTag(parser);
9385 return;
9386 }
9387 final int num = Integer.parseInt(numAttr);
9388 LevelStepTracker steps = new LevelStepTracker(num);
9389 if (isCharge) {
9390 dit.mChargeSteps = steps;
9391 } else {
9392 dit.mDischargeSteps = steps;
9393 }
9394 int i = 0;
9395 int outerDepth = parser.getDepth();
9396 int type;
9397 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
9398 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
9399 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
9400 continue;
9401 }
9402
9403 String tagName = parser.getName();
9404 if ("s".equals(tagName)) {
9405 if (i < num) {
9406 String valueAttr = parser.getAttributeValue(null, "v");
9407 if (valueAttr != null) {
9408 steps.decodeEntryAt(i, valueAttr);
9409 i++;
9410 }
9411 }
9412 } else {
9413 Slog.w(TAG, "Unknown element under <" + tag + ">: "
9414 + parser.getName());
9415 XmlUtils.skipCurrentTag(parser);
9416 }
9417 }
9418 steps.mNumStepDurations = i;
9419 }
9420
9421 @Override
9422 public DailyItem getDailyItemLocked(int daysAgo) {
9423 int index = mDailyItems.size()-1-daysAgo;
9424 return index >= 0 ? mDailyItems.get(index) : null;
9425 }
9426
9427 @Override
9428 public long getCurrentDailyStartTime() {
9429 return mDailyStartTime;
9430 }
9431
9432 @Override
9433 public long getNextMinDailyDeadline() {
9434 return mNextMinDailyDeadline;
9435 }
9436
9437 @Override
9438 public long getNextMaxDailyDeadline() {
9439 return mNextMaxDailyDeadline;
9440 }
9441
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009442 @Override
9443 public boolean startIteratingOldHistoryLocked() {
9444 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
9445 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08009446 if ((mHistoryIterator = mHistory) == null) {
9447 return false;
9448 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009449 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn1fadab52011-04-14 17:57:33 -07009450 mHistoryReadTmp.clear();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009451 mReadOverflow = false;
9452 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08009453 return true;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07009454 }
9455
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009456 @Override
9457 public boolean getNextOldHistoryLocked(HistoryItem out) {
9458 boolean end = mHistoryBuffer.dataPosition() >= mHistoryBuffer.dataSize();
9459 if (!end) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08009460 readHistoryDelta(mHistoryBuffer, mHistoryReadTmp);
Dianne Hackborn1fadab52011-04-14 17:57:33 -07009461 mReadOverflow |= mHistoryReadTmp.cmd == HistoryItem.CMD_OVERFLOW;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009462 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -07009463 HistoryItem cur = mHistoryIterator;
9464 if (cur == null) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009465 if (!mReadOverflow && !end) {
9466 Slog.w(TAG, "Old history ends before new history!");
9467 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -07009468 return false;
9469 }
9470 out.setTo(cur);
9471 mHistoryIterator = cur.next;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009472 if (!mReadOverflow) {
9473 if (end) {
9474 Slog.w(TAG, "New history ends before old history!");
Dianne Hackborn1fadab52011-04-14 17:57:33 -07009475 } else if (!out.same(mHistoryReadTmp)) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07009476 PrintWriter pw = new FastPrintWriter(new LogWriter(android.util.Log.WARN, TAG));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009477 pw.println("Histories differ!");
9478 pw.println("Old history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -07009479 (new HistoryPrinter()).printNextItem(pw, out, 0, false, true);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009480 pw.println("New history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -07009481 (new HistoryPrinter()).printNextItem(pw, mHistoryReadTmp, 0, false,
9482 true);
Dianne Hackborn8c841092013-06-24 13:46:13 -07009483 pw.flush();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009484 }
9485 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -07009486 return true;
9487 }
9488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009489 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009490 public void finishIteratingOldHistoryLocked() {
9491 mIteratingHistory = false;
9492 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08009493 mHistoryIterator = null;
9494 }
9495
9496 public int getHistoryTotalSize() {
9497 return MAX_HISTORY_BUFFER;
9498 }
9499
9500 public int getHistoryUsedSize() {
9501 return mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009502 }
9503
9504 @Override
9505 public boolean startIteratingHistoryLocked() {
9506 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
9507 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08009508 if (mHistoryBuffer.dataSize() <= 0) {
9509 return false;
9510 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009511 mHistoryBuffer.setDataPosition(0);
9512 mReadOverflow = false;
9513 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08009514 mReadHistoryStrings = new String[mHistoryTagPool.size()];
9515 mReadHistoryUids = new int[mHistoryTagPool.size()];
9516 mReadHistoryChars = 0;
9517 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
9518 final HistoryTag tag = ent.getKey();
9519 final int idx = ent.getValue();
9520 mReadHistoryStrings[idx] = tag.string;
9521 mReadHistoryUids[idx] = tag.uid;
9522 mReadHistoryChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -08009523 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08009524 return true;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009525 }
9526
9527 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -08009528 public int getHistoryStringPoolSize() {
9529 return mReadHistoryStrings.length;
9530 }
9531
9532 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08009533 public int getHistoryStringPoolBytes() {
9534 // Each entry is a fixed 12 bytes: 4 for index, 4 for uid, 4 for string size
9535 // Each string character is 2 bytes.
9536 return (mReadHistoryStrings.length * 12) + (mReadHistoryChars * 2);
9537 }
9538
9539 @Override
9540 public String getHistoryTagPoolString(int index) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08009541 return mReadHistoryStrings[index];
9542 }
9543
9544 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08009545 public int getHistoryTagPoolUid(int index) {
9546 return mReadHistoryUids[index];
9547 }
9548
9549 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009550 public boolean getNextHistoryLocked(HistoryItem out) {
Dianne Hackborn1fadab52011-04-14 17:57:33 -07009551 final int pos = mHistoryBuffer.dataPosition();
9552 if (pos == 0) {
9553 out.clear();
9554 }
9555 boolean end = pos >= mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009556 if (end) {
9557 return false;
9558 }
9559
Dianne Hackborn99009ea2014-04-18 16:23:42 -07009560 final long lastRealtime = out.time;
9561 final long lastWalltime = out.currentTime;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08009562 readHistoryDelta(mHistoryBuffer, out);
Dianne Hackborn37de0982014-05-09 09:32:18 -07009563 if (out.cmd != HistoryItem.CMD_CURRENT_TIME
9564 && out.cmd != HistoryItem.CMD_RESET && lastWalltime != 0) {
Dianne Hackborn99009ea2014-04-18 16:23:42 -07009565 out.currentTime = lastWalltime + (out.time - lastRealtime);
9566 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009567 return true;
9568 }
9569
9570 @Override
9571 public void finishIteratingHistoryLocked() {
9572 mIteratingHistory = false;
9573 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn099bc622014-01-22 13:39:16 -08009574 mReadHistoryStrings = null;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009575 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009576
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009577 @Override
Dianne Hackbornb5e31652010-09-07 12:13:55 -07009578 public long getHistoryBaseTime() {
9579 return mHistoryBaseTime;
9580 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009581
Dianne Hackbornb5e31652010-09-07 12:13:55 -07009582 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009583 public int getStartCount() {
9584 return mStartCount;
9585 }
9586
9587 public boolean isOnBattery() {
9588 return mOnBattery;
9589 }
9590
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07009591 public boolean isCharging() {
9592 return mCharging;
9593 }
9594
Mike Mac2f518a2017-09-19 16:06:03 -07009595 public boolean isScreenOn(int state) {
Mike Maa7724752017-10-10 15:29:25 -07009596 return state == Display.STATE_ON || state == Display.STATE_VR;
Mike Mac2f518a2017-09-19 16:06:03 -07009597 }
9598
9599 public boolean isScreenOff(int state) {
9600 return state == Display.STATE_OFF;
9601 }
9602
9603 public boolean isScreenDoze(int state) {
9604 return state == Display.STATE_DOZE || state == Display.STATE_DOZE_SUSPEND;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009605 }
9606
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009607 void initTimes(long uptime, long realtime) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08009608 mStartClockTime = System.currentTimeMillis();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009609 mOnBatteryTimeBase.init(uptime, realtime);
9610 mOnBatteryScreenOffTimeBase.init(uptime, realtime);
Dianne Hackborn4590e522014-03-24 13:36:46 -07009611 mRealtime = 0;
9612 mUptime = 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009613 mRealtimeStart = realtime;
Dianne Hackborn4590e522014-03-24 13:36:46 -07009614 mUptimeStart = uptime;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009615 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009616
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08009617 void initDischarge() {
9618 mLowDischargeAmountSinceCharge = 0;
9619 mHighDischargeAmountSinceCharge = 0;
9620 mDischargeAmountScreenOn = 0;
9621 mDischargeAmountScreenOnSinceCharge = 0;
9622 mDischargeAmountScreenOff = 0;
9623 mDischargeAmountScreenOffSinceCharge = 0;
Mike Mac2f518a2017-09-19 16:06:03 -07009624 mDischargeAmountScreenDoze = 0;
9625 mDischargeAmountScreenDozeSinceCharge = 0;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009626 mDischargeStepTracker.init();
9627 mChargeStepTracker.init();
Adam Lesinski3ee3f632016-06-08 13:55:55 -07009628 mDischargeScreenOffCounter.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -07009629 mDischargeScreenDozeCounter.reset(false);
Adam Lesinski3ee3f632016-06-08 13:55:55 -07009630 mDischargeCounter.reset(false);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08009631 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08009632
9633 public void resetAllStatsCmdLocked() {
9634 resetAllStatsLocked();
Joe Onoratoabded112016-02-08 16:49:39 -08009635 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -07009636 long uptime = mSecUptime * 1000;
Joe Onoratoabded112016-02-08 16:49:39 -08009637 long mSecRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08009638 long realtime = mSecRealtime * 1000;
9639 mDischargeStartLevel = mHistoryCur.batteryLevel;
9640 pullPendingStateUpdatesLocked();
Dianne Hackborn40c87252014-03-19 16:55:40 -07009641 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07009642 mDischargeCurrentLevel = mDischargeUnplugLevel = mDischargePlugLevel
9643 = mCurrentBatteryLevel = mHistoryCur.batteryLevel;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009644 mOnBatteryTimeBase.reset(uptime, realtime);
9645 mOnBatteryScreenOffTimeBase.reset(uptime, realtime);
9646 if ((mHistoryCur.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) == 0) {
Mike Mac2f518a2017-09-19 16:06:03 -07009647 if (isScreenOn(mScreenState)) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08009648 mDischargeScreenOnUnplugLevel = mHistoryCur.batteryLevel;
Mike Mac2f518a2017-09-19 16:06:03 -07009649 mDischargeScreenDozeUnplugLevel = 0;
9650 mDischargeScreenOffUnplugLevel = 0;
9651 } else if (isScreenDoze(mScreenState)) {
9652 mDischargeScreenOnUnplugLevel = 0;
9653 mDischargeScreenDozeUnplugLevel = mHistoryCur.batteryLevel;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08009654 mDischargeScreenOffUnplugLevel = 0;
9655 } else {
9656 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -07009657 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08009658 mDischargeScreenOffUnplugLevel = mHistoryCur.batteryLevel;
9659 }
9660 mDischargeAmountScreenOn = 0;
9661 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -07009662 mDischargeAmountScreenDoze = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08009663 }
Dianne Hackborn40c87252014-03-19 16:55:40 -07009664 initActiveHistoryEventsLocked(mSecRealtime, mSecUptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08009665 }
9666
9667 private void resetAllStatsLocked() {
Adam Lesinski8ce36942016-05-26 16:05:35 -07009668 final long uptimeMillis = mClocks.uptimeMillis();
9669 final long elapsedRealtimeMillis = mClocks.elapsedRealtime();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009670 mStartCount = 0;
Adam Lesinski8ce36942016-05-26 16:05:35 -07009671 initTimes(uptimeMillis * 1000, elapsedRealtimeMillis * 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009672 mScreenOnTimer.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -07009673 mScreenDozeTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009674 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009675 mScreenBrightnessTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009676 }
Adam Lesinski1a76a622016-06-22 10:28:47 -07009677
9678 if (mPowerProfile != null) {
9679 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
9680 } else {
9681 mEstimatedBatteryCapacity = -1;
9682 }
Jocelyn Dangc627d102017-04-14 13:15:14 -07009683 mMinLearnedBatteryCapacity = -1;
9684 mMaxLearnedBatteryCapacity = -1;
Jeff Browne95c3cd2014-05-02 16:59:26 -07009685 mInteractiveTimer.reset(false);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07009686 mPowerSaveModeEnabledTimer.reset(false);
Adam Lesinski8ce36942016-05-26 16:05:35 -07009687 mLastIdleTimeStart = elapsedRealtimeMillis;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07009688 mLongestLightIdleTime = 0;
9689 mLongestFullIdleTime = 0;
9690 mDeviceIdleModeLightTimer.reset(false);
9691 mDeviceIdleModeFullTimer.reset(false);
9692 mDeviceLightIdlingTimer.reset(false);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07009693 mDeviceIdlingTimer.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009694 mPhoneOnTimer.reset(false);
9695 mAudioOnTimer.reset(false);
9696 mVideoOnTimer.reset(false);
Dianne Hackbornabc7c492014-06-30 16:57:46 -07009697 mFlashlightOnTimer.reset(false);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07009698 mCameraOnTimer.reset(false);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08009699 mBluetoothScanTimer.reset(false);
Wink Saville52840902011-02-18 12:40:47 -08009700 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009701 mPhoneSignalStrengthsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009702 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009703 mPhoneSignalScanningTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009704 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009705 mPhoneDataConnectionsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009706 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07009707 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08009708 mNetworkByteActivityCounters[i].reset(false);
9709 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07009710 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009711 mMobileRadioActiveTimer.reset(false);
9712 mMobileRadioActivePerAppTimer.reset(false);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07009713 mMobileRadioActiveAdjustedTime.reset(false);
Dianne Hackbornd45665b2014-02-26 12:35:32 -08009714 mMobileRadioActiveUnknownTime.reset(false);
9715 mMobileRadioActiveUnknownCount.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009716 mWifiOnTimer.reset(false);
9717 mGlobalWifiRunningTimer.reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08009718 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009719 mWifiStateTimer[i].reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08009720 }
Dianne Hackborn3251b902014-06-20 14:40:53 -07009721 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
9722 mWifiSupplStateTimer[i].reset(false);
9723 }
9724 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
9725 mWifiSignalStrengthsTimer[i].reset(false);
9726 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009727 mWifiActivity.reset(false);
9728 mBluetoothActivity.reset(false);
9729 mModemActivity.reset(false);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009730 mNumConnectivityChange = mLoadedNumConnectivityChange = mUnpluggedNumConnectivityChange = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009731
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009732 for (int i=0; i<mUidStats.size(); i++) {
Bookatz993a0be2017-07-21 09:03:23 -07009733 if (mUidStats.valueAt(i).reset(uptimeMillis * 1000, elapsedRealtimeMillis * 1000)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009734 mUidStats.remove(mUidStats.keyAt(i));
9735 i--;
9736 }
9737 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009738
Bookatz50df7112017-08-04 14:53:26 -07009739 if (mRpmStats.size() > 0) {
9740 for (SamplingTimer timer : mRpmStats.values()) {
9741 mOnBatteryTimeBase.remove(timer);
9742 }
9743 mRpmStats.clear();
9744 }
9745 if (mScreenOffRpmStats.size() > 0) {
9746 for (SamplingTimer timer : mScreenOffRpmStats.values()) {
9747 mOnBatteryScreenOffTimeBase.remove(timer);
9748 }
9749 mScreenOffRpmStats.clear();
9750 }
9751
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009752 if (mKernelWakelockStats.size() > 0) {
9753 for (SamplingTimer timer : mKernelWakelockStats.values()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009754 mOnBatteryScreenOffTimeBase.remove(timer);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009755 }
9756 mKernelWakelockStats.clear();
9757 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07009758
James Carr3a226052016-07-01 14:49:52 -07009759 if (mKernelMemoryStats.size() > 0) {
9760 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
9761 mOnBatteryTimeBase.remove(mKernelMemoryStats.valueAt(i));
9762 }
9763 mKernelMemoryStats.clear();
9764 }
9765
Dianne Hackborna1bd7922014-03-21 11:07:11 -07009766 if (mWakeupReasonStats.size() > 0) {
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07009767 for (SamplingTimer timer : mWakeupReasonStats.values()) {
9768 mOnBatteryTimeBase.remove(timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07009769 }
9770 mWakeupReasonStats.clear();
9771 }
9772
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08009773 mLastHistoryStepDetails = null;
9774 mLastStepCpuUserTime = mLastStepCpuSystemTime = 0;
9775 mCurStepCpuUserTime = mCurStepCpuSystemTime = 0;
9776 mLastStepCpuUserTime = mCurStepCpuUserTime = 0;
9777 mLastStepCpuSystemTime = mCurStepCpuSystemTime = 0;
9778 mLastStepStatUserTime = mCurStepStatUserTime = 0;
9779 mLastStepStatSystemTime = mCurStepStatSystemTime = 0;
9780 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime = 0;
9781 mLastStepStatIrqTime = mCurStepStatIrqTime = 0;
9782 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime = 0;
9783 mLastStepStatIdleTime = mCurStepStatIdleTime = 0;
9784
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08009785 initDischarge();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009786
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009787 clearHistoryLocked();
9788 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009789
Dianne Hackborn40c87252014-03-19 16:55:40 -07009790 private void initActiveHistoryEventsLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08009791 for (int i=0; i<HistoryItem.EVENT_COUNT; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07009792 if (!mRecordAllHistory && i == HistoryItem.EVENT_PROC) {
9793 // Not recording process starts/stops.
9794 continue;
9795 }
Dianne Hackborn37de0982014-05-09 09:32:18 -07009796 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(i);
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08009797 if (active == null) {
9798 continue;
9799 }
Dianne Hackborn37de0982014-05-09 09:32:18 -07009800 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
9801 SparseIntArray uids = ent.getValue();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08009802 for (int j=0; j<uids.size(); j++) {
Dianne Hackborn37de0982014-05-09 09:32:18 -07009803 addHistoryEventLocked(elapsedRealtimeMs, uptimeMs, i, ent.getKey(),
9804 uids.keyAt(j));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08009805 }
9806 }
9807 }
9808 }
9809
Mike Mac2f518a2017-09-19 16:06:03 -07009810 void updateDischargeScreenLevelsLocked(int oldState, int newState) {
9811 updateOldDischargeScreenLevelLocked(oldState);
9812 updateNewDischargeScreenLevelLocked(newState);
9813 }
9814
9815 private void updateOldDischargeScreenLevelLocked(int state) {
9816 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08009817 int diff = mDischargeScreenOnUnplugLevel - mDischargeCurrentLevel;
9818 if (diff > 0) {
9819 mDischargeAmountScreenOn += diff;
9820 mDischargeAmountScreenOnSinceCharge += diff;
9821 }
Mike Mac2f518a2017-09-19 16:06:03 -07009822 } else if (isScreenDoze(state)) {
9823 int diff = mDischargeScreenDozeUnplugLevel - mDischargeCurrentLevel;
9824 if (diff > 0) {
9825 mDischargeAmountScreenDoze += diff;
9826 mDischargeAmountScreenDozeSinceCharge += diff;
9827 }
9828 } else if (isScreenOff(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08009829 int diff = mDischargeScreenOffUnplugLevel - mDischargeCurrentLevel;
9830 if (diff > 0) {
9831 mDischargeAmountScreenOff += diff;
9832 mDischargeAmountScreenOffSinceCharge += diff;
9833 }
9834 }
Mike Mac2f518a2017-09-19 16:06:03 -07009835 }
9836
9837 private void updateNewDischargeScreenLevelLocked(int state) {
9838 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08009839 mDischargeScreenOnUnplugLevel = mDischargeCurrentLevel;
9840 mDischargeScreenOffUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -07009841 mDischargeScreenDozeUnplugLevel = 0;
9842 } else if (isScreenDoze(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08009843 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -07009844 mDischargeScreenDozeUnplugLevel = mDischargeCurrentLevel;
9845 mDischargeScreenOffUnplugLevel = 0;
9846 } else if (isScreenOff(state)) {
9847 mDischargeScreenOnUnplugLevel = 0;
9848 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08009849 mDischargeScreenOffUnplugLevel = mDischargeCurrentLevel;
9850 }
9851 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009852
Dianne Hackborna7c837f2014-01-15 16:20:44 -08009853 public void pullPendingStateUpdatesLocked() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08009854 if (mOnBatteryInternal) {
Mike Mac2f518a2017-09-19 16:06:03 -07009855 updateDischargeScreenLevelsLocked(mScreenState, mScreenState);
Dianne Hackborn77b987f2014-02-26 16:20:52 -08009856 }
Dianne Hackborna7c837f2014-01-15 16:20:44 -08009857 }
9858
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009859 private final NetworkStatsFactory mNetworkStatsFactory = new NetworkStatsFactory();
9860 private final Pools.Pool<NetworkStats> mNetworkStatsPool = new Pools.SynchronizedPool<>(6);
9861
9862 private final Object mWifiNetworkLock = new Object();
9863
9864 @GuardedBy("mWifiNetworkLock")
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009865 private String[] mWifiIfaces = EmptyArray.STRING;
9866
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009867 @GuardedBy("mWifiNetworkLock")
9868 private NetworkStats mLastWifiNetworkStats = new NetworkStats(0, -1);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009869
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009870 private final Object mModemNetworkLock = new Object();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009871
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009872 @GuardedBy("mModemNetworkLock")
9873 private String[] mModemIfaces = EmptyArray.STRING;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009874
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009875 @GuardedBy("mModemNetworkLock")
9876 private NetworkStats mLastModemNetworkStats = new NetworkStats(0, -1);
9877
9878 private NetworkStats readNetworkStatsLocked(String[] ifaces) {
9879 try {
9880 if (!ArrayUtils.isEmpty(ifaces)) {
9881 return mNetworkStatsFactory.readNetworkStatsDetail(NetworkStats.UID_ALL, ifaces,
9882 NetworkStats.TAG_NONE, mNetworkStatsPool.acquire());
9883 }
9884 } catch (IOException e) {
9885 Slog.e(TAG, "failed to read network stats for ifaces: " + Arrays.toString(ifaces));
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009886 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009887 return null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009888 }
9889
9890 /**
9891 * Distribute WiFi energy info and network traffic to apps.
9892 * @param info The energy information from the WiFi controller.
9893 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009894 public void updateWifiState(@Nullable final WifiActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -07009895 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009896 Slog.d(TAG, "Updating wifi stats: " + Arrays.toString(mWifiIfaces));
Adam Lesinskia7c90c82015-06-18 14:52:24 -07009897 }
9898
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009899 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -07009900 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009901 synchronized (mWifiNetworkLock) {
9902 final NetworkStats latestStats = readNetworkStatsLocked(mWifiIfaces);
9903 if (latestStats != null) {
9904 delta = NetworkStats.subtract(latestStats, mLastWifiNetworkStats, null, null,
9905 mNetworkStatsPool.acquire());
9906 mNetworkStatsPool.release(mLastWifiNetworkStats);
9907 mLastWifiNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -07009908 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009909 }
9910
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009911 synchronized (this) {
9912 if (!mOnBatteryInternal) {
9913 if (delta != null) {
9914 mNetworkStatsPool.release(delta);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009915 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009916 return;
9917 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009918
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009919 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
9920 SparseLongArray rxPackets = new SparseLongArray();
9921 SparseLongArray txPackets = new SparseLongArray();
9922 long totalTxPackets = 0;
9923 long totalRxPackets = 0;
9924 if (delta != null) {
9925 NetworkStats.Entry entry = new NetworkStats.Entry();
9926 final int size = delta.size();
9927 for (int i = 0; i < size; i++) {
9928 entry = delta.getValues(i, entry);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009929
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009930 if (DEBUG_ENERGY) {
9931 Slog.d(TAG, "Wifi uid " + entry.uid + ": delta rx=" + entry.rxBytes
9932 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
9933 + " txPackets=" + entry.txPackets);
9934 }
9935
9936 if (entry.rxBytes == 0 && entry.txBytes == 0) {
9937 // Skip the lookup below since there is no work to do.
9938 continue;
9939 }
9940
9941 final Uid u = getUidStatsLocked(mapUid(entry.uid));
9942 if (entry.rxBytes != 0) {
9943 u.noteNetworkActivityLocked(NETWORK_WIFI_RX_DATA, entry.rxBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -08009944 entry.rxPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009945 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
9946 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_RX_DATA, entry.rxBytes,
9947 entry.rxPackets);
9948 }
9949 mNetworkByteActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
9950 entry.rxBytes);
9951 mNetworkPacketActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
9952 entry.rxPackets);
9953
9954 rxPackets.put(u.getUid(), entry.rxPackets);
9955
9956 // Sum the total number of packets so that the Rx Power can
9957 // be evenly distributed amongst the apps.
9958 totalRxPackets += entry.rxPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -08009959 }
Adam Lesinskie08af192015-03-25 16:42:59 -07009960
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009961 if (entry.txBytes != 0) {
9962 u.noteNetworkActivityLocked(NETWORK_WIFI_TX_DATA, entry.txBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -08009963 entry.txPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009964 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
9965 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_TX_DATA, entry.txBytes,
9966 entry.txPackets);
9967 }
9968 mNetworkByteActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
9969 entry.txBytes);
9970 mNetworkPacketActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
9971 entry.txPackets);
9972
9973 txPackets.put(u.getUid(), entry.txPackets);
9974
9975 // Sum the total number of packets so that the Tx Power can
9976 // be evenly distributed amongst the apps.
9977 totalTxPackets += entry.txPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -08009978 }
Adam Lesinskiba88e682015-12-08 12:06:55 -08009979 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009980 mNetworkStatsPool.release(delta);
9981 delta = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07009982 }
9983
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009984 if (info != null) {
9985 mHasWifiReporting = true;
Adam Lesinskie08af192015-03-25 16:42:59 -07009986
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009987 // Measured in mAms
9988 final long txTimeMs = info.getControllerTxTimeMillis();
9989 final long rxTimeMs = info.getControllerRxTimeMillis();
9990 final long idleTimeMs = info.getControllerIdleTimeMillis();
9991 final long totalTimeMs = txTimeMs + rxTimeMs + idleTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -07009992
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009993 long leftOverRxTimeMs = rxTimeMs;
9994 long leftOverTxTimeMs = txTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -07009995
Adam Lesinskie08af192015-03-25 16:42:59 -07009996 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009997 Slog.d(TAG, "------ BEGIN WiFi power blaming ------");
9998 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
9999 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
10000 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
10001 Slog.d(TAG, " Total Time: " + totalTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070010002 }
Adam Lesinskie08af192015-03-25 16:42:59 -070010003
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010004 long totalWifiLockTimeMs = 0;
10005 long totalScanTimeMs = 0;
10006
10007 // On the first pass, collect some totals so that we can normalize power
10008 // calculations if we need to.
10009 final int uidStatsSize = mUidStats.size();
10010 for (int i = 0; i < uidStatsSize; i++) {
10011 final Uid uid = mUidStats.valueAt(i);
10012
10013 // Sum the total scan power for all apps.
10014 totalScanTimeMs += uid.mWifiScanTimer.getTimeSinceMarkLocked(
10015 elapsedRealtimeMs * 1000) / 1000;
10016
10017 // Sum the total time holding wifi lock for all apps.
10018 totalWifiLockTimeMs += uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
10019 elapsedRealtimeMs * 1000) / 1000;
10020 }
10021
10022 if (DEBUG_ENERGY && totalScanTimeMs > rxTimeMs) {
10023 Slog.d(TAG,
10024 " !Estimated scan time > Actual rx time (" + totalScanTimeMs + " ms > "
10025 + rxTimeMs + " ms). Normalizing scan time.");
10026 }
10027 if (DEBUG_ENERGY && totalScanTimeMs > txTimeMs) {
10028 Slog.d(TAG,
10029 " !Estimated scan time > Actual tx time (" + totalScanTimeMs + " ms > "
10030 + txTimeMs + " ms). Normalizing scan time.");
10031 }
10032
10033 // Actually assign and distribute power usage to apps.
10034 for (int i = 0; i < uidStatsSize; i++) {
10035 final Uid uid = mUidStats.valueAt(i);
10036
10037 long scanTimeSinceMarkMs = uid.mWifiScanTimer.getTimeSinceMarkLocked(
10038 elapsedRealtimeMs * 1000) / 1000;
10039 if (scanTimeSinceMarkMs > 0) {
10040 // Set the new mark so that next time we get new data since this point.
10041 uid.mWifiScanTimer.setMark(elapsedRealtimeMs);
10042
10043 long scanRxTimeSinceMarkMs = scanTimeSinceMarkMs;
10044 long scanTxTimeSinceMarkMs = scanTimeSinceMarkMs;
10045
10046 // Our total scan time is more than the reported Tx/Rx time.
10047 // This is possible because the cost of a scan is approximate.
10048 // Let's normalize the result so that we evenly blame each app
10049 // scanning.
10050 //
10051 // This means that we may have apps that transmitted/received packets not be
10052 // blamed for this, but this is fine as scans are relatively more expensive.
10053 if (totalScanTimeMs > rxTimeMs) {
10054 scanRxTimeSinceMarkMs = (rxTimeMs * scanRxTimeSinceMarkMs) /
10055 totalScanTimeMs;
10056 }
10057 if (totalScanTimeMs > txTimeMs) {
10058 scanTxTimeSinceMarkMs = (txTimeMs * scanTxTimeSinceMarkMs) /
10059 totalScanTimeMs;
10060 }
10061
10062 if (DEBUG_ENERGY) {
10063 Slog.d(TAG, " ScanTime for UID " + uid.getUid() + ": Rx:"
10064 + scanRxTimeSinceMarkMs + " ms Tx:"
10065 + scanTxTimeSinceMarkMs + " ms)");
10066 }
10067
10068 ControllerActivityCounterImpl activityCounter =
10069 uid.getOrCreateWifiControllerActivityLocked();
10070 activityCounter.getRxTimeCounter().addCountLocked(scanRxTimeSinceMarkMs);
10071 activityCounter.getTxTimeCounters()[0].addCountLocked(
10072 scanTxTimeSinceMarkMs);
10073 leftOverRxTimeMs -= scanRxTimeSinceMarkMs;
10074 leftOverTxTimeMs -= scanTxTimeSinceMarkMs;
10075 }
10076
10077 // Distribute evenly the power consumed while Idle to each app holding a WiFi
10078 // lock.
10079 final long wifiLockTimeSinceMarkMs =
10080 uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
10081 elapsedRealtimeMs * 1000) / 1000;
10082 if (wifiLockTimeSinceMarkMs > 0) {
10083 // Set the new mark so that next time we get new data since this point.
10084 uid.mFullWifiLockTimer.setMark(elapsedRealtimeMs);
10085
10086 final long myIdleTimeMs = (wifiLockTimeSinceMarkMs * idleTimeMs)
10087 / totalWifiLockTimeMs;
10088 if (DEBUG_ENERGY) {
10089 Slog.d(TAG, " IdleTime for UID " + uid.getUid() + ": "
10090 + myIdleTimeMs + " ms");
10091 }
10092 uid.getOrCreateWifiControllerActivityLocked().getIdleTimeCounter()
10093 .addCountLocked(myIdleTimeMs);
10094 }
10095 }
10096
Adam Lesinskie08af192015-03-25 16:42:59 -070010097 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010098 Slog.d(TAG, " New RxPower: " + leftOverRxTimeMs + " ms");
10099 Slog.d(TAG, " New TxPower: " + leftOverTxTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070010100 }
Adam Lesinskie08af192015-03-25 16:42:59 -070010101
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010102 // Distribute the remaining Tx power appropriately between all apps that transmitted
10103 // packets.
10104 for (int i = 0; i < txPackets.size(); i++) {
10105 final Uid uid = getUidStatsLocked(txPackets.keyAt(i));
10106 final long myTxTimeMs = (txPackets.valueAt(i) * leftOverTxTimeMs)
10107 / totalTxPackets;
10108 if (DEBUG_ENERGY) {
10109 Slog.d(TAG, " TxTime for UID " + uid.getUid() + ": " + myTxTimeMs + " ms");
10110 }
10111 uid.getOrCreateWifiControllerActivityLocked().getTxTimeCounters()[0]
10112 .addCountLocked(myTxTimeMs);
10113 }
Adam Lesinskie08af192015-03-25 16:42:59 -070010114
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010115 // Distribute the remaining Rx power appropriately between all apps that received
10116 // packets.
10117 for (int i = 0; i < rxPackets.size(); i++) {
10118 final Uid uid = getUidStatsLocked(rxPackets.keyAt(i));
10119 final long myRxTimeMs = (rxPackets.valueAt(i) * leftOverRxTimeMs)
10120 / totalRxPackets;
10121 if (DEBUG_ENERGY) {
10122 Slog.d(TAG, " RxTime for UID " + uid.getUid() + ": " + myRxTimeMs + " ms");
10123 }
10124 uid.getOrCreateWifiControllerActivityLocked().getRxTimeCounter()
10125 .addCountLocked(myRxTimeMs);
10126 }
Adam Lesinskie08af192015-03-25 16:42:59 -070010127
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010128 // Any left over power use will be picked up by the WiFi category in BatteryStatsHelper.
10129
10130
10131 // Update WiFi controller stats.
10132 mWifiActivity.getRxTimeCounter().addCountLocked(info.getControllerRxTimeMillis());
10133 mWifiActivity.getTxTimeCounters()[0].addCountLocked(
10134 info.getControllerTxTimeMillis());
10135 mWifiActivity.getIdleTimeCounter().addCountLocked(
10136 info.getControllerIdleTimeMillis());
10137
10138 // POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
10139 final double opVolt = mPowerProfile.getAveragePower(
10140 PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
10141 if (opVolt != 0) {
10142 // We store the power drain as mAms.
10143 mWifiActivity.getPowerCounter().addCountLocked(
10144 (long) (info.getControllerEnergyUsed() / opVolt));
10145 }
Adam Lesinskie08af192015-03-25 16:42:59 -070010146 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010147 }
10148 }
10149
10150 /**
10151 * Distribute Cell radio energy info and network traffic to apps.
10152 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010153 public void updateMobileRadioState(@Nullable final ModemActivityInfo activityInfo) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010154 if (DEBUG_ENERGY) {
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010155 Slog.d(TAG, "Updating mobile radio stats with " + activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010156 }
10157
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010158 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070010159 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010160 synchronized (mModemNetworkLock) {
10161 final NetworkStats latestStats = readNetworkStatsLocked(mModemIfaces);
10162 if (latestStats != null) {
10163 delta = NetworkStats.subtract(latestStats, mLastModemNetworkStats, null, null,
10164 mNetworkStatsPool.acquire());
10165 mNetworkStatsPool.release(mLastModemNetworkStats);
10166 mLastModemNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070010167 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010168 }
10169
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010170 synchronized (this) {
10171 if (!mOnBatteryInternal) {
10172 if (delta != null) {
10173 mNetworkStatsPool.release(delta);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010174 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010175 return;
Adam Lesinskie08af192015-03-25 16:42:59 -070010176 }
10177
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070010178 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010179 long radioTime = mMobileRadioActivePerAppTimer.getTimeSinceMarkLocked(
10180 elapsedRealtimeMs * 1000);
10181 mMobileRadioActivePerAppTimer.setMark(elapsedRealtimeMs);
10182
10183 long totalRxPackets = 0;
10184 long totalTxPackets = 0;
10185 if (delta != null) {
10186 NetworkStats.Entry entry = new NetworkStats.Entry();
10187 final int size = delta.size();
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010188 for (int i = 0; i < size; i++) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010189 entry = delta.getValues(i, entry);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010190 if (entry.rxPackets == 0 && entry.txPackets == 0) {
10191 continue;
10192 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010193
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010194 if (DEBUG_ENERGY) {
10195 Slog.d(TAG, "Mobile uid " + entry.uid + ": delta rx=" + entry.rxBytes
10196 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
10197 + " txPackets=" + entry.txPackets);
10198 }
10199
10200 totalRxPackets += entry.rxPackets;
10201 totalTxPackets += entry.txPackets;
10202
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010203 final Uid u = getUidStatsLocked(mapUid(entry.uid));
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010204 u.noteNetworkActivityLocked(NETWORK_MOBILE_RX_DATA, entry.rxBytes,
10205 entry.rxPackets);
10206 u.noteNetworkActivityLocked(NETWORK_MOBILE_TX_DATA, entry.txBytes,
10207 entry.txPackets);
10208 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
10209 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_RX_DATA,
10210 entry.rxBytes, entry.rxPackets);
10211 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_TX_DATA,
10212 entry.txBytes, entry.txPackets);
10213 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010214
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010215 mNetworkByteActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
10216 entry.rxBytes);
10217 mNetworkByteActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
10218 entry.txBytes);
10219 mNetworkPacketActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
10220 entry.rxPackets);
10221 mNetworkPacketActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
10222 entry.txPackets);
10223 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010224
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010225 // Now distribute proportional blame to the apps that did networking.
10226 long totalPackets = totalRxPackets + totalTxPackets;
10227 if (totalPackets > 0) {
10228 for (int i = 0; i < size; i++) {
10229 entry = delta.getValues(i, entry);
10230 if (entry.rxPackets == 0 && entry.txPackets == 0) {
10231 continue;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010232 }
10233
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010234 final Uid u = getUidStatsLocked(mapUid(entry.uid));
10235
10236 // Distribute total radio active time in to this app.
10237 final long appPackets = entry.rxPackets + entry.txPackets;
10238 final long appRadioTime = (radioTime * appPackets) / totalPackets;
10239 u.noteMobileRadioActiveTimeLocked(appRadioTime);
10240
10241 // Remove this app from the totals, so that we don't lose any time
10242 // due to rounding.
10243 radioTime -= appRadioTime;
10244 totalPackets -= appPackets;
10245
10246 if (activityInfo != null) {
10247 ControllerActivityCounterImpl activityCounter =
10248 u.getOrCreateModemControllerActivityLocked();
10249 if (totalRxPackets > 0 && entry.rxPackets > 0) {
10250 final long rxMs = (entry.rxPackets * activityInfo.getRxTimeMillis())
10251 / totalRxPackets;
10252 activityCounter.getRxTimeCounter().addCountLocked(rxMs);
10253 }
10254
10255 if (totalTxPackets > 0 && entry.txPackets > 0) {
10256 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
10257 long txMs =
10258 entry.txPackets * activityInfo.getTxTimeMillis()[lvl];
10259 txMs /= totalTxPackets;
10260 activityCounter.getTxTimeCounters()[lvl].addCountLocked(txMs);
10261 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010262 }
10263 }
10264 }
10265 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010266
10267 if (radioTime > 0) {
10268 // Whoops, there is some radio time we can't blame on an app!
10269 mMobileRadioActiveUnknownTime.addCountLocked(radioTime);
10270 mMobileRadioActiveUnknownCount.addCountLocked(1);
10271 }
10272
10273 mNetworkStatsPool.release(delta);
10274 delta = null;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010275 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010276
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010277 if (activityInfo != null) {
10278 mHasModemReporting = true;
10279 mModemActivity.getIdleTimeCounter().addCountLocked(
10280 activityInfo.getIdleTimeMillis());
10281 mModemActivity.getRxTimeCounter().addCountLocked(activityInfo.getRxTimeMillis());
10282 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
10283 mModemActivity.getTxTimeCounters()[lvl]
10284 .addCountLocked(activityInfo.getTxTimeMillis()[lvl]);
10285 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010286
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010287 // POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
10288 final double opVolt = mPowerProfile.getAveragePower(
10289 PowerProfile.POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
10290 if (opVolt != 0) {
10291 // We store the power drain as mAms.
10292 mModemActivity.getPowerCounter().addCountLocked(
10293 (long) (activityInfo.getEnergyUsed() / opVolt));
10294 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010295 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010296 }
10297 }
10298
10299 /**
10300 * Distribute Bluetooth energy info and network traffic to apps.
10301 * @param info The energy information from the bluetooth controller.
10302 */
10303 public void updateBluetoothStateLocked(@Nullable final BluetoothActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010304 if (DEBUG_ENERGY) {
Adam Lesinski50e47602015-12-04 17:04:54 -080010305 Slog.d(TAG, "Updating bluetooth stats: " + info);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010306 }
10307
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010308 if (info == null || !mOnBatteryInternal) {
10309 return;
10310 }
Adam Lesinskie283d332015-04-16 12:29:25 -070010311
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010312 mHasBluetoothReporting = true;
10313
Bookatz867c0d72017-03-07 18:23:42 -080010314 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010315 final long rxTimeMs = info.getControllerRxTimeMillis();
10316 final long txTimeMs = info.getControllerTxTimeMillis();
10317
10318 if (DEBUG_ENERGY) {
10319 Slog.d(TAG, "------ BEGIN BLE power blaming ------");
10320 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
10321 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
10322 Slog.d(TAG, " Idle Time: " + info.getControllerIdleTimeMillis() + " ms");
10323 }
10324
10325 long totalScanTimeMs = 0;
10326
10327 final int uidCount = mUidStats.size();
10328 for (int i = 0; i < uidCount; i++) {
10329 final Uid u = mUidStats.valueAt(i);
10330 if (u.mBluetoothScanTimer == null) {
10331 continue;
Adam Lesinskie283d332015-04-16 12:29:25 -070010332 }
Adam Lesinski50e47602015-12-04 17:04:54 -080010333
Bookatzaa4594a2017-03-24 12:39:56 -070010334 totalScanTimeMs += u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010335 elapsedRealtimeMs * 1000) / 1000;
10336 }
10337
10338 final boolean normalizeScanRxTime = (totalScanTimeMs > rxTimeMs);
10339 final boolean normalizeScanTxTime = (totalScanTimeMs > txTimeMs);
10340
10341 if (DEBUG_ENERGY) {
10342 Slog.d(TAG, "Normalizing scan power for RX=" + normalizeScanRxTime
10343 + " TX=" + normalizeScanTxTime);
10344 }
10345
10346 long leftOverRxTimeMs = rxTimeMs;
10347 long leftOverTxTimeMs = txTimeMs;
10348
10349 for (int i = 0; i < uidCount; i++) {
10350 final Uid u = mUidStats.valueAt(i);
10351 if (u.mBluetoothScanTimer == null) {
10352 continue;
10353 }
10354
Bookatzaa4594a2017-03-24 12:39:56 -070010355 long scanTimeSinceMarkMs = u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010356 elapsedRealtimeMs * 1000) / 1000;
10357 if (scanTimeSinceMarkMs > 0) {
10358 // Set the new mark so that next time we get new data since this point.
10359 u.mBluetoothScanTimer.setMark(elapsedRealtimeMs);
10360
10361 long scanTimeRxSinceMarkMs = scanTimeSinceMarkMs;
10362 long scanTimeTxSinceMarkMs = scanTimeSinceMarkMs;
10363
10364 if (normalizeScanRxTime) {
10365 // Scan time is longer than the total rx time in the controller,
10366 // so distribute the scan time proportionately. This means regular traffic
10367 // will not blamed, but scans are more expensive anyways.
10368 scanTimeRxSinceMarkMs = (rxTimeMs * scanTimeRxSinceMarkMs) / totalScanTimeMs;
10369 }
10370
10371 if (normalizeScanTxTime) {
10372 // Scan time is longer than the total tx time in the controller,
10373 // so distribute the scan time proportionately. This means regular traffic
10374 // will not blamed, but scans are more expensive anyways.
10375 scanTimeTxSinceMarkMs = (txTimeMs * scanTimeTxSinceMarkMs) / totalScanTimeMs;
10376 }
10377
10378 final ControllerActivityCounterImpl counter =
10379 u.getOrCreateBluetoothControllerActivityLocked();
10380 counter.getRxTimeCounter().addCountLocked(scanTimeRxSinceMarkMs);
10381 counter.getTxTimeCounters()[0].addCountLocked(scanTimeTxSinceMarkMs);
10382
10383 leftOverRxTimeMs -= scanTimeRxSinceMarkMs;
10384 leftOverTxTimeMs -= scanTimeTxSinceMarkMs;
10385 }
10386 }
10387
10388 if (DEBUG_ENERGY) {
10389 Slog.d(TAG, "Left over time for traffic RX=" + leftOverRxTimeMs
10390 + " TX=" + leftOverTxTimeMs);
10391 }
10392
10393 //
10394 // Now distribute blame to apps that did bluetooth traffic.
10395 //
10396
10397 long totalTxBytes = 0;
10398 long totalRxBytes = 0;
10399
10400 final UidTraffic[] uidTraffic = info.getUidTraffic();
10401 final int numUids = uidTraffic != null ? uidTraffic.length : 0;
10402 for (int i = 0; i < numUids; i++) {
10403 final UidTraffic traffic = uidTraffic[i];
10404
10405 // Add to the global counters.
10406 mNetworkByteActivityCounters[NETWORK_BT_RX_DATA].addCountLocked(
10407 traffic.getRxBytes());
10408 mNetworkByteActivityCounters[NETWORK_BT_TX_DATA].addCountLocked(
10409 traffic.getTxBytes());
10410
10411 // Add to the UID counters.
10412 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
10413 u.noteNetworkActivityLocked(NETWORK_BT_RX_DATA, traffic.getRxBytes(), 0);
10414 u.noteNetworkActivityLocked(NETWORK_BT_TX_DATA, traffic.getTxBytes(), 0);
10415
10416 // Calculate the total traffic.
10417 totalTxBytes += traffic.getTxBytes();
10418 totalRxBytes += traffic.getRxBytes();
10419 }
10420
10421 if ((totalTxBytes != 0 || totalRxBytes != 0) &&
10422 (leftOverRxTimeMs != 0 || leftOverTxTimeMs != 0)) {
Adam Lesinski50e47602015-12-04 17:04:54 -080010423 for (int i = 0; i < numUids; i++) {
10424 final UidTraffic traffic = uidTraffic[i];
10425
Adam Lesinski50e47602015-12-04 17:04:54 -080010426 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010427 final ControllerActivityCounterImpl counter =
10428 u.getOrCreateBluetoothControllerActivityLocked();
10429
10430 if (totalRxBytes > 0 && traffic.getRxBytes() > 0) {
10431 final long timeRxMs = (leftOverRxTimeMs * traffic.getRxBytes()) / totalRxBytes;
10432
10433 if (DEBUG_ENERGY) {
10434 Slog.d(TAG, "UID=" + traffic.getUid() + " rx_bytes=" + traffic.getRxBytes()
10435 + " rx_time=" + timeRxMs);
10436 }
10437 counter.getRxTimeCounter().addCountLocked(timeRxMs);
10438 leftOverRxTimeMs -= timeRxMs;
10439 }
10440
10441 if (totalTxBytes > 0 && traffic.getTxBytes() > 0) {
10442 final long timeTxMs = (leftOverTxTimeMs * traffic.getTxBytes()) / totalTxBytes;
10443
10444 if (DEBUG_ENERGY) {
10445 Slog.d(TAG, "UID=" + traffic.getUid() + " tx_bytes=" + traffic.getTxBytes()
10446 + " tx_time=" + timeTxMs);
10447 }
10448
10449 counter.getTxTimeCounters()[0].addCountLocked(timeTxMs);
10450 leftOverTxTimeMs -= timeTxMs;
10451 }
Adam Lesinski50e47602015-12-04 17:04:54 -080010452 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010453 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010454
10455 mBluetoothActivity.getRxTimeCounter().addCountLocked(
10456 info.getControllerRxTimeMillis());
10457 mBluetoothActivity.getTxTimeCounters()[0].addCountLocked(
10458 info.getControllerTxTimeMillis());
10459 mBluetoothActivity.getIdleTimeCounter().addCountLocked(
10460 info.getControllerIdleTimeMillis());
10461
10462 // POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
10463 final double opVolt = mPowerProfile.getAveragePower(
10464 PowerProfile.POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
10465 if (opVolt != 0) {
10466 // We store the power drain as mAms.
10467 mBluetoothActivity.getPowerCounter().addCountLocked(
10468 (long) (info.getControllerEnergyUsed() / opVolt));
10469 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010470 }
10471
10472 /**
Bookatz0b8a0502017-09-13 11:51:52 -070010473 * Read and record Resource Power Manager (RPM) state and voter times.
10474 * If RPM stats were fetched more recently than RPM_STATS_UPDATE_FREQ_MS ago, uses the old data
10475 * instead of fetching it anew.
Bookatz50df7112017-08-04 14:53:26 -070010476 */
10477 public void updateRpmStatsLocked() {
10478 if (mPlatformIdleStateCallback == null) return;
Bookatz0b8a0502017-09-13 11:51:52 -070010479 long now = SystemClock.elapsedRealtime();
10480 if (now - mLastRpmStatsUpdateTimeMs >= RPM_STATS_UPDATE_FREQ_MS) {
10481 mPlatformIdleStateCallback.fillLowPowerStats(mTmpRpmStats);
10482 mLastRpmStatsUpdateTimeMs = now;
10483 }
Bookatz50df7112017-08-04 14:53:26 -070010484
10485 for (Map.Entry<String, RpmStats.PowerStatePlatformSleepState> pstate
10486 : mTmpRpmStats.mPlatformLowPowerStats.entrySet()) {
10487
10488 // Update values for this platform state.
10489 final String pName = pstate.getKey();
10490 final long pTimeUs = pstate.getValue().mTimeMs * 1000;
10491 final int pCount = pstate.getValue().mCount;
10492 getRpmTimerLocked(pName).update(pTimeUs, pCount);
Bookatz82b341172017-09-07 19:06:08 -070010493 if (SCREEN_OFF_RPM_STATS_ENABLED) {
10494 getScreenOffRpmTimerLocked(pName).update(pTimeUs, pCount);
10495 }
Bookatz50df7112017-08-04 14:53:26 -070010496
10497 // Update values for each voter of this platform state.
10498 for (Map.Entry<String, RpmStats.PowerStateElement> voter
10499 : pstate.getValue().mVoters.entrySet()) {
10500 final String vName = pName + "." + voter.getKey();
10501 final long vTimeUs = voter.getValue().mTimeMs * 1000;
10502 final int vCount = voter.getValue().mCount;
10503 getRpmTimerLocked(vName).update(vTimeUs, vCount);
Bookatz82b341172017-09-07 19:06:08 -070010504 if (SCREEN_OFF_RPM_STATS_ENABLED) {
10505 getScreenOffRpmTimerLocked(vName).update(vTimeUs, vCount);
10506 }
Bookatz50df7112017-08-04 14:53:26 -070010507 }
10508 }
10509
10510 for (Map.Entry<String, RpmStats.PowerStateSubsystem> subsys
10511 : mTmpRpmStats.mSubsystemLowPowerStats.entrySet()) {
10512
10513 final String subsysName = subsys.getKey();
10514 for (Map.Entry<String, RpmStats.PowerStateElement> sstate
10515 : subsys.getValue().mStates.entrySet()) {
10516 final String name = subsysName + "." + sstate.getKey();
10517 final long timeUs = sstate.getValue().mTimeMs * 1000;
10518 final int count = sstate.getValue().mCount;
10519 getRpmTimerLocked(name).update(timeUs, count);
Bookatz82b341172017-09-07 19:06:08 -070010520 if (SCREEN_OFF_RPM_STATS_ENABLED) {
10521 getScreenOffRpmTimerLocked(name).update(timeUs, count);
10522 }
Bookatz50df7112017-08-04 14:53:26 -070010523 }
10524 }
10525 }
10526
10527 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010528 * Read and distribute kernel wake lock use across apps.
10529 */
10530 public void updateKernelWakelocksLocked() {
10531 final KernelWakelockStats wakelockStats = mKernelWakelockReader.readKernelWakelockStats(
10532 mTmpWakelockStats);
10533 if (wakelockStats == null) {
10534 // Not crashing might make board bringup easier.
10535 Slog.w(TAG, "Couldn't get kernel wake lock stats");
10536 return;
10537 }
10538
10539 for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
10540 String name = ent.getKey();
10541 KernelWakelockStats.Entry kws = ent.getValue();
10542
10543 SamplingTimer kwlt = mKernelWakelockStats.get(name);
10544 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -070010545 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010546 mKernelWakelockStats.put(name, kwlt);
10547 }
Adam Lesinskid84ad302016-05-17 18:31:02 -070010548
Adam Lesinski757c6ea2016-04-21 09:55:41 -070010549 kwlt.update(kws.mTotalTime, kws.mCount);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010550 kwlt.setUpdateVersion(kws.mVersion);
10551 }
10552
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070010553 int numWakelocksSetStale = 0;
Adam Lesinskid84ad302016-05-17 18:31:02 -070010554 // Set timers to stale if they didn't appear in /d/wakeup_sources (or /proc/wakelocks)
10555 // this time.
10556 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
10557 SamplingTimer st = ent.getValue();
10558 if (st.getUpdateVersion() != wakelockStats.kernelWakelockVersion) {
10559 st.endSample();
10560 numWakelocksSetStale++;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010561 }
10562 }
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070010563
Adam Lesinskid84ad302016-05-17 18:31:02 -070010564 // Record whether we've seen a non-zero time (for debugging b/22716723).
10565 if (wakelockStats.isEmpty()) {
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070010566 Slog.wtf(TAG, "All kernel wakelocks had time of zero");
10567 }
10568
10569 if (numWakelocksSetStale == mKernelWakelockStats.size()) {
10570 Slog.wtf(TAG, "All kernel wakelocks were set stale. new version=" +
10571 wakelockStats.kernelWakelockVersion);
10572 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010573 }
10574
Adam Lesinski72478f02015-06-17 15:39:43 -070010575 // We use an anonymous class to access these variables,
10576 // so they can't live on the stack or they'd have to be
10577 // final MutableLong objects (more allocations).
10578 // Used in updateCpuTimeLocked().
10579 long mTempTotalCpuUserTimeUs;
10580 long mTempTotalCpuSystemTimeUs;
Sudheer Shankab8ad5942017-08-08 12:16:09 -070010581 long[][] mWakeLockAllocationsUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070010582
Adam Lesinski06af1fa2015-05-05 17:35:35 -070010583 /**
James Carr3a226052016-07-01 14:49:52 -070010584 * Reads the newest memory stats from the kernel.
10585 */
10586 public void updateKernelMemoryBandwidthLocked() {
10587 mKernelMemoryBandwidthStats.updateStats();
10588 LongSparseLongArray bandwidthEntries = mKernelMemoryBandwidthStats.getBandwidthEntries();
10589 final int bandwidthEntryCount = bandwidthEntries.size();
10590 int index;
10591 for (int i = 0; i < bandwidthEntryCount; i++) {
10592 SamplingTimer timer;
10593 if ((index = mKernelMemoryStats.indexOfKey(bandwidthEntries.keyAt(i))) >= 0) {
10594 timer = mKernelMemoryStats.valueAt(index);
10595 } else {
10596 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
10597 mKernelMemoryStats.put(bandwidthEntries.keyAt(i), timer);
10598 }
10599 timer.update(bandwidthEntries.valueAt(i), 1);
10600 if (DEBUG_MEMORY) {
10601 Slog.d(TAG, String.format("Added entry %d and updated timer to: "
10602 + "mUnpluggedReportedTotalTime %d size %d", bandwidthEntries.keyAt(i),
10603 mKernelMemoryStats.get(
10604 bandwidthEntries.keyAt(i)).mUnpluggedReportedTotalTime,
10605 mKernelMemoryStats.size()));
10606 }
10607 }
10608 }
10609
10610 /**
Adam Lesinski72478f02015-06-17 15:39:43 -070010611 * Read and distribute CPU usage across apps. If their are partial wakelocks being held
10612 * and we are on battery with screen off, we give more of the cpu time to those apps holding
10613 * wakelocks. If the screen is on, we just assign the actual cpu time an app used.
Adam Lesinski06af1fa2015-05-05 17:35:35 -070010614 */
Sudheer Shankab8ad5942017-08-08 12:16:09 -070010615 public void updateCpuTimeLocked() {
Adam Lesinski52290c9c2015-09-21 16:54:52 -070010616 if (mPowerProfile == null) {
10617 return;
10618 }
10619
Adam Lesinski72478f02015-06-17 15:39:43 -070010620 if (DEBUG_ENERGY_CPU) {
10621 Slog.d(TAG, "!Cpu updating!");
10622 }
10623
Sudheer Shankab8ad5942017-08-08 12:16:09 -070010624 if (mCpuFreqs == null) {
10625 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
10626 }
10627
Sudheer Shanka38383232017-07-25 09:55:03 -070010628 // Calculate the wakelocks we have to distribute amongst. The system is excluded as it is
10629 // usually holding the wakelock on behalf of an app.
10630 // And Only distribute cpu power to wakelocks if the screen is off and we're on battery.
10631 ArrayList<StopwatchTimer> partialTimersToConsider = null;
Adam Lesinski72478f02015-06-17 15:39:43 -070010632 if (mOnBatteryScreenOffTimeBase.isRunning()) {
Sudheer Shanka38383232017-07-25 09:55:03 -070010633 partialTimersToConsider = new ArrayList<>();
10634 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070010635 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070010636 // Since the collection and blaming of wakelocks can be scheduled to run after
10637 // some delay, the mPartialTimers list may have new entries. We can't blame
10638 // the newly added timer for past cpu time, so we only consider timers that
10639 // were present for one round of collection. Once a timer has gone through
10640 // a round of collection, its mInList field is set to true.
Adam Lesinski72478f02015-06-17 15:39:43 -070010641 if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) {
Sudheer Shanka38383232017-07-25 09:55:03 -070010642 partialTimersToConsider.add(timer);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070010643 }
Adam Lesinski72478f02015-06-17 15:39:43 -070010644 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070010645 }
Sudheer Shanka38383232017-07-25 09:55:03 -070010646 markPartialTimersAsEligible();
Adam Lesinski72478f02015-06-17 15:39:43 -070010647
Sudheer Shanka38383232017-07-25 09:55:03 -070010648 // When the battery is not on, we don't attribute the cpu times to any timers but we still
10649 // need to take the snapshots.
10650 if (!mOnBatteryInternal) {
10651 mKernelUidCpuTimeReader.readDelta(null);
10652 mKernelUidCpuFreqTimeReader.readDelta(null);
10653 for (int cluster = mKernelCpuSpeedReaders.length - 1; cluster >= 0; --cluster) {
10654 mKernelCpuSpeedReaders[cluster].readDelta();
10655 }
10656 return;
10657 }
Adam Lesinski72478f02015-06-17 15:39:43 -070010658
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010659 mUserInfoProvider.refreshUserIds();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070010660 final SparseLongArray updatedUids = mKernelUidCpuFreqTimeReader.perClusterTimesAvailable()
10661 ? null : new SparseLongArray();
Sudheer Shanka38383232017-07-25 09:55:03 -070010662 readKernelUidCpuTimesLocked(partialTimersToConsider, updatedUids);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070010663 // updatedUids=null means /proc/uid_time_in_state provides snapshots of per-cluster cpu
10664 // freqs, so no need to approximate these values.
10665 if (updatedUids != null) {
10666 updateClusterSpeedTimes(updatedUids);
Sudheer Shanka671985f2017-05-19 11:33:42 -070010667 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070010668 readKernelUidCpuFreqTimesLocked(partialTimersToConsider);
Sudheer Shanka38383232017-07-25 09:55:03 -070010669 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070010670
Sudheer Shanka38383232017-07-25 09:55:03 -070010671 /**
10672 * Mark the current partial timers as gone through a collection so that they will be
10673 * considered in the next cpu times distribution to wakelock holders.
10674 */
10675 @VisibleForTesting
10676 public void markPartialTimersAsEligible() {
10677 if (ArrayUtils.referenceEquals(mPartialTimers, mLastPartialTimers)) {
10678 // No difference, so each timer is now considered for the next collection.
10679 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
10680 mPartialTimers.get(i).mInList = true;
10681 }
10682 } else {
10683 // The lists are different, meaning we added (or removed a timer) since the last
10684 // collection.
10685 for (int i = mLastPartialTimers.size() - 1; i >= 0; --i) {
10686 mLastPartialTimers.get(i).mInList = false;
10687 }
10688 mLastPartialTimers.clear();
Adam Lesinski72478f02015-06-17 15:39:43 -070010689
Sudheer Shanka38383232017-07-25 09:55:03 -070010690 // Mark the current timers as gone through a collection.
10691 final int numPartialTimers = mPartialTimers.size();
10692 for (int i = 0; i < numPartialTimers; ++i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070010693 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070010694 timer.mInList = true;
10695 mLastPartialTimers.add(timer);
Adam Lesinski72478f02015-06-17 15:39:43 -070010696 }
10697 }
Sudheer Shanka38383232017-07-25 09:55:03 -070010698 }
Adam Lesinski72478f02015-06-17 15:39:43 -070010699
Sudheer Shanka38383232017-07-25 09:55:03 -070010700 /**
10701 * Take snapshot of cpu times (aggregated over all uids) at different frequencies and
10702 * calculate cpu times spent by each uid at different frequencies.
10703 *
10704 * @param updatedUids The uids for which times spent at different frequencies are calculated.
10705 */
10706 @VisibleForTesting
10707 public void updateClusterSpeedTimes(@NonNull SparseLongArray updatedUids) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070010708 long totalCpuClustersTimeMs = 0;
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010709 // Read the time spent for each cluster at various cpu frequencies.
Sudheer Shankaaf857412017-07-21 00:14:24 -070010710 final long[][] clusterSpeedTimesMs = new long[mKernelCpuSpeedReaders.length][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010711 for (int cluster = 0; cluster < mKernelCpuSpeedReaders.length; cluster++) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070010712 clusterSpeedTimesMs[cluster] = mKernelCpuSpeedReaders[cluster].readDelta();
10713 if (clusterSpeedTimesMs[cluster] != null) {
10714 for (int speed = clusterSpeedTimesMs[cluster].length - 1; speed >= 0; --speed) {
10715 totalCpuClustersTimeMs += clusterSpeedTimesMs[cluster][speed];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010716 }
10717 }
10718 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070010719 if (totalCpuClustersTimeMs != 0) {
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010720 // We have cpu times per freq aggregated over all uids but we need the times per uid.
10721 // So, we distribute total time spent by an uid to different cpu freqs based on the
10722 // amount of time cpu was running at that freq.
10723 final int updatedUidsCount = updatedUids.size();
10724 for (int i = 0; i < updatedUidsCount; ++i) {
10725 final Uid u = getUidStatsLocked(updatedUids.keyAt(i));
Sudheer Shankaaf857412017-07-21 00:14:24 -070010726 final long appCpuTimeUs = updatedUids.valueAt(i);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010727 // Add the cpu speeds to this UID.
10728 final int numClusters = mPowerProfile.getNumCpuClusters();
Sudheer Shanka38383232017-07-25 09:55:03 -070010729 if (u.mCpuClusterSpeedTimesUs == null ||
10730 u.mCpuClusterSpeedTimesUs.length != numClusters) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070010731 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010732 }
10733
Sudheer Shankaaf857412017-07-21 00:14:24 -070010734 for (int cluster = 0; cluster < clusterSpeedTimesMs.length; cluster++) {
10735 final int speedsInCluster = clusterSpeedTimesMs[cluster].length;
10736 if (u.mCpuClusterSpeedTimesUs[cluster] == null || speedsInCluster !=
10737 u.mCpuClusterSpeedTimesUs[cluster].length) {
10738 u.mCpuClusterSpeedTimesUs[cluster]
10739 = new LongSamplingCounter[speedsInCluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010740 }
10741
Sudheer Shankaaf857412017-07-21 00:14:24 -070010742 final LongSamplingCounter[] cpuSpeeds = u.mCpuClusterSpeedTimesUs[cluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010743 for (int speed = 0; speed < speedsInCluster; speed++) {
10744 if (cpuSpeeds[speed] == null) {
10745 cpuSpeeds[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
10746 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070010747 cpuSpeeds[speed].addCountLocked(appCpuTimeUs
10748 * clusterSpeedTimesMs[cluster][speed]
10749 / totalCpuClustersTimeMs);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010750 }
10751 }
10752 }
10753 }
Sudheer Shanka38383232017-07-25 09:55:03 -070010754 }
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010755
Sudheer Shanka38383232017-07-25 09:55:03 -070010756 /**
10757 * Take a snapshot of the cpu times spent by each uid and update the corresponding counters.
10758 * If {@param partialTimers} is not null and empty, then we assign a portion of cpu times to
10759 * wakelock holders.
10760 *
10761 * @param partialTimers The wakelock holders among which the cpu times will be distributed.
10762 * @param updatedUids If not null, then the uids found in the snapshot will be added to this.
10763 */
10764 @VisibleForTesting
10765 public void readKernelUidCpuTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
10766 @Nullable SparseLongArray updatedUids) {
10767 mTempTotalCpuUserTimeUs = mTempTotalCpuSystemTimeUs = 0;
10768 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
10769 final long startTimeMs = mClocks.uptimeMillis();
Adam Lesinski72478f02015-06-17 15:39:43 -070010770
Sudheer Shanka38383232017-07-25 09:55:03 -070010771 mKernelUidCpuTimeReader.readDelta((uid, userTimeUs, systemTimeUs) -> {
10772 uid = mapUid(uid);
10773 if (Process.isIsolated(uid)) {
10774 // This could happen if the isolated uid mapping was removed before that process
10775 // was actually killed.
10776 mKernelUidCpuTimeReader.removeUid(uid);
10777 Slog.d(TAG, "Got readings for an isolated uid with no mapping: " + uid);
10778 return;
10779 }
10780 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
10781 Slog.d(TAG, "Got readings for an invalid user's uid " + uid);
10782 mKernelUidCpuTimeReader.removeUid(uid);
10783 return;
10784 }
10785 final Uid u = getUidStatsLocked(uid);
10786
10787 // Accumulate the total system and user time.
10788 mTempTotalCpuUserTimeUs += userTimeUs;
10789 mTempTotalCpuSystemTimeUs += systemTimeUs;
10790
10791 StringBuilder sb = null;
10792 if (DEBUG_ENERGY_CPU) {
10793 sb = new StringBuilder();
10794 sb.append(" got time for uid=").append(u.mUid).append(": u=");
10795 TimeUtils.formatDuration(userTimeUs / 1000, sb);
10796 sb.append(" s=");
10797 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
10798 sb.append("\n");
10799 }
10800
10801 if (numWakelocks > 0) {
10802 // We have wakelocks being held, so only give a portion of the
10803 // time to the process. The rest will be distributed among wakelock
10804 // holders.
10805 userTimeUs = (userTimeUs * WAKE_LOCK_WEIGHT) / 100;
10806 systemTimeUs = (systemTimeUs * WAKE_LOCK_WEIGHT) / 100;
10807 }
10808
10809 if (sb != null) {
10810 sb.append(" adding to uid=").append(u.mUid).append(": u=");
10811 TimeUtils.formatDuration(userTimeUs / 1000, sb);
10812 sb.append(" s=");
10813 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
10814 Slog.d(TAG, sb.toString());
10815 }
10816
10817 u.mUserCpuTime.addCountLocked(userTimeUs);
10818 u.mSystemCpuTime.addCountLocked(systemTimeUs);
10819 if (updatedUids != null) {
10820 updatedUids.put(u.getUid(), userTimeUs + systemTimeUs);
10821 }
10822 });
10823
10824 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
10825 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
10826 Slog.d(TAG, "Reading cpu stats took " + elapsedTimeMs + "ms");
10827 }
10828
10829 if (numWakelocks > 0) {
10830 // Distribute a portion of the total cpu time to wakelock holders.
10831 mTempTotalCpuUserTimeUs = (mTempTotalCpuUserTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
10832 mTempTotalCpuSystemTimeUs =
10833 (mTempTotalCpuSystemTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
10834
10835 for (int i = 0; i < numWakelocks; ++i) {
10836 final StopwatchTimer timer = partialTimers.get(i);
10837 final int userTimeUs = (int) (mTempTotalCpuUserTimeUs / (numWakelocks - i));
10838 final int systemTimeUs = (int) (mTempTotalCpuSystemTimeUs / (numWakelocks - i));
10839
10840 if (DEBUG_ENERGY_CPU) {
10841 final StringBuilder sb = new StringBuilder();
10842 sb.append(" Distributing wakelock uid=").append(timer.mUid.mUid)
10843 .append(": u=");
10844 TimeUtils.formatDuration(userTimeUs / 1000, sb);
10845 sb.append(" s=");
10846 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
10847 Slog.d(TAG, sb.toString());
10848 }
10849
10850 timer.mUid.mUserCpuTime.addCountLocked(userTimeUs);
10851 timer.mUid.mSystemCpuTime.addCountLocked(systemTimeUs);
10852 if (updatedUids != null) {
10853 final int uid = timer.mUid.getUid();
10854 updatedUids.put(uid, updatedUids.get(uid, 0) + userTimeUs + systemTimeUs);
10855 }
10856
10857 final Uid.Proc proc = timer.mUid.getProcessStatsLocked("*wakelock*");
10858 proc.addCpuTimeLocked(userTimeUs / 1000, systemTimeUs / 1000);
10859
10860 mTempTotalCpuUserTimeUs -= userTimeUs;
10861 mTempTotalCpuSystemTimeUs -= systemTimeUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070010862 }
10863 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070010864 }
10865
Sudheer Shanka38383232017-07-25 09:55:03 -070010866 /**
10867 * Take a snapshot of the cpu times spent by each uid in each freq and update the
10868 * corresponding counters.
Sudheer Shankab8ad5942017-08-08 12:16:09 -070010869 *
10870 * @param partialTimers The wakelock holders among which the cpu freq times will be distributed.
Sudheer Shanka38383232017-07-25 09:55:03 -070010871 */
10872 @VisibleForTesting
Sudheer Shankab8ad5942017-08-08 12:16:09 -070010873 public void readKernelUidCpuFreqTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers) {
10874 final boolean perClusterTimesAvailable =
10875 mKernelUidCpuFreqTimeReader.perClusterTimesAvailable();
10876 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
10877 final int numClusters = mPowerProfile.getNumCpuClusters();
10878 mWakeLockAllocationsUs = null;
10879 mKernelUidCpuFreqTimeReader.readDelta((uid, cpuFreqTimeMs) -> {
10880 uid = mapUid(uid);
10881 if (Process.isIsolated(uid)) {
10882 mKernelUidCpuFreqTimeReader.removeUid(uid);
10883 Slog.d(TAG, "Got freq readings for an isolated uid with no mapping: " + uid);
10884 return;
Sudheer Shanka38383232017-07-25 09:55:03 -070010885 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070010886 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
10887 Slog.d(TAG, "Got freq readings for an invalid user's uid " + uid);
10888 mKernelUidCpuFreqTimeReader.removeUid(uid);
10889 return;
10890 }
10891 final Uid u = getUidStatsLocked(uid);
10892 if (u.mCpuFreqTimeMs == null || u.mCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
10893 u.mCpuFreqTimeMs = new LongSamplingCounterArray(mOnBatteryTimeBase);
10894 }
10895 u.mCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs);
10896 if (u.mScreenOffCpuFreqTimeMs == null ||
10897 u.mScreenOffCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
10898 u.mScreenOffCpuFreqTimeMs = new LongSamplingCounterArray(
10899 mOnBatteryScreenOffTimeBase);
10900 }
10901 u.mScreenOffCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070010902
Sudheer Shankab8ad5942017-08-08 12:16:09 -070010903 if (perClusterTimesAvailable) {
10904 if (u.mCpuClusterSpeedTimesUs == null ||
10905 u.mCpuClusterSpeedTimesUs.length != numClusters) {
10906 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070010907 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070010908 if (numWakelocks > 0 && mWakeLockAllocationsUs == null) {
10909 mWakeLockAllocationsUs = new long[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070010910 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070010911
10912 int freqIndex = 0;
10913 for (int cluster = 0; cluster < numClusters; ++cluster) {
10914 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
10915 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
10916 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
10917 u.mCpuClusterSpeedTimesUs[cluster]
10918 = new LongSamplingCounter[speedsInCluster];
10919 }
10920 if (numWakelocks > 0 && mWakeLockAllocationsUs[cluster] == null) {
10921 mWakeLockAllocationsUs[cluster] = new long[speedsInCluster];
10922 }
10923 final LongSamplingCounter[] cpuTimesUs = u.mCpuClusterSpeedTimesUs[cluster];
10924 for (int speed = 0; speed < speedsInCluster; ++speed) {
10925 if (cpuTimesUs[speed] == null) {
10926 cpuTimesUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
10927 }
10928 final long appAllocationUs;
10929 if (mWakeLockAllocationsUs != null) {
10930 appAllocationUs =
10931 (cpuFreqTimeMs[freqIndex] * 1000 * WAKE_LOCK_WEIGHT) / 100;
10932 mWakeLockAllocationsUs[cluster][speed] +=
10933 (cpuFreqTimeMs[freqIndex] * 1000 - appAllocationUs);
10934 } else {
10935 appAllocationUs = cpuFreqTimeMs[freqIndex] * 1000;
10936 }
10937 cpuTimesUs[speed].addCountLocked(appAllocationUs);
10938 freqIndex++;
10939 }
Sudheer Shanka38383232017-07-25 09:55:03 -070010940 }
Sudheer Shanka38383232017-07-25 09:55:03 -070010941 }
10942 });
Sudheer Shankab8ad5942017-08-08 12:16:09 -070010943
10944 if (mWakeLockAllocationsUs != null) {
10945 for (int i = 0; i < numWakelocks; ++i) {
10946 final Uid u = partialTimers.get(i).mUid;
10947 if (u.mCpuClusterSpeedTimesUs == null ||
10948 u.mCpuClusterSpeedTimesUs.length != numClusters) {
10949 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
10950 }
10951
10952 for (int cluster = 0; cluster < numClusters; ++cluster) {
10953 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
10954 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
10955 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
10956 u.mCpuClusterSpeedTimesUs[cluster]
10957 = new LongSamplingCounter[speedsInCluster];
10958 }
10959 final LongSamplingCounter[] cpuTimeUs = u.mCpuClusterSpeedTimesUs[cluster];
10960 for (int speed = 0; speed < speedsInCluster; ++speed) {
10961 if (cpuTimeUs[speed] == null) {
10962 cpuTimeUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
10963 }
10964 final long allocationUs =
10965 mWakeLockAllocationsUs[cluster][speed] / (numWakelocks - i);
10966 cpuTimeUs[speed].addCountLocked(allocationUs);
10967 mWakeLockAllocationsUs[cluster][speed] -= allocationUs;
10968 }
10969 }
10970 }
10971 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070010972 }
10973
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010974 boolean setChargingLocked(boolean charging) {
10975 if (mCharging != charging) {
10976 mCharging = charging;
10977 if (charging) {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070010978 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010979 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070010980 mHistoryCur.states2 &= ~HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010981 }
10982 mHandler.sendEmptyMessage(MSG_REPORT_CHARGING);
10983 return true;
10984 }
10985 return false;
10986 }
10987
Mike Mac2f518a2017-09-19 16:06:03 -070010988 protected void setOnBatteryLocked(final long mSecRealtime, final long mSecUptime,
10989 final boolean onBattery, final int oldStatus, final int level, final int chargeUAh) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010990 boolean doWrite = false;
10991 Message m = mHandler.obtainMessage(MSG_REPORT_POWER_CHANGE);
10992 m.arg1 = onBattery ? 1 : 0;
10993 mHandler.sendMessage(m);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010994
Dianne Hackborn40c87252014-03-19 16:55:40 -070010995 final long uptime = mSecUptime * 1000;
10996 final long realtime = mSecRealtime * 1000;
Mike Mac2f518a2017-09-19 16:06:03 -070010997 final int screenState = mScreenState;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010998 if (onBattery) {
10999 // We will reset our status if we are unplugging after the
11000 // battery was last full, or the level is at 100, or
11001 // we have gone through a significant charge (from a very low
11002 // level to a now very high level).
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080011003 boolean reset = false;
Dianne Hackborn9a755432014-05-15 17:05:22 -070011004 if (!mNoAutoReset && (oldStatus == BatteryManager.BATTERY_STATUS_FULL
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011005 || level >= 90
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070011006 || (mDischargeCurrentLevel < 20 && level >= 80)
11007 || (getHighDischargeAmountSinceCharge() >= 200
11008 && mHistoryBuffer.dataSize() >= MAX_HISTORY_BUFFER))) {
Dianne Hackborn73d6a822014-09-29 10:52:47 -070011009 Slog.i(TAG, "Resetting battery stats: level=" + level + " status=" + oldStatus
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070011010 + " dischargeLevel=" + mDischargeCurrentLevel
Dianne Hackborn73d6a822014-09-29 10:52:47 -070011011 + " lowAmount=" + getLowDischargeAmountSinceCharge()
11012 + " highAmount=" + getHighDischargeAmountSinceCharge());
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011013 // Before we write, collect a snapshot of the final aggregated
11014 // stats to be reported in the next checkin. Only do this if we have
11015 // a sufficient amount of data to make it interesting.
11016 if (getLowDischargeAmountSinceCharge() >= 20) {
11017 final Parcel parcel = Parcel.obtain();
11018 writeSummaryToParcel(parcel, true);
11019 BackgroundThread.getHandler().post(new Runnable() {
11020 @Override public void run() {
11021 synchronized (mCheckinFile) {
11022 FileOutputStream stream = null;
11023 try {
11024 stream = mCheckinFile.startWrite();
11025 stream.write(parcel.marshall());
11026 stream.flush();
11027 FileUtils.sync(stream);
11028 stream.close();
11029 mCheckinFile.finishWrite(stream);
11030 } catch (IOException e) {
11031 Slog.w("BatteryStats",
11032 "Error writing checkin battery statistics", e);
11033 mCheckinFile.failWrite(stream);
11034 } finally {
11035 parcel.recycle();
11036 }
11037 }
11038 }
11039 });
11040 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011041 doWrite = true;
11042 resetAllStatsLocked();
Ying Wai (Daniel) Fan442ab762017-01-31 22:00:10 -080011043 if (chargeUAh > 0 && level > 0) {
Adam Lesinskif9b20a92016-06-17 17:30:01 -070011044 // Only use the reported coulomb charge value if it is supported and reported.
Ying Wai (Daniel) Fan9238b612017-01-18 15:50:19 -080011045 mEstimatedBatteryCapacity = (int) ((chargeUAh / 1000) / (level / 100.0));
Adam Lesinskif9b20a92016-06-17 17:30:01 -070011046 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011047 mDischargeStartLevel = level;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080011048 reset = true;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011049 mDischargeStepTracker.init();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011050 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070011051 if (mCharging) {
11052 setChargingLocked(false);
11053 }
11054 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080011055 mOnBattery = mOnBatteryInternal = true;
Dianne Hackborn260c5022014-04-29 11:23:16 -070011056 mLastDischargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070011057 mMinDischargeStepLevel = level;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011058 mDischargeStepTracker.clearTime();
11059 mDailyDischargeStepTracker.clearTime();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011060 mInitStepMode = mCurStepMode;
11061 mModStepMode = 0;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080011062 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011063 mHistoryCur.batteryLevel = (byte)level;
11064 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
11065 if (DEBUG_HISTORY) Slog.v(TAG, "Battery unplugged to: "
11066 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011067 if (reset) {
11068 mRecordingHistory = true;
11069 startRecordingHistory(mSecRealtime, mSecUptime, reset);
11070 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070011071 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011072 mDischargeCurrentLevel = mDischargeUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070011073 if (isScreenOn(screenState)) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011074 mDischargeScreenOnUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070011075 mDischargeScreenDozeUnplugLevel = 0;
11076 mDischargeScreenOffUnplugLevel = 0;
11077 } else if (isScreenDoze(screenState)) {
11078 mDischargeScreenOnUnplugLevel = 0;
11079 mDischargeScreenDozeUnplugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011080 mDischargeScreenOffUnplugLevel = 0;
11081 } else {
11082 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070011083 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011084 mDischargeScreenOffUnplugLevel = level;
11085 }
11086 mDischargeAmountScreenOn = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070011087 mDischargeAmountScreenDoze = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011088 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070011089 updateTimeBasesLocked(true, screenState, uptime, realtime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011090 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070011091 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080011092 mOnBattery = mOnBatteryInternal = false;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080011093 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011094 mHistoryCur.batteryLevel = (byte)level;
11095 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
11096 if (DEBUG_HISTORY) Slog.v(TAG, "Battery plugged to: "
11097 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -070011098 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011099 mDischargeCurrentLevel = mDischargePlugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011100 if (level < mDischargeUnplugLevel) {
11101 mLowDischargeAmountSinceCharge += mDischargeUnplugLevel-level-1;
11102 mHighDischargeAmountSinceCharge += mDischargeUnplugLevel-level;
11103 }
Mike Mac2f518a2017-09-19 16:06:03 -070011104 updateDischargeScreenLevelsLocked(screenState, screenState);
11105 updateTimeBasesLocked(false, screenState, uptime, realtime);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011106 mChargeStepTracker.init();
Dianne Hackborn260c5022014-04-29 11:23:16 -070011107 mLastChargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070011108 mMaxChargeStepLevel = level;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011109 mInitStepMode = mCurStepMode;
11110 mModStepMode = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011111 }
11112 if (doWrite || (mLastWriteTime + (60 * 1000)) < mSecRealtime) {
11113 if (mFile != null) {
11114 writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011115 }
11116 }
11117 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011118
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011119 private void startRecordingHistory(final long elapsedRealtimeMs, final long uptimeMs,
11120 boolean reset) {
11121 mRecordingHistory = true;
11122 mHistoryCur.currentTime = System.currentTimeMillis();
Dianne Hackborn37de0982014-05-09 09:32:18 -070011123 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs,
11124 reset ? HistoryItem.CMD_RESET : HistoryItem.CMD_CURRENT_TIME,
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011125 mHistoryCur);
11126 mHistoryCur.currentTime = 0;
11127 if (reset) {
11128 initActiveHistoryEventsLocked(elapsedRealtimeMs, uptimeMs);
11129 }
11130 }
11131
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070011132 private void recordCurrentTimeChangeLocked(final long currentTime, final long elapsedRealtimeMs,
11133 final long uptimeMs) {
11134 if (mRecordingHistory) {
11135 mHistoryCur.currentTime = currentTime;
11136 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_CURRENT_TIME,
11137 mHistoryCur);
11138 mHistoryCur.currentTime = 0;
11139 }
11140 }
11141
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080011142 private void recordShutdownLocked(final long elapsedRealtimeMs, final long uptimeMs) {
11143 if (mRecordingHistory) {
11144 mHistoryCur.currentTime = System.currentTimeMillis();
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080011145 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_SHUTDOWN,
11146 mHistoryCur);
11147 mHistoryCur.currentTime = 0;
11148 }
11149 }
11150
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011151 private void scheduleSyncExternalStatsLocked(String reason, int updateFlags) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011152 if (mExternalSync != null) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011153 mExternalSync.scheduleSync(reason, updateFlags);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011154 }
11155 }
11156
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011157 // This should probably be exposed in the API, though it's not critical
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011158 public static final int BATTERY_PLUGGED_NONE = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011159
Bookatz8c6571b2017-10-24 15:04:41 -070011160 public void setBatteryStateLocked(final int status, final int health, final int plugType,
11161 final int level, /* not final */ int temp, final int volt, final int chargeUAh,
11162 final int chargeFullUAh) {
Adam Lesinski29ddfe52017-03-29 19:29:00 -070011163 // Temperature is encoded without the signed bit, so clamp any negative temperatures to 0.
11164 temp = Math.max(0, temp);
11165
Bookatz8c6571b2017-10-24 15:04:41 -070011166 reportChangesToStatsLog(mHaveBatteryLevel ? mHistoryCur : null,
11167 status, plugType, level, temp);
11168
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011169 final boolean onBattery = plugType == BATTERY_PLUGGED_NONE;
Joe Onoratoabded112016-02-08 16:49:39 -080011170 final long uptime = mClocks.uptimeMillis();
11171 final long elapsedRealtime = mClocks.elapsedRealtime();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011172 if (!mHaveBatteryLevel) {
11173 mHaveBatteryLevel = true;
11174 // We start out assuming that the device is plugged in (not
11175 // on battery). If our first report is now that we are indeed
11176 // plugged in, then twiddle our state to correctly reflect that
11177 // since we won't be going through the full setOnBattery().
11178 if (onBattery == mOnBattery) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070011179 if (onBattery) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011180 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070011181 } else {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011182 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070011183 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011184 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070011185 // Always start out assuming charging, that will be updated later.
Dianne Hackborn0c820db2015-04-14 17:47:34 -070011186 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011187 mHistoryCur.batteryStatus = (byte)status;
11188 mHistoryCur.batteryLevel = (byte)level;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070011189 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011190 mMaxChargeStepLevel = mMinDischargeStepLevel =
11191 mLastChargeStepLevel = mLastDischargeStepLevel = level;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070011192 mLastChargingStateLevel = level;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011193 } else if (mCurrentBatteryLevel != level || mOnBattery != onBattery) {
11194 recordDailyStatsIfNeededLocked(level >= 100 && onBattery);
11195 }
11196 int oldStatus = mHistoryCur.batteryStatus;
11197 if (onBattery) {
11198 mDischargeCurrentLevel = level;
11199 if (!mRecordingHistory) {
11200 mRecordingHistory = true;
11201 startRecordingHistory(elapsedRealtime, uptime, true);
11202 }
11203 } else if (level < 96) {
11204 if (!mRecordingHistory) {
11205 mRecordingHistory = true;
11206 startRecordingHistory(elapsedRealtime, uptime, true);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011207 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070011208 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011209 mCurrentBatteryLevel = level;
11210 if (mDischargePlugLevel < 0) {
11211 mDischargePlugLevel = level;
Marco Nelissend8593312009-04-30 14:45:06 -070011212 }
Adam Lesinski926969b2016-04-28 17:31:12 -070011213
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011214 if (onBattery != mOnBattery) {
11215 mHistoryCur.batteryLevel = (byte)level;
11216 mHistoryCur.batteryStatus = (byte)status;
11217 mHistoryCur.batteryHealth = (byte)health;
11218 mHistoryCur.batteryPlugType = (byte)plugType;
11219 mHistoryCur.batteryTemperature = (short)temp;
11220 mHistoryCur.batteryVoltage = (char)volt;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070011221 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
11222 // Only record discharges
11223 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
11224 mDischargeCounter.addCountLocked(chargeDiff);
11225 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070011226 if (isScreenDoze(mScreenState)) {
11227 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
11228 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070011229 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070011230 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070011231 setOnBatteryLocked(elapsedRealtime, uptime, onBattery, oldStatus, level, chargeUAh);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011232 } else {
11233 boolean changed = false;
11234 if (mHistoryCur.batteryLevel != level) {
11235 mHistoryCur.batteryLevel = (byte)level;
11236 changed = true;
Marco Nelissend8593312009-04-30 14:45:06 -070011237
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011238 // TODO(adamlesinski): Schedule the creation of a HistoryStepDetails record
11239 // which will pull external stats.
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011240 scheduleSyncExternalStatsLocked("battery-level", ExternalStatsSync.UPDATE_ALL);
Evan Millarc64edde2009-04-18 12:26:32 -070011241 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011242 if (mHistoryCur.batteryStatus != status) {
11243 mHistoryCur.batteryStatus = (byte)status;
11244 changed = true;
11245 }
11246 if (mHistoryCur.batteryHealth != health) {
11247 mHistoryCur.batteryHealth = (byte)health;
11248 changed = true;
11249 }
11250 if (mHistoryCur.batteryPlugType != plugType) {
11251 mHistoryCur.batteryPlugType = (byte)plugType;
11252 changed = true;
11253 }
11254 if (temp >= (mHistoryCur.batteryTemperature+10)
11255 || temp <= (mHistoryCur.batteryTemperature-10)) {
11256 mHistoryCur.batteryTemperature = (short)temp;
11257 changed = true;
11258 }
11259 if (volt > (mHistoryCur.batteryVoltage+20)
11260 || volt < (mHistoryCur.batteryVoltage-20)) {
11261 mHistoryCur.batteryVoltage = (char)volt;
11262 changed = true;
11263 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070011264 if (chargeUAh >= (mHistoryCur.batteryChargeUAh+10)
11265 || chargeUAh <= (mHistoryCur.batteryChargeUAh-10)) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -070011266 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
11267 // Only record discharges
11268 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
11269 mDischargeCounter.addCountLocked(chargeDiff);
11270 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070011271 if (isScreenDoze(mScreenState)) {
11272 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
11273 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070011274 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070011275 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski926969b2016-04-28 17:31:12 -070011276 changed = true;
11277 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011278 long modeBits = (((long)mInitStepMode) << STEP_LEVEL_INITIAL_MODE_SHIFT)
11279 | (((long)mModStepMode) << STEP_LEVEL_MODIFIED_MODE_SHIFT)
11280 | (((long)(level&0xff)) << STEP_LEVEL_LEVEL_SHIFT);
11281 if (onBattery) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070011282 changed |= setChargingLocked(false);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011283 if (mLastDischargeStepLevel != level && mMinDischargeStepLevel > level) {
11284 mDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
11285 modeBits, elapsedRealtime);
11286 mDailyDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
11287 modeBits, elapsedRealtime);
11288 mLastDischargeStepLevel = level;
11289 mMinDischargeStepLevel = level;
11290 mInitStepMode = mCurStepMode;
11291 mModStepMode = 0;
11292 }
11293 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070011294 if (level >= 90) {
11295 // If the battery level is at least 90%, always consider the device to be
11296 // charging even if it happens to go down a level.
11297 changed |= setChargingLocked(true);
11298 mLastChargeStepLevel = level;
11299 } if (!mCharging) {
11300 if (mLastChargeStepLevel < level) {
11301 // We have not reporting that we are charging, but the level has now
11302 // gone up, so consider the state to be charging.
11303 changed |= setChargingLocked(true);
11304 mLastChargeStepLevel = level;
11305 }
11306 } else {
11307 if (mLastChargeStepLevel > level) {
11308 // We had reported that the device was charging, but here we are with
11309 // power connected and the level going down. Looks like the current
11310 // power supplied isn't enough, so consider the device to now be
11311 // discharging.
11312 changed |= setChargingLocked(false);
11313 mLastChargeStepLevel = level;
11314 }
11315 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011316 if (mLastChargeStepLevel != level && mMaxChargeStepLevel < level) {
11317 mChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
11318 modeBits, elapsedRealtime);
11319 mDailyChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
11320 modeBits, elapsedRealtime);
11321 mLastChargeStepLevel = level;
11322 mMaxChargeStepLevel = level;
11323 mInitStepMode = mCurStepMode;
11324 mModStepMode = 0;
Evan Millarc64edde2009-04-18 12:26:32 -070011325 }
11326 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070011327 if (changed) {
11328 addHistoryRecordLocked(elapsedRealtime, uptime);
11329 }
Evan Millarc64edde2009-04-18 12:26:32 -070011330 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011331 if (!onBattery && status == BatteryManager.BATTERY_STATUS_FULL) {
11332 // We don't record history while we are plugged in and fully charged.
11333 // The next time we are unplugged, history will be cleared.
11334 mRecordingHistory = DEBUG;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080011335 }
Adam Lesinski041d9172016-12-12 12:03:56 -080011336
Jocelyn Dangc627d102017-04-14 13:15:14 -070011337 if (mMinLearnedBatteryCapacity == -1) {
11338 mMinLearnedBatteryCapacity = chargeFullUAh;
11339 } else {
11340 Math.min(mMinLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski041d9172016-12-12 12:03:56 -080011341 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070011342 mMaxLearnedBatteryCapacity = Math.max(mMaxLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski33dac552015-03-09 15:24:48 -070011343 }
11344
Bookatz8c6571b2017-10-24 15:04:41 -070011345 // Inform StatsLog of setBatteryState changes.
11346 // If this is the first reporting, pass in recentPast == null.
11347 private void reportChangesToStatsLog(HistoryItem recentPast,
11348 final int status, final int plugType, final int level, final int temp) {
11349
11350 if (recentPast == null || recentPast.batteryStatus != status) {
11351 StatsLog.write(StatsLog.CHARGING_STATE_CHANGED, status);
11352 }
11353 if (recentPast == null || recentPast.batteryPlugType != plugType) {
11354 StatsLog.write(StatsLog.PLUGGED_STATE_CHANGED, plugType);
11355 }
11356 if (recentPast == null || recentPast.batteryLevel != level) {
11357 StatsLog.write(StatsLog.BATTERY_LEVEL_CHANGED, level);
11358 }
11359 // Let's just always print the temperature, regardless of whether it changed.
11360 StatsLog.write(StatsLog.DEVICE_TEMPERATURE_REPORTED, temp);
11361 }
11362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011363 public long getAwakeTimeBattery() {
11364 return computeBatteryUptime(getBatteryUptimeLocked(), STATS_CURRENT);
11365 }
11366
11367 public long getAwakeTimePlugged() {
Joe Onoratoabded112016-02-08 16:49:39 -080011368 return (mClocks.uptimeMillis() * 1000) - getAwakeTimeBattery();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011369 }
11370
11371 @Override
11372 public long computeUptime(long curTime, int which) {
11373 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011374 case STATS_SINCE_CHARGED: return mUptime + (curTime-mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011375 case STATS_CURRENT: return (curTime-mUptimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070011376 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getUptimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011377 }
11378 return 0;
11379 }
11380
11381 @Override
11382 public long computeRealtime(long curTime, int which) {
11383 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011384 case STATS_SINCE_CHARGED: return mRealtime + (curTime-mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011385 case STATS_CURRENT: return (curTime-mRealtimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070011386 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getRealtimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011387 }
11388 return 0;
11389 }
11390
11391 @Override
11392 public long computeBatteryUptime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011393 return mOnBatteryTimeBase.computeUptime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011394 }
11395
11396 @Override
11397 public long computeBatteryRealtime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011398 return mOnBatteryTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011399 }
11400
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011401 @Override
11402 public long computeBatteryScreenOffUptime(long curTime, int which) {
11403 return mOnBatteryScreenOffTimeBase.computeUptime(curTime, which);
11404 }
11405
11406 @Override
11407 public long computeBatteryScreenOffRealtime(long curTime, int which) {
11408 return mOnBatteryScreenOffTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011409 }
11410
Dianne Hackborn260c5022014-04-29 11:23:16 -070011411 private long computeTimePerLevel(long[] steps, int numSteps) {
11412 // For now we'll do a simple average across all steps.
11413 if (numSteps <= 0) {
11414 return -1;
11415 }
11416 long total = 0;
11417 for (int i=0; i<numSteps; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011418 total += steps[i] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070011419 }
11420 return total / numSteps;
11421 /*
11422 long[] buckets = new long[numSteps];
11423 int numBuckets = 0;
11424 int numToAverage = 4;
11425 int i = 0;
11426 while (i < numSteps) {
11427 long totalTime = 0;
11428 int num = 0;
11429 for (int j=0; j<numToAverage && (i+j)<numSteps; j++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011430 totalTime += steps[i+j] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070011431 num++;
11432 }
11433 buckets[numBuckets] = totalTime / num;
11434 numBuckets++;
11435 numToAverage *= 2;
11436 i += num;
11437 }
11438 if (numBuckets < 1) {
11439 return -1;
11440 }
11441 long averageTime = buckets[numBuckets-1];
11442 for (i=numBuckets-2; i>=0; i--) {
11443 averageTime = (averageTime + buckets[i]) / 2;
11444 }
11445 return averageTime;
11446 */
11447 }
11448
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011449 @Override
11450 public long computeBatteryTimeRemaining(long curTime) {
11451 if (!mOnBattery) {
11452 return -1;
11453 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070011454 /* Simple implementation just looks at the average discharge per level across the
11455 entire sample period.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011456 int discharge = (getLowDischargeAmountSinceCharge()+getHighDischargeAmountSinceCharge())/2;
11457 if (discharge < 2) {
11458 return -1;
11459 }
11460 long duration = computeBatteryRealtime(curTime, STATS_SINCE_CHARGED);
11461 if (duration < 1000*1000) {
11462 return -1;
11463 }
11464 long usPerLevel = duration/discharge;
11465 return usPerLevel * mCurrentBatteryLevel;
Dianne Hackborn260c5022014-04-29 11:23:16 -070011466 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011467 if (mDischargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070011468 return -1;
11469 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011470 long msPerLevel = mDischargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070011471 if (msPerLevel <= 0) {
11472 return -1;
11473 }
11474 return (msPerLevel * mCurrentBatteryLevel) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011475 }
11476
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011477 @Override
11478 public LevelStepTracker getDischargeLevelStepTracker() {
11479 return mDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070011480 }
11481
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011482 @Override
11483 public LevelStepTracker getDailyDischargeLevelStepTracker() {
11484 return mDailyDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070011485 }
11486
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011487 @Override
11488 public long computeChargeTimeRemaining(long curTime) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070011489 if (mOnBattery) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011490 // Not yet working.
11491 return -1;
11492 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070011493 /* Broken
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011494 int curLevel = mCurrentBatteryLevel;
11495 int plugLevel = mDischargePlugLevel;
11496 if (plugLevel < 0 || curLevel < (plugLevel+1)) {
11497 return -1;
11498 }
11499 long duration = computeBatteryRealtime(curTime, STATS_SINCE_UNPLUGGED);
11500 if (duration < 1000*1000) {
11501 return -1;
11502 }
11503 long usPerLevel = duration/(curLevel-plugLevel);
11504 return usPerLevel * (100-curLevel);
Dianne Hackborn260c5022014-04-29 11:23:16 -070011505 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011506 if (mChargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070011507 return -1;
11508 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011509 long msPerLevel = mChargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070011510 if (msPerLevel <= 0) {
11511 return -1;
11512 }
11513 return (msPerLevel * (100-mCurrentBatteryLevel)) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011514 }
11515
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011516 @Override
11517 public LevelStepTracker getChargeLevelStepTracker() {
11518 return mChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070011519 }
11520
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011521 @Override
11522 public LevelStepTracker getDailyChargeLevelStepTracker() {
11523 return mDailyChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070011524 }
11525
Dianne Hackborn88e98df2015-03-23 13:29:14 -070011526 @Override
11527 public ArrayList<PackageChange> getDailyPackageChanges() {
11528 return mDailyPackageChanges;
11529 }
11530
Joe Onoratoe1acd632016-02-23 13:25:10 -080011531 protected long getBatteryUptimeLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080011532 return mOnBatteryTimeBase.getUptime(mClocks.uptimeMillis() * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011533 }
11534
11535 @Override
11536 public long getBatteryUptime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011537 return mOnBatteryTimeBase.getUptime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011538 }
11539
11540 @Override
11541 public long getBatteryRealtime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011542 return mOnBatteryTimeBase.getRealtime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011543 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -070011544
The Android Open Source Project10592532009-03-18 17:39:46 -070011545 @Override
Evan Millar633a1742009-04-02 16:36:33 -070011546 public int getDischargeStartLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070011547 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070011548 return getDischargeStartLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070011549 }
11550 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011551
Evan Millar633a1742009-04-02 16:36:33 -070011552 public int getDischargeStartLevelLocked() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011553 return mDischargeUnplugLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070011554 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011555
The Android Open Source Project10592532009-03-18 17:39:46 -070011556 @Override
Evan Millar633a1742009-04-02 16:36:33 -070011557 public int getDischargeCurrentLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070011558 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070011559 return getDischargeCurrentLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070011560 }
11561 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011562
Evan Millar633a1742009-04-02 16:36:33 -070011563 public int getDischargeCurrentLevelLocked() {
Dianne Hackborne4a59512010-12-07 11:08:07 -080011564 return mDischargeCurrentLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070011565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011566
Amith Yamasanie43530a2009-08-21 13:11:37 -070011567 @Override
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070011568 public int getLowDischargeAmountSinceCharge() {
11569 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080011570 int val = mLowDischargeAmountSinceCharge;
11571 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
11572 val += mDischargeUnplugLevel-mDischargeCurrentLevel-1;
11573 }
11574 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070011575 }
11576 }
11577
11578 @Override
11579 public int getHighDischargeAmountSinceCharge() {
11580 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080011581 int val = mHighDischargeAmountSinceCharge;
11582 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
11583 val += mDischargeUnplugLevel-mDischargeCurrentLevel;
11584 }
11585 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070011586 }
11587 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070011588
11589 @Override
11590 public int getDischargeAmount(int which) {
11591 int dischargeAmount = which == STATS_SINCE_CHARGED
11592 ? getHighDischargeAmountSinceCharge()
11593 : (getDischargeStartLevel() - getDischargeCurrentLevel());
11594 if (dischargeAmount < 0) {
11595 dischargeAmount = 0;
11596 }
11597 return dischargeAmount;
11598 }
11599
Mike Mac2f518a2017-09-19 16:06:03 -070011600 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011601 public int getDischargeAmountScreenOn() {
11602 synchronized(this) {
11603 int val = mDischargeAmountScreenOn;
Mike Mac2f518a2017-09-19 16:06:03 -070011604 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011605 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
11606 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
11607 }
11608 return val;
11609 }
11610 }
11611
Mike Mac2f518a2017-09-19 16:06:03 -070011612 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011613 public int getDischargeAmountScreenOnSinceCharge() {
11614 synchronized(this) {
11615 int val = mDischargeAmountScreenOnSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -070011616 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011617 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
11618 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
11619 }
11620 return val;
11621 }
11622 }
11623
Mike Mac2f518a2017-09-19 16:06:03 -070011624 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011625 public int getDischargeAmountScreenOff() {
11626 synchronized(this) {
11627 int val = mDischargeAmountScreenOff;
Mike Mac2f518a2017-09-19 16:06:03 -070011628 if (mOnBattery && isScreenOff(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011629 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
11630 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
11631 }
Mike Mac2f518a2017-09-19 16:06:03 -070011632 // For backward compatibility, doze discharge is counted into screen off.
11633 return val + getDischargeAmountScreenDoze();
11634 }
11635 }
11636
11637 @Override
11638 public int getDischargeAmountScreenOffSinceCharge() {
11639 synchronized(this) {
11640 int val = mDischargeAmountScreenOffSinceCharge;
11641 if (mOnBattery && isScreenOff(mScreenState)
11642 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
11643 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
11644 }
11645 // For backward compatibility, doze discharge is counted into screen off.
11646 return val + getDischargeAmountScreenDozeSinceCharge();
11647 }
11648 }
11649
11650 @Override
11651 public int getDischargeAmountScreenDoze() {
11652 synchronized(this) {
11653 int val = mDischargeAmountScreenDoze;
11654 if (mOnBattery && isScreenDoze(mScreenState)
11655 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
11656 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
11657 }
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011658 return val;
11659 }
11660 }
11661
Mike Mac2f518a2017-09-19 16:06:03 -070011662 @Override
11663 public int getDischargeAmountScreenDozeSinceCharge() {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011664 synchronized(this) {
Mike Mac2f518a2017-09-19 16:06:03 -070011665 int val = mDischargeAmountScreenDozeSinceCharge;
11666 if (mOnBattery && isScreenDoze(mScreenState)
11667 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
11668 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011669 }
11670 return val;
11671 }
11672 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070011673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011674 /**
11675 * Retrieve the statistics object for a particular uid, creating if needed.
11676 */
11677 public Uid getUidStatsLocked(int uid) {
11678 Uid u = mUidStats.get(uid);
11679 if (u == null) {
Joe Onoratoabded112016-02-08 16:49:39 -080011680 u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011681 mUidStats.put(uid, u);
11682 }
11683 return u;
11684 }
11685
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070011686 public void onCleanupUserLocked(int userId) {
11687 final int firstUidForUser = UserHandle.getUid(userId, 0);
11688 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
11689 mKernelUidCpuFreqTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
11690 mKernelUidCpuTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
11691 }
11692
11693 public void onUserRemovedLocked(int userId) {
11694 final int firstUidForUser = UserHandle.getUid(userId, 0);
11695 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
11696 mUidStats.put(firstUidForUser, null);
11697 mUidStats.put(lastUidForUser, null);
11698 final int firstIndex = mUidStats.indexOfKey(firstUidForUser);
11699 final int lastIndex = mUidStats.indexOfKey(lastUidForUser);
11700 mUidStats.removeAtRange(firstIndex, lastIndex - firstIndex + 1);
11701 }
11702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011703 /**
11704 * Remove the statistics object for a particular uid.
11705 */
11706 public void removeUidStatsLocked(int uid) {
Adam Lesinskib83ffee2015-05-12 14:43:47 -070011707 mKernelUidCpuTimeReader.removeUid(uid);
Sudheer Shanka6d8dcec2017-06-01 12:09:03 -070011708 mKernelUidCpuFreqTimeReader.removeUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011709 mUidStats.remove(uid);
11710 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -070011711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011712 /**
11713 * Retrieve the statistics object for a particular process, creating
11714 * if needed.
11715 */
11716 public Uid.Proc getProcessStatsLocked(int uid, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070011717 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011718 Uid u = getUidStatsLocked(uid);
11719 return u.getProcessStatsLocked(name);
11720 }
11721
11722 /**
11723 * Retrieve the statistics object for a particular process, creating
11724 * if needed.
11725 */
11726 public Uid.Pkg getPackageStatsLocked(int uid, String pkg) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070011727 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011728 Uid u = getUidStatsLocked(uid);
11729 return u.getPackageStatsLocked(pkg);
11730 }
11731
11732 /**
11733 * Retrieve the statistics object for a particular service, creating
11734 * if needed.
11735 */
11736 public Uid.Pkg.Serv getServiceStatsLocked(int uid, String pkg, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070011737 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011738 Uid u = getUidStatsLocked(uid);
11739 return u.getServiceStatsLocked(pkg, name);
11740 }
11741
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011742 public void shutdownLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080011743 recordShutdownLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011744 writeSyncLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011745 mShuttingDown = true;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011746 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011747
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011748 Parcel mPendingWrite = null;
11749 final ReentrantLock mWriteLock = new ReentrantLock();
11750
11751 public void writeAsyncLocked() {
11752 writeLocked(false);
11753 }
11754
11755 public void writeSyncLocked() {
11756 writeLocked(true);
11757 }
11758
11759 void writeLocked(boolean sync) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011760 if (mFile == null) {
11761 Slog.w("BatteryStats", "writeLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011762 return;
11763 }
11764
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011765 if (mShuttingDown) {
11766 return;
11767 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011768
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011769 Parcel out = Parcel.obtain();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011770 writeSummaryToParcel(out, true);
Joe Onoratoabded112016-02-08 16:49:39 -080011771 mLastWriteTime = mClocks.elapsedRealtime();
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011772
11773 if (mPendingWrite != null) {
11774 mPendingWrite.recycle();
11775 }
11776 mPendingWrite = out;
11777
11778 if (sync) {
11779 commitPendingDataToDisk();
11780 } else {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011781 BackgroundThread.getHandler().post(new Runnable() {
11782 @Override public void run() {
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011783 commitPendingDataToDisk();
11784 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011785 });
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011786 }
11787 }
11788
11789 public void commitPendingDataToDisk() {
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070011790 final Parcel next;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011791 synchronized (this) {
11792 next = mPendingWrite;
11793 mPendingWrite = null;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070011794 if (next == null) {
11795 return;
11796 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011797 }
11798
Amith Yamasanid2450862017-02-07 15:58:24 -080011799 mWriteLock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011800 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011801 FileOutputStream stream = new FileOutputStream(mFile.chooseForWrite());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011802 stream.write(next.marshall());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011803 stream.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070011804 FileUtils.sync(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011805 stream.close();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011806 mFile.commit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011807 } catch (IOException e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011808 Slog.w("BatteryStats", "Error writing battery statistics", e);
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011809 mFile.rollback();
11810 } finally {
11811 next.recycle();
11812 mWriteLock.unlock();
Suchi Amalapurapu8550f252009-09-29 15:20:32 -070011813 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011814 }
11815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011816 public void readLocked() {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011817 if (mDailyFile != null) {
11818 readDailyStatsLocked();
11819 }
11820
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011821 if (mFile == null) {
11822 Slog.w("BatteryStats", "readLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011823 return;
11824 }
11825
11826 mUidStats.clear();
11827
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011828 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011829 File file = mFile.chooseForRead();
11830 if (!file.exists()) {
11831 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011832 }
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011833 FileInputStream stream = new FileInputStream(file);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011834
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011835 byte[] raw = BatteryStatsHelper.readFully(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011836 Parcel in = Parcel.obtain();
11837 in.unmarshall(raw, 0, raw.length);
11838 in.setDataPosition(0);
11839 stream.close();
11840
11841 readSummaryFromParcel(in);
Dianne Hackborn00e25212014-02-19 10:49:24 -080011842 } catch(Exception e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011843 Slog.e("BatteryStats", "Error reading battery statistics", e);
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011844 resetAllStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011845 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011846
Dianne Hackborncd0e3352014-08-07 17:08:09 -070011847 mEndPlatformVersion = Build.ID;
11848
Dianne Hackborne5167ca2014-03-08 14:39:10 -080011849 if (mHistoryBuffer.dataPosition() > 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011850 mRecordingHistory = true;
Joe Onoratoabded112016-02-08 16:49:39 -080011851 final long elapsedRealtime = mClocks.elapsedRealtime();
11852 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -080011853 if (USE_OLD_HISTORY) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011854 addHistoryRecordLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborne5167ca2014-03-08 14:39:10 -080011855 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011856 addHistoryBufferLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
11857 startRecordingHistory(elapsedRealtime, uptime, false);
Dianne Hackborne8c88e62011-08-17 19:09:09 -070011858 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011859
11860 recordDailyStatsIfNeededLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011861 }
11862
11863 public int describeContents() {
11864 return 0;
11865 }
11866
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011867 void readHistory(Parcel in, boolean andOldHistory) throws ParcelFormatException {
Dianne Hackbornae384452011-06-28 12:33:48 -070011868 final long historyBaseTime = in.readLong();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011869
11870 mHistoryBuffer.setDataSize(0);
11871 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080011872 mHistoryTagPool.clear();
11873 mNextHistoryTagIdx = 0;
11874 mNumHistoryTagChars = 0;
Dianne Hackborn099bc622014-01-22 13:39:16 -080011875
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080011876 int numTags = in.readInt();
11877 for (int i=0; i<numTags; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080011878 int idx = in.readInt();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080011879 String str = in.readString();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011880 if (str == null) {
11881 throw new ParcelFormatException("null history tag string");
11882 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080011883 int uid = in.readInt();
11884 HistoryTag tag = new HistoryTag();
11885 tag.string = str;
11886 tag.uid = uid;
11887 tag.poolIdx = idx;
11888 mHistoryTagPool.put(tag, idx);
11889 if (idx >= mNextHistoryTagIdx) {
11890 mNextHistoryTagIdx = idx+1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080011891 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080011892 mNumHistoryTagChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080011893 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011894
11895 int bufSize = in.readInt();
11896 int curPos = in.dataPosition();
11897 if (bufSize >= (MAX_MAX_HISTORY_BUFFER*3)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011898 throw new ParcelFormatException("File corrupt: history data buffer too large " +
11899 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011900 } else if ((bufSize&~3) != bufSize) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011901 throw new ParcelFormatException("File corrupt: history data buffer not aligned " +
11902 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011903 } else {
11904 if (DEBUG_HISTORY) Slog.i(TAG, "***************** READING NEW HISTORY: " + bufSize
11905 + " bytes at " + curPos);
11906 mHistoryBuffer.appendFrom(in, curPos, bufSize);
11907 in.setDataPosition(curPos + bufSize);
Dianne Hackborn32907cf2010-06-10 17:50:20 -070011908 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011909
Dianne Hackbornae384452011-06-28 12:33:48 -070011910 if (andOldHistory) {
11911 readOldHistory(in);
11912 }
11913
11914 if (DEBUG_HISTORY) {
11915 StringBuilder sb = new StringBuilder(128);
11916 sb.append("****************** OLD mHistoryBaseTime: ");
11917 TimeUtils.formatDuration(mHistoryBaseTime, sb);
11918 Slog.i(TAG, sb.toString());
11919 }
11920 mHistoryBaseTime = historyBaseTime;
11921 if (DEBUG_HISTORY) {
11922 StringBuilder sb = new StringBuilder(128);
11923 sb.append("****************** NEW mHistoryBaseTime: ");
11924 TimeUtils.formatDuration(mHistoryBaseTime, sb);
11925 Slog.i(TAG, sb.toString());
11926 }
11927
11928 // We are just arbitrarily going to insert 1 minute from the sample of
11929 // the last run until samples in this run.
11930 if (mHistoryBaseTime > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -080011931 long oldnow = mClocks.elapsedRealtime();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070011932 mHistoryBaseTime = mHistoryBaseTime - oldnow + 1;
Dianne Hackbornae384452011-06-28 12:33:48 -070011933 if (DEBUG_HISTORY) {
11934 StringBuilder sb = new StringBuilder(128);
11935 sb.append("****************** ADJUSTED mHistoryBaseTime: ");
11936 TimeUtils.formatDuration(mHistoryBaseTime, sb);
11937 Slog.i(TAG, sb.toString());
11938 }
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -070011939 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070011940 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011941
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011942 void readOldHistory(Parcel in) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070011943 if (!USE_OLD_HISTORY) {
11944 return;
11945 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011946 mHistory = mHistoryEnd = mHistoryCache = null;
11947 long time;
Conley Owens5e3357f2011-05-02 09:59:30 -070011948 while (in.dataAvail() > 0 && (time=in.readLong()) >= 0) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011949 HistoryItem rec = new HistoryItem(time, in);
11950 addHistoryRecordLocked(rec);
11951 }
11952 }
11953
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011954 void writeHistory(Parcel out, boolean inclData, boolean andOldHistory) {
Dianne Hackbornae384452011-06-28 12:33:48 -070011955 if (DEBUG_HISTORY) {
11956 StringBuilder sb = new StringBuilder(128);
11957 sb.append("****************** WRITING mHistoryBaseTime: ");
11958 TimeUtils.formatDuration(mHistoryBaseTime, sb);
Dianne Hackborn40c87252014-03-19 16:55:40 -070011959 sb.append(" mLastHistoryElapsedRealtime: ");
11960 TimeUtils.formatDuration(mLastHistoryElapsedRealtime, sb);
Dianne Hackbornae384452011-06-28 12:33:48 -070011961 Slog.i(TAG, sb.toString());
11962 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070011963 out.writeLong(mHistoryBaseTime + mLastHistoryElapsedRealtime);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011964 if (!inclData) {
11965 out.writeInt(0);
11966 out.writeInt(0);
11967 return;
11968 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080011969 out.writeInt(mHistoryTagPool.size());
11970 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
11971 HistoryTag tag = ent.getKey();
Dianne Hackborn099bc622014-01-22 13:39:16 -080011972 out.writeInt(ent.getValue());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080011973 out.writeString(tag.string);
11974 out.writeInt(tag.uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -080011975 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011976 out.writeInt(mHistoryBuffer.dataSize());
11977 if (DEBUG_HISTORY) Slog.i(TAG, "***************** WRITING HISTORY: "
11978 + mHistoryBuffer.dataSize() + " bytes at " + out.dataPosition());
11979 out.appendFrom(mHistoryBuffer, 0, mHistoryBuffer.dataSize());
Dianne Hackbornae384452011-06-28 12:33:48 -070011980
11981 if (andOldHistory) {
11982 writeOldHistory(out);
11983 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011984 }
11985
11986 void writeOldHistory(Parcel out) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070011987 if (!USE_OLD_HISTORY) {
11988 return;
11989 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011990 HistoryItem rec = mHistory;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070011991 while (rec != null) {
11992 if (rec.time >= 0) rec.writeToParcel(out, 0);
11993 rec = rec.next;
11994 }
11995 out.writeLong(-1);
11996 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011997
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011998 public void readSummaryFromParcel(Parcel in) throws ParcelFormatException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011999 final int version = in.readInt();
12000 if (version != VERSION) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070012001 Slog.w("BatteryStats", "readFromParcel: version got " + version
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012002 + ", expected " + VERSION + "; erasing old stats");
12003 return;
12004 }
12005
Dianne Hackbornae384452011-06-28 12:33:48 -070012006 readHistory(in, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012008 mStartCount = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012009 mUptime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012010 mRealtime = in.readLong();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080012011 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070012012 mStartPlatformVersion = in.readString();
12013 mEndPlatformVersion = in.readString();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012014 mOnBatteryTimeBase.readSummaryFromParcel(in);
12015 mOnBatteryScreenOffTimeBase.readSummaryFromParcel(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012016 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012017 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070012018 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012019 mCurrentBatteryLevel = in.readInt();
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012020 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070012021 mMinLearnedBatteryCapacity = in.readInt();
12022 mMaxLearnedBatteryCapacity = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012023 mLowDischargeAmountSinceCharge = in.readInt();
12024 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012025 mDischargeAmountScreenOnSinceCharge = in.readInt();
12026 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070012027 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012028 mDischargeStepTracker.readFromParcel(in);
12029 mChargeStepTracker.readFromParcel(in);
12030 mDailyDischargeStepTracker.readFromParcel(in);
12031 mDailyChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012032 mDischargeCounter.readSummaryFromParcelLocked(in);
12033 mDischargeScreenOffCounter.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070012034 mDischargeScreenDozeCounter.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070012035 int NPKG = in.readInt();
12036 if (NPKG > 0) {
12037 mDailyPackageChanges = new ArrayList<>(NPKG);
12038 while (NPKG > 0) {
12039 NPKG--;
12040 PackageChange pc = new PackageChange();
12041 pc.mPackageName = in.readString();
12042 pc.mUpdate = in.readInt() != 0;
12043 pc.mVersionCode = in.readInt();
12044 mDailyPackageChanges.add(pc);
12045 }
12046 } else {
12047 mDailyPackageChanges = null;
12048 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012049 mDailyStartTime = in.readLong();
12050 mNextMinDailyDeadline = in.readLong();
12051 mNextMaxDailyDeadline = in.readLong();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012052
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012053 mStartCount++;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012054
Jeff Browne95c3cd2014-05-02 16:59:26 -070012055 mScreenState = Display.STATE_UNKNOWN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012056 mScreenOnTimer.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070012057 mScreenDozeTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn617f8772009-03-31 15:04:46 -070012058 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
12059 mScreenBrightnessTimer[i].readSummaryFromParcelLocked(in);
12060 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070012061 mInteractive = false;
12062 mInteractiveTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012063 mPhoneOn = false;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070012064 mPowerSaveModeEnabledTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070012065 mLongestLightIdleTime = in.readLong();
12066 mLongestFullIdleTime = in.readLong();
12067 mDeviceIdleModeLightTimer.readSummaryFromParcelLocked(in);
12068 mDeviceIdleModeFullTimer.readSummaryFromParcelLocked(in);
12069 mDeviceLightIdlingTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070012070 mDeviceIdlingTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012071 mPhoneOnTimer.readSummaryFromParcelLocked(in);
Wink Saville52840902011-02-18 12:40:47 -080012072 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn627bba72009-03-24 22:32:56 -070012073 mPhoneSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
12074 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070012075 mPhoneSignalScanningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn627bba72009-03-24 22:32:56 -070012076 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
12077 mPhoneDataConnectionsTimer[i].readSummaryFromParcelLocked(in);
12078 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070012079 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080012080 mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
12081 mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070012082 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012083 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborne13c4c02014-02-11 17:18:35 -080012084 mMobileRadioActiveTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080012085 mMobileRadioActivePerAppTimer.readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012086 mMobileRadioActiveAdjustedTime.readSummaryFromParcelLocked(in);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080012087 mMobileRadioActiveUnknownTime.readSummaryFromParcelLocked(in);
12088 mMobileRadioActiveUnknownCount.readSummaryFromParcelLocked(in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012089 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
The Android Open Source Project10592532009-03-18 17:39:46 -070012090 mWifiOn = false;
12091 mWifiOnTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070012092 mGlobalWifiRunning = false;
12093 mGlobalWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080012094 for (int i=0; i<NUM_WIFI_STATES; i++) {
12095 mWifiStateTimer[i].readSummaryFromParcelLocked(in);
12096 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070012097 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
12098 mWifiSupplStateTimer[i].readSummaryFromParcelLocked(in);
12099 }
12100 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
12101 mWifiSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
12102 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080012103 mWifiActivity.readSummaryFromParcel(in);
12104 mBluetoothActivity.readSummaryFromParcel(in);
12105 mModemActivity.readSummaryFromParcel(in);
12106 mHasWifiReporting = in.readInt() != 0;
12107 mHasBluetoothReporting = in.readInt() != 0;
12108 mHasModemReporting = in.readInt() != 0;
Adam Lesinski33dac552015-03-09 15:24:48 -070012109
Dianne Hackborn1e01d162014-12-04 17:46:42 -080012110 mNumConnectivityChange = mLoadedNumConnectivityChange = in.readInt();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070012111 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -070012112 mFlashlightOnTimer.readSummaryFromParcelLocked(in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070012113 mCameraOnNesting = 0;
12114 mCameraOnTimer.readSummaryFromParcelLocked(in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012115 mBluetoothScanNesting = 0;
12116 mBluetoothScanTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012117
Bookatz50df7112017-08-04 14:53:26 -070012118 int NRPMS = in.readInt();
12119 if (NRPMS > 10000) {
12120 throw new ParcelFormatException("File corrupt: too many rpm stats " + NRPMS);
12121 }
12122 for (int irpm = 0; irpm < NRPMS; irpm++) {
12123 if (in.readInt() != 0) {
12124 String rpmName = in.readString();
12125 getRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
12126 }
12127 }
12128 int NSORPMS = in.readInt();
12129 if (NSORPMS > 10000) {
12130 throw new ParcelFormatException("File corrupt: too many screen-off rpm stats " + NSORPMS);
12131 }
12132 for (int irpm = 0; irpm < NSORPMS; irpm++) {
12133 if (in.readInt() != 0) {
12134 String rpmName = in.readString();
12135 getScreenOffRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
12136 }
12137 }
12138
Evan Millarc64edde2009-04-18 12:26:32 -070012139 int NKW = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070012140 if (NKW > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070012141 throw new ParcelFormatException("File corrupt: too many kernel wake locks " + NKW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070012142 }
Evan Millarc64edde2009-04-18 12:26:32 -070012143 for (int ikw = 0; ikw < NKW; ikw++) {
12144 if (in.readInt() != 0) {
12145 String kwltName = in.readString();
12146 getKernelWakelockTimerLocked(kwltName).readSummaryFromParcelLocked(in);
12147 }
12148 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070012149
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012150 int NWR = in.readInt();
12151 if (NWR > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070012152 throw new ParcelFormatException("File corrupt: too many wakeup reasons " + NWR);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012153 }
12154 for (int iwr = 0; iwr < NWR; iwr++) {
12155 if (in.readInt() != 0) {
12156 String reasonName = in.readString();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070012157 getWakeupReasonTimerLocked(reasonName).readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012158 }
12159 }
12160
James Carr3a226052016-07-01 14:49:52 -070012161 int NMS = in.readInt();
12162 for (int ims = 0; ims < NMS; ims++) {
12163 if (in.readInt() != 0) {
12164 long kmstName = in.readLong();
12165 getKernelMemoryTimerLocked(kmstName).readSummaryFromParcelLocked(in);
12166 }
12167 }
12168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012169 final int NU = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070012170 if (NU > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070012171 throw new ParcelFormatException("File corrupt: too many uids " + NU);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070012172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012173 for (int iu = 0; iu < NU; iu++) {
12174 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080012175 Uid u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012176 mUidStats.put(uid, u);
12177
Bookatz867c0d72017-03-07 18:23:42 -080012178 u.mOnBatteryBackgroundTimeBase.readSummaryFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -070012179 u.mOnBatteryScreenOffBackgroundTimeBase.readSummaryFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -080012180
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070012181 u.mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012182 if (in.readInt() != 0) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070012183 u.mWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012184 }
The Android Open Source Project10592532009-03-18 17:39:46 -070012185 u.mFullWifiLockOut = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012186 if (in.readInt() != 0) {
12187 u.mFullWifiLockTimer.readSummaryFromParcelLocked(in);
12188 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070012189 u.mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012190 if (in.readInt() != 0) {
Nick Pelly6ccaa542012-06-15 15:22:47 -070012191 u.mWifiScanTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012192 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070012193 u.mWifiBatchedScanBinStarted = Uid.NO_BATCHED_SCAN_STARTED;
12194 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
12195 if (in.readInt() != 0) {
12196 u.makeWifiBatchedScanBin(i, null);
12197 u.mWifiBatchedScanTimer[i].readSummaryFromParcelLocked(in);
12198 }
12199 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070012200 u.mWifiMulticastEnabled = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012201 if (in.readInt() != 0) {
12202 u.mWifiMulticastTimer.readSummaryFromParcelLocked(in);
12203 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012204 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080012205 u.createAudioTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012206 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012207 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080012208 u.createVideoTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
12209 }
12210 if (in.readInt() != 0) {
Ruben Brunk6d2c3632015-05-26 17:32:16 -070012211 u.createFlashlightTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
12212 }
12213 if (in.readInt() != 0) {
12214 u.createCameraTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
12215 }
12216 if (in.readInt() != 0) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -070012217 u.createForegroundActivityTimerLocked().readSummaryFromParcelLocked(in);
12218 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012219 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070012220 u.createForegroundServiceTimerLocked().readSummaryFromParcelLocked(in);
12221 }
12222 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -070012223 u.createAggregatedPartialWakelockTimerLocked().readSummaryFromParcelLocked(in);
12224 }
12225 if (in.readInt() != 0) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012226 u.createBluetoothScanTimerLocked().readSummaryFromParcelLocked(in);
12227 }
Bookatz956f36bf2017-04-28 09:48:17 -070012228 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -070012229 u.createBluetoothUnoptimizedScanTimerLocked().readSummaryFromParcelLocked(in);
12230 }
12231 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -070012232 u.createBluetoothScanResultCounterLocked().readSummaryFromParcelLocked(in);
12233 }
Bookatzb1f04f32017-05-19 13:57:32 -070012234 if (in.readInt() != 0) {
12235 u.createBluetoothScanResultBgCounterLocked().readSummaryFromParcelLocked(in);
12236 }
Dianne Hackborna8d10942015-11-19 17:55:19 -080012237 u.mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -070012238 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
12239 if (in.readInt() != 0) {
12240 u.makeProcessState(i, null);
12241 u.mProcessStateTimer[i].readSummaryFromParcelLocked(in);
12242 }
12243 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070012244 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080012245 u.createVibratorOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012246 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070012247
Dianne Hackborn617f8772009-03-31 15:04:46 -070012248 if (in.readInt() != 0) {
12249 if (u.mUserActivityCounters == null) {
12250 u.initUserActivityLocked();
12251 }
12252 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
12253 u.mUserActivityCounters[i].readSummaryFromParcelLocked(in);
12254 }
12255 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012256
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070012257 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080012258 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070012259 u.initNetworkActivityLocked();
12260 }
12261 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080012262 u.mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
12263 u.mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070012264 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080012265 u.mMobileRadioActiveTime.readSummaryFromParcelLocked(in);
12266 u.mMobileRadioActiveCount.readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070012267 }
12268
Adam Lesinski06af1fa2015-05-05 17:35:35 -070012269 u.mUserCpuTime.readSummaryFromParcelLocked(in);
12270 u.mSystemCpuTime.readSummaryFromParcelLocked(in);
12271
Adam Lesinski6832f392015-09-05 18:05:40 -070012272 if (in.readInt() != 0) {
12273 final int numClusters = in.readInt();
12274 if (mPowerProfile != null && mPowerProfile.getNumCpuClusters() != numClusters) {
12275 throw new ParcelFormatException("Incompatible cpu cluster arrangement");
Adam Lesinski06af1fa2015-05-05 17:35:35 -070012276 }
Adam Lesinski6832f392015-09-05 18:05:40 -070012277
Sudheer Shankaaf857412017-07-21 00:14:24 -070012278 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -070012279 for (int cluster = 0; cluster < numClusters; cluster++) {
Adam Lesinski6832f392015-09-05 18:05:40 -070012280 if (in.readInt() != 0) {
Adam Lesinskia57a5402015-09-28 10:21:33 -070012281 final int NSB = in.readInt();
12282 if (mPowerProfile != null &&
12283 mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != NSB) {
12284 throw new ParcelFormatException("File corrupt: too many speed bins " +
12285 NSB);
12286 }
12287
Sudheer Shankaaf857412017-07-21 00:14:24 -070012288 u.mCpuClusterSpeedTimesUs[cluster] = new LongSamplingCounter[NSB];
Adam Lesinski6832f392015-09-05 18:05:40 -070012289 for (int speed = 0; speed < NSB; speed++) {
12290 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012291 u.mCpuClusterSpeedTimesUs[cluster][speed] = new LongSamplingCounter(
Adam Lesinski6832f392015-09-05 18:05:40 -070012292 mOnBatteryTimeBase);
Sudheer Shankaaf857412017-07-21 00:14:24 -070012293 u.mCpuClusterSpeedTimesUs[cluster][speed].readSummaryFromParcelLocked(in);
Adam Lesinski6832f392015-09-05 18:05:40 -070012294 }
12295 }
Adam Lesinskia57a5402015-09-28 10:21:33 -070012296 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012297 u.mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -070012298 }
12299 }
12300 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012301 u.mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -070012302 }
12303
Sudheer Shanka59f5c002017-05-15 10:57:15 -070012304 u.mCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
12305 in, mOnBatteryTimeBase);
12306 u.mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
12307 in, mOnBatteryScreenOffTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012308
12309 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -070012310 u.mMobileRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
12311 u.mMobileRadioApWakeupCount.readSummaryFromParcelLocked(in);
12312 } else {
12313 u.mMobileRadioApWakeupCount = null;
12314 }
12315
12316 if (in.readInt() != 0) {
12317 u.mWifiRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
12318 u.mWifiRadioApWakeupCount.readSummaryFromParcelLocked(in);
12319 } else {
12320 u.mWifiRadioApWakeupCount = null;
12321 }
12322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012323 int NW = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070012324 if (NW > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070012325 throw new ParcelFormatException("File corrupt: too many wake locks " + NW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070012326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012327 for (int iw = 0; iw < NW; iw++) {
12328 String wlName = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070012329 u.readWakeSummaryFromParcelLocked(wlName, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012330 }
12331
Dianne Hackbornfdb19562014-07-11 16:03:36 -070012332 int NS = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070012333 if (NS > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070012334 throw new ParcelFormatException("File corrupt: too many syncs " + NS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070012335 }
12336 for (int is = 0; is < NS; is++) {
12337 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070012338 u.readSyncSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070012339 }
12340
12341 int NJ = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070012342 if (NJ > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070012343 throw new ParcelFormatException("File corrupt: too many job timers " + NJ);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070012344 }
12345 for (int ij = 0; ij < NJ; ij++) {
12346 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070012347 u.readJobSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070012348 }
12349
Dianne Hackborn94326cb2017-06-28 16:17:20 -070012350 u.readJobCompletionsFromParcelLocked(in);
12351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012352 int NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080012353 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070012354 throw new ParcelFormatException("File corrupt: too many sensors " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070012355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012356 for (int is = 0; is < NP; is++) {
12357 int seNumber = in.readInt();
12358 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -080012359 u.getSensorTimerLocked(seNumber, true).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012360 }
12361 }
12362
12363 NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080012364 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070012365 throw new ParcelFormatException("File corrupt: too many processes " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070012366 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012367 for (int ip = 0; ip < NP; ip++) {
12368 String procName = in.readString();
12369 Uid.Proc p = u.getProcessStatsLocked(procName);
12370 p.mUserTime = p.mLoadedUserTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012371 p.mSystemTime = p.mLoadedSystemTime = in.readLong();
Jeff Sharkey3e013e82013-04-25 14:48:19 -070012372 p.mForegroundTime = p.mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012373 p.mStarts = p.mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -080012374 p.mNumCrashes = p.mLoadedNumCrashes = in.readInt();
12375 p.mNumAnrs = p.mLoadedNumAnrs = in.readInt();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070012376 p.readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012377 }
12378
12379 NP = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070012380 if (NP > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070012381 throw new ParcelFormatException("File corrupt: too many packages " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070012382 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012383 for (int ip = 0; ip < NP; ip++) {
12384 String pkgName = in.readString();
12385 Uid.Pkg p = u.getPackageStatsLocked(pkgName);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070012386 final int NWA = in.readInt();
12387 if (NWA > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070012388 throw new ParcelFormatException("File corrupt: too many wakeup alarms " + NWA);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070012389 }
12390 p.mWakeupAlarms.clear();
12391 for (int iwa=0; iwa<NWA; iwa++) {
12392 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -070012393 Counter c = new Counter(mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070012394 c.readSummaryFromParcelLocked(in);
12395 p.mWakeupAlarms.put(tag, c);
12396 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070012397 NS = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080012398 if (NS > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070012399 throw new ParcelFormatException("File corrupt: too many services " + NS);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080012400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012401 for (int is = 0; is < NS; is++) {
12402 String servName = in.readString();
12403 Uid.Pkg.Serv s = u.getServiceStatsLocked(pkgName, servName);
12404 s.mStartTime = s.mLoadedStartTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012405 s.mStarts = s.mLoadedStarts = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012406 s.mLaunches = s.mLoadedLaunches = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012407 }
12408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012409 }
12410 }
12411
12412 /**
12413 * Writes a summary of the statistics to a Parcel, in a format suitable to be written to
12414 * disk. This format does not allow a lossless round-trip.
12415 *
12416 * @param out the Parcel to be written to.
12417 */
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012418 public void writeSummaryToParcel(Parcel out, boolean inclHistory) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080012419 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070012420
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012421 // Pull the clock time. This may update the time and make a new history entry
12422 // if we had originally pulled a time before the RTC was set.
12423 long startClockTime = getStartClockTime();
12424
Joe Onoratoabded112016-02-08 16:49:39 -080012425 final long NOW_SYS = mClocks.uptimeMillis() * 1000;
12426 final long NOWREAL_SYS = mClocks.elapsedRealtime() * 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012427
12428 out.writeInt(VERSION);
12429
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012430 writeHistory(out, inclHistory, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012432 out.writeInt(mStartCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012433 out.writeLong(computeUptime(NOW_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012434 out.writeLong(computeRealtime(NOWREAL_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012435 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070012436 out.writeString(mStartPlatformVersion);
12437 out.writeString(mEndPlatformVersion);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012438 mOnBatteryTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
12439 mOnBatteryScreenOffTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012440 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012441 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070012442 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012443 out.writeInt(mCurrentBatteryLevel);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012444 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070012445 out.writeInt(mMinLearnedBatteryCapacity);
12446 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborne4a59512010-12-07 11:08:07 -080012447 out.writeInt(getLowDischargeAmountSinceCharge());
12448 out.writeInt(getHighDischargeAmountSinceCharge());
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012449 out.writeInt(getDischargeAmountScreenOnSinceCharge());
12450 out.writeInt(getDischargeAmountScreenOffSinceCharge());
Mike Mac2f518a2017-09-19 16:06:03 -070012451 out.writeInt(getDischargeAmountScreenDozeSinceCharge());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012452 mDischargeStepTracker.writeToParcel(out);
12453 mChargeStepTracker.writeToParcel(out);
12454 mDailyDischargeStepTracker.writeToParcel(out);
12455 mDailyChargeStepTracker.writeToParcel(out);
Adam Lesinski67c134f2016-06-10 15:15:08 -070012456 mDischargeCounter.writeSummaryFromParcelLocked(out);
12457 mDischargeScreenOffCounter.writeSummaryFromParcelLocked(out);
Mike Mac2f518a2017-09-19 16:06:03 -070012458 mDischargeScreenDozeCounter.writeSummaryFromParcelLocked(out);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070012459 if (mDailyPackageChanges != null) {
12460 final int NPKG = mDailyPackageChanges.size();
12461 out.writeInt(NPKG);
12462 for (int i=0; i<NPKG; i++) {
12463 PackageChange pc = mDailyPackageChanges.get(i);
12464 out.writeString(pc.mPackageName);
12465 out.writeInt(pc.mUpdate ? 1 : 0);
12466 out.writeInt(pc.mVersionCode);
12467 }
12468 } else {
12469 out.writeInt(0);
12470 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012471 out.writeLong(mDailyStartTime);
12472 out.writeLong(mNextMinDailyDeadline);
12473 out.writeLong(mNextMaxDailyDeadline);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012474
12475 mScreenOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Mike Mac2f518a2017-09-19 16:06:03 -070012476 mScreenDozeTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070012477 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012478 mScreenBrightnessTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070012479 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070012480 mInteractiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070012481 mPowerSaveModeEnabledTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070012482 out.writeLong(mLongestLightIdleTime);
12483 out.writeLong(mLongestFullIdleTime);
12484 mDeviceIdleModeLightTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12485 mDeviceIdleModeFullTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12486 mDeviceLightIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070012487 mDeviceIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012488 mPhoneOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Wink Saville52840902011-02-18 12:40:47 -080012489 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012490 mPhoneSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070012491 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012492 mPhoneSignalScanningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070012493 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012494 mPhoneDataConnectionsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070012495 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070012496 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080012497 mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
12498 mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070012499 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012500 mMobileRadioActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12501 mMobileRadioActivePerAppTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012502 mMobileRadioActiveAdjustedTime.writeSummaryFromParcelLocked(out);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080012503 mMobileRadioActiveUnknownTime.writeSummaryFromParcelLocked(out);
12504 mMobileRadioActiveUnknownCount.writeSummaryFromParcelLocked(out);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012505 mWifiOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12506 mGlobalWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080012507 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012508 mWifiStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080012509 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070012510 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
12511 mWifiSupplStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12512 }
12513 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
12514 mWifiSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12515 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080012516 mWifiActivity.writeSummaryToParcel(out);
12517 mBluetoothActivity.writeSummaryToParcel(out);
12518 mModemActivity.writeSummaryToParcel(out);
12519 out.writeInt(mHasWifiReporting ? 1 : 0);
12520 out.writeInt(mHasBluetoothReporting ? 1 : 0);
12521 out.writeInt(mHasModemReporting ? 1 : 0);
12522
Dianne Hackborn1e01d162014-12-04 17:46:42 -080012523 out.writeInt(mNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070012524 mFlashlightOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070012525 mCameraOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012526 mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012527
Bookatz50df7112017-08-04 14:53:26 -070012528 out.writeInt(mRpmStats.size());
12529 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
12530 Timer rpmt = ent.getValue();
12531 if (rpmt != null) {
12532 out.writeInt(1);
12533 out.writeString(ent.getKey());
12534 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12535 } else {
12536 out.writeInt(0);
12537 }
12538 }
12539 out.writeInt(mScreenOffRpmStats.size());
12540 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
12541 Timer rpmt = ent.getValue();
12542 if (rpmt != null) {
12543 out.writeInt(1);
12544 out.writeString(ent.getKey());
12545 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12546 } else {
12547 out.writeInt(0);
12548 }
12549 }
12550
Evan Millarc64edde2009-04-18 12:26:32 -070012551 out.writeInt(mKernelWakelockStats.size());
12552 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
12553 Timer kwlt = ent.getValue();
12554 if (kwlt != null) {
12555 out.writeInt(1);
12556 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012557 kwlt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12558 } else {
12559 out.writeInt(0);
12560 }
12561 }
12562
12563 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070012564 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
12565 SamplingTimer timer = ent.getValue();
12566 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012567 out.writeInt(1);
12568 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070012569 timer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Evan Millarc64edde2009-04-18 12:26:32 -070012570 } else {
12571 out.writeInt(0);
12572 }
12573 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012574
James Carr3a226052016-07-01 14:49:52 -070012575 out.writeInt(mKernelMemoryStats.size());
12576 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
12577 Timer kmt = mKernelMemoryStats.valueAt(i);
12578 if (kmt != null) {
12579 out.writeInt(1);
12580 out.writeLong(mKernelMemoryStats.keyAt(i));
12581 kmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12582 } else {
12583 out.writeInt(0);
12584 }
12585 }
12586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012587 final int NU = mUidStats.size();
12588 out.writeInt(NU);
12589 for (int iu = 0; iu < NU; iu++) {
12590 out.writeInt(mUidStats.keyAt(iu));
12591 Uid u = mUidStats.valueAt(iu);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012592
Bookatz867c0d72017-03-07 18:23:42 -080012593 u.mOnBatteryBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatzc8c44962017-05-11 12:12:54 -070012594 u.mOnBatteryScreenOffBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatz867c0d72017-03-07 18:23:42 -080012595
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070012596 if (u.mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012597 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012598 u.mWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012599 } else {
12600 out.writeInt(0);
12601 }
12602 if (u.mFullWifiLockTimer != null) {
12603 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012604 u.mFullWifiLockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012605 } else {
12606 out.writeInt(0);
12607 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070012608 if (u.mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012609 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012610 u.mWifiScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012611 } else {
12612 out.writeInt(0);
12613 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070012614 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
12615 if (u.mWifiBatchedScanTimer[i] != null) {
12616 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012617 u.mWifiBatchedScanTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Robert Greenwalta029ea12013-09-25 16:38:12 -070012618 } else {
12619 out.writeInt(0);
12620 }
12621 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012622 if (u.mWifiMulticastTimer != null) {
12623 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012624 u.mWifiMulticastTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012625 } else {
12626 out.writeInt(0);
12627 }
12628 if (u.mAudioTurnedOnTimer != null) {
12629 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012630 u.mAudioTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012631 } else {
12632 out.writeInt(0);
12633 }
12634 if (u.mVideoTurnedOnTimer != null) {
12635 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012636 u.mVideoTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012637 } else {
12638 out.writeInt(0);
12639 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -070012640 if (u.mFlashlightTurnedOnTimer != null) {
12641 out.writeInt(1);
12642 u.mFlashlightTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12643 } else {
12644 out.writeInt(0);
12645 }
12646 if (u.mCameraTurnedOnTimer != null) {
12647 out.writeInt(1);
12648 u.mCameraTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12649 } else {
12650 out.writeInt(0);
12651 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070012652 if (u.mForegroundActivityTimer != null) {
12653 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012654 u.mForegroundActivityTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Jeff Sharkey3e013e82013-04-25 14:48:19 -070012655 } else {
12656 out.writeInt(0);
12657 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070012658 if (u.mForegroundServiceTimer != null) {
12659 out.writeInt(1);
12660 u.mForegroundServiceTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12661 } else {
12662 out.writeInt(0);
12663 }
Bookatzc8c44962017-05-11 12:12:54 -070012664 if (u.mAggregatedPartialWakelockTimer != null) {
12665 out.writeInt(1);
12666 u.mAggregatedPartialWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12667 } else {
12668 out.writeInt(0);
12669 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012670 if (u.mBluetoothScanTimer != null) {
12671 out.writeInt(1);
12672 u.mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12673 } else {
12674 out.writeInt(0);
12675 }
Bookatzb1f04f32017-05-19 13:57:32 -070012676 if (u.mBluetoothUnoptimizedScanTimer != null) {
12677 out.writeInt(1);
12678 u.mBluetoothUnoptimizedScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12679 } else {
12680 out.writeInt(0);
12681 }
Bookatz956f36bf2017-04-28 09:48:17 -070012682 if (u.mBluetoothScanResultCounter != null) {
12683 out.writeInt(1);
12684 u.mBluetoothScanResultCounter.writeSummaryFromParcelLocked(out);
12685 } else {
12686 out.writeInt(0);
12687 }
Bookatzb1f04f32017-05-19 13:57:32 -070012688 if (u.mBluetoothScanResultBgCounter != null) {
12689 out.writeInt(1);
12690 u.mBluetoothScanResultBgCounter.writeSummaryFromParcelLocked(out);
12691 } else {
12692 out.writeInt(0);
12693 }
Dianne Hackborn61659e52014-07-09 16:13:01 -070012694 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
12695 if (u.mProcessStateTimer[i] != null) {
12696 out.writeInt(1);
12697 u.mProcessStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12698 } else {
12699 out.writeInt(0);
12700 }
12701 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -080012702 if (u.mVibratorOnTimer != null) {
12703 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012704 u.mVibratorOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna06de0f2012-12-11 16:34:47 -080012705 } else {
12706 out.writeInt(0);
12707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012708
Dianne Hackborn617f8772009-03-31 15:04:46 -070012709 if (u.mUserActivityCounters == null) {
12710 out.writeInt(0);
12711 } else {
12712 out.writeInt(1);
12713 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
12714 u.mUserActivityCounters[i].writeSummaryFromParcelLocked(out);
12715 }
12716 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012717
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080012718 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070012719 out.writeInt(0);
12720 } else {
12721 out.writeInt(1);
12722 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080012723 u.mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
12724 u.mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070012725 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080012726 u.mMobileRadioActiveTime.writeSummaryFromParcelLocked(out);
12727 u.mMobileRadioActiveCount.writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070012728 }
12729
Adam Lesinski06af1fa2015-05-05 17:35:35 -070012730 u.mUserCpuTime.writeSummaryFromParcelLocked(out);
12731 u.mSystemCpuTime.writeSummaryFromParcelLocked(out);
12732
Sudheer Shankaaf857412017-07-21 00:14:24 -070012733 if (u.mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -070012734 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -070012735 out.writeInt(u.mCpuClusterSpeedTimesUs.length);
12736 for (LongSamplingCounter[] cpuSpeeds : u.mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -070012737 if (cpuSpeeds != null) {
12738 out.writeInt(1);
12739 out.writeInt(cpuSpeeds.length);
12740 for (LongSamplingCounter c : cpuSpeeds) {
12741 if (c != null) {
12742 out.writeInt(1);
12743 c.writeSummaryFromParcelLocked(out);
12744 } else {
12745 out.writeInt(0);
12746 }
12747 }
12748 } else {
12749 out.writeInt(0);
12750 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070012751 }
Adam Lesinski6832f392015-09-05 18:05:40 -070012752 } else {
12753 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070012754 }
12755
Sudheer Shanka59f5c002017-05-15 10:57:15 -070012756 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mCpuFreqTimeMs);
12757 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mScreenOffCpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012758
Adam Lesinski5f056f62016-07-14 16:56:08 -070012759 if (u.mMobileRadioApWakeupCount != null) {
12760 out.writeInt(1);
12761 u.mMobileRadioApWakeupCount.writeSummaryFromParcelLocked(out);
12762 } else {
12763 out.writeInt(0);
12764 }
12765
12766 if (u.mWifiRadioApWakeupCount != null) {
12767 out.writeInt(1);
12768 u.mWifiRadioApWakeupCount.writeSummaryFromParcelLocked(out);
12769 } else {
12770 out.writeInt(0);
12771 }
12772
Dianne Hackbornd953c532014-08-16 18:17:38 -070012773 final ArrayMap<String, Uid.Wakelock> wakeStats = u.mWakelockStats.getMap();
12774 int NW = wakeStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012775 out.writeInt(NW);
Dianne Hackborn61659e52014-07-09 16:13:01 -070012776 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070012777 out.writeString(wakeStats.keyAt(iw));
12778 Uid.Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -070012779 if (wl.mTimerFull != null) {
12780 out.writeInt(1);
12781 wl.mTimerFull.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12782 } else {
12783 out.writeInt(0);
12784 }
12785 if (wl.mTimerPartial != null) {
12786 out.writeInt(1);
12787 wl.mTimerPartial.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12788 } else {
12789 out.writeInt(0);
12790 }
12791 if (wl.mTimerWindow != null) {
12792 out.writeInt(1);
12793 wl.mTimerWindow.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12794 } else {
12795 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012796 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070012797 if (wl.mTimerDraw != null) {
Adam Lesinski9425fe22015-06-19 12:02:13 -070012798 out.writeInt(1);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070012799 wl.mTimerDraw.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9425fe22015-06-19 12:02:13 -070012800 } else {
12801 out.writeInt(0);
12802 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012803 }
12804
Bookatz2bffb5b2017-04-13 11:59:33 -070012805 final ArrayMap<String, DualTimer> syncStats = u.mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070012806 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070012807 out.writeInt(NS);
12808 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070012809 out.writeString(syncStats.keyAt(is));
12810 syncStats.valueAt(is).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070012811 }
12812
Bookatzaa4594a2017-03-24 12:39:56 -070012813 final ArrayMap<String, DualTimer> jobStats = u.mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070012814 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070012815 out.writeInt(NJ);
12816 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070012817 out.writeString(jobStats.keyAt(ij));
12818 jobStats.valueAt(ij).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070012819 }
12820
Dianne Hackborn94326cb2017-06-28 16:17:20 -070012821 u.writeJobCompletionsToParcelLocked(out);
12822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012823 int NSE = u.mSensorStats.size();
12824 out.writeInt(NSE);
Dianne Hackborn61659e52014-07-09 16:13:01 -070012825 for (int ise=0; ise<NSE; ise++) {
12826 out.writeInt(u.mSensorStats.keyAt(ise));
12827 Uid.Sensor se = u.mSensorStats.valueAt(ise);
12828 if (se.mTimer != null) {
12829 out.writeInt(1);
12830 se.mTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12831 } else {
12832 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012833 }
12834 }
12835
12836 int NP = u.mProcessStats.size();
12837 out.writeInt(NP);
Dianne Hackborn61659e52014-07-09 16:13:01 -070012838 for (int ip=0; ip<NP; ip++) {
12839 out.writeString(u.mProcessStats.keyAt(ip));
12840 Uid.Proc ps = u.mProcessStats.valueAt(ip);
12841 out.writeLong(ps.mUserTime);
12842 out.writeLong(ps.mSystemTime);
12843 out.writeLong(ps.mForegroundTime);
12844 out.writeInt(ps.mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080012845 out.writeInt(ps.mNumCrashes);
12846 out.writeInt(ps.mNumAnrs);
Dianne Hackborn61659e52014-07-09 16:13:01 -070012847 ps.writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012848 }
12849
12850 NP = u.mPackageStats.size();
12851 out.writeInt(NP);
12852 if (NP > 0) {
12853 for (Map.Entry<String, BatteryStatsImpl.Uid.Pkg> ent
12854 : u.mPackageStats.entrySet()) {
12855 out.writeString(ent.getKey());
12856 Uid.Pkg ps = ent.getValue();
Dianne Hackborn1e725a72015-03-24 18:23:19 -070012857 final int NWA = ps.mWakeupAlarms.size();
12858 out.writeInt(NWA);
12859 for (int iwa=0; iwa<NWA; iwa++) {
12860 out.writeString(ps.mWakeupAlarms.keyAt(iwa));
12861 ps.mWakeupAlarms.valueAt(iwa).writeSummaryFromParcelLocked(out);
12862 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070012863 NS = ps.mServiceStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012864 out.writeInt(NS);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070012865 for (int is=0; is<NS; is++) {
12866 out.writeString(ps.mServiceStats.keyAt(is));
12867 BatteryStatsImpl.Uid.Pkg.Serv ss = ps.mServiceStats.valueAt(is);
12868 long time = ss.getStartTimeToNowLocked(
12869 mOnBatteryTimeBase.getUptime(NOW_SYS));
12870 out.writeLong(time);
12871 out.writeInt(ss.mStarts);
12872 out.writeInt(ss.mLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012873 }
12874 }
12875 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012876 }
12877 }
12878
12879 public void readFromParcel(Parcel in) {
12880 readFromParcelLocked(in);
12881 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012883 void readFromParcelLocked(Parcel in) {
12884 int magic = in.readInt();
12885 if (magic != MAGIC) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -070012886 throw new ParcelFormatException("Bad magic number: #" + Integer.toHexString(magic));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012887 }
12888
Dianne Hackbornae384452011-06-28 12:33:48 -070012889 readHistory(in, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012891 mStartCount = in.readInt();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080012892 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070012893 mStartPlatformVersion = in.readString();
12894 mEndPlatformVersion = in.readString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012895 mUptime = in.readLong();
12896 mUptimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012897 mRealtime = in.readLong();
12898 mRealtimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012899 mOnBattery = in.readInt() != 0;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012900 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070012901 mMinLearnedBatteryCapacity = in.readInt();
12902 mMaxLearnedBatteryCapacity = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012903 mOnBatteryInternal = false; // we are no longer really running.
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012904 mOnBatteryTimeBase.readFromParcel(in);
12905 mOnBatteryScreenOffTimeBase.readFromParcel(in);
12906
Jeff Browne95c3cd2014-05-02 16:59:26 -070012907 mScreenState = Display.STATE_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080012908 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070012909 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012910 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080012911 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
12912 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012913 }
Dianne Hackborn29325132014-05-21 15:01:03 -070012914 mInteractive = false;
Joe Onoratoabded112016-02-08 16:49:39 -080012915 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012916 mPhoneOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080012917 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
12918 mOnBatteryTimeBase, in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070012919 mLongestLightIdleTime = in.readLong();
12920 mLongestFullIdleTime = in.readLong();
Joe Onoratoabded112016-02-08 16:49:39 -080012921 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -14, null,
12922 mOnBatteryTimeBase, in);
12923 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -11, null,
12924 mOnBatteryTimeBase, in);
12925 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null,
12926 mOnBatteryTimeBase, in);
12927 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase, in);
12928 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012929 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080012930 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012931 null, mOnBatteryTimeBase, in);
12932 }
Joe Onoratoabded112016-02-08 16:49:39 -080012933 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
12934 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012935 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080012936 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012937 null, mOnBatteryTimeBase, in);
12938 }
12939 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
12940 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
12941 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
12942 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012943 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Joe Onoratoabded112016-02-08 16:49:39 -080012944 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null,
12945 mOnBatteryTimeBase, in);
Kweku Adams87b19ec2017-10-09 12:40:03 -070012946 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
Joe Onoratoabded112016-02-08 16:49:39 -080012947 mOnBatteryTimeBase, in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012948 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012949 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
12950 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase, in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012951 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012952 mWifiOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080012953 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012954 mGlobalWifiRunning = false;
Joe Onoratoabded112016-02-08 16:49:39 -080012955 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null,
12956 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012957 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080012958 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012959 null, mOnBatteryTimeBase, in);
12960 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070012961 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080012962 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070012963 null, mOnBatteryTimeBase, in);
12964 }
12965 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080012966 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070012967 null, mOnBatteryTimeBase, in);
12968 }
Adam Lesinski33dac552015-03-09 15:24:48 -070012969
Adam Lesinski21f76aa2016-01-25 12:27:06 -080012970 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
12971 NUM_WIFI_TX_LEVELS, in);
12972 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
12973 NUM_BT_TX_LEVELS, in);
12974 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
12975 ModemActivityInfo.TX_POWER_LEVELS, in);
12976 mHasWifiReporting = in.readInt() != 0;
12977 mHasBluetoothReporting = in.readInt() != 0;
12978 mHasModemReporting = in.readInt() != 0;
12979
Dianne Hackborn1e01d162014-12-04 17:46:42 -080012980 mNumConnectivityChange = in.readInt();
12981 mLoadedNumConnectivityChange = in.readInt();
12982 mUnpluggedNumConnectivityChange = in.readInt();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070012983 mAudioOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080012984 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
Dianne Hackborn10eaa852014-07-22 22:54:55 -070012985 mVideoOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080012986 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070012987 mFlashlightOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080012988 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070012989 mCameraOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080012990 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012991 mBluetoothScanNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080012992 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012993 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012994 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070012995 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012996 mCurrentBatteryLevel = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012997 mLowDischargeAmountSinceCharge = in.readInt();
12998 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012999 mDischargeAmountScreenOn = in.readInt();
13000 mDischargeAmountScreenOnSinceCharge = in.readInt();
13001 mDischargeAmountScreenOff = in.readInt();
13002 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070013003 mDischargeAmountScreenDoze = in.readInt();
13004 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013005 mDischargeStepTracker.readFromParcel(in);
13006 mChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070013007 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070013008 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase, in);
13009 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013010 mLastWriteTime = in.readLong();
13011
Bookatz50df7112017-08-04 14:53:26 -070013012 mRpmStats.clear();
13013 int NRPMS = in.readInt();
13014 for (int irpm = 0; irpm < NRPMS; irpm++) {
13015 if (in.readInt() != 0) {
13016 String rpmName = in.readString();
13017 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
13018 mRpmStats.put(rpmName, rpmt);
13019 }
13020 }
13021 mScreenOffRpmStats.clear();
13022 int NSORPMS = in.readInt();
13023 for (int irpm = 0; irpm < NSORPMS; irpm++) {
13024 if (in.readInt() != 0) {
13025 String rpmName = in.readString();
13026 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
13027 mScreenOffRpmStats.put(rpmName, rpmt);
13028 }
13029 }
13030
Evan Millarc64edde2009-04-18 12:26:32 -070013031 mKernelWakelockStats.clear();
13032 int NKW = in.readInt();
13033 for (int ikw = 0; ikw < NKW; ikw++) {
13034 if (in.readInt() != 0) {
13035 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080013036 SamplingTimer kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -070013037 mKernelWakelockStats.put(wakelockName, kwlt);
13038 }
13039 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013040
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013041 mWakeupReasonStats.clear();
13042 int NWR = in.readInt();
13043 for (int iwr = 0; iwr < NWR; iwr++) {
13044 if (in.readInt() != 0) {
13045 String reasonName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080013046 SamplingTimer timer = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013047 mWakeupReasonStats.put(reasonName, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013048 }
13049 }
13050
James Carr3a226052016-07-01 14:49:52 -070013051 mKernelMemoryStats.clear();
13052 int nmt = in.readInt();
13053 for (int imt = 0; imt < nmt; imt++) {
13054 if (in.readInt() != 0) {
13055 Long bucket = in.readLong();
13056 SamplingTimer kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
13057 mKernelMemoryStats.put(bucket, kmt);
13058 }
13059 }
13060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013061 mPartialTimers.clear();
13062 mFullTimers.clear();
13063 mWindowTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013064 mWifiRunningTimers.clear();
13065 mFullWifiLockTimers.clear();
Nick Pelly6ccaa542012-06-15 15:22:47 -070013066 mWifiScanTimers.clear();
Robert Greenwalta029ea12013-09-25 16:38:12 -070013067 mWifiBatchedScanTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013068 mWifiMulticastTimers.clear();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070013069 mAudioTurnedOnTimers.clear();
13070 mVideoTurnedOnTimers.clear();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013071 mFlashlightTurnedOnTimers.clear();
13072 mCameraTurnedOnTimers.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013073
13074 int numUids = in.readInt();
13075 mUidStats.clear();
13076 for (int i = 0; i < numUids; i++) {
13077 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080013078 Uid u = new Uid(this, uid);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013079 u.readFromParcelLocked(mOnBatteryTimeBase, mOnBatteryScreenOffTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013080 mUidStats.append(uid, u);
13081 }
13082 }
13083
13084 public void writeToParcel(Parcel out, int flags) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013085 writeToParcelLocked(out, true, flags);
13086 }
13087
13088 public void writeToParcelWithoutUids(Parcel out, int flags) {
13089 writeToParcelLocked(out, false, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013090 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013091
13092 @SuppressWarnings("unused")
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013093 void writeToParcelLocked(Parcel out, boolean inclUids, int flags) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013094 // Need to update with current kernel wake lock counts.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080013095 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013096
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070013097 // Pull the clock time. This may update the time and make a new history entry
13098 // if we had originally pulled a time before the RTC was set.
13099 long startClockTime = getStartClockTime();
13100
Joe Onoratoabded112016-02-08 16:49:39 -080013101 final long uSecUptime = mClocks.uptimeMillis() * 1000;
13102 final long uSecRealtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013103 final long batteryRealtime = mOnBatteryTimeBase.getRealtime(uSecRealtime);
13104 final long batteryScreenOffRealtime = mOnBatteryScreenOffTimeBase.getRealtime(uSecRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013106 out.writeInt(MAGIC);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013107
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013108 writeHistory(out, true, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013110 out.writeInt(mStartCount);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070013111 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013112 out.writeString(mStartPlatformVersion);
13113 out.writeString(mEndPlatformVersion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013114 out.writeLong(mUptime);
13115 out.writeLong(mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013116 out.writeLong(mRealtime);
13117 out.writeLong(mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013118 out.writeInt(mOnBattery ? 1 : 0);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070013119 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070013120 out.writeInt(mMinLearnedBatteryCapacity);
13121 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013122 mOnBatteryTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
13123 mOnBatteryScreenOffTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
13124
13125 mScreenOnTimer.writeToParcel(out, uSecRealtime);
Mike Mac2f518a2017-09-19 16:06:03 -070013126 mScreenDozeTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013127 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
13128 mScreenBrightnessTimer[i].writeToParcel(out, uSecRealtime);
13129 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070013130 mInteractiveTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070013131 mPowerSaveModeEnabledTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070013132 out.writeLong(mLongestLightIdleTime);
13133 out.writeLong(mLongestFullIdleTime);
13134 mDeviceIdleModeLightTimer.writeToParcel(out, uSecRealtime);
13135 mDeviceIdleModeFullTimer.writeToParcel(out, uSecRealtime);
13136 mDeviceLightIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013137 mDeviceIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013138 mPhoneOnTimer.writeToParcel(out, uSecRealtime);
13139 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
13140 mPhoneSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
13141 }
13142 mPhoneSignalScanningTimer.writeToParcel(out, uSecRealtime);
13143 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
13144 mPhoneDataConnectionsTimer[i].writeToParcel(out, uSecRealtime);
13145 }
13146 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
13147 mNetworkByteActivityCounters[i].writeToParcel(out);
13148 mNetworkPacketActivityCounters[i].writeToParcel(out);
13149 }
13150 mMobileRadioActiveTimer.writeToParcel(out, uSecRealtime);
13151 mMobileRadioActivePerAppTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013152 mMobileRadioActiveAdjustedTime.writeToParcel(out);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013153 mMobileRadioActiveUnknownTime.writeToParcel(out);
13154 mMobileRadioActiveUnknownCount.writeToParcel(out);
13155 mWifiOnTimer.writeToParcel(out, uSecRealtime);
13156 mGlobalWifiRunningTimer.writeToParcel(out, uSecRealtime);
13157 for (int i=0; i<NUM_WIFI_STATES; i++) {
13158 mWifiStateTimer[i].writeToParcel(out, uSecRealtime);
13159 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070013160 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13161 mWifiSupplStateTimer[i].writeToParcel(out, uSecRealtime);
13162 }
13163 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13164 mWifiSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
13165 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080013166 mWifiActivity.writeToParcel(out, 0);
13167 mBluetoothActivity.writeToParcel(out, 0);
13168 mModemActivity.writeToParcel(out, 0);
13169 out.writeInt(mHasWifiReporting ? 1 : 0);
13170 out.writeInt(mHasBluetoothReporting ? 1 : 0);
13171 out.writeInt(mHasModemReporting ? 1 : 0);
13172
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013173 out.writeInt(mNumConnectivityChange);
13174 out.writeInt(mLoadedNumConnectivityChange);
13175 out.writeInt(mUnpluggedNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070013176 mFlashlightOnTimer.writeToParcel(out, uSecRealtime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013177 mCameraOnTimer.writeToParcel(out, uSecRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013178 mBluetoothScanTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013179 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013180 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070013181 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013182 out.writeInt(mCurrentBatteryLevel);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013183 out.writeInt(mLowDischargeAmountSinceCharge);
13184 out.writeInt(mHighDischargeAmountSinceCharge);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013185 out.writeInt(mDischargeAmountScreenOn);
13186 out.writeInt(mDischargeAmountScreenOnSinceCharge);
13187 out.writeInt(mDischargeAmountScreenOff);
13188 out.writeInt(mDischargeAmountScreenOffSinceCharge);
Mike Mac2f518a2017-09-19 16:06:03 -070013189 out.writeInt(mDischargeAmountScreenDoze);
13190 out.writeInt(mDischargeAmountScreenDozeSinceCharge);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013191 mDischargeStepTracker.writeToParcel(out);
13192 mChargeStepTracker.writeToParcel(out);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070013193 mDischargeCounter.writeToParcel(out);
13194 mDischargeScreenOffCounter.writeToParcel(out);
Mike Mac2f518a2017-09-19 16:06:03 -070013195 mDischargeScreenDozeCounter.writeToParcel(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013196 out.writeLong(mLastWriteTime);
13197
Bookatz50df7112017-08-04 14:53:26 -070013198 out.writeInt(mRpmStats.size());
13199 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
13200 SamplingTimer rpmt = ent.getValue();
13201 if (rpmt != null) {
13202 out.writeInt(1);
13203 out.writeString(ent.getKey());
13204 rpmt.writeToParcel(out, uSecRealtime);
13205 } else {
13206 out.writeInt(0);
13207 }
13208 }
13209 out.writeInt(mScreenOffRpmStats.size());
13210 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
13211 SamplingTimer rpmt = ent.getValue();
13212 if (rpmt != null) {
13213 out.writeInt(1);
13214 out.writeString(ent.getKey());
13215 rpmt.writeToParcel(out, uSecRealtime);
13216 } else {
13217 out.writeInt(0);
13218 }
13219 }
13220
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013221 if (inclUids) {
13222 out.writeInt(mKernelWakelockStats.size());
13223 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
13224 SamplingTimer kwlt = ent.getValue();
13225 if (kwlt != null) {
13226 out.writeInt(1);
13227 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013228 kwlt.writeToParcel(out, uSecRealtime);
13229 } else {
13230 out.writeInt(0);
13231 }
13232 }
13233 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013234 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
13235 SamplingTimer timer = ent.getValue();
13236 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013237 out.writeInt(1);
13238 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013239 timer.writeToParcel(out, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013240 } else {
13241 out.writeInt(0);
13242 }
Evan Millarc64edde2009-04-18 12:26:32 -070013243 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013244 } else {
Bookatzba78b2b2017-10-10 11:06:33 -070013245 out.writeInt(0);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013246 out.writeInt(0);
Evan Millarc64edde2009-04-18 12:26:32 -070013247 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070013248
James Carr3a226052016-07-01 14:49:52 -070013249 out.writeInt(mKernelMemoryStats.size());
13250 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
13251 SamplingTimer kmt = mKernelMemoryStats.valueAt(i);
13252 if (kmt != null) {
13253 out.writeInt(1);
13254 out.writeLong(mKernelMemoryStats.keyAt(i));
13255 kmt.writeToParcel(out, uSecRealtime);
13256 } else {
13257 out.writeInt(0);
13258 }
13259 }
13260
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013261 if (inclUids) {
13262 int size = mUidStats.size();
13263 out.writeInt(size);
13264 for (int i = 0; i < size; i++) {
13265 out.writeInt(mUidStats.keyAt(i));
13266 Uid uid = mUidStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013267
Bookatz867c0d72017-03-07 18:23:42 -080013268 uid.writeToParcelLocked(out, uSecUptime, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013269 }
13270 } else {
13271 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013272 }
13273 }
13274
13275 public static final Parcelable.Creator<BatteryStatsImpl> CREATOR =
13276 new Parcelable.Creator<BatteryStatsImpl>() {
13277 public BatteryStatsImpl createFromParcel(Parcel in) {
13278 return new BatteryStatsImpl(in);
13279 }
13280
13281 public BatteryStatsImpl[] newArray(int size) {
13282 return new BatteryStatsImpl[size];
13283 }
13284 };
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013285
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013286 public void prepareForDumpLocked() {
13287 // Need to retrieve current kernel wake lock stats before printing.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080013288 pullPendingStateUpdatesLocked();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070013289
13290 // Pull the clock time. This may update the time and make a new history entry
13291 // if we had originally pulled a time before the RTC was set.
13292 getStartClockTime();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013293 }
13294
Dianne Hackbornc51cf032014-03-02 19:08:15 -080013295 public void dumpLocked(Context context, PrintWriter pw, int flags, int reqUid, long histStart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013296 if (DEBUG) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013297 pw.println("mOnBatteryTimeBase:");
13298 mOnBatteryTimeBase.dump(pw, " ");
13299 pw.println("mOnBatteryScreenOffTimeBase:");
13300 mOnBatteryScreenOffTimeBase.dump(pw, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070013301 Printer pr = new PrintWriterPrinter(pw);
Mike Mac2f518a2017-09-19 16:06:03 -070013302 pr.println("*** Screen on timer:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070013303 mScreenOnTimer.logState(pr, " ");
Mike Mac2f518a2017-09-19 16:06:03 -070013304 pr.println("*** Screen doze timer:");
13305 mScreenDozeTimer.logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070013306 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070013307 pr.println("*** Screen brightness #" + i + ":");
13308 mScreenBrightnessTimer[i].logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070013309 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070013310 pr.println("*** Interactive timer:");
13311 mInteractiveTimer.logState(pr, " ");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070013312 pr.println("*** Power save mode timer:");
13313 mPowerSaveModeEnabledTimer.logState(pr, " ");
Dianne Hackborn08c47a52015-10-15 12:38:14 -070013314 pr.println("*** Device idle mode light timer:");
13315 mDeviceIdleModeLightTimer.logState(pr, " ");
13316 pr.println("*** Device idle mode full timer:");
13317 mDeviceIdleModeFullTimer.logState(pr, " ");
13318 pr.println("*** Device light idling timer:");
13319 mDeviceLightIdlingTimer.logState(pr, " ");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013320 pr.println("*** Device idling timer:");
13321 mDeviceIdlingTimer.logState(pr, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070013322 pr.println("*** Phone timer:");
13323 mPhoneOnTimer.logState(pr, " ");
Wink Saville52840902011-02-18 12:40:47 -080013324 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3251b902014-06-20 14:40:53 -070013325 pr.println("*** Phone signal strength #" + i + ":");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070013326 mPhoneSignalStrengthsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070013327 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070013328 pr.println("*** Signal scanning :");
13329 mPhoneSignalScanningTimer.logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070013330 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070013331 pr.println("*** Data connection type #" + i + ":");
13332 mPhoneDataConnectionsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070013333 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013334 pr.println("*** mMobileRadioPowerState=" + mMobileRadioPowerState);
Dianne Hackborne13c4c02014-02-11 17:18:35 -080013335 pr.println("*** Mobile network active timer:");
13336 mMobileRadioActiveTimer.logState(pr, " ");
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013337 pr.println("*** Mobile network active adjusted timer:");
13338 mMobileRadioActiveAdjustedTime.logState(pr, " ");
Dianne Hackborn0c820db2015-04-14 17:47:34 -070013339 pr.println("*** mWifiRadioPowerState=" + mWifiRadioPowerState);
Dianne Hackborn1d442e02009-04-20 18:14:05 -070013340 pr.println("*** Wifi timer:");
13341 mWifiOnTimer.logState(pr, " ");
13342 pr.println("*** WifiRunning timer:");
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013343 mGlobalWifiRunningTimer.logState(pr, " ");
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013344 for (int i=0; i<NUM_WIFI_STATES; i++) {
13345 pr.println("*** Wifi state #" + i + ":");
13346 mWifiStateTimer[i].logState(pr, " ");
13347 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070013348 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13349 pr.println("*** Wifi suppl state #" + i + ":");
13350 mWifiSupplStateTimer[i].logState(pr, " ");
13351 }
13352 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13353 pr.println("*** Wifi signal strength #" + i + ":");
13354 mWifiSignalStrengthsTimer[i].logState(pr, " ");
13355 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -070013356 pr.println("*** Flashlight timer:");
13357 mFlashlightOnTimer.logState(pr, " ");
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013358 pr.println("*** Camera timer:");
13359 mCameraOnTimer.logState(pr, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013360 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -080013361 super.dumpLocked(context, pw, flags, reqUid, histStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013362 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013363}